问题描述
使用线性回归拟合一些数据很容易,但是有没有办法找到用多项式线拟合 3 个或更多点的最佳曲线?
这是我的预期结果:
解决方法
您可以使用 numpy 的 polyfit
实现多项式回归:
import numpy as np
n = 2
z = np.polyfit(x,y,n) # Expects `x` as 1d array
quadratic_regressor = np.poly1d(z)
或使用 SKLearn 的 preprocessing.PolynomialFeatures
:
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
n = 2
quadratic_regressor = Pipeline([('pf',PolynomialFeatures(n)),('clf',LinearRegression())])
quadratic_regressor.fit(x,y) # Expects `x` as 2d array
示例:
x = [0,1,2]
y = [10,1]
plt.scatter(x,y)
x_ = np.linspace(-1,4)
plt.plot(x_,quadratic_regressor(x_)) # Numpy
plt.plot(x_,quadratic_regressor.predict(x_.reshape(-1,1))) # SKLearn