使用tensorflow2识别手写数字
时间: 2023-12-04 12:05:58 浏览: 64
下面是一个简单的示例代码,使用tensorflow2来训练一个手写数字识别模型:
```python
import tensorflow as tf
from tensorflow.keras import layers, models
# 加载MNIST数据集
mnist = tf.keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
# 对数据进行归一化处理
train_images = train_images / 255.0
test_images = test_images / 255.0
# 定义卷积神经网络模型
model = models.Sequential([
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Flatten(),
layers.Dense(64, activation='relu'),
layers.Dense(10, activation='softmax')
])
# 编译模型并训练
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(train_images.reshape(-1, 28, 28, 1), train_labels, epochs=5)
# 评估模型
test_loss, test_acc = model.evaluate(test_images.reshape(-1, 28, 28, 1), test_labels)
print('Test accuracy:', test_acc)
```
首先加载MNIST数据集,并对数据进行归一化处理。然后定义一个卷积神经网络模型,包含两个卷积层和两个池化层。最后编译模型并训练,评估模型的准确率。
阅读全文