卷积神经网络手写数字识别代码
时间: 2023-08-10 08:08:27 浏览: 91
以下是一个使用Keras实现卷积神经网络手写数字识别的代码示例:
```python
import numpy as np
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.datasets import mnist
from keras.utils import to_categorical
# 加载MNIST数据集
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 转换为浮点数并归一化
x_train = x_train.astype('float32') / 255
x_test = x_test.astype('float32') / 255
# 将标签转换为one-hot编码
y_train = to_categorical(y_train, 10)
y_test = 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[:, :, :, np.newaxis], y_train,
batch_size=128,
epochs=10,
validation_data=(x_test[:, :, :, np.newaxis], y_test))
# 评估模型
score = model.evaluate(x_test[:, :, :, np.newaxis], y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
# 随机显示一些测试图像和它们的预测结果
predictions = model.predict(x_test[:, :, :, np.newaxis])
fig = plt.figure(figsize=(8, 8))
for i in range(16):
idx = np.random.randint(len(x_test))
ax = fig.add_subplot(4, 4, i+1)
ax.imshow(x_test[idx], cmap='gray')
ax.set_title('Predicted: {}'.format(np.argmax(predictions[idx])))
ax.axis('off')
plt.show()
```
这个代码使用了两个卷积层和一个全连接层,以及一些常用的技巧,如最大池化和Dropout来提高模型的性能。在训练和测试后,代码还会随机显示一些测试图像和它们的预测结果。
阅读全文