基于python使用卷积神经网络进行MNIST数据集分类
时间: 2024-12-18 16:35:08 浏览: 30
基于Python实现卷积神经网络分类MNIST数据集【100011707】
5星 · 资源好评率100%
基于Python的卷积神经网络(CNN)对MNIST手写数字数据集进行分类是一个常见的机器学习入门示例。MNIST是一组包含60,000个训练样本和10,000个测试样本的小型图像数据库,每个像素值都在0到255之间,用于单个灰度图像的手写数字识别。
以下是使用Keras库(它是在TensorFlow等深度学习框架之上建立的高级API)实现的一个简单步骤:
1. **导入必要的库**:
```python
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
```
2. **加载和预处理数据**:
```python
(train_images, train_labels), (test_images, test_labels) = datasets.mnist.load_data()
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
```
3. **构建卷积神经网络模型**:
```python
model = models.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(64, activation='relu'),
layers.Dropout(0.5),
layers.Dense(10, activation='softmax')
])
```
4. **编译和训练模型**:
```python
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
history = model.fit(train_images, train_labels, epochs=10, validation_data=(test_images, test_labels))
```
5. **评估模型**:
```python
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print('\nTest accuracy:', test_acc)
```
阅读全文