【问题标题】:Transform gradient descent with L2 regularisation to code将具有 L2 正则化的梯度下降转换为代码
【发布时间】:2019-02-26 01:32:46
【问题描述】:

我一直在写这行代码 - 这是一个非常简单的代码行,让我很困惑。

我应该编写带有参数的梯度下降函数——权重、X、y、train_len(定义为 X 的行数)、alpha、learning_rate 和 num_iter。

The first derivative of the loss function wrt to weight is here. 我试过这样写代码:

for i in range(0, n_iter):

  weights = weights - learning_rate * (np.multiply(-2, np.dot(X.transpose(), y - np.dot(X, weights))) + np.multiply(2*alpha, weights))

return weights

不幸的是,当我尝试使用梯度下降函数时,我得到了 nan。

【问题讨论】:

  • 一般提示:写X.T而不是X.transpose()alpha*weights而不是np.multiply()
  • 什么时候收到nans?经过一步还是多步?您在for 循环中提供的唯一代码是什么?
  • @cheersmate 我需要检查我什么时候得到了 nans,是的,我在 for 循环中的任何东西都在这里。
  • 但是你不应该在每次迭代期间重新计算X 吗?您需要先进行前向传递,然后再进行反向传递...

标签: python-3.x numpy gradient-descent


【解决方案1】:
for i in range(0, n_iter):
  first_derivative = -2 * np.dot(X.T, y - np.dot(X, weights)) + 2 * alpha * weights
  weights = weights - (learning_rate / train_len) * first_derivative
return weights

原来我忘了除以训练样本的数量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-11
    • 2020-11-30
    • 2018-04-21
    • 1970-01-01
    • 1970-01-01
    • 2021-05-09
    • 2018-01-31
    相关资源
    最近更新 更多