利用Tensorflow框架设计卷积神经网络完成基于fashion-minst数据集的图像识别
时间: 2024-12-30 13:37:48 浏览: 56
利用TensorFlow框架设计卷积神经网络(CNN)来处理Fashion-MNIST数据集是一项常见的机器学习任务。Fashion-MNIST是一个包含10种常见服装类别(如T恤、裤子等)的手写数字风格图片的数据集。以下是步骤概述:
1. **导入库**:
```python
import tensorflow as tf
from tensorflow.keras import layers
(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.fashion_mnist.load_data()
```
2. **预处理数据**:
- 归一化像素值范围到0-1之间
```python
train_images, test_images = train_images / 255.0, test_images / 255.0
```
3. **构建模型**:
使用Sequential API创建一个包含卷积层、池化层、全连接层和激活函数的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') # 输出层,10个节点对应10个类别
])
```
4. **编译模型**:
设置损失函数(如`sparse_categorical_crossentropy`),优化器(如Adam)和评估指标(accuracy)。
```python
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
```
5. **训练模型**:
```python
history = model.fit(train_images.reshape(-1, 28, 28, 1), train_labels, epochs=10,
validation_data=(test_images.reshape(-1, 28, 28, 1), test_labels))
```
6. **评估模型**:
测试模型在测试集上的性能。
```python
_, test_acc = model.evaluate(test_images.reshape(-1, 28, 28, 1), test_labels, verbose=2)
print(f'Test accuracy: {test_acc}')
```
阅读全文
相关推荐

















