【问题标题】:Training a single linear neuron for regression using batch gradient descent使用批量梯度下降训练单个线性神经元进行回归
【发布时间】:2016-06-15 14:59:45
【问题描述】:

我正在尝试使用梯度下降来训练一些权重,但是我没有取得太大的成功。 我一开始的学习率lr 为 0.01,而我的成本实际上飞涨,这让我感到惊讶。我只能假设它还不足以找到任何局部最小值。将其更改为 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()

【问题讨论】:

    标签: python python-3.x numpy matplotlib machine-learning


    【解决方案1】:

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

    0.0001 的 alpha 对我来说效果很好。

    【讨论】:

    • 哇,谢谢,就这么简单。我可能应该慢慢减少它,而不是跳到如此荒谬的小数字。当我想到它时,它是有道理的,它正在逐渐降低渐变,它无法到达任何地方。
    • 没问题!这是一个容易犯的错误。
    猜你喜欢
    • 2014-10-10
    • 2022-08-14
    • 2015-07-11
    • 2015-11-23
    • 2023-03-11
    • 2021-02-27
    • 2019-08-29
    • 2017-06-20
    • 2019-10-09
    相关资源
    最近更新 更多