手写数字识别编译与训练,然后给定单张数字进行识别
代码
import tensorflow as tf
from tensorflow.keras.datasets import mnist
# 加载MNIST数据集
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 数据预处理
x_train = x_train.reshape(x_train.shape[0], 28, 28, 1).astype('float32') / 255.0
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1).astype('float32') / 255.0
# 定义模型
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
tf.keras.layers.MaxPooling2D((2, 2)),
tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
tf.keras.layers.MaxPooling2D((2, 2)),
tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(10)
])
# 编译模型
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
# 训练模型
model.fit(x_train, y_train, epochs=5)
# 评估模型
model.evaluate(x_test, y_test, verbose=2)
# 预测手写数字
import numpy as np
from PIL import Image
# 加载手写数字图片
img = Image.open('5qq.jpg').convert('L')
img = img.resize((28, 28))
img_arr = np.array(img)
img_arr = img_arr.reshape((1, 28, 28, 1)).astype('float32') / 255.0
# 预测手写数字
predictions = model.predict(img_arr)
digit = np.argmax(predictions[0])
print('Predicted digit:', digit)
结果如下
图像如下
代码保存图像文件为"5qq.jpg",自行下载图像并进行改名即可运行得到结果