Ram*_*Ram 5 matlab machine-learning
我正在学习机器学习课程.机器学习对我来说是一个很好的领域.在第一次编程练习中,我在梯度体面算法中遇到了一些困难.如果有人可以帮助我,我将不胜感激.
这是更新thetas的说明;
"你将在文件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);
end
end
Run Code Online (Sandbox Code Playgroud)
所以我这样做是为了同时更新这些内容;
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;
Run Code Online (Sandbox Code Playgroud)
我运行此代码时收到错误.有人可以帮我吗?
jer*_*use 17
我已经解释了为什么你可以使用矢量化形式:
theta = theta - (alpha/m) * (X' * (X * theta - y));
或等同物
theta = theta - (alpha/m) * ((X * theta - y)' * X)';
在这个答案.
梯度下降算法矩阵版本的说明:
假设给出以下X,y和θ值:
这里
进一步,
h(x) = ([X] * [?])
(mx 1我们训练集的预测值矩阵) h(x)-y = ([X] * [?] - [y])
(我们预测中的mx 1错误矩阵)机器学习的整个目标是最小化预测中的错误.基于上述推论,我们的误差矩阵是m x 1
矢量矩阵如下:
为了计算θ的新的价值Ĵ,我们必须得到乘用j所有错误(m行)的总和日的训练集X的特征值也就是说,把所有的值E,分别为J乘他们个功能的的相应训练例子,并添加它们放在一起.这将帮助我们在得到θ的新的(希望更好)值Ĵ.对所有j或特征数重复此过程.在矩阵形式中,这可以写成:
[E]' x [X]
将给出一个行向量矩阵,因为E'是1 xm矩阵,X是mxn矩阵.但我们对获得列矩阵很感兴趣,因此我们将转换结果矩阵.小智 5
theta = theta - (alpha/m) * (X' * (X * theta - y));
Run Code Online (Sandbox Code Playgroud)
这是正确的答案
小智 5
temp0 = theta(1,1) - (alpha/m)*sum((X*theta-y));
temp1 = theta(2,1) - (alpha/m)*sum((X*theta-y).*X(:,2));
theta(1,1) = temp0;
theta(2,1) = temp1;
Run Code Online (Sandbox Code Playgroud)
或者您可以使用以下代码.它更简单.只有两个参数theta1和theta2.但如果存在更多参数,那就更好了.
for i=1:2
theta(i) = theta(i) - (alpha/m)*sum((X*theta-y).*X(:,i));
end
Run Code Online (Sandbox Code Playgroud)
您收到的错误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)
Run Code Online (Sandbox Code Playgroud)
如果你想这样做(X*theta-y).*X
,那么X*theta-y
和的X
大小应该相同。如果不是,您将需要检查您的算法。
归档时间: |
|
查看次数: |
12268 次 |
最近记录: |