线性回归的梯度下降法爆炸

我正在尝试使用这个资源来实现线性回归的梯度下降法:https://spin.atomicobject.com/2014/06/24/gradient-descent-linear-regression/

我的问题是我的权重在爆炸(指数增长),基本上在做与预期相反的事情。

首先我创建了一个数据集:

def y(x, a):    return 2*x + a*np.random.random_sample(len(x)) - a/2x = np.arange(20)y_true = y(x,10)

看起来像这样:

随机数据

以及要优化的线性函数:

def y_predict(x, m, b):    return m*x + b

所以对于一些随机选择的参数,结果是这样的:

m0 = 1b0 = 1a = y_predict(x, m0, b0)plt.scatter(x, y_true)plt.plot(x, a)plt.show()

输入图片描述

现在成本函数看起来像这样:

cost = (1/2)* np.sum((y_true - a) ** 2)

成本相对于预测的偏导数(dc_da):

dc_da = (a - y_true) # 仍然是一个向量

成本相对于斜率参数的偏导数(dc_dm):

dc_dm = dc_da.dot(x) # 现在是一个常数 

以及成本相对于y截距参数的偏导数(dc_db):

dc_db = np.sum(dc_da) # 也是一个常数

最后是梯度下降法的实现:

iterations = 10m0 = 1b0 = 1learning_rate = 0.1N = len(x)for i in range(iterations):        a = y_predict(x, m0, b0)        cost = (1/2) * np.sum((y_true - a) ** 2)        dc_da = (a - y_true)        mgrad = dc_da.dot(x)    bgrad = np.sum(dc_da)        m0 -= learning_rate * (2 / N) * mgrad    b0 -= learning_rate * (2 / N) * bgrad        if (i % 2 == 0):        print("Iteration {}".format(i))        print("Cost: {}, m: {}, b: {}\n".format(cost, m0, b0))

结果是这样的:

Iteration 0Cost: 1341.5241150881411, m: 26.02473879743261, b: 2.8683883457327797Iteration 2Cost: 409781757.38124645, m: 13657.166910552878, b: 1053.5831308528543Iteration 4Cost: 132510115599264.75, m: 7765058.4350503925, b: 598610.1166795876Iteration 6Cost: 4.284947676217907e+19, m: 4415631880.089208, b: 340401694.5610262Iteration 8Cost: 1.3856132043127762e+25, m: 2510967578365.3584, b: 193570850213.62192

我的实现有什么问题?


回答:

问题出在学习率上。

在0.1的学习率下,步长太大,导致它们逃离了下坡梯度。

在0.001的学习率下,结果是这样的:

Iteration 0Cost: 1341.5241150881411, m: 1.250247387974326, b: 1.0186838834573277Iteration 20Cost: 74.23350734398517, m: 2.0054600094398487, b: 1.0648169455682297Iteration 40Cost: 74.14854910310204, m: 2.00886824141609, b: 1.0531220375231194Iteration 60Cost: 74.07892801481468, m: 2.0097830838155835, b: 1.0413622803654885Iteration 80Cost: 74.01078231057598, m: 2.0106800645568503, b: 1.0297271562539492

看起来像这样:

plt.scatter(x,y_true)plt.plot(x, a)plt.show()

输入图片描述

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

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