keras处理欠拟合和过拟合的实例讲解

 更新时间:2020年05月25日 08:46:01   作者:Lzj000lzj  
这篇文章主要介绍了keras处理欠拟合和过拟合的实例讲解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

baseline

import tensorflow.keras.layers as layers
baseline_model = keras.Sequential(
[
 layers.Dense(16, activation='relu', input_shape=(NUM_WORDS,)),
 layers.Dense(16, activation='relu'),
 layers.Dense(1, activation='sigmoid')
]
)
baseline_model.compile(optimizer='adam',
      loss='binary_crossentropy',
      metrics=['accuracy', 'binary_crossentropy'])
baseline_model.summary()

baseline_history = baseline_model.fit(train_data, train_labels,
          epochs=20, batch_size=512,
          validation_data=(test_data, test_labels),
          verbose=2)

小模型

small_model = keras.Sequential(
[
 layers.Dense(4, activation='relu', input_shape=(NUM_WORDS,)),
 layers.Dense(4, activation='relu'),
 layers.Dense(1, activation='sigmoid')
]
)
small_model.compile(optimizer='adam',
      loss='binary_crossentropy',
      metrics=['accuracy', 'binary_crossentropy'])
small_model.summary()
small_history = small_model.fit(train_data, train_labels,
          epochs=20, batch_size=512,
          validation_data=(test_data, test_labels),
          verbose=2)

大模型

big_model = keras.Sequential(
[
 layers.Dense(512, activation='relu', input_shape=(NUM_WORDS,)),
 layers.Dense(512, activation='relu'),
 layers.Dense(1, activation='sigmoid')
]
)
big_model.compile(optimizer='adam',
      loss='binary_crossentropy',
      metrics=['accuracy', 'binary_crossentropy'])
big_model.summary()
big_history = big_model.fit(train_data, train_labels,
          epochs=20, batch_size=512,
          validation_data=(test_data, test_labels),
          verbose=2)

绘图比较上述三个模型

def plot_history(histories, key='binary_crossentropy'):
 plt.figure(figsize=(16,10))
 
 for name, history in histories:
 val = plt.plot(history.epoch, history.history['val_'+key],
     '--', label=name.title()+' Val')
 plt.plot(history.epoch, history.history[key], color=val[0].get_color(),
    label=name.title()+' Train')

 plt.xlabel('Epochs')
 plt.ylabel(key.replace('_',' ').title())
 plt.legend()

 plt.xlim([0,max(history.epoch)])


plot_history([('baseline', baseline_history),
    ('small', small_history),
    ('big', big_history)])

三个模型在迭代过程中在训练集的表现都会越来越好,并且都会出现过拟合的现象

大模型在训练集上表现更好,过拟合的速度更快

l2正则减少过拟合

l2_model = keras.Sequential(
[
 layers.Dense(16, kernel_regularizer=keras.regularizers.l2(0.001), 
     activation='relu', input_shape=(NUM_WORDS,)),
 layers.Dense(16, kernel_regularizer=keras.regularizers.l2(0.001), 
     activation='relu'),
 layers.Dense(1, activation='sigmoid')
]
)
l2_model.compile(optimizer='adam',
      loss='binary_crossentropy',
      metrics=['accuracy', 'binary_crossentropy'])
l2_model.summary()
l2_history = l2_model.fit(train_data, train_labels,
          epochs=20, batch_size=512,
          validation_data=(test_data, test_labels),
          verbose=2)
plot_history([('baseline', baseline_history),
    ('l2', l2_history)])

可以发现正则化之后的模型在验证集上的过拟合程度减少

添加dropout减少过拟合

dpt_model = keras.Sequential(
[
 layers.Dense(16, activation='relu', input_shape=(NUM_WORDS,)),
 layers.Dropout(0.5),
 layers.Dense(16, activation='relu'),
 layers.Dropout(0.5),
 layers.Dense(1, activation='sigmoid')
]
)
dpt_model.compile(optimizer='adam',
      loss='binary_crossentropy',
      metrics=['accuracy', 'binary_crossentropy'])
