"""
使用CNN训练minist数据集
"""
# 导入模块
from tensorflow.keras.utils import to_categorical
from tensorflow.keras import models, layers
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.datasets import mnist
# 加载数据集
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
# 将图片由二维铺展成为一维,并进行归一化处理
train_images = train_images.reshape(60000, 28, 28, 1).astype('float') / 255
test_images = test_images.reshape(10000, 28, 28, 1).astype('float') / 255
# 将训练集和测试集标签转换为one-hot编码
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)
# 打印输出第0个训练集和测试集的标签
print("train_labels[0]:", train_labels[0])
print("test_labels[0]", test_labels[0])
# 搭建LeNet网络
def LeNet():
network = models.Sequential()
network.add(layers.Conv2D(filters=6, kernel_size=(3, 3), padding='same',
activation='relu', input_shape=(28, 28, 1)))
network.add(layers.AveragePooling2D(pool_size=(2, 2)))
network.add(layers.Conv2D(filters=16, kernel_size=(3, 3), padding='same',
activation='relu'))
network.add(layers.BatchNormalization())
network.add(layers.AveragePooling2D(pool_size=(2, 2)))
network.add(layers.Conv2D(filters=160, kernel_size=(3, 3), padding='same',
activation='relu'))
network.add(layers.BatchNormalization())
network.add(layers.Dropout(0.03))
network.add(layers.Flatten())
network.add(layers.Dense(units=84, activation='relu'))
network.add(layers.Dropout(0.03))
network.add(layers.Dense(units=10, activation='softmax'))
return network
networks = LeNet()
# print(networks.summary())
# 编译:确定优化器和损失函数等
networks.compile(optimizer=RMSprop(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy'])
# 训练网络,用fit函数,epochs表示训练多少个回合,batch_size表示每次训练给多大的数据
networks.fit(train_images, train_labels, epochs=20, batch_size=235, verbose=1)
# 在测试集上预测前五张图片
y_pre = networks.predict(test_images[:5])
# 输出打印测试集在LeNet网络中测试前五张图片的结果和真实测试集前五张图片的结果
print("y_pre:\n", y_pre)
print("test_labels:\n", test_labels[:5])
# 在测试集上测试模型的性能
test_loss, test_accuracy = networks.evaluate(test_images, test_labels)
print("test_loss:", test_loss, " test_accuracy:", test_accuracy)