下标索引必须是实数正整数或逻辑

时间:2015-07-29 21:46:42

标签: octave gradient-descent

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.
%

    hypothesis = x*theta;
    theta_0 = theta(1) - alpha(1/m)*sum((hypothesis-y)*x);
    theta_1 = theta(2) - alpha(1/m)*sum((hypothesis-y)*x);
    theta(1) = theta_0;
    theta(2) = theta_1;








% ============================================================

% Save the cost J in every iteration    
    J_history(iter) = computeCost(X, y, theta);

end

end

我一直收到此错误

error: gradientDescent: subscript indices must be either positive integers less than 2^31 or logicals

在第一个theta和=

之间的这一行
theta_0 = theta(1) - alpha(1/m)*sum((hypothesis-y)*x);

我非常喜欢八度,所以请放轻松我 先感谢您。 这是来自第2周的机器学习课程

1 个答案:

答案 0 :(得分:2)

99%确定您的错误在topsig指出的行上,您有alpha(1/m)

如果你给你的函数提供了一个输入值的例子以及你希望看作输出的内容会有所帮助,但我从你的评论中假设

% taking num_iters gradient steps with learning rate alpha

alpha是一个常数,而不是一个函数。因此,你有alpha(1/m)行,中间没有任何操作符。当您使用alpha的值对1/m编制索引时,八度音阶会看到此情况。

即,如果你有一个数组

x = [3 4 5]
x*(2) = [6 8 10]  %% two times each element in the array
x(2) = [4]  %% second element in the array

你所做的事似乎没有意义,因为' m = length(y)'这将输出一个标量,所以

x = [3 4 5]; m = 3;
x*(1/m) = x*(1/3) = [1 1.3333 1.6666]  %% element / 3
x(1/m) = ___error___  %% the 1/3 element in the array makes no sense

请注意,对于某些错误,它始终指示错误的位置位于赋值运算符(行开头的等号)。如果它指向那里,你通常必须在该行的其他地方寻找实际错误。在这里,它试图应用非整数下标(1/m)

而大喊大叫