python-3.x - 绘制训练误差性能与时期数作为学习率 η 的函数
问题描述
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 个空白图表。
我想绘制训练误差性能与时期数的关系,作为学习率 η 的函数。
有人可以更正代码并告诉我哪里出错了吗?
解决方案
我认为您会遇到其他一些问题,即您正在绘制一个值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()
推荐阅读
- python - 如何在 Python 中的框前显示文本?
- html - 视频未在 html 中显示保持空白或黑色
- delphi - 在 FMX 中如何获取 TWebBrowser 控件的当前 URL?
- c# - 创建动态爬升方法
- spring-boot - beans.factory.UnsatisfiedDependencyException:创建具有名称的 bean 时出错
- excel - 返回列与所选颜色匹配的行 EXCEL
- c# - 将进度条绘制到按钮背景中
- php - PHP - 数组中的数字范围
- django - Django Heroku 服务器错误(500),当我设置 Debug - False 时它工作正常
- camunda - 从camunda java委托调用需要很长时间才能完成的服务