【Python】Dropout抑制过拟合

Tensorflow实现Dropout抑制过拟合

import tensorflow as tf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Dropout抑制过拟合
(train_image, train_label), (test_image, test_label) = tf.keras.datasets.fashion_mnist.load_data()
train_label_onehot = tf.keras.utils.to_categorical(train_label)

test_label_onehot = tf.keras.utils.to_categorical(test_label)

model = tf.keras.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(28, 28)))
model.add(tf.keras.layers.Dense(128, activation='relu'))

model.add(tf.keras.layers.Dropout(0.5))
model.add(tf.keras.layers.Dense(128, activation='relu'))

model.add(tf.keras.layers.Dropout(0.5))
model.add(tf.keras.layers.Dense(128, activation='relu'))

model.add(tf.keras.layers.Dropout(0.5))
model.add(tf.keras.layers.Dense(10, activation='softmax'))

model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.001), loss='categorical_crossentropy', metrics=['acc'])
history = model.fit(train_image, train_label_onehot, epochs=10, validation_data=(test_image, test_label_onehot))

plt.plot(history.epoch, history.history.get('loss'), label='loss')
plt.plot(history.epoch, history.history.get('val_loss'), label='val_loss')
plt.legend()
plt.show()

plt.plot(history.epoch, history.history.get('acc'), label='acc')
plt.plot(history.epoch, history.history.get('val_acc'), label='val_acc')
# 加载图例
plt.legend()
plt.show()

你可能感兴趣的:(机器学习,python,tensorflow,keras)