用 python 代码编写一个手写体数字识别的程序
时间: 2023-05-23 17:06:33 浏览: 123
手写体数字的识别程序
4星 · 用户满意度95%
A:以下是一个简单的手写数字识别程序,使用Keras和Tensorflow库训练了一个CNN模型:
```python
# 导入所需的库
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D
from keras.optimizers import Adam
# 加载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)
# 将标签进行 one-hot 编码
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), input_shape=(28, 28, 1)))
model.add(Activation('relu'))
# 添加池化层
model.add(MaxPooling2D(pool_size=(2, 2)))
# 添加卷积层和池化层
model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
# 添加全连接层
model.add(Flatten())
model.add(Dense(128))
model.add(Activation('relu'))
model.add(Dropout(0.5))
# 添加输出层
model.add(Dense(10))
model.add(Activation('softmax'))
# 编译模型
model.compile(optimizer=Adam(), loss='categorical_crossentropy', 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 accuracy:', score[1])
```
运行程序后,可以使用自己的手写数字图像进行测试。
阅读全文