1. 程式人生 > >深度學習(多變數線性迴歸)

深度學習(多變數線性迴歸)

今天完成了多變數線性迴歸的程式設計練習,除了訓練引數theta以外,還要訓練學習速率alpha。資料下載地址

%x資料有兩個屬性:x(1)是房子的大小,x(2)是房子臥室的個數
%y資料是房子的價格
clear;
clc;
%% 匯入資料
x=load('ex3x.dat');
y=load('ex3y.dat');
%% 對x資料進行標準化處理
x = [ones(size(x,1),1),x];
meanx = mean(x);%求均值
sigmax = std(x);%求標準偏差
x(:,2) = (x(:,2)-meanx(2))./sigmax(2);
x(:,3) = (x(:,3
)-meanx(3))./sigmax(3); %% 初始化引數 figure; itera_num = 100; %迭代次數 sample_num =size(x,1); %樣本的個數 alpha = [0.01,0.03,0.1,0.3,1,1.3]; %定義6種學習速率(3倍間隔) plotstyle ={'b','r','g','k','b--','r--'}; %定義6種曲線的顏色 for k=1:length(alpha) theta=zeros(size(x,2
),1); %初始化引數 Jtheta =zeros(itera_num, 1); %每一個迭代次數下的代價值 for i=1:itera_num Jtheta(i)=(1/(2*sample_num)).*(x*theta-y)'*(x*theta-y); grad=(1/sample_num).*x'*(x*theta-y); theta=theta-alpha(k).*grad; end plot(1:100,Jtheta(1:100),char(plotstyle{k}),'LineWidth'
, 2)%此處一定要通過char函式來轉換 hold on; if alpha(k)==1 theta_result=theta; end end legend('alpha=0.01','alpha=0.03','alpha=0.1','alpha=0.3','alpha=1','alpha=1.3'); xlabel('Number of iterations'); ylabel('Cost function'); title('comparison result'); %% 預測結果 price=theta_result'*[1,(1650-meanx(2))/sigmax(2),(3-meanx(3)/sigmax(3))]'; fprintf('當房子大小為1650時,臥室個數3時,房價為%f\n',price);

執行結果為:
多變數線性迴歸結果