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)
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.preprocessing import StandardScaler
def PolymialRegression(degree):
return Pipeline([
("poly",PolynomialFeatures(degree=degree)),
("std_scaler",StandardScaler()),
("lin_reg",LinearRegression())
])
from sklearn.metrics import mean_squared_error
poly_reg = PolymialRegression(degree=100)
poly_reg.fit(X,y)
y_predict = poly_reg.predict(X)
mean_squared_error(y,y_predict)
输出:0.6870911922673567
X_plot = np.linspace(-3,3,100).reshape(100,1)
y_plot = poly_reg.predict(X_plot)
plt.scatter(x,y)
plt.plot(X_plot[:,0],y_plot,color='r')
plt.axis([-3,3,-1,10])
plt.show()
输出图片:
整个样本使用该曲线进行预测的时候,相应的误差变小了。可是一旦有了新的样本点,这个曲线可能就不能很好的进行预测了。
假设有一个新的样本对应的xxx在2.5左右,那么根据曲线预测的结果得到yyy可能在0.5左右,该样本位于上图中的紫色点,很明显,该紫色样本点与之前的蓝色样本点不在一个趋势上,我们直观的想就会觉得这个预测结果是错误的。我们称我们之前的得到的这条曲线它的泛华能力(由此及彼的能力)是非常弱的。
测试数据集的意义
我们将数据集分为训练数据集和测试数据集,如果我们用训练数据集得到了一个模型,测试数据集对于这个模型来说就是全新的样本,如果该模型对于测试数据集也能获得会很好的效果的话,就称该模型具有很好的泛化效果。如果该模型对于测试数据集不能得到好的效果,说明该模型不具有很好的效果,则该模型泛化能力弱,多半是遭遇了过拟合。
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(X,y,random_state=666)
#对于线性回归
lin_reg = LinearRegression()
lin_reg.fit(X_train,y_train)
y_predict = lin_reg.predict(X_test)
mean_squared_error(y_test,y_predict)
输出:2.219996526939657388
# 对于多项式回归
poly2_reg = PolymialRegression(degree=2)
poly2_reg.fit(X_train,y_train)
y2_predict = poly2_reg.predict(X_test)
mean_squared_error(y_test,y2_predict)
输出:0.8035641056297901
# degree=10得到的模型拟合度肯定要比degree=2时的拟合度强,但是得到的误差却更大,说明其泛化能力变差了
poly10_reg = PolymialRegression(degree=10)
poly10_reg.fit(X_train,y_train)
y10_predict = poly10_reg.predict(X_test)
mean_squared_error(y_test,y10_predict)
输出:0.9212930722150697
poly100_reg = PolymialRegression(degree=100)
poly100_reg.fit(X_train,y_train)
y100_predict = poly100_reg.predict(X_test)
mean_squared_error(y_test,y100_predict)
输出:14075780347.739939
由以上实验我们可知,随着degree的增大,模型的拟合度高,但误差也越来越大,模型的泛化能力变差
通过测试数据集判断模型的好坏