卷积神经网络实现手写数字识别python代码实现
时间: 2023-10-21 18:04:02 浏览: 90
基于卷积神经网络的手写数字识别系统的设计与实现代码大全.doc
以下是一个简单的 CNN 实现手写数字识别的 Python 代码示例:
```python
import numpy as np
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D
from tensorflow.keras.utils import to_categorical
# 加载手写数字数据集
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 将像素值标准化到 0-1 范围内,并将标签转换为 one-hot 编码
x_train = x_train.astype('float32') / 255
x_test = x_test.astype('float32') / 255
y_train = to_categorical(y_train, 10)
y_test = to_categorical(y_test, 10)
# 将数据集的形状调整为适合 CNN 的格式
x_train = np.expand_dims(x_train, axis=-1)
x_test = np.expand_dims(x_test, axis=-1)
# 构建 CNN 模型
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'])
# 训练 CNN 模型
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])
```
希望能对你有所帮助。
阅读全文