使用Python实现多项式回归可以借助numpy和sklearn这两个库,具体步骤如下:
- 导入numpy和sklearn库:
import numpy as np from sklearn.linear_model import LinearRegression from sklearn.preprocessing import PolynomialFeatures
- 准备数据集:
x = np.array([1,2,3,4,5,6]).reshape((-1, 1)) y = np.array([9,15,23,33,45,59])
- 定义多项式次数并进行数据预处理:
n_degree = 3 poly_features = PolynomialFeatures(degree=n_degree) x_poly = poly_features.fit_transform(x)
- 使用线性回归模型进行训练和预测:
model = LinearRegression() model.fit(x_poly, y) y_pred = model.predict(x_poly)
- 绘制拟合曲线:
import matplotlib.pyplot as plt plt.scatter(x, y) plt.plot(x, y_pred, color='red') plt.show()
注意事项:
多项式次数不宜过高,否则容易过拟合。
数据集宜较大,以减少对拟合曲线的影响。
以上是使用Python实现多项式回归的基本步骤,希望能对你有所帮助。