Image Classification with TensorFlow Keras: A Step-by-Step Guide
import os # 用于操作系统文件路径的处理 import numpy as np # 用于科学计算 import matplotlib.pyplot as plt # 用于数据可视化 import tensorflow as tf # 用于深度学习 from tensorflow import keras # 用于深度学习 from tensorflow.keras import layers # 用于构建深度学习模型
定义训练集和测试集路径
train_dir = 'C:/Users/28938/Desktop/shengdu/Data/train' test_dir = 'C:/Users/28938/Desktop/shengdu/Data/test'
定义类别标签
class_names = ['MEN_Coats', 'MEN_Hood', 'MEN_Suits', 'WOMEN_Dress', 'WOMEN_Hood']
定义图像尺寸和批次大小
img_height = 224 img_width = 224 batch_size = 32
从目录中读取训练集和测试集
train_ds = keras.preprocessing.image_dataset_from_directory( train_dir, validation_split=0.2, # 将20%的数据作为验证集 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 )
定义数据增强器,用于增强训练集数据
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), # 随机缩放 ] )
定义模型输入
input_shape = (img_height, img_width, 3)
建立模型
model = keras.Sequential([ data_augmentation, # 数据增强器 layers.experimental.preprocessing.Rescaling(1./255), # 将像素值缩放到0到1之间 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), # Dropout层,防止过拟合 layers.Flatten(), # 将多维张量展平为一维张量 layers.Dense(256, activation='relu'), # 全连接层 layers.Dense(len(class_names)) # 输出层,输出每个类别的概率 ])
编译模型
model.compile(optimizer='adam', # Adam优化器 loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), # 多分类交叉熵损失函数 metrics=['accuracy']) # 评估指标
打印模型结构
model.summary()
设定训练参数
epochs = 10 batch_size = 16
训练模型
history = model.fit(train_ds, validation_data=val_ds, epochs=epochs, batch_size=batch_size)
对模型进行评估
test_loss, test_acc = model.evaluate(test_ds) print('Test accuracy:', test_acc)
对模型进行预测
predictions = model.predict(test_ds)
绘制模型准确度和损失随时间变化的曲线
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() # 显示绘制的图像
AI 优化版
原文地址:https://www.cveoy.top/t/topic/ouqg 著作权归作者所有。请勿转载和采集!