sklearn中的多項式回歸算法


sklearn中的多項式回歸算法

1、多項式回歸法
多項式回歸的思路和線性回歸的思路以及優化算法是一致的,它是在線性回歸的基礎上在原來的數據集維度特征上增加一些另外的多項式特征,使得原始數據集的維度增加,然后基於升維后的數據集用線性回歸的思路進行求解,從而得到相應的預測結果和各項的系數。


2、多項式回歸的函數在pyhton的sklearn機器學習庫中沒有專門的定義,因為它只是線性回歸方式的一種特例,但是我們自己可以按照多元線性回歸的方式對整個過程進行相關的定義,然后包裝成為一個函數進行相關的調用即可。
3、對於多項式回歸方式的實現過程有以下兩種:
(1)原理實現的過程代碼(以一元二次函數的擬合為例):
import numpy as np
import matplotlib.pyplot as plt
x=np.random.uniform(-3,3,size=100)
X=x.reshape(-1,1)
y=0.5*x**2+x+2+np.random.normal(0,1,size=100)
plt.figure()
plt.scatter(x,y)
from sklearn.linear_model import LinearRegression
l1=LinearRegression()
l1.fit(X,y)
y_p=l1.predict(X)
plt.plot(X,y_p,"r")
print(l1.score(X,y))

###1-1多項式回歸的思路(使用線性回歸的的思路,添加新的特征即可,即原數據集的維數增加)
print((x**2).shape)
x2=np.hstack([X,X**2])
print(x2.shape)
L2=LinearRegression()
L2.fit(x2,y)
y_p2=L2.predict(x2)
plt.figure()
plt.scatter(x,y)
plt.plot(X,y_p,"g")
plt.plot(np.sort(x),y_p2[np.argsort(x)],"r") #輸出多維數據時的擬合結果
plt.show()
print(L2.score(x2,y))
print(L2.coef_,L2.intercept_)

(2)sklearn中的整體實現過程:
#sklearn中的多項式回歸和pipeline
import numpy as np
import matplotlib.pyplot as plt
x=np.random.uniform(-3,3,size=100)
X=x.reshape(-1,1)
y=0.5*x**2+x+2+np.random.normal(0,1,size=100)
from sklearn.preprocessing import PolynomialFeatures
p1=PolynomialFeatures(degree=2) #degree的含義是多項式數據中添加特征的最高次數
p1.fit(X)
x3=p1.transform(X)
print(x3.shape)
print(x3[:5,0])
print(x3[:5,1])
print(x3[:5,2])
print(x3[:5,])
from sklearn.linear_model import LinearRegression
l3=LinearRegression()
l3.fit(x3,y)
y_p3=l3.predict(x3)
plt.figure()
plt.scatter(x,y)
plt.plot(np.sort(x),y_p3[np.argsort(x)],"r")
plt.show()
print(l3.score(x3,y))
print(l3.coef_,L2.intercept_)
print(x3.shape)

(3)利用上述原理進行函數的自我封裝調用代碼:
#自己封裝一個多項式回歸的函數
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures
def polynomialRegression(degree):
       return Pipeline([("poly",PolynomialFeatures(degree=degree)),
                                   ("std_scaler",StandardScaler()),
                                   ( "lin_reg",LinearRegression())
                                    ])
poly2_reg=polynomialRegression(10)
poly2_reg.fit(X,y)
y2=poly2_reg.predict(X)
print(mean_squared_error(y,y2))
print(poly2_reg.score(X,y))
plt.figure()
plt.scatter(X,y)
plt.plot(np.sort(x),y2[np.argsort(x)],"r")
plt.show()
x1=np.linspace(-3,3,100).reshape(100,1)
y11=poly2_reg.predict(x1)
plt.plot(x1,y11,"r")
#plt.axis([-3,3,-1,10])
plt.show()
運行結果如下所示:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM