编写一个python的手写数字识别
时间: 2023-08-04 19:24:32 浏览: 90
基于Python实现的手写数字识别系统.zip
5星 · 资源好评率100%
好的,下面是一个简单的Python手写数字识别的示例代码,基于深度学习框架Keras和MNIST数据集:
```python
# 导入必要的库
import numpy as np
import matplotlib.pyplot as plt
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D
# 加载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
X_test = X_test.reshape(X_test.shape[0], 28, 28, 1).astype('float32') / 255
y_train = np_utils.to_categorical(y_train, 10)
y_test = np_utils.to_categorical(y_test, 10)
# 定义模型结构
model = Sequential()
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(10, activation='softmax'))
# 编译模型
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# 训练模型
model.fit(X_train, y_train, batch_size=128, epochs=10, validation_data=(X_test, y_test))
# 评估模型
score = model.evaluate(X_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
# 预测结果
prediction = model.predict(X_test[:10])
print('预测结果:', np.argmax(prediction, axis=1))
# 显示数字图像
for i in range(10):
plt.subplot(2, 5, i+1)
plt.imshow(X_test[i].reshape(28, 28), cmap='gray')
plt.show()
```
这段代码使用了卷积神经网络(CNN)来对手写数字进行识别,通过对MNIST数据集进行训练和测试,可以得到较高的准确率。
阅读全文