图像分类模型构建与训练:TensorFlow实战
图像分类模型构建与训练:TensorFlow 实战
本代码演示了使用 TensorFlow 和 Keras 构建一个图像分类模型,并使用预处理、数据增强、模型训练、评估和可视化等技术进行模型训练和评估。
1. 导入库
import os
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
2. 定义数据路径
# 定义训练集和测试集路径
train_dir = 'C:/Users/28938/Desktop/shengdu/Data/train'
test_dir = 'C:/Users/28938/Desktop/shengdu/Data/test'
3. 定义类别标签
# 定义类别标签
class_names = ['MEN_Coats', 'MEN_Hood', 'MEN_Suits', 'WOMEN_Dress', 'WOMEN_Hood']
4. 定义图像尺寸和批次大小
# 定义图像尺寸和批次大小
img_height = 224
img_width = 224
batch_size = 32
5. 读取训练集和测试集
# 从目录中读取训练集和测试集
train_ds = keras.preprocessing.image_dataset_from_directory(
train_dir,
validation_split=0.2,
subset='training',
seed=42,
image_size=(img_height, img_width),
batch_size=batch_size
)
val_ds = keras.preprocessing.image_dataset_from_directory(
train_dir,
validation_split=0.2,
subset='validation',
seed=42,
image_size=(img_height, img_width),
batch_size=batch_size
)
test_ds = keras.preprocessing.image_dataset_from_directory(
test_dir,
seed=42,
image_size=(img_height, img_width),
batch_size=batch_size
)
6. 定义数据增强器
# 定义数据增强器
data_augmentation = keras.Sequential(
[
layers.experimental.preprocessing.RandomFlip('horizontal', input_shape=(img_height, img_width, 3)),
layers.experimental.preprocessing.RandomRotation(0.1),
layers.experimental.preprocessing.RandomZoom(0.1),
]
)
7. 定义模型输入
# 定义模型输入
input_shape = (img_height, img_width, 3)
8. 建立模型
# 建立模型
model = keras.Sequential([
data_augmentation,
layers.experimental.preprocessing.Rescaling(1./255),
layers.Conv2D(32, 3, padding='same', activation='relu', input_shape=input_shape),
layers.MaxPooling2D(),
layers.Conv2D(64, 3, padding='same', activation='relu'),
layers.MaxPooling2D(),
layers.Conv2D(128, 3, padding='same', activation='relu'),
layers.MaxPooling2D(),
layers.Dropout(0.2),
layers.Flatten(),
layers.Dense(256, activation='relu'),
layers.Dense(len(class_names))
])
9. 编译模型
# 编译模型
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
10. 打印模型结构
# 打印模型结构
model.summary()
11. 设定训练参数
# 设定训练参数
epochs = 10
batch_size = 16
12. 训练模型
history = model.fit(train_ds, validation_data=val_ds, epochs=epochs, batch_size=batch_size)
13. 评估模型
# 对模型进行评估
test_loss, test_acc = model.evaluate(test_ds)
print('Test accuracy:', test_acc)
14. 模型预测
# 对模型进行预测
predictions = model.predict(test_ds)
15. 绘制模型准确度和损失曲线
# 绘制模型准确度和损失随时间变化的曲线
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs_range = range(epochs)
plt.figure(figsize=(8, 8))
plt.subplot(2, 1, 1)
plt.plot(epochs_range, acc, label='Training Accuracy')
plt.plot(epochs_range, val_acc, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(2, 1, 2)
plt.plot(epochs_range, loss, label='Training Loss')
plt.plot(epochs_range, val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()
代码解释
- 导入必要的库:
os、numpy、matplotlib.pyplot、tensorflow和keras。 - 定义训练集和测试集路径。
- 定义类别标签。
- 定义图像尺寸和批次大小。
- 从目录中读取训练集和测试集,包括训练集、验证集和测试集。
- 定义数据增强器。
- 定义模型输入。
- 建立模型,包括数据增强、归一化、卷积层、池化层、Dropout 层、全连接层和输出层。
- 编译模型,包括损失函数、优化器和评价指标。
- 打印模型结构。
- 设定训练参数,包括训练轮数和批次大小。
- 训练模型,包括训练集和验证集。
- 对模型进行评估,包括测试集准确度和损失。
- 对模型进行预测。
- 绘制模型准确度和损失随时间变化的曲线,包括训练集和验证集的准确度和损失。
本代码提供了一个简单的图像分类模型构建和训练的示例,你可以根据自己的需求进行调整和扩展。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/oup4 著作权归作者所有。请勿转载和采集!