Получение градиентного спуска для работы в октаве (курс Эндрю Нга по машинному обучению, упражнение 1) - PullRequest
1 голос
/ 11 апреля 2019

Итак, я пытаюсь реализовать / решить первый урок по программированию на машинном курсе Эндрю Нг на Coursera. У меня проблемы с реализацией линейного градиентного спуска (для одной переменной) в октаве. Я не получаю те же значения параметров, как в решении, но мои параметры движутся в одном направлении (по крайней мере, я так думаю). Так что я могу иметь где-то в моем коде ошибку. Может быть, тот, кто имеет больше опыта, чем я, может просветить меня.

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);

theta1 = theta(1);
theta2 = theta(2);

temp0 = 0;
temp1 = 0;

h = X * theta;
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.
    %
    temp0 = 0;
    temp1 = 0;
    for i=1:m
        error = (h(i) - y(i));
        temp0 = temp0 + error * X(i, 1));;
        temp1 = temp1 + error * X(i, 2));
    end
    theta1 = theta1 - ((alpha/m) * temp0);
    theta2 = theta2 - ((alpha/m) * temp1);
    theta = [theta1;theta2];

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

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

end
end

Мои ожидаемые результаты для упражнения 1 с тэтой, инициализированной [0; 0], должны быть для тета1: -3.6303 и для тета2: 1.1664

Но я становлюсь, как результат, theta1 равен 0,095420 , а thetha2 равен 0.51890

here's a photo where you can see my function

Это формула, которую я использую для линейного градиентного спуска.

this is my formula for linear gradien descent

where  in the formula this is h(x)

EDIT1: Отредактированный код. Теперь я получил для theta1:

87,587

и для тета2

979,93

1 Ответ

0 голосов
/ 12 апреля 2019

Теперь я знаю, в чем заключалась моя проблема. Я собираюсь описать это быстро для тех, кто может быть заинтересован в этом. Поэтому я случайно назвал avriable h вне моей петли. Поэтому каждый раз в цикле он вычисляется с одним и тем же значением.

Вот фиксированный код:

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);

theta1 = theta(1);
theta2 = theta(2);

temp0 = 0;
temp1 = 0;
error = 0;

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

    h = X * theta; %heres the variable i moved into the loop

    temp0 = 0;
    temp1 = 0;
    for i=1:m
        error = (h(i) - y(i));
        temp0 = temp0 + (error * X(i, 1));
        temp1 = temp1 + (error * X(i, 2));
        %disp(error);
    end
    theta1 = theta1 - ((alpha/m) * temp0);
    theta2 = theta2 - ((alpha/m) * temp1);
    theta = [theta1;theta2];

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

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

end
end
...