프로그래밍/잡탕
[Octave] Gradient Descent Multi feature
터프 프로그래머
2015. 4. 18. 21:45
hypothesis theta의 값을 X * theta로 쉽게 구하기 위해 X = [ones(length(data(:, 1)), 1) data] 로 정의.
(쉽게 말하면 X의 맨 왼쪽에 값이 1인 원소의 컬럼을 추가.)
function cost = costFunctionJ(X, y, theta)
m = length(X(:, 1));
h = X * theta;
h = h .^ 2;
cost = 1 / (2 * m) * sum(h);
function [final_theta, history_theta, history_cost] = gradientDescentMulti(X, y, theta, alpha, iteration)
m = length(X(:, 1));
final_theta = theta;
history_theta = [theta];
history_cost = [costFunctionJ(X, y, theta)];
for iter = 1:iteration
h = X * final_theta;
new_theta = final_theta - alpha * 1 / m * ( transpose(X) * (h - y) );
final_theta = new_theta;
history_theta = [ history_theta final_theta ];
history_cost = [ history_cost costFunctionJ(X, y, final_theta) ];
end