在 Python 中拟合多项式回归?

问题描述

使用线性回归拟合一些数据很容易,但是有没有办法找到用多项式线拟合 3 个或更多点的最佳曲线?

这是我的预期结果:

enter image description here

解决方法

您可以使用 numpypolyfit 实现多项式回归:

import numpy as np

n = 2
z = np.polyfit(x,y,n) # Expects `x` as 1d array
quadratic_regressor = np.poly1d(z)

或使用 SKLearnpreprocessing.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

enter image description here