2017-07-14 39 views
1

使用下面的代碼我只想擬合迴歸曲線來對未按預期工作的數據進行採樣。使用PolynomialFeatures和LinearRegression的流水線 - 意外的結果

X = 10*np.random.rand(100) 
y= 2*X**2+3*X-5+3*np.random.rand(100) 
xfit=np.linspace(0,10,100) 


poly_model=make_pipeline(PolynomialFeatures(2),LinearRegression()) 
poly_model.fit(X[:,np.newaxis],y) 


y_pred=poly_model.predict(X[:,np.newaxis]) 


plt.scatter(X,y) 
plt.plot(X[:,np.newaxis],y_pred,color="red") 

plt.show() 

enter image description here

Shouldnt't會有一個曲線,該曲線是完全擬合到數據點?因爲訓練數據(X [:,np.newaxis])和用於預測y_pred的數據相同(也是(X [:,np.newaxis])。

如果我改用xfit數據預測模型爲所期望的結果...

... 

y_pred=poly_model.predict(xfit[:,np.newaxis]) 

plt.scatter(X,y) 
plt.plot(xfit[:,np.newaxis],y_pred,color="red") 

plt.show() 

enter image description here

因此,whats的問題,這樣的行爲的解釋?

回答

1

兩個地塊之間的區別是,在line

plt.plot(X[:,np.newaxis],y_pred,color="red") 

X[:,np.newaxis]的值進行排序,而在

plt.plot(xfit[:,np.newaxis],y_pred,color="red") 

xfit[:,np.newaxis]的值進行排序。

現在,plt.plot按行連接數組中的任意兩個連續值,並且由於它們沒有排序,所以在第一個圖中會得到這一串線。

更換

plt.plot(X[:,np.newaxis],y_pred,color="red") 

plt.scatter(X[:,np.newaxis],y_pred,color="red") 

,你會得到這個漂亮的數字:

enter image description here

0

基於我已想出儀法伯的回答其他方式。由於X值不排序我可以解決這個問題根本的價值觀與排序:

X=np.sort(X) 

現在剩下的代碼可以保持靜止,將提供所需的結果。

enter image description here