利用Keras中的权重约束减少深度神经网络中的过拟合
运行该示例会创建一个散点图,显示每个类中观察的半圆形或月亮形状。我们可以看到点的分散中的噪音使得卫星不太明显。 这是一个很好的测试问题,因为类不能用一行来分隔,例如不是线性可分的,需要非线性方法,如神经网络来解决。我们只生成了100个样本,这对于神经网络而言很小,提供了过度拟合训练数据集的机会,并且在测试数据集上具有更高的误差:使用正则化的一个好例子。此外,样本具有噪声,使模型有机会学习不一致的样本的各个方面。 过度多层感知器 我们可以开发一个MLP模型来解决这个二进制分类问题。该模型将具有一个隐藏层,其具有比解决该问题所需的节点更多的节点,从而提供过度拟合的机会。我们还将训练模型的时间超过确保模型过度所需的时间。在我们定义模型之前,我们将数据集拆分为训练集和测试集,使用30个示例来训练模型,使用70个示例来评估拟合模型的性能。 X, y = make_moons(n_samples=100, noise=0.2, random_state=1) # split into train and test n_train = 30 trainX, testX = X[:n_train, :], X[n_train:, :] trainy, testy = y[:n_train], y[n_train:] 接下来,我们可以定义模型。隐藏层使用隐藏层中的500个节点和整流的线性激活函数。在输出层中使用S形激活函数以预测0或1的类值。该模型使用二元交叉熵损失函数进行优化,适用于二元分类问题和梯度下降的有效Adam版本。 # define model model = Sequential() model.add(Dense(500, input_dim=2, activation='relu')) model.add(Dense(1, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) 然后,定义的模型拟合4,000个训练数据,默认批量大小为32。我们还将使用测试数据集作为验证数据集。 # fit model history = model.fit(trainX, trainy, validation_data=(testX, testy), epochs=4000, verbose=0) 我们可以在测试数据集上评估模型的性能并报告结果。 # evaluate the model _, train_acc = model.evaluate(trainX, trainy, verbose=0) _, test_acc = model.evaluate(testX, testy, verbose=0) print('Train: %.3f, Test: %.3f' % (train_acc, test_acc)) 最后,我们将在每个时期的训练集和测试集上绘制模型的性能。如果模型确实过度拟合训练数据集,我们将期望训练集上的准确度线图继续增加并且测试设置上升然后随着模型在训练数据集中学习统计噪声而再次下降。 # plot history pyplot.plot(history.history['acc'], label='train') pyplot.plot(history.history['val_acc'], label='test') pyplot.legend() pyplot.show() 我们可以将所有这些部分组合在一起; 下面列出了完整的示例。 # mlp overfit on the moons dataset from sklearn.datasets import make_moons from keras.layers import Dense from keras.models import Sequential from matplotlib import pyplot # generate 2d classification dataset X, y = make_moons(n_samples=100, noise=0.2, random_state=1) # split into train and test n_train = 30 trainX, testX = X[:n_train, :], X[n_train:, :] trainy, testy = y[:n_train], y[n_train:] # define model model = Sequential() model.add(Dense(500, input_dim=2, activation='relu')) model.add(Dense(1, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # fit model history = model.fit(trainX, trainy, validation_data=(testX, testy), epochs=4000, verbose=0) # evaluate the model _, train_acc = model.evaluate(trainX, trainy, verbose=0) _, test_acc = model.evaluate(testX, testy, verbose=0) print('Train: %.3f, Test: %.3f' % (train_acc, test_acc)) # plot history pyplot.plot(history.history['acc'], label='train') pyplot.plot(history.history['val_acc'], label='test') pyplot.legend() pyplot.show() (编辑:晋中站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |