本文主要講解在matlab中實現Linear Regression和Logistic Regression的代碼,並不涉及公式推導。具體的計算公式和推導,相關的機器學習文章和視頻一大堆,推薦看Andrew NG的公開課。
一、線性回歸(Linear Regression)
方法一、利用公式 :
function [ theta ] = linearReg() %線性回歸。 X=[1 1;1 2;1 3;1 4]; %注意第一列全為1,即x0=1,第二列才為x1 Y=[1.1;2.2;2.7;3.8]; A=inv(X'*X); theta=A*X'*Y; %根據公式theta=(X'*X)^(-1)*X'*Y; end
這種方法最簡單,但是公式推導過程很復雜。
方法二:使用梯度下降法迭代
function theta=linearRegression() % 梯度下降法尋找最合適的theta,使得J最小 options=optimset('GradObj','on','MaxIter',100); inittheta=[1 1]'; theta=fminunc(@costFunc,inittheta,options); end %% function [J,gradient]= costFunc(theta) %J為代價函數。 %y=theta(0)*x0+theta(1)*x1; 找出最好的theta來擬合曲線。 %使得J最小的theta就是最好的theta x=[1;2;3;4]; y=[1.1;2.2;2.7;3.8]; m=size(x,1); hypothesis=theta(1)+theta(2)*x; delta=hypothesis-y; J=sum(delta.^2)/(2*m); gradient(1)=sum(delta.*1)/m; %x0=1; gradient(2)=sum(delta.*x)/m; end
這兩種方法,都采用數據:
x=[1;2;3;4];
y=[1.1;2.2;2.7;3.8];
當然,用的時候可以換成其它數據,兩種方法得出的結果都是
theta = 0.3000 0.8600
即可以學習到線性函數:
Y=0.3000+0.8600*X;
二、Logistic回歸(Logistic Regression)
方法一、利用matlab自帶的函數glmfit() :
function theta=logisticRegression() % logistic regression的參數theta,可以用matlab自帶函數glmfit求出 x = [0.0 0.1 0.7 1.0 1.1 1.3 1.4 1.7 2.1 2.2]'; y = [0 0 1 0 0 0 1 1 1 1]'; theta = glmfit(x, [y ones(10,1)], 'binomial', 'link', 'logit') end
方法二:使用梯度下降法迭代
function theta =logisticReg() % 梯度下降法尋找最合適的theta,使得代價函數J最小 options=optimset('GradObj','on','MaxIter',100); inittheta=[0 0]'; theta=fminunc(@costFunc,inittheta,options); end %% function [J,gradient] = costFunc(theta) x = [0.0 0.1 0.7 1.0 1.1 1.3 1.4 1.7 2.1 2.2]'; y = [0 0 1 0 0 0 1 1 1 1]'; m=size(x,1); tmp=theta(1)+theta(2)*x; %theta'x hypothesis=1./(1+exp(-tmp)); %logistic function delta=log(hypothesis+0.01).*y+(1-y).*log(1-hypothesis+0.01); %加上0.01是為了防止x為0 J=-sum(delta)/m; gradient(1)=sum(hypothesis-y)/m; %x0=1; gradient(2)=sum((hypothesis-y).*x)/m; %theta=theta-a*gradient; gradient=-J'(theta) end
兩種方法都使用數據:
x = [0.0 0.1 0.7 1.0 1.1 1.3 1.4 1.7 2.1 2.2]';
y = [0 0 1 0 0 0 1 1 1 1]';
注意,Y的值只能取0和1兩種。
得到結果:
theta = -3.4932 2.9402
即可以學習到函數:
Y=1/(1+exp(3.4932-2.9402*x));