首页 > 解决方案 > 绘制训练误差性能与时期数作为学习率 η 的函数

问题描述

class LinearRegressionUsingGD:

    def __init__(self, n_iterations=1000):
        self.n_iterations = n_iterations

    def fit(self, x, y, lrate):
        self.cost_ = []
        self.w_ = np.zeros((x.shape[1], 1))
        m = x.shape[0]

        for _ in range(self.n_iterations):
            y_pred = np.dot(x, self.w_)
            residuals = y_pred - y
            gradient_vector = np.dot(x.T, residuals)
            self.w_ -= (lrate / m) * gradient_vector
            cost = np.sum((residuals ** 2)) / (2 * m)
            self.cost_.append(cost)
        return self.w_, self.cost_

        pyplot.plot(self.cost_, lrate, label='train')
        pyplot.title('lrate='+str(lrate), pad=-50)


lr = LinearRegressionUsingGD()

learning_rates = [1E-6, 1E-5, 1E-4, 1E-3, 1E-2, 1E-1]

for i in range(len(learning_rates)):
  # determine the plot number
  plot_no = 420 + (i+1)
  pyplot.subplot(plot_no)
  # fit model and plot learning curves for a learning rate
  lr.fit(X_train, y_train, learning_rates[i])

pyplot.show()

我在我的 Jupyter 笔记本中运行上面的代码,它只给了我 6 个空白图表。

我想绘制训练误差性能与时期数的关系,作为学习率 η 的函数。

有人可以更正代码并告诉我哪里出错了吗?

标签: python-3.xmatplotlibmachine-learninggoogle-colaboratory

解决方案


我认为您会遇到其他一些问题,即您正在绘制一个值lrate一千次,但您的主要问题是通过摆脱return self.w_, self.cost_. 它不会在您的代码中使用,并且会在绘图之前退出该函数。一个简化的工作示例是:

import numpy as np
import pylab as pyplot

class LinearRegressionUsingGD:

    def __init__(self, n_iterations=1000):
        self.n_iterations = n_iterations

    def fit(self, lrate):
        self.cost_ = []

        for _ in range(self.n_iterations):
            self.cost_.append(np.random.random())

        pyplot.plot(self.cost_, [lrate]*1000, label='train')
        pyplot.title('lrate='+str(lrate), pad=-50)


lr = LinearRegressionUsingGD()
learning_rates = [1E-6, 1E-5, 1E-4, 1E-3, 1E-2, 1E-1]

for i in range(len(learning_rates)):
  plot_no = 420 + (i+1)
  pyplot.subplot(plot_no)
  lr.fit(learning_rates[i])

pyplot.show()

推荐阅读