多项式回归
前面我们拟合直线用到了线性回归,而非线性回归中,则需要建立因变量和自变量之间的非线性关系。多项式回归模型是线性回归模型的一种,此时回归函数关于回归系数是线性的。由于任一函数都可以用多项式逼近,所以应用非常广泛。
公式
其中,m表示多项式的阶数,
x
j
x^j
xj 表示 x 的 j 次幂,w 则代表该多项式的系数。
构造数据集
# 构造数据集
import numpy as np
x = np.random.uniform(-3, 3, size=100)
X = x.reshape((-1, 1))
y = 0.5 * x**2 + x + 2 + np.random.normal(size=100)
使用Pipeline封装多个重复操作
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
# 使用Pipeline封装多个重复操作
pipeline = Pipeline([
("poly", PolynomialFeatures(degree=2)), # 多项式回归
("std_scaler", StandardScaler()), # 标准化
("lin_reg", LinearRegression()) # 线性回归
])
训练拟合模型进行预测
pipeline.fit(X, y)
y_predict = pipeline.predict(X)
绘图
import matplotlib.pyplot as plt
# 绘图
plt.scatter(x, y)
plt.plot(np.sort(x), y_predict[np.argsort(x)], color='r')
plt.show()
由上图可以看出得到的拟合模型是一条没有规律的曲线,随着PolynomialFeatures(degree=2))中参数的增大,拟合度会随之增加,但是达到一定的拟合度后,模型预测结果偏差会出现逐渐增大的现象,即过拟合现象
相关概念:
欠拟合:过于简单的模型,无论是训练数据还是测试数据都无法给出足够精度的现象;
过拟合:过于复杂的模型,对于训练数据具有很高的精度,但对于测试数据通常精度很低的现象;
全部代码
import numpy as np
import matplotlib.pyplot as plt
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
# 构造数据集
x = np.random.uniform(-3, 3, size=100)
X = x.reshape((-1, 1))
y = 0.5 * x**2 + x + 2 + np.random.normal(size=100)
print(X.shape, y.shape)
# 使用Pipeline封装多个重复操作
pipeline = Pipeline([
("poly", PolynomialFeatures(degree=2)), # 多项式回归
("std_scaler", StandardScaler()), # 标准化
("lin_reg", LinearRegression()) # 线性回归
])
pipeline.fit(X, y)
y_predict = pipeline.predict(X)
# 绘图
plt.scatter(x, y)
plt.plot(np.sort(x), y_predict[np.argsort(x)], color='r')
plt.show()
博客园:https://www.cnblogs.com/yj179101536/
欢迎评论!