手写数字识别python卷积神经网络
时间: 2024-07-13 17:01:26 浏览: 82
基于Python的MNIST手写数字识别卷积神经网络设计源码
手写数字识别通常使用Python中的卷积神经网络(Convolutional Neural Networks, CNN),因为CNN特别适合处理图像数据。在Keras或TensorFlow库中,你可以按照以下步骤构建一个简单的CNN模型来进行MNIST数据集的手写数字识别:
1. 导入必要的库:
```python
import tensorflow as tf
from tensorflow.keras import layers
```
2. 加载并预处理MNIST数据集:
```python
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_train = x_train.reshape(-1, 28, 28, 1).astype('float32') / 255
x_test = x_test.reshape(-1, 28, 28, 1).astype('float32') / 255
y_train = tf.keras.utils.to_categorical(y_train, 10)
y_test = tf.keras.utils.to_categorical(y_test, 10)
```
3. 构建CNN模型:
```python
model = tf.keras.Sequential([
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Flatten(),
layers.Dense(128, activation='relu'),
layers.Dropout(0.5),
layers.Dense(10, activation='softmax')
])
```
4. 编译并训练模型:
```python
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
model.fit(x_train, y_train, epochs=10, validation_data=(x_test, y_test))
```
5. 测试模型性能:
```python
test_loss, test_acc = model.evaluate(x_test, y_test)
print(f"Test accuracy: {test_acc}")
```
阅读全文