[英]How to fit a polynomial curve to data using scikit-learn?
使用scikit-learn
與Python,我試圖將二次多項式曲線的一組數據,使模型可以是以下形式的y = a2x^2 + a1x + a0
和an
系數將通過提供模型。
我不知道如何使用該包來擬合多項式曲線,並且似乎很少有關於如何做的明確參考(我已經看了一會兒)。 我已經看到了與NumPy做類似事情的這個問題 ,而且這個問題比我要求的更復雜 。
希望一個好的解決方案可以像這樣(從我正在使用的線性擬合代碼改編的樣本):
x = my_x_data.reshape(len(profile), 1)
y = my_y_data.reshape(len(profile), 1)
regression = linear_model.LinearRegression(degree=2) # or PolynomialRegression(degree=2) or QuadraticRegression()
regression.fit(x, y)
我認為scikit-learn
會有這樣的設施,因為它很常見(例如,在R
,擬合的公式可以在代碼中提供,並且它們應該能夠在這種用途中相互替換 -案件)。
有什么好方法可以做到這一點,或者我在哪里可以找到有關如何正確執行此操作的信息?
可能重復: https : //stats.stackexchange.com/questions/58739/polynomial-regression-using-scikit-learn 。
是否因某些原因使用scikit-learn進行此操作至關重要? 使用numpy可以非常輕松地執行所需的操作:
z = np.poly1d(np.polyfit(x,y,2))
之后z(x)
返回x
擬合的值。
scikit-learn解決方案幾乎肯定只是圍繞相同代碼的包裝器。
我相信薩爾瓦多達利在這里的回答將回答你的問題。 在scikit-learn中,從數據構造多項式特征,然后對該擴展數據集運行線性回歸就足夠了。 如果您有興趣閱讀有關它的文檔,可以在此處找到更多信息。 為方便起見,我將發布Salvador Dali提供的示例代碼:
from sklearn.preprocessing import PolynomialFeatures
from sklearn import linear_model
X = [[0.44, 0.68], [0.99, 0.23]]
vector = [109.85, 155.72]
predict= [0.49, 0.18]
poly = PolynomialFeatures(degree=2)
X_ = poly.fit_transform(X)
predict_ = poly.fit_transform(predict)
clf = linear_model.LinearRegression()
clf.fit(X_, vector)
print clf.predict(predict_)
AGML的答案可以包含在scikit-learn-compatible類中,如下所示:
class PolyEstimator:
def __init__(self, degree=2):
self.degree = degree
def fit(self, x, y):
self.z = np.poly1d(np.polyfit(x.flatten().tolist(), y, self.degree))
def predict(self, x):
return self.z(x.flatten().tolist())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.