在Matlab中使用梯度下降法

我在Coursera上学习机器学习课程。对于我来说,机器学习是一个非常有趣的领域。在第一次编程练习中,我在梯度下降算法上遇到了一些困难。如果有人能帮我,我将不胜感激。

以下是更新theta的说明:

“你将在gradientDescent.m文件中实现梯度下降。循环结构已经为你编写,你只需要在每次迭代中提供对θ的更新。

    function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)    %GRADIENTDESCENT Performs gradient descent to learn theta    %   theta = GRADIENTDESENT(X, y, theta, alpha, num_iters) updates theta by     %   taking num_iters gradient steps with learning rate alpha   % Initialize some useful values   m = length(y); % number of training examples   J_history = zeros(num_iters, 1);   for iter = 1:num_iters% ====================== YOUR CODE HERE ======================% Instructions: Perform a single gradient step on the parameter vector%               theta. %% Hint: While debugging, it can be useful to print out the values%       of the cost function (computeCost) and gradient here.%    % ============================================================% Save the cost J in every iteration    J_history(iter) = computeCost(X, y, theta);endend

所以我这样做来同时更新theta:

    temp0 = theta(1,1) - (alpha/m)*sum((X*theta-y));    temp1 = theta(2,1) - (alpha/m)*sum((X*theta-y).*X);    theta(1,1) = temp0;    theta(2,1) = temp1;

当我运行这段代码时出现了错误。请问有人能帮我吗?


回答:

你遇到的错误是Error using .* Matrix dimensions must agree. Error in gradientDescent (line 20) temp1 = theta(2,1) - (alpha/m)*sum((X*theta-y).*X);,这意味着.*操作无法进行。在该行之前,添加以下代码:

size(X*theta-y)size(X)

如果你想执行(X*theta-y).*X,那么X*theta-yX应该具有相同的大小。如果它们大小不一致,你需要检查你的算法。

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

发表回复

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