Python手写数字识别
时间: 2023-11-19 16:56:21 浏览: 95
Python实现手写数字识别(神经网络、mnist数据集).zip
5星 · 资源好评率100%
Python手写数字识别是指使用Python编程语言实现的一种数字识别算法,它可以对手写数字进行自动识别。常用的手写数字识别算法包括K近邻算法、支持向量机(SVM)算法、神经网络算法等。其中,神经网络算法是目前最为流行和有效的手写数字识别算法之一。下面是一个简单的基于神经网络的Python手写数字识别示例,使用Keras库来构建神经网络模型,使用MNIST数据集进行训练和测试。
```python
import numpy as np
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.utils import np_utils
# 加载MNIST数据集
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# 数据预处理
X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)
X_test = X_test.reshape(X_test.shape[0], 28, 28, 1)
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 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, kernel_size=(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, verbose=1, 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])
# 预测手写数字
img = cv2.imread('test.jpg', 0)
img = cv2.resize(img, (28, 28))
img = img.reshape(1, 28, 28, 1)
img = img.astype('float32')
img /= 255
result = model.predict_classes(img)
print(result)
```
阅读全文