dpt_model.summary()
dpt_history = dpt_model.fit(train_data, train_labels,
          epochs=20, batch_size=512,
          validation_data=(test_data, test_labels),
          verbose=2)
plot_history([('baseline', baseline_history),
    ('dropout', dpt_history)])

批正则化

model = keras.Sequential([
 layers.Dense(64, activation='relu', input_shape=(784,)),
 layers.BatchNormalization(),
 layers.Dense(64, activation='relu'),
 layers.BatchNormalization(),
 layers.Dense(64, activation='relu'),
 layers.BatchNormalization(),
 layers.Dense(10, activation='softmax')
])
model.compile(optimizer=keras.optimizers.SGD(),
    loss=keras.losses.SparseCategoricalCrossentropy(),
    metrics=['accuracy'])
model.summary()
history = model.fit(x_train, y_train, batch_size=256, epochs=100, validation_split=0.3, verbose=0)
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.legend(['training', 'validation'], loc='upper left')
plt.show()

总结

防止神经网络中过度拟合的最常用方法:

获取更多训练数据。

减少网络容量。

添加权重正规化。

添加dropout。

以上这篇keras处理欠拟合和过拟合的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • 利用Python实现Markdown文档格式转换详解

    利用Python实现Markdown文档格式转换详解

    这篇文章主要介绍了如何利用Python中的MarkItDown库将多种文件高效转换为Markdown文本,以及如何使用Python-Markdown库将Markdown文本转换为HTML,需要的可以参考下
    2025-03-03
  • Python实现自定义Jupyter魔法命令

    Python实现自定义Jupyter魔法命令

    相信大家都用过 jupyter,也用过里面的魔法命令,这些魔法命令都以%或者%%开头。用法还是比较简单的,但是我们能不能自定义魔法命令呢?本文就来教大家如何自定义Jupyter魔法命令
    2022-08-08
  • Python装饰器实现方法及应用场景详解

    Python装饰器实现方法及应用场景详解

    这篇文章主要介绍了Python装饰器实现方法及应用场景详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-03-03
  • Django异步任务之Celery的基本使用

    Django异步任务之Celery的基本使用

    这篇文章主要给大家介绍了关于Django异步任务之Celery使用的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用Django具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-03-03
  • Python WXPY实现微信监控报警功能的代码

    Python WXPY实现微信监控报警功能的代码

    本篇文章主要介绍了Python WXPY实现微信监控报警功能的代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-10-10
  • python实现飞船游戏的纵向移动

    python实现飞船游戏的纵向移动

    这篇文章主要为大家详细介绍了python实现飞船游戏的纵向移动,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-04-04
  • 人工智能学习pyTorch自建数据集及可视化结果实现过程

    人工智能学习pyTorch自建数据集及可视化结果实现过程

    这篇文章主要为大家介绍了人工智能学习pyTorch自建数据集及可视化结果的实现过程,有需要的朋友可以借鉴参考下,希望能够有所帮助
    2021-11-11
  • python+matplotlib演示电偶极子实例代码

    python+matplotlib演示电偶极子实例代码

    这篇文章主要介绍了python+matplotlib演示电偶极子实例代码,具有一定借鉴价值,需要的朋友可以参考下
    2018-01-01
  • Python实现内存泄露排查的示例详解

    Python实现内存泄露排查的示例详解

    一般在python代码块的调试过程中会使用memory-profiler、filprofiler、objgraph等三种方式进行辅助分析,今天这里主要介绍使用objgraph对象提供的函数接口来进行内存泄露的分析,感兴趣的可以了解一下
    2023-01-01
  • Python中的http.server库用法详细介绍

    Python中的http.server库用法详细介绍

    这篇文章主要给大家介绍了关于Python中http.server库用法的相关资料,http.server是Python标准库中的一个模块,用于创建基本的HTTP服务器,它提供了处理HTTP请求的基本框架和核心类,需要的朋友可以参考下
    2024-11-11

最新评论