【问题标题】:Implementing stochastic gradient descent实现随机梯度下降
【发布时间】:2021-02-20 16:17:57
【问题描述】:

我正在尝试使用多元线性回归和 L2 范数作为损失函数来实现随机梯度下降的基本方法。

结果可以看这张图:

它离理想的回归线很远,但我真的不明白为什么会这样。我仔细检查了所有数组尺寸,它们似乎都合适。

以下是我的源代码。如果有人能看到我的错误或给我提示,我将不胜感激。

def SGD(x,y,learning_rate):
    theta = np.array([[0],[0]])
    
    for i in range(N):
        xi = x[i].reshape(1,-1)
        y_pre = xi@theta

        theta = theta + learning_rate*(y[i]-y_pre[0][0])*xi.T

    print(theta)

    return theta
    

N = 100
x = np.array(np.linspace(-2,2,N))
y = 4*x + 5 + np.random.uniform(-1,1,N)

X = np.array([x**0,x**1]).T

plt.scatter(x,y,s=6)

th = SGD(X,y,0.1)

y_reg = np.matmul(X,th)
print(y_reg)
print(x)
plt.plot(x,y_reg)

plt.show()

编辑:另一种解决方案是使用x = np.random.permutation(x) 打乱测量

【问题讨论】:

  • 尝试使用较小的学习率并增加迭代次数
  • @Marat 0.01 的学习率已经很低了,我怎样才能通过只有 100 个测量点的迭代来增加数量?
  • 迭代次数可能要高得多。

标签: python numpy regression


【解决方案1】:

为了说明我的评论,

def SGD(x,y,n,learning_rate):
    theta = np.array([[0],[0]])

    # currently it does exactly one iteration. do more
    for _ in range(n):
        for i in range(len(x)):
            xi = x[i].reshape(1,-1)
            y_pre = xi@theta

            theta = theta + learning_rate*(y[i]-y_pre[0][0])*xi.T

    print(theta)

    return theta

SGD(X,y,10,0.01) 产生正确的结果

【讨论】:

  • 谢谢,我对 ML 很陌生,这是我的第一个任务。非常感谢!
猜你喜欢
  • 2016-09-25
  • 2011-07-04
  • 1970-01-01
  • 2016-06-13
  • 2017-02-19
  • 2018-07-14
  • 1970-01-01
  • 2018-12-10
  • 1970-01-01
相关资源
最近更新 更多