网络编程
位置:首页>> 网络编程>> Python编程>> keras处理欠拟合和过拟合的实例讲解

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

作者:Lzj000lzj  发布时间:2022-06-23 05:14:38 

标签: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)])

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

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

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

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)])

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

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

添加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)])

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

批正则化


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。

来源:https://blog.csdn.net/Lzj000lzj/article/details/94132842

0
投稿

猜你喜欢

  • iframe的背景颜色在IE下为window的当前窗口颜色(默认白色,可以在显示外观处对其进行设置),这导致在大幅背景上插入iframe时,
  • 前言众所周知,appsetting.json 配置文件是.Net 的重大革新之心,抛开了以前繁杂的xml文件,使用了更简洁易懂的json方式
  • 一、环境win10、Python3.6、OpenCV3.x;编译器:pycharm5.0.3二、实现目标根据需要追踪的物体颜色,设定阈值,在
  • 前言在开发中一些需求需要通过程序操作excel文档,例如导出excel、导入excel、向excel文档中插入图片、表格和图表等信息,使用E
  • leastsq作用:最小化一组方程的平方和。参数设置:func 误差函数x0 初始化的参数args 其他的额外参数举个例子:首先创建样本点i
  • 一、查询某个字段重复   select *     from User u     whe
  • 在Intel的早期,Andy Grove遇到一个雇员 - 他建议公司在芯片的基础上开发个人计算机。AndyGrove疑问道“个人计算机能做什
  • 前言在业务迭代中,随着数据量的上升,会出现慢SQL情况,但是当我们去分析单条SQL的时候,发现其执行速度并没有那么慢,原因是什么呢,那么就可
  • 不知道从什么时候开始,在网络上到处可以看到div+css,到底什么是div+css呢?难道就是传说中的标准重构吗?标准从最简单的根源来说不是
  • 静态页面运行代码框你也许见的多了,而动态asp运行代码框你一定很少见到,看看本文吧!保存为runasp.asp运行。账号密码admin,登陆
  • SELECT ABS(DATEDIFF(dd,EndDate,BeginDate)) FROM dbo.WorkingPlan 其中,Wor
  • 使用Vue实现简单的用户登录界面,登录成功以后查询账号用户类型进行相应的页面路由跳转,效果如下图所示:HTML部分:<div clas
  • 本文实例为大家分享了opencv实现图像校正的具体代码,供大家参考,具体内容如下1.引言:python实现倾斜图像校正操作2.思路流程:(1
  • php多进程实现PHP有一组进程控制函数(编译时需要–enable-pcntl与posix扩展),使得php能在nginx系统中实现跟c一样
  • 一、85%的广告没人看解读:如何挤进那15%的成功广告中去,吸引了读者就是成功了一半。Quester视角:反过来讲,只有不到1/5的广告能吸
  • 业务场景:前后端分离需要对接数据接口。接口测试是在postman做的,今天才开始和前端对接,由于这是我第一次做后端接口开发(第一次嘛,问题比
  • 看了大峡搞的级联菜单,我也班门弄斧一把,嘿嘿,花了一点时间搞了个级联菜单贴上来看看。本例中只要你选择成员分类名称就会自动显示成员名称:&nb
  • 相对于Java方式的聊天室,Python同样可以做得到。而且可以做的更加的优雅。想必少了那么多的各种流的Python Socket,你一定会
  • 本实验中分别针对空库、脱机、联机三种方式,配置一主两从的mysql标准异步复制。只做整服务器级别的复制,不考虑对个别库表或使用过滤复制的情况
  • 1.函数array()功能:创建一个数组变量格式:array(list)参数:list为数组变量中的每个数值列,中间用逗号间隔例子:<
手机版 网络编程 asp之家 www.aspxhome.com