手写数字识别

手写数字识别代码`
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt
import numpy as np

(x_train, y_train), (x_test, y_test) = datasets.mnist.load_data()

x_train = x_train.reshape((60000, 28, 28, 1)).astype('float32') / 255
x_test = x_test.reshape((10000, 28, 28, 1)).astype('float32') / 255

y_train = tf.keras.utils.to_categorical(y_train, 10)
y_test = tf.keras.utils.to_categorical(y_test, 10)

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.Conv2D(64, (3, 3), activation='relu'),
layers.Flatten(),
layers.Dense(64, activation='relu'),
layers.Dense(10, activation='softmax')
])

model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])

history = model.fit(x_train, y_train, epochs=10, batch_size=64,
validation_split=0.1)

test_loss, test_acc = model.evaluate(x_test, y_test)
print(f'\n测试集准确率:{test_acc:.4f}')

plt.plot(history.history['accuracy'], label='训练准确率')
plt.plot(history.history['val_accuracy'], label='验证准确率')
plt.xlabel('迭代轮次')
plt.ylabel('准确率')
plt.legend()
plt.show()

sample_img = x_test[0:1]
pred = model.predict(sample_img)
pred_label = np.argmax(pred)
true_label = np.argmax(y_test[0])

plt.imshow(sample_img.reshape(28,28), cmap='gray')
plt.title(f'预测标签:{pred_label},真实标签:{true_label}')
plt.axis('off')
plt.show()`

屏幕截图2025.12

posted @ 2025-12-21 18:56  YMH^_^  阅读(3)  评论(0)    收藏  举报