和上一节一样自定义数据集并绘制散点图:
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(666)
x = np.random.uniform(-3.0, 3.0, size=100)
X = x.reshape(-1, 1)
y = 0.5 * x**2 + x + 2 +np.random.normal(0, 1, size=100)
plt.scatter(X, y)
plt.show()
使用线性回归进行拟合:
from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression()
lin_reg.fit(X, y)
lin_reg.score(X, y)
可得到准确度为:0.4953707811865009
下面使用均方误差进行衡量:
y_predict = lin_reg.predict(X)
from sklearn.metrics import mean_squared_error
mean_squared_error(y, y_predict)
得,使用线性回归后的均方误差值为:3.0750025765636577
拟合结果可视化为:
此结果是欠拟合的。
再来看看使用多项式回归的均方误差是多少:
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures
from sklearn.preprocessing import StandardScaler
def PolynomialRegression(degree):
return Pipeline([
("poly", PolynomialFeatures(degree=degree)),
("std_scaler", StandardScaler()),
("lin_reg", LinearRegression())
])
poly2_reg = PolynomialRegression(degree=2)
poly2_reg.fit(X, y)
y2_predict = poly2_reg.predict(X)
mean_squared_error(y, y2_predict)
此时,误差降为:1.0987392142417858
可视化结果为:
若令 degree=10 再次可视化:
误差降为:1.050846676376416
,但此结果是过拟合的。
令 degree=100:
误差降为:0.6815400563822077
,同样是过拟合的。
结论:对于二次函数,若用一次幂进行拟合,结果是欠拟合;用高于二次幂进行拟合,则是过拟合的结果。欠拟合和过拟合都不能反应数据集的特点,都不是我们想要的结果,只有用二次幂进行拟合才能反应数据的特点。对其他次幂函数进行拟合同理。
关于过拟合的误差虽然低于拟合,但其泛化能力差(下一节学习模型的泛化能力)。