簡單易學的機器學習演算法——線性迴歸(1)
阿新 • • 發佈:2022-05-04
一、線性迴歸的概念
對連續型資料做出預測屬於迴歸問題。舉個簡單的例子:例如我們在知道房屋面積(HouseArea)和臥室的數量(Bedrooms)的情況下要求房屋的價格(Price)。通過一組資料,我們得到了這樣的關係:
這樣的關係就叫做線性迴歸方程,其中
為迴歸係數。當我們知道房屋面積以及臥室數量時,就可以求出房屋的價格。當然還有一類是非線性迴歸。
二、基本線性迴歸
三、基本線性迴歸實驗
原始的資料
最佳擬合直線
MATLAB程式碼
主函式
%% load Data A = load('ex0.txt'); X = A(:,1:2);%讀取x Y = A(:,3); ws = standRegres(X,Y); %% plot the regression function x = 0:1; y = ws(1,:)+ws(2,:)*x; hold on xlabel x; ylabel y; plot(X(:,2),Y(:,1),'.'); plot(x,y); hold off
求權重的過程
function [ ws ] = standRegres( X, Y )
[m,n] = size(X);
ws = zeros(m,1);
XTX = X'*X;
if det(XTX) == 0
disp('This matrix is singular, cannot do inverse');
end
ws = XTX^(-1) *(X'*Y);
end
四、區域性加權線性迴歸
線上性迴歸中會出現欠擬合的情況,有些方法可以用來解決這樣的問題。區域性加權線性迴歸(LWLR)就是這樣的一種方法。區域性加權線性迴歸採用的是給預測點附近的每個點賦予一定的權重,此時的迴歸係數可以表示為
為給每個點的權重。
LWLR使用核函式來對附近的點賦予更高的權重,常用的有高斯核,對應的權重為
這樣的權重矩陣只含對角元素。
五、區域性加權線性迴歸實驗
對上組資料做同樣的處理:
MATLAB程式碼
主函式
%% load Data A = load('ex0.txt'); X = A(:,1:2); Y = A(:,3); [SX,index] = sort(X);%得到排序和索引 %yHat = lwlrTest(SX, X, Y, 1); %yHat = lwlrTest(SX, X, Y, 0.01); %yHat = lwlrTest(SX, X, Y, 0.003); hold on xlabel x; ylabel y; plot(X(:,2),Y(:,1),'.'); plot(SX(:,2),yHat(:,:)); hold off
LWLR
function [ output ] = lwlr( testPoint, X, Y, k )
[m,n] = size(X);%得到資料集的大小
weight = zeros(m,m);
for i = 1:m
diff = testPoint - X(i,:);
weight(i,i) = exp(diff * diff'./(-2*k^2));
end
XTX = X'*(weight * X);
if det(XTX) == 0
disp('his matrix is singular, cannot do inverse');
end
ws = XTX^(-1) * (X' * (weight * Y));
output = testPoint * ws;
end
function [ y ] = lwlrTest( test, X, Y, k )
[m,n] = size(X);
y = zeros(m,1);
for i = 1:m
y(i,:) = lwlr(test(i,:), X, Y, k);
end
end
當
時是欠擬合,當
時是過擬合,選擇合適的
很重要。