簡體   English   中英

Sklearn 線性回歸輸出

[英]Sklearn Linear Regression output

我正在嘗試使用線性回歸將拋物線擬合到一個簡單的生成數據集中,但是無論我做什么曲線,我直接從模型中得到的結果都是難以理解的混亂。

import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression

#xtrain, ytrain datasets have been generated earlier

model = LinearRegression(fit_intercept = True)
model.fit(np.hstack([xtrain, xtrain**2]), ytrain)  
xfit = np.linspace(-3,3,20)  
yfit = model.predict(np.hstack([xtrain, xtrain**2]))
plt.plot(xfit, yfit)
plt.scatter(xtrain, ytrain, color="black")

此代碼輸出以下圖形:

代碼輸出

但是,當我通過簡單地更改以下代碼行從模型生成的系數手動生成圖時,我得到了我想要的結果。

手動輸出

yfit = model.coef_[0]*xfit + model.coef_[1]*xfit**2 + model.intercept_

這似乎有點笨拙的處理方式,所以我想學習如何正確生成曲線。 我認為問題一定是我的數據的離散性,但我無法自己弄清楚。

這是您修復的錯誤:

yfit = model.predict(np.hstack([xfit, xfit**2]))

在您的代碼中,您在 X 軸上繪制xfit值,而在 Y 軸上繪制f(xtrain)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM