이전에 Gradient Descent라는 기법을 이용하여 단항에서 자동으로 새터를 구해 주었습니다.

이번에는 다항일 때의 Gradient Descent 기법을 알아 보겠습니다.



다항일 때는 별로 달라지는게 없고 x0이 원래 존재 했었지만 1이여서 생략 했던 것이고

이전에 구한 multiple variable cost function에 h를 구한 식을 가져다가 

n(number of features) 만큼 iteration을 돌리면 됩니다.





식을 그림과 같으며 코드를 구현해 보면

* Gradient Descent Multi

function [theta, J_history] = gradientDescentMulti(x, y, theta, alpha, iterations)


m = length(y); % number of rows

n = size(x, 2); % number of features

    


    h = zeros(n, 1);

    J_history = zeros(iterations, 1);

    for i=1:iterations


    % sum of all hypotesis * x

    for j=1:n

H = (theta' * x')';

h(j) = sum((H - y)' * x(:, j));


    end


    % update theta

    for j=1:n

    theta(j) = theta(j) - alpha * (h(j) / m);

    end


    % add history

    J_history(i) = computeCostMulti(x, y, theta);

 

    end


end


다항 코스트 펑션 구하는 코드 + 단항 GD 코드로 구해지는 것을 알 수 있습니다.


>> data = load('ex1data2.txt');

>> n = size(data, 2);

>> x = data(:, 1:n-1);

>> y = data(:, n);

>> m = length(x);

>> [x, mu, sigma] = meanNormalization(x);

>> x = [ones(m, 1), x]; % add x0 1

>> theta = zeros(n, 1)

>> alpha = 0.01;

>> iterations = 1500;

>> theta = gradientDescentMulti(x, y, theta, alpha, iterations)


theta =


  3.4041e+005

  1.1063e+005

  -6.6493e+003


새터가 새로 변경된 것을 볼 수 있습니다.


그럼 코스트 펑션을 다시 구해보면


>> computeCostMulti(x, y, theta)

ans =   2.0433e+009


위와 같이 코스트 펑션이 나옵니다.

이 값이 reasonable 한지는 차차 알아보도록 하겠습니다.

'ML > octave구현 - w1' 카테고리의 다른 글

[octave] Stochastic Gradient descent  (0) 2016.03.22
[octave] Normal equation  (0) 2016.03.13
[octave] feature mean normalization  (0) 2016.03.10
[octave] multiple variable cost function  (0) 2016.03.10
[octave] 임의 값 예측  (0) 2016.03.07

+ Recent posts