用python利用卷积神经网络实现手写数字识别
时间: 2023-08-15 10:28:13 浏览: 117
好的,手写数字识别是一个经典的计算机视觉任务,可以用卷积神经网络(CNN)来解决。以下是一个基本的步骤:
1.导入必要的库和数据集:
```python
import tensorflow as tf
from tensorflow import keras
# 加载数据集
mnist = keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
```
2.对图像进行归一化处理:
```python
# 归一化处理 0-1 之间
train_images = train_images / 255.0
test_images = test_images / 255.0
```
3.构建CNN模型:
```python
model = keras.Sequential([
keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(28, 28, 1)),
keras.layers.MaxPooling2D((2,2)),
keras.layers.Flatten(),
keras.layers.Dense(128, activation='relu'),
keras.layers.Dense(10)
])
```
4.编译模型并进行训练:
```python
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
model.fit(train_images, train_labels, epochs=5, validation_data=(test_images, test_labels))
```
5.评估模型性能:
```python
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print('\nTest accuracy:', test_acc)
```
这样,我们就可以用CNN来实现手写数字识别了。
阅读全文