python数字识别代码
时间: 2023-10-12 16:16:24 浏览: 89
以下是Python实现手写数字识别的代码示例:
```python
import numpy as np
import tensorflow as tf
from tensorflow import keras
# 加载MNIST数据集
mnist = 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 = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation=tf.nn.relu),
keras.layers.Dense(10, activation=tf.nn.softmax)
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# 训练模型
model.fit(train_images, train_labels, epochs=5)
# 在测试集上评估模型
test_loss, test_acc = model.evaluate(test_images, test_labels)
print('Test accuracy:', test_acc)
# 使用模型进行预测
predictions = model.predict(test_images)
print(np.argmax(predictions[0])) # 输出第一张测试图片的预测值
```
阅读全文