logo

TensorFlow教程:Keras基础实战①服装图像分类全解

作者:JC2025.09.18 17:02浏览量:0

简介:本文通过TensorFlow与Keras框架,系统讲解服装图像分类的完整流程,涵盖数据加载、模型构建、训练优化及评估部署,适合机器学习初学者及进阶开发者。

TensorFlow教程汇总—Keras机器学习基础① 对服装图像进行分类

一、引言:为什么选择服装图像分类?

服装图像分类是计算机视觉领域的经典任务,其应用场景涵盖电商推荐、智能试衣、库存管理等。相较于传统图像分类任务(如手写数字识别),服装图像具有更复杂的纹理、形状和姿态变化,对模型的特征提取能力提出更高要求。本文以TensorFlow 2.x中的Keras API为核心,通过完整的代码示例,从数据加载到模型部署,系统讲解服装图像分类的实现流程。

二、环境准备与数据集介绍

1. 环境配置

建议使用Python 3.7+环境,安装TensorFlow 2.x版本(如pip install tensorflow)。Keras作为TensorFlow的高级API,无需单独安装。

2. 数据集选择:Fashion MNIST

Fashion MNIST是MNIST的升级版,包含10类服装图像(T-shirt/top、Trouser、Pullover等),每类7000张灰度图(28×28像素)。其优势在于:

  • 数据量适中(6万训练集,1万测试集)
  • 类别多样性覆盖基础服装类型
  • 无需复杂预处理
  1. import tensorflow as tf
  2. from tensorflow.keras.datasets import fashion_mnist
  3. # 加载数据集
  4. (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()

三、数据预处理与可视化

1. 像素值归一化

原始图像像素值为0-255,需归一化至0-1范围以加速模型收敛:

  1. train_images = train_images / 255.0
  2. test_images = test_images / 255.0

2. 标签编码

将类别标签转换为独热编码(One-Hot Encoding):

  1. from tensorflow.keras.utils import to_categorical
  2. train_labels = to_categorical(train_labels)
  3. test_labels = to_categorical(test_labels)

3. 数据可视化

使用Matplotlib查看部分样本:

  1. import matplotlib.pyplot as plt
  2. class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
  3. 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
  4. plt.figure(figsize=(10,10))
  5. for i in range(25):
  6. plt.subplot(5,5,i+1)
  7. plt.xticks([])
  8. plt.yticks([])
  9. plt.grid(False)
  10. plt.imshow(train_images[i], cmap=plt.cm.binary)
  11. plt.xlabel(class_names[train_labels[i].argmax()])
  12. plt.show()

四、模型构建:Keras Sequential API

1. 基础CNN模型

服装图像分类推荐使用卷积神经网络(CNN),其结构如下:

  1. from tensorflow.keras.models import Sequential
  2. from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
  3. model = Sequential([
  4. # 输入层:28×28灰度图,需扩展为4D张量(样本数,高,宽,通道数)
  5. tf.keras.layers.Reshape((28,28,1), input_shape=(28,28)),
  6. # 第一卷积层:32个3×3卷积核,ReLU激活
  7. Conv2D(32, (3,3), activation='relu', input_shape=(28,28,1)),
  8. MaxPooling2D((2,2)),
  9. # 第二卷积层:64个3×3卷积核
  10. Conv2D(64, (3,3), activation='relu'),
  11. MaxPooling2D((2,2)),
  12. # 展平层
  13. Flatten(),
  14. # 全连接层:128个神经元
  15. Dense(128, activation='relu'),
  16. # 输出层:10个类别,Softmax激活
  17. Dense(10, activation='softmax')
  18. ])

2. 模型编译

配置损失函数、优化器和评估指标:

  1. model.compile(optimizer='adam',
  2. loss='categorical_crossentropy',
  3. metrics=['accuracy'])

五、模型训练与优化

1. 基础训练

  1. history = model.fit(train_images, train_labels,
  2. epochs=10,
  3. batch_size=64,
  4. validation_data=(test_images, test_labels))

2. 训练过程可视化

  1. plt.plot(history.history['accuracy'], label='accuracy')
  2. plt.plot(history.history['val_accuracy'], label='val_accuracy')
  3. plt.xlabel('Epoch')
  4. plt.ylabel('Accuracy')
  5. plt.ylim([0, 1])
  6. plt.legend(loc='lower right')
  7. plt.show()

3. 优化策略

  • 数据增强:通过旋转、缩放等操作扩充数据集
    ```python
    from tensorflow.keras.preprocessing.image import ImageDataGenerator

datagen = ImageDataGenerator(
rotation_range=10,
zoom_range=0.1,
width_shift_range=0.1,
height_shift_range=0.1)

生成增强数据并训练

datagen.fit(train_images)
model.fit(datagen.flow(train_images, train_labels, batch_size=64),
epochs=20)

  1. - **模型调参**:调整卷积核数量、全连接层神经元数
  2. - **正则化**:添加Dropout层防止过拟合
  3. ```python
  4. from tensorflow.keras.layers import Dropout
  5. model.add(Dropout(0.5)) # 在全连接层后添加50%丢弃率

六、模型评估与部署

1. 测试集评估

  1. test_loss, test_acc = model.evaluate(test_images, test_labels)
  2. print(f'Test accuracy: {test_acc}')

2. 单张图像预测

  1. import numpy as np
  2. def predict_image(img):
  3. img_array = tf.expand_dims(img, 0) # 扩展为batch维度
  4. predictions = model.predict(img_array)
  5. predicted_class = np.argmax(predictions[0])
  6. return class_names[predicted_class]
  7. # 示例预测
  8. sample_img = test_images[0]
  9. print(predict_image(sample_img)) # 输出预测类别

3. 模型保存与加载

  1. # 保存模型
  2. model.save('fashion_mnist_model.h5')
  3. # 加载模型
  4. loaded_model = tf.keras.models.load_model('fashion_mnist_model.h5')

七、进阶方向

  1. 迁移学习:使用预训练模型(如MobileNetV2)进行特征提取
    1. base_model = tf.keras.applications.MobileNetV2(input_shape=(224,224,3),
    2. include_top=False,
    3. weights='imagenet')
    4. base_model.trainable = False # 冻结预训练层
  2. 多标签分类:修改输出层为Sigmoid激活,适用于同时标注多个类别的场景
  3. 实时分类:结合OpenCV实现摄像头实时服装识别

八、常见问题与解决方案

  1. 过拟合问题
    • 增加训练数据量
    • 添加L2正则化或Dropout层
    • 早停法(Early Stopping)
      ```python
      from tensorflow.keras.callbacks import EarlyStopping

early_stop = EarlyStopping(monitor=’val_loss’, patience=3)
model.fit(…, callbacks=[early_stop])
```

  1. 训练速度慢

    • 使用GPU加速(tf.config.list_physical_devices('GPU')
    • 减小batch_size(但需平衡内存占用)
  2. 模型性能瓶颈

    • 尝试更深的网络结构(如ResNet)
    • 调整学习率(使用tf.keras.optimizers.Adam(learning_rate=0.0001)

九、总结与学习资源

本文通过Fashion MNIST数据集,系统演示了使用TensorFlow Keras实现服装图像分类的全流程。关键步骤包括数据预处理、CNN模型构建、训练优化和部署。对于进阶学习者,推荐以下资源:

通过实践本文代码,读者可快速掌握Keras机器学习基础,并为后续复杂视觉任务打下坚实基础。

相关文章推荐

发表评论