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

我在尝试使用梯度下降法来训练一些权重,但效果不佳。我最初设定的学习率lr为0.01,结果成本反而急剧上升,这让我很惊讶。我只能假设这个学习率不够小,无法找到任何局部最小值。将其改为0.0000000000001后,成本得以稳定并缓慢下降。

第998次迭代 | 成本: 2444.995584

第999次迭代 | 成本: 2444.995577

第1000次迭代 | 成本: 2444.995571

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

然而,这些权重可能有问题,或者是我绘图的方式有误:

enter image description here

import numpy as npimport matplotlib.pyplot as pltdef 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 functionx = np.arange(1, 200, 2)d = np.random.uniform(-10, 10, x.size)y = .4 * x + 3 + d# number of training samplesm = y.size# add a column of ones for bias valuesit = np.ones(shape=(m, 2))it[:, 1] = xm, n = np.shape(it)# initialise weights to 0w = np.zeros(n)iter = 1000             # number of iterationslr = 0.0000000000001    # learning rate / alphatrained_w = gradient_descent(it, y, w, lr, m, iter)result = trained_w[1] * x + trained_w[0]    # linear plot of our predicted functionprint("Final weights: %s | %s" % (trained_w[1], trained_w[0]))plt.plot(x, y, 'gx')plt.plot(x, result)plt.show()

回答:

你过度补偿了。这里的学习率太小,需要数十亿次迭代才能收敛。将其设置为比0.01小,但比你现在设置的大一些的值。

我使用0.0001的alpha值时效果很好。

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注