基于tensorflow使用lenet-5实现对mnist手写数字识别分类
时间: 2023-07-29 18:08:44 浏览: 147
基于Tensorflow的MNIST手写数字识别分类
好的,下面是基于 TensorFlow 使用 LeNet-5 实现对 MNIST 手写数字识别分类的步骤:
1. 安装 TensorFlow:可以通过 pip 安装,命令为 `pip install tensorflow`。
2. 导入必要的库:
```
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
```
3. 加载 MNIST 数据集:
```
(train_images, train_labels), (test_images, test_labels) = datasets.mnist.load_data()
```
4. 对数据进行预处理:
```
train_images = train_images.reshape((60000, 28, 28, 1))
test_images = test_images.reshape((10000, 28, 28, 1))
train_images, test_images = train_images / 255.0, test_images / 255.0
```
5. 构建 LeNet-5 模型:
```
model = models.Sequential()
model.add(layers.Conv2D(6, (5, 5), activation='relu', input_shape=(28, 28, 1)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(16, (5, 5), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Flatten())
model.add(layers.Dense(120, activation='relu'))
model.add(layers.Dense(84, activation='relu'))
model.add(layers.Dense(10, activation='softmax'))
```
6. 编译模型:
```
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
```
7. 训练模型:
```
model.fit(train_images, train_labels, epochs=5,
validation_data=(test_images, test_labels))
```
8. 测试模型:
```
test_loss, test_acc = model.evaluate(test_images, test_labels)
print('Test accuracy:', test_acc)
```
以上就是基于 TensorFlow 使用 LeNet-5 实现对 MNIST 手写数字识别分类的步骤。
阅读全文