在 Octave 中实现梯度下降的问题
Trouble Implementing Gradient Descent in Octave
我一直在尝试在 Octave 中实现梯度下降。这是我目前的代码:
function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)
%GRADIENTDESCENT Performs gradient descent to learn theta
% theta = GRADIENTDESCENT(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.
%
theta
X
y
theta' .* X
for inner = 1:length(theta)
hypothesis = (X * theta - y)';
% Updating the parameters
temp0 = theta(1) - (alpha * (1/m) * hypothesis * X(:, 1));
temp1 = theta(2) - (alpha * (1/m) * hypothesis * X(:, 2));
theta(1) = temp0;
theta(2) = temp1;
J_history(iter) = computeCost(X, y, theta);
end
end
我真的不知道这段代码出了什么问题,它可以编译并运行,但它是自动分级的,每次都失败。
编辑:抱歉,不具体。我应该实现 GD 的单个步骤,而不是整个循环
编辑 2:这是全部内容。只有 for 循环内的内容与 imo 相关。
编辑 3:两个测试用例都失败了,所以我的计算有问题。
我认为我的问题是出于某种原因我在那里有一个额外的 for 循环。
我一直在尝试在 Octave 中实现梯度下降。这是我目前的代码:
function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)
%GRADIENTDESCENT Performs gradient descent to learn theta
% theta = GRADIENTDESCENT(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.
%
theta
X
y
theta' .* X
for inner = 1:length(theta)
hypothesis = (X * theta - y)';
% Updating the parameters
temp0 = theta(1) - (alpha * (1/m) * hypothesis * X(:, 1));
temp1 = theta(2) - (alpha * (1/m) * hypothesis * X(:, 2));
theta(1) = temp0;
theta(2) = temp1;
J_history(iter) = computeCost(X, y, theta);
end
end
我真的不知道这段代码出了什么问题,它可以编译并运行,但它是自动分级的,每次都失败。
编辑:抱歉,不具体。我应该实现 GD 的单个步骤,而不是整个循环
编辑 2:这是全部内容。只有 for 循环内的内容与 imo 相关。
编辑 3:两个测试用例都失败了,所以我的计算有问题。
我认为我的问题是出于某种原因我在那里有一个额外的 for 循环。