2014-10-30 6 views
0

벡터화를 사용하여 그라디언트 디센트에 대한 코드를 구현했지만 비용 함수가 정확하게 감소하지 않는 것으로 보입니다. 대신 비용 함수가 매 반복마다 증가하고 있습니다. 는 n + 1 개 벡터로 세타 가정벡터화를 사용하여 비용 함수를 올바르게 업데이트하지 않는 그라디언트 디센트의 옥타브 코드

는, Y가 (N + 1)

function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters) 

m = length(y); % number of training examples 
n = length(theta); % number of features 
J_history = zeros(num_iters, 1); 
error = ((theta' * X')' - y)*(alpha/m); 
descent = zeros(size(theta),1); 

for iter = 1:num_iters 
for i = 1:n 
    descent(i) = descent(i) + sum(error.* X(:,i)); 
    i = i + 1; 
end 

theta = theta - descent; 
J_history(iter) = computeCost(X, y, theta); 
disp("the value of cost function is : "), disp(J_history(iter)); 
iter = iter + 1; 
end 

컴퓨팅 비용 함수 인 설계 매트릭스 분 *로 오전 벡터 및 X 될 :

function J = computeCost(X, y, theta) 
m = length(y); 
J = 0; 
for i = 1:m, 
    H = theta' * X(i,:)'; 
    E = H - y(i); 
    SQE = E^2; 
    J = (J + SQE); 
    i = i+1; 
end; 
J = J/(2*m); 
+1

해서는 안'I = 1 : 당신을위한 n' 증가'i'? 당신은 또한 루프 안에서 그것을하고 있습니다. (내가 옥타브를 한 지 오래 ..) –

+0

예 – Dcoder

답변

2

당신은 그것을 더 벡터화 할 수

function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters) 
    m = length(y); 
    J_history = zeros(num_iters, 1); 

    for iter = 1:num_iters 

     delta = (theta' * X'-y')*X; 
     theta = theta - alpha/m*delta'; 
     J_history(iter) = computeCost(X, y, theta); 

    end 

end