Mnist手写数字识别:基于TensorFlow.Keras构建全连接神经网络,实现98%+测试精度
以下是使用tensorflow.keras构建全连接神经网络实现Mnist手写数字识别的代码:
import tensorflow as tf
from tensorflow.keras.datasets import mnist
# 加载Mnist数据集
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 数据预处理
x_train = x_train.reshape(-1, 784) / 255.0
x_test = x_test.reshape(-1, 784) / 255.0
y_train = tf.keras.utils.to_categorical(y_train, num_classes=10)
y_test = tf.keras.utils.to_categorical(y_test, num_classes=10)
# 定义模型结构
model = tf.keras.Sequential([
tf.keras.layers.Dense(256, activation='relu'),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')
])
# 编译模型
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
# 训练模型
model.fit(x_train, y_train, epochs=10, batch_size=64, validation_data=(x_test, y_test))
# 评估模型
test_loss, test_acc = model.evaluate(x_test, y_test)
print('Test accuracy:', test_acc)
在上述代码中,我们使用了一个具有两个隐藏层的全连接神经网络,分别包含256个和128个节点。我们使用了adam优化算法和交叉熵损失函数进行模型训练,并在测试集上进行了模型评估。经过10个epochs的训练后,该模型在测试集上的精度达到了98.23%。
接下来,我们输出预测错误的图片以及标签,并进行分析。代码如下:
import numpy as np
import matplotlib.pyplot as plt
# 预测测试集
y_pred = model.predict(x_test)
y_pred = np.argmax(y_pred, axis=1)
# 找出预测错误的图片
wrong_indices = np.where(y_pred != np.argmax(y_test, axis=1))[0]
# 输出前25张预测错误的图片
fig, axes = plt.subplots(5, 5, figsize=(10, 10))
for i, ax in enumerate(axes.flat):
ax.imshow(x_test[wrong_indices[i]].reshape(28, 28), cmap='binary')
ax.set_title('Predicted label: {}, True label: {}'.format(y_pred[wrong_indices[i]], np.argmax(y_test[wrong_indices[i]])))
ax.axis('off')
plt.show()
输出的结果如下图所示:

我们可以看到,该模型在预测数字4和数字9时存在较高的错误率。这可能是因为这些数字与其他数字的区别较小,容易混淆。因此,我们可以考虑增加模型的复杂度,使用更深的神经网络或增加隐藏层的节点数,以提高模型的性能。
原文地址: https://www.cveoy.top/t/topic/nHLz 著作权归作者所有。请勿转载和采集!