微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

实施随机梯度下降

如何解决实施随机梯度下降

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

结果可以在这张照片中看到:

enter image description here

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

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

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,s=6)

th = SGD(X,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)

解决方法

为了说明我的评论,

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,10,0.01)产生正确的结果

10 iterations

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。