(1)过拟合与欠拟合定义
过拟合:创建的机器学习和深度学习模型在进行训练的时,表现的过于优越;
欠拟合:创建的机器学习和深度学习模型没有很好的捕捉到数据特征,不能很好地拟合数据;
(2)使用sklearn展示过拟合&欠拟合
import numpy as np
import matplotlib.pyplot as plt
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score
def true_fun(X):
return np.sin(1.5 * np.pi * X)
np.random.seed(0)
n_samples = 30
degrees = [1, 4, 15]
X = np.sort(np.random.rand(n_samples)) #产生随机样本,并进行排序
y = true_fun(X) + np.random.randn(n_samples) * 0.1 #在真实函数的基础上添加噪声
plt.figure(figsize=(14, 5)) #设置图像的大小
for i in range(len(degrees)):
ax = plt.subplot(1, len(degrees), i + 1) #分配显示图
plt.setp(ax, xticks=(), yticks=())
#分别生成1次、4次、15次多项式
polynomial_features = PolynomialFeatures(degree=degrees[i],
include_bias=False)
linear_regression = LinearRegression()
# pipeline将数据处理和模型拟合结合在一起
pipeline = Pipeline([("polynomial_features", polynomial_features),
("linear_regression", linear_regression)])
pipeline.fit(X[:, np.newaxis], y)
# 使用交叉验证评估模型
scores = cross_val_score(pipeline, X[:, np.newaxis], y,
scoring="neg_mean_squared_error", cv=10)
#绘制结果图
X_test = np.linspace(0, 1, 100)
plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label="Model")
plt.plot(X_test, true_fun(X_test), label="True function")
plt.scatter(X, y, edgecolor='b', s=20, label="Samples")
plt.xlabel("x")
plt.ylabel("y")
plt.xlim((0, 1))
plt.ylim((-2, 2))
plt.legend(loc="best")
plt.title("Degree {}\nMSE = {:.2e}(+/- {:.2e})".format(
degrees[i], -scores.mean(), scores.std()))
plt.show()
效果图:
说明:左图一,蓝线表现出欠拟合状态;左图二,蓝线模型能够很好的拟合;左图三,蓝线表现出过拟合状态
注:本文章代码主要参考sklearn官网提供的例程:https://scikit-learn.org/stable/
了解更多关于《计算机视觉与图形学》相关知识,请关注公众号:
下载我们视频中代码和相关讲义,请在公众号回复:计算机视觉课程资料