梯度下降算法在Matlab中给出错误答案

我在学习机器学习课程,并尝试在Matlab中实现梯度下降算法。单独测试时,computeCost函数运行正常。我用它来查看每次迭代的成本,但似乎成本根本没有减少。成本只是随机波动。alpha的值被给定为0.01,所以我知道这不是学习率过大的问题。我得到的theta值与预期输出相差很大。我哪里做错了?提前谢谢!

function theta = gradientDescent(X, y, theta, alpha, num_iters)%GRADIENTDESCENT Performs gradient descent to learn theta% Initialize some useful valuesm = length(y); % number of training examplestemp1=0;temp2=0;for iter = 1:num_itersfor k = 1:m    temp1 = temp1 + (theta(1) + theta(2)*X(k, 2) - y(k));    temp2 = temp2 + ((theta(1) + theta(2)*X(k, 2) - y(k))*X(k, 2));end theta(1) = theta(1)-(1/m)*alpha*temp1;theta(2) = theta(2)-(1/m)*alpha*temp2;computeCost(X, y, theta)endend

编辑:这里也附上computeCost函数

function J = computeCost(X, y, theta)m = length(y); % number of training examplesJ = 0;temp = 0;for index = 1:m    temp = temp + (theta(1) + theta(2)*X(index, 2)-y(index))^2;end J = temp/(2*m); end

回答:

尝试更改:

temp1=0;temp2=0;for iter = 1:num_iters

for iter = 1:num_iters  temp1=0;  temp2=0;

梯度需要在每次迭代时重新计算(否则你实际上是在引入动量项)。

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

发表回复

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