機器學習之線性迴歸(Linear Regression)
阿新 • • 發佈:2018-12-11
線性學習中最基礎的迴歸之一,本文從線性迴歸的數學假設,公式推導,模型演算法以及實際程式碼執行幾方面對這一回歸進行全面的剖析~
一:線性迴歸的數學假設
1.假設輸入的X和Y是線性關係,預測的y與X通過線性方程建立機器學習模型
2.輸入的Y和X之間滿足方程Y= θ X+e,e是誤差項,噪音項,假設e是獨立同分布的,服從IID(independent and identity distribution)和均值為0,方差為某一定數的正態分佈(也叫高斯分佈)e服從正態分佈是由中新計值定理決定的二、線性迴歸建模
2.1方程式表示:
數學形式:
矩陣形式: 其中,X矩陣是m行(n+1)列的,每一行是一個樣本,每一列是樣本的某一個特徵 θ矩陣(n+1)行一列的,它是X的權重,也是線性迴歸要學習的引數 import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import RidgeCV
from sklearn.cross_validation import train_test_split
'''#load data
n=100
x = np.arange(1,100,n)+np.random.randn(n)
y = 4*x - 3 + np.random.randn(n)
plt . figure ()
plt . plot(x, y, 'r*', label='X')
plt . ylabel (" Y" )
plt . xlabel (" X")
plt . legend(loc="best")
plt . tight_layout()
plt . show()
'''
data = ['C:\\Users\\123\\Desktop\\weather\\2015.txt',]
w = np. loadtxt ( data [0] , skiprows =1)
y = w[:,7]/10
x = w[:,10]
plt . figure ()
plt . plot(x,y,"b*",label="Atmospheric pressure")
plt . ylabel (" Temperatures" )
plt . xlabel ("Atmospheric pressure " )
plt . title (' Temperatures trent chart of Shanghai in year 2015 ')
plt . tight_layout()
plt . legend(loc="best")
plt . show()
x = x.reshape(-1, 1)
x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=1)
lr = LinearRegression()
lr . fit ( x_train , y_train)
y_lr = lr.predict ( x_test )
cv = RidgeCV(alphas=np.logspace(-3, 2, 100))
cv . fit ( x_train , y_train)
y_cv = cv.predict ( x_test )
print lr.coef_
print lr.intercept_
print "mes of Linear Regresion squares is", np. mean(( y_lr - y_test ) ** 2)
print "accuracy of Linear regression is",lr.score(x_test,y_test)
print cv.coef_
print cv.intercept_
print "mes of Linear Regresion+Ridge squares is", np. mean(( y_cv - y_test ) ** 2)
print "accuracy of Linear regression is",cv.score(x_test,y_test)
x1 = np.arange(len(x_test))
plt.plot(x1,y_test,"y*-",label="Test")
plt.plot(x1,y_lr,"ro-",label="Predict")
plt.plot(x1,y_cv,"b^-",label="Predict+Ridge")
plt . ylabel (" Temperatures" )
plt . xlabel (" Atmospheric pressure")
plt . title (' Predict chart ')
plt . legend(loc="best")
plt . tight_layout()
plt . show()
執行程式碼作圖如下:
圖一是2015年氣溫和氣壓的曲線圖,可以看到有比較明顯的線性趨勢的關係,說明我們可以用線性迴歸來進行預測,接下來我們就進行預測
預測後的test和predict的圖如下:
上圖分別用了線性迴歸的解析解以及基於Ridge 懲罰的線性迴歸,從擬合結果看,兩種方法效果差不多,最後,將預測準確率輸出:
兩種方法的準確率大概都在~87%,Ridge迴歸的效果稍好但不明顯。
總結:以上從線性迴歸的假設背景,數學推導,以及機器學習的建模,演算法,優化和實際程式碼執行幾方面對機器學習的線性迴歸做了比較全面的瞭解和梳理。每一種機器學習演算法都有其適用的應用情況,只要熟悉這個模型的這些知識就可以遊刃有餘的完成自己的實際任務啦~~
參考資料:Ng斯坦福CS229視訊和相關資料