利用卷积神经网络进行手写数字识别
时间: 2023-09-14 07:09:51 浏览: 121
利用卷积神经网络(CNN)进行手写数字识别是一个常见的应用。下面是一个使用TensorFlow和Keras库实现手写数字识别的示例:
```python
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt
# 加载手写数字数据集(MNIST)
(train_images, train_labels), (test_images, test_labels) = datasets.mnist.load_data()
# 数据预处理
train_images = train_images.reshape((60000, 28, 28, 1))
test_images = test_images.reshape((10000, 28, 28, 1))
train_images, test_images = train_images / 255.0, test_images / 255.0
# 构建卷积神经网络模型
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10))
# 编译和训练模型
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
model.fit(train_images, train_labels, epochs=10, validation_data=(test_images, test_labels))
# 测试模型
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print('测试准确率:', test_acc)
```
在上述示例中,我们首先加载MNIST手写数字数据集,然后对图像进行预处理,将其转换为CNN所需的格式。接下来,我们使
阅读全文