文件下载
链接: https://pan.baidu.com/s/1UQydHMXQQAKiYdBc6VFbOA 提取码: wfde
"""
多项式回归
多项式 + 线性回归 管线方式 创建多项式回归
"""
import numpy as np
import matplotlib.pyplot as mp
import sklearn.linear_model as lm
import sklearn.metrics as sm
import sklearn.pipeline as pl
import sklearn.preprocessing as sp
# 读取文本
x, y = np.loadtxt("./single.txt", delimiter=",", unpack=True)
x = x.reshape(-1, 1)
# 绘制散点
mp.figure("Linear Regression", facecolor="lightgray")
mp.title("Linear Regression", fontsize=16)
mp.grid(linestyle=":")
mp.scatter(x, y, s=70, color="dodgerblue", label="samples")
# 多项式回归
model = pl.make_pipeline(sp.PolynomialFeatures(10),
lm.LinearRegression())
model.fit(x, y)
prd_y = model.predict(x)
# 评估当前模型
print("平均绝对值误差:", sm.mean_absolute_error(y, prd_y))
print("平均平方误差:", sm.mean_squared_error(y, prd_y))
print("中位绝对值误差:", sm.median_absolute_error(y, prd_y))
print("R2得分:", sm.r2_score(y, prd_y))
# 因为X的值有大小变换
# 绘制 连续的 X与预测值
x = np.linspace(x.min(), x.max(), 500)
x = x.reshape(-1, 1)
prd_y = model.predict(x)
mp.plot(x, prd_y, color="orangered", label="Poly")
mp.legend()
mp.tight_layout()
mp.show()