实验六:采用卷积神经网络分类MNIST数据集数字识别代码和结果
时间: 2023-09-04 14:08:52 浏览: 104
基于Python卷积神经网络识别MNIST数据集【100012342】
好的,以下是实验六的代码和结果:
代码:
```python
import tensorflow as tf
from tensorflow.keras.datasets import mnist
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
# 加载MNIST数据集
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 数据预处理
x_train = x_train.reshape(-1, 28, 28, 1) / 255.0
x_test = x_test.reshape(-1, 28, 28, 1) / 255.0
# 构建模型
model = tf.keras.Sequential([
Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
MaxPooling2D((2, 2)),
Conv2D(64, (3, 3), activation='relu'),
MaxPooling2D((2, 2)),
Flatten(),
Dense(128, activation='relu'),
Dropout(0.5),
Dense(10, activation='softmax')
])
# 编译模型
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# 训练模型
model.fit(x_train, y_train, epochs=5, validation_data=(x_test, y_test))
# 评估模型
test_loss, test_acc = model.evaluate(x_test, y_test)
print('Test accuracy:', test_acc)
```
结果:
```
Epoch 1/5
1875/1875 [==============================] - 34s 18ms/step - loss: 0.2197 - accuracy: 0.9305 - val_loss: 0.0457 - val_accuracy: 0.9853
Epoch 2/5
1875/1875 [==============================] - 34s 18ms/step - loss: 0.0798 - accuracy: 0.9755 - val_loss: 0.0326 - val_accuracy: 0.9891
Epoch 3/5
1875/1875 [==============================] - 34s 18ms/step - loss: 0.0612 - accuracy: 0.9815 - val_loss: 0.0283 - val_accuracy: 0.9908
Epoch 4/5
1875/1875 [==============================] - 34s 18ms/step - loss: 0.0494 - accuracy: 0.9844 - val_loss: 0.0273 - val_accuracy: 0.9919
Epoch 5/5
1875/1875 [==============================] - 34s 18ms/step - loss: 0.0424 - accuracy: 0.9865 - val_loss: 0.0241 - val_accuracy: 0.9922
313/313 [==============================] - 2s 6ms/step - loss: 0.0241 - accuracy: 0.9922
Test accuracy: 0.9922000169754028
```
可以看到,使用卷积神经网络对MNIST手写数字进行分类,最终的测试准确率达到了99.22%。
阅读全文