앞서 새터로 인하여 cost function와 그래프 모양이 어떻게 변하는지 알아 보았습니다.
여기서는 새터를 자동으로 구해주는 알고리즘인 Gradient Descent 알고리즘에 대해 설명합니다.
* Gradient Descent
gradient descent의 알고리즘은 위와 같습니다.
간단하게 설명하면
: 입력한 iteration 개수 만큼
: 각 새터를 구하고 그값을 이용하여 iteration 을 돌립니다.
: 알파 값도 입력해줍니다.
자세한 이론은 심화 강의를 통해 학습하기 바랍니다.
alpha 값과 iteration 값을 입력해줍니다.
코드는 아래와 같습니다.
function theta = gradientDescent(x, y, theta, alpha, iterations)
m = length(y); % number of rows
for i=1:iterations
h1 = 0;
h2 = 0;
for j=1:m
h1 = h1 + (theta(1) + theta(2) * x(j, 2) - y(j));
h2 = h2 + (theta(1) + theta(2) * x(j, 2) - y(j)) * x(j, 2);
end
theta(1) = theta(1) - alpha * (h1 / m);
theta(2) = theta(2) - alpha * (h2 / m);
% computeCost(x, y, theta); % print cost function
end
end
: 앞서 구한 cost function과 유사하며 iterations, alpha 값을 더 입력해준 것이 특징입니다.
그럼 알파, 이터레이션 값까지 하여 알고리즘을 통해 새터를 구한 값을 대입해서 계산합니다.
>> data = load('ex1data1.txt');
>> y = data(:, 2);
>> m = length(y);
>> x = [ones(m, 1), data(:,1)];
>> theta = zeros(2, 1);
>> alpha = 0.01;
>> iterations = 1500;
>> theta = gradientDescent(x, y, theta, alpha, iterations)
theta =
-3.6303
1.1664
구한 새터값은 위와 같다. cost function을 구해봅니다.
>> computeCost(x, y, theta)
ans = 4.4834
값이 4.4로 좋아 보입니다.
그래프로 나타나면
>> plotManualTheta(x, y, theta)
위와 같이 꽤 괜찮은 그래프가 그려지는 것을 볼 수 있습니다.
'ML > octave구현 - w1' 카테고리의 다른 글
[octave] multiple variable cost function (0) | 2016.03.10 |
---|---|
[octave] 임의 값 예측 (0) | 2016.03.07 |
[octave] 새터에 따른 그래프 모양 확인 (0) | 2016.03.06 |
[octave] Cost Function 구하기 (0) | 2016.03.06 |
[octave] 데이터 뿌리기 (plot) (0) | 2016.03.06 |