权重在梯度下降的多项式回归中爆炸

时间:2020-01-22 00:05:28

标签: python machine-learning regression linear-regression

我刚刚开始学习机器学习,并一直在尝试将多项式拟合正弦曲线生成的数据。我知道如何以封闭形式进行此操作,但我也在尝试使其与梯度下降一起使用。 但是,即使罚款期非常长,我的体重也达到了疯狂的高度。我究竟做错了什么? 这是代码:

import numpy as np
import matplotlib.pyplot as plt
from math import pi

N = 10
D = 5

X = np.linspace(0,100, N)
Y = np.sin(0.1*X)*50
X = X.reshape(N, 1)


Xb = np.array([[1]*N]).T
for i in range(1, D):
    Xb = np.concatenate((Xb, X**i), axis=1)

#Randomly initializie the weights
w = np.random.randn(D)/np.sqrt(D)

#Solving in closed form works
#w = np.linalg.solve((Xb.T.dot(Xb)),Xb.T.dot(Y))
#Yhat = Xb.dot(w)

#Gradient descent
learning_rate = 0.0001
for i in range(500):
    Yhat = Xb.dot(w)
    delta = Yhat - Y
    w = w - learning_rate*(Xb.T.dot(delta) + 100*w)

print('Final w: ', w)
plt.scatter(X, Y)
plt.plot(X,Yhat)
plt.show()

谢谢!

1 个答案:

答案 0 :(得分:0)

更新theta时,您必须采用theta并将其减去学习权重乘以theta导数除以训练集大小。您还必须将刑期除以训练规模集。但是主要的问题是您的学习率太大。对于以后的调试,打印成本以查看梯度下降是否有效以及学习率是否太小或恰好是有帮助的。

下面是二阶多项式的代码,该代码找到了最佳theta(如您所见,学习率确实很小)。我还添加了成本函数。

package de.scrum_master.stackoverflow.q59842227

import spock.lang.Specification

class FileCreatorTest extends Specification {
  def "index info file created"() {
    given:
    File file = Mock() {
      createNewFile() >> true
    }

    expect:
    new FileCreator().createIndexInfoFile(file)
  }

  def "no index info file created"() {
    given:
    File file = Mock()

    expect:
    !new FileCreator().createIndexInfoFile(file)
  }
}