python如何实现手写数字转手写文字的识别呢? 如下代码只能实现手写数字模型的训练与识别……怎么修改为手写汉字的模型训练与识别呢?
模型训练并输出结果
```python
import numpy as np
import matplotlib.pyplot as plt
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras.utils import to_categorical
from keras.datasets import mnist
#下载地址https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz
local_path = "d:/mnist.npz"
(X_train, y_train), (X_test, y_test) = mnist.load_data(path=local_path)
# 加载MNIST手写数字数据集
#(X_train, y_train), (X_test, y_test) = mnist.load_data()
# 数据预处理
X_train = X_train.reshape(X_train.shape[0], 28*28).astype('float32') / 255
X_test = X_test.reshape(X_test.shape[0], 28*28).astype('float32') / 255
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)
# 创建模型
model = Sequential()
model.add(Dense(512, activation='relu', input_shape=(28*28,)))
model.add(Dense(10, activation='softmax'))
# 编译模型
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# 训练模型
history = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=128)
# 绘制准确率和损失曲线
plt.figure(figsize=(12, 4))
plt.subplot(1, 2, 1)
plt.plot(history.history['accuracy'], label='Training Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.legend()
plt.title('Accuracy')
plt.subplot(1, 2, 2)
plt.plot(history.history['loss'], label='Training Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.legend()
plt.title('Loss')
# 评估模型
scores = model.evaluate(X_test, y_test, verbose=0)
print("准确率: %.2f%%" % (scores[1] * 100))
# 预测样例
predictions = model.predict(X_test[:10])
print("预测结果:", np.argmax(predictions, axis=1))
print("实际结果:", np.argmax(y_test[:10], axis=1))
# 显示图像和预测结果
plt.figure(figsize=(10, 3))
for i in range(10):
plt.subplot(2, 5, i+1)
plt.imshow(X_test[i].reshape((28, 28)), cmap='gray')
plt.axis('off')
plt.title("Prediction: %d" % np.argmax(predictions[i]))
plt.show()
# 保存模型
model.save('./mnist_model.h5')
训练出模型数据后,传入图片和模型进行识别……
import numpy as np
import matplotlib.pyplot as plt
from keras.datasets import mnist
from keras.models import load_model
from PIL import Image
# 加载已经训练好的模型(假设你已将训练好的模型保存为 'mnist_model.h5')
model = load_model('d:/mnist_model.h5')
def preprocess_image(image_path, img_size=28):
# 打开图像,并调整大小到28x28
img = Image.open(image_path).convert("L").resize((img_size, img_size))
# 将图像转换为灰度数组,并归一化
img_array = np.array(img) / 255.0
img_array = img_array.reshape(1, img_size * img_size)
return img_array
# 提交一张手写字体图片路径并输出识别结果
custom_image_path = "d:/lixiaochun.jpg" # 替换为你的图片路径
custom_img_preprocessed = preprocess_image(custom_image_path)
# 使用模型进行预测
prediction = model.predict(custom_img_preprocessed)
predicted_digit = np.argmax(prediction)
print(f"识别出的手写数字为:{predicted_digit}")
# 可以选择显示这个预测的图像
plt.imshow(Image.open(custom_image_path).convert("L"), cmap='gray')
plt.title(f"预测结果: {predicted_digit}")
plt.axis('off')
plt.show()
```