# 首先就是先导入numpy和keras库
import numpy as np
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
from matplotlib import pyplot as plt
# 设置随机数种子以获得可重复的结果
np.random.seed(7)
# 加载MNIST数据集
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 数据预处理
x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)
input_shape = (28, 28, 1)
# 将像素值标准化为0到1之间的值
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
# 将类别标签转换为one-hot编码
y_train = np.eye(10)[y_train]
y_test = np.eye(10)[y_test]
# 创建模型(LeNet-5)
# 输入层
model = Sequential()
# 第一卷积层C1
model.add(Conv2D(6, kernel_size=(5, 5), activation='relu', input_shape=input_shape))
# 第一池化层S2
model.add(MaxPooling2D(pool_size=(2, 2)))
# 第二卷积层C3
model.add(Conv2D(16, kernel_size=(5, 5), activation='relu'))
# 第二池化层S4
model.add(MaxPooling2D(pool_size=(2, 2)))
# 展平层
model.add(Flatten())
# 第一全连接层C5
model.add(Dense(120, activation='relu'))
# 第一Dropout层
model.add(Dropout(0.5))
# 第二全连接层F6
model.add(Dense(84, activation='relu'))
# 第二Dropout层
model.add(Dropout(0.5))
# 输出层
model.add(Dense(10, activation='softmax'))
# 编译模型
model.compile(loss=K.categorical_crossentropy, optimizer='adam', metrics=['accuracy'])
# 训练模型
model.fit(x_train, y_train, batch_size=128, epochs=10, verbose=1, validation_data=(x_test, y_test))
# 评估模型
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
# 选择要显示的样本数量
num_samples = 10
# 随机选择一些样本索引
sample_indices = np.random.choice(x_test.shape[0], num_samples, replace=False)
# 获取选定的样本及其对应的标签
selected_samples = x_test[sample_indices]
selected_labels = y_test[sample_indices]
# 显示选定的样本及其对应的标签
fig, axes = plt.subplots(nrows=num_samples, ncols=2, figsize=(10, 5))
for i, (sample, label) in enumerate(zip(selected_samples, selected_labels)):
axes[i, 0].imshow(sample.reshape(28, 28), cmap='gray')
axes[i, 0].axis('off')
axes[i, 1].text(0.5, 0.5, f'Label: {np.argmax(label)}', fontsize=12, ha='center', va='center')
axes[i, 1].axis('off')
plt.show()
【使用Keras构建并训练MNIST手写数字识别模型】
于 2023-11-18 08:00:00 首次发布