我已經經歷了堆棧溢出中的許多代碼並在同一行上創建了自己的代碼。這個代碼有一些問題,我無法理解。我存儲的價值theta1和theta2以及成本函數分析的目的。 x和y的數據可從此 Openclassroom頁面下載。它具有可以在記事本中打開的.dat文件形式的x和Y數據。梯度下降Matlab實現
%Single Variate Gradient Descent Algorithm%%
clc
clear all
close all;
% Step 1 Load x series/ Input data and Output data* y series
x=load('D:\Office Docs_Jay\software\ex2x.dat');
y=load('D:\Office Docs_Jay\software\ex2y.dat');
%Plot the input vectors
plot(x,y,'o');
ylabel('Height in meters');
xlabel('Age in years');
% Step 2 Add an extra column of ones in input vector
[m n]=size(x);
X=[ones(m,1) x];%Concatenate the ones column with x;
% Step 3 Create Theta vector
theta=zeros(n+1,1);%theta 0,1
% Create temporary values for storing summation
temp1=0;
temp2=0;
% Define Learning Rate alpha and Max Iterations
alpha=0.07;
max_iterations=1;
% Step 4 Iterate over loop
for i=1:1:max_iterations
%Calculate Hypothesis for all training example
for k=1:1:m
h(k)=theta(1,1)+theta(2,1)*X(k,2); %#ok<AGROW>
temp1=temp1+(h(k)-y(k));
temp2=temp2+(h(k)-y(k))*X(k,2);
end
% Simultaneous Update
tmp1=theta(1,1)-(alpha*1/(2*m)*temp1);
tmp2=theta(2,1)-(alpha*(1/(2*m))*temp2);
theta(1,1)=tmp1;
theta(2,1)=tmp2;
theta1_history(i)=theta(2,1); %#ok<AGROW>
theta0_history(i)=theta(1,1); %#ok<AGROW>
% Step 5 Calculate cost function
tmp3=0;
tmp4=0;
for p=1:m
tmp3=tmp3+theta(1,1)+theta(2,1)*X(p,1);
tmp4=tmp4+theta(1,1)+theta(2,1)*X(p,2);
end
J1_theta0(i)=tmp3*(1/(2*m)); %#ok<AGROW>
J2_theta1(i)=tmp4*(1/(2*m)); %#ok<AGROW>
end
theta
hold on;
plot(X(:,2),theta(1,1)+theta(2,1)*X);
我越來越
theta的值作爲 0.0373 和0.1900應該是0.0745和0.3800
這個值是大約兩倍,我期待。
我們無法在沒有數據的情況下重現您的問題。 – Daniel
嘿謝謝你的回覆。我已經添加了輸入數據鏈接的鏈接。 – Incpetor
你好,你必須使用矩陣屬性。這個頁面上的答案http://stackoverflow.com/a/33215224/2046575是非常好的。 –