为什么我的梯度下降算法无法正确工作?

我试图将Andrew NG机器学习课程中的线性回归梯度下降算法复制到Python中,但不知为何我的实现无法正确工作。

以下是我的Octave实现,运行正常:

function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)J_history = zeros(num_iters, 1);for iter = 1:num_iters    prediction = X*theta;    margin_error = prediction - y;    gradient = 1/m * (alpha * (X' * margin_error));    theta = theta - gradient;    J_history(iter) = computeCost(X, y, theta);endend

然而,当我将其翻译成Python时,得到的结果却不准确。成本似乎在上升而不是下降。

以下是我的Python实现:

def gradientDescent(x, y, theta, alpha, iters):    m = len(y)    J_history = np.matrix(np.zeros((iters,1)))    for i in range(iters):        prediction = x*theta.T        margin_error = prediction - y        gradient = 1/m * (alpha * (x.T * margin_error))        theta = theta - gradient        J_history[i] = computeCost(x,y,theta)    return theta,J_history

我的代码能够编译,没有任何问题。请注意这是theta:

theta = np.matrix(np.array([0,0]))

Alpha和iters设置为如下值:

alpha = 0.01iters = 1000

当我运行opt_theta, cost = gradientDescent(x, y, theta, alpha, iters)并打印opt_theta时,我得到的是:

matrix([[  2.36890383e+16,  -1.40798902e+16],        [  2.47503758e+17,  -2.36890383e+16]])

而我应该得到的是:

matrix([[-3.24140214, 1.1272942 ]])

我哪里做错了?

编辑:

成本函数

def computeCost(x, y, theta):#   Get length of data set    m = len(y)    # We get theta transpose because we are working with a numpy array [0,0] for example    prediction = x * theta.T    J = 1/(2*m) * np.sum(np.power((prediction - y), 2))    return J

回答:

看这里:

>>> A = np.matrix([3,3,3])>>> B = np.matrix([[1,1,1], [2,2,2]])>>> A-Bmatrix([[2, 2, 2],        [1, 1, 1]])

矩阵是广播在一起的。

“这是因为np.matrix继承自np.array。np.matrix覆盖了乘法运算,但没有覆盖加法和减法”

在你的情况下,theta(1×2)减去gradient(2×1),结果得到2×2。尝试在减去之前转置gradient。

theta = theta - gradient.T

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中创建了一个多类分类项目。该项目可以对…

发表回复

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