通过sklearn展示过拟合&欠拟合

(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/

了解更多关于《计算机视觉与图形学》相关知识,请关注公众号:

下载我们视频中代码和相关讲义,请在公众号回复:计算机视觉课程资料

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
解决过拟合欠拟合的方法有很多,下面是一些基本的解决方法和相应的代码实现: 解决过拟合的方法: 1. 数据增强:通过对训练数据进行一些随机变换,增加数据量,使模型不容易记住训练集的特征,从而减少过拟合。 ```python from tensorflow.keras.preprocessing.image import ImageDataGenerator datagen = ImageDataGenerator( rotation_range=20, # 随机旋转角度 width_shift_range=0.2, # 水平方向平移 height_shift_range=0.2, # 垂直方向平移 shear_range=0.2, # 剪切变换 zoom_range=0.2, # 随机缩放 horizontal_flip=True, # 水平翻转 fill_mode='nearest' # 填充方式 ) ``` 2. 正则化:通过在损失函数中增加正则项,限制模型的复杂度,避免过拟合。 ```python from tensorflow.keras import regularizers model = Sequential([ Dense(64, activation='relu', kernel_regularizer=regularizers.l2(0.001)), Dropout(0.5), Dense(10, activation='softmax') ]) ``` 3. 提前停止:在训练过程中,当验证集的准确率不再提高时,提前结束训练,避免过拟合。 ```python from tensorflow.keras.callbacks import EarlyStopping early_stopping = EarlyStopping(monitor='val_acc', patience=5) model.fit(x_train, y_train, validation_data=(x_val, y_val), epochs=100, callbacks=[early_stopping]) ``` 解决欠拟合的方法: 1. 增加模型复杂度:增加模型的层数、神经元数量等,提高模型的表达能力,避免欠拟合。 ```python model = Sequential([ Dense(128, activation='relu'), Dense(64, activation='relu'), Dense(10, activation='softmax') ]) ``` 2. 增加训练次数:增加训练次数,让模型更充分地学习数据特征,避免欠拟合。 ```python model.fit(x_train, y_train, validation_data=(x_val, y_val), epochs=100) ``` 3. 特征工程:通过对原始数据进行一些特征变换,提高数据的表达能力,避免欠拟合。 ```python from sklearn.preprocessing import PolynomialFeatures poly = PolynomialFeatures(degree=2) x_train_poly = poly.fit_transform(x_train) x_val_poly = poly.transform(x_val) model = Sequential([ Dense(64, activation='relu', input_shape=(x_train_poly.shape[1],)), Dense(10, activation='softmax') ]) model.fit(x_train_poly, y_train, validation_data=(x_val_poly, y_val), epochs=100) ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值