Skip to main content
 首页 » 编程设计

python之使用批量梯度下降训练单个线性神经元进行回归

2025年05月04日15lonelyxmas

我正在尝试使用梯度下降来训练一些权重,但是我没有取得太大的成功。 我以 0.01 的学习率 lr 开始,我的成本实际上飙升,这让我感到惊讶。我只能假设它不够小,无法找到任何局部最小值。将其更改为 0.0000000000001 使其稳定并足够缓慢地下降。

迭代 998 |费用:2444.995584

迭代 999 |费用:2444.995577

迭代 1000 |费用:2444.995571

最终权重:5.66633309647e-07 | 4.32179246434e-09

然而,要么这些权重有问题,要么我如何绘制它们:

import numpy as np 
import matplotlib.pyplot as plt 
 
 
def gradient_descent(x, y, w, lr, m, iter): 
    xTrans = x.transpose() 
    for i in range(iter): 
        prediction = np.dot(x, w) 
        loss = prediction - y 
        cost = np.sum(loss ** 2) / m 
 
        print("Iteration %d | Cost: %f" % (i + 1, cost)) 
 
        gradient = np.dot(xTrans, loss) / m     # avg gradient 
 
        w = w - lr * gradient   # update the weight vector 
 
    return w 
 
# generate data from uniform distribution -10. +10 and linear function 
x = np.arange(1, 200, 2) 
d = np.random.uniform(-10, 10, x.size) 
y = .4 * x + 3 + d 
 
# number of training samples 
m = y.size 
 
# add a column of ones for bias values 
it = np.ones(shape=(m, 2)) 
it[:, 1] = x 
 
m, n = np.shape(it) 
 
# initialise weights to 0 
w = np.zeros(n) 
 
iter = 1000             # number of iterations 
lr = 0.0000000000001    # learning rate / alpha 
 
trained_w = gradient_descent(it, y, w, lr, m, iter) 
result = trained_w[1] * x + trained_w[0]    # linear plot of our predicted function 
print("Final weights: %s | %s" % (trained_w[1], trained_w[0])) 
 
plt.plot(x, y, 'gx') 
plt.plot(x, result) 
 
plt.show() 

请您参考如下方法:

你过度补偿了。这里的学习率非常小,需要数十亿次迭代才能收敛。将其设置为小于 0.01,但大于您现在拥有的值。

Alpha 为 0.0001 对我来说效果很好。