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 from keras.layers.core import Dropout

导入了必要的库,包括操作系统相关的 os 库、数值计算相关的 numpy 库、数据可视化相关的 matplotlib 库、深度学习相关的 tensorflow 库和 keras 库,以及一些需要用到的深度学习层和函数。

  1. 定义训练集和测试集路径 train_dir = 'C:/Users/28938/Desktop/shengdu/Data/train' test_dir = 'C:/Users/28938/Desktop/shengdu/Data/test'

定义了训练集和测试集的路径,这里使用的是绝对路径。

  1. 定义类别标签 class_names = ['MEN_Coats', 'MEN_Hood', 'MEN_Suits', 'WOMEN_Dress', 'WOMEN_Hood']

定义了分类任务中可能的类别标签,共有5类。

  1. 定义图像尺寸和批次大小 img_height = 224 img_width = 224 batch_size = 32

定义了图像的尺寸和每个批次的大小。

  1. 从目录中读取训练集和测试集 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 )

使用 keras 库中的 image_dataset_from_directory 函数从指定目录中读取训练集和测试集,这里需要指定目录路径、验证集的比例、图像尺寸和批次大小等参数。

  1. 定义函数以展示图像 def plotImages(img_arr): fig, axes = plt.subplots(1, 5, figsize=(20,20)) axes = axes.flatten() for img, ax in zip( img_arr, axes): ax.imshow(img) ax.axis('off') plt.tight_layout() plt.show()

定义了一个用于展示图像的函数,可以将多张图像分别显示在一行中。

  1. 定义数据增强器 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), ] )

定义了一个数据增强器,包括随机水平翻转、随机旋转和随机缩放等操作,可以防止过拟合。

  1. 定义模型输入 input_shape = (img_height, img_width, 3)

定义了模型的输入尺寸。

  1. 建立模型 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.Dropout(0.2), layers.Conv2D(64, 3, padding='same', activation='relu'), layers.MaxPooling2D(), layers.Dropout(0.2), 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)) ])

建立了一个卷积神经网络模型,包括了卷积层、池化层、扁平化层和全连接层等。

  1. 编译模型 model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy'])

编译模型,指定了优化器、损失函数和评价指标等。

  1. 打印模型结构 model.summary()

打印出了模型的结构信息。

  1. 显示前5张图像 plt.figure(figsize=(10, 10)) for images, labels in train_ds.take(1): for i in range(5): ax = plt.subplot(5, 5, i + 1) plt.imshow(images[i].numpy().astype("uint8")) plt.title(class_names[labels[i]]) plt.axis("off")

显示了训练集中前5张图像,并标注了相应的类别。

  1. 设定训练参数 epochs = 15

设定了训练轮数。

  1. 开始训练模型 history = model.fit(train_ds, validation_data=val_ds, epochs=epochs, batch_size=batch_size)

开始训练模型,并将训练集和验证集传入模型中进行训练。

  1. 对模型进行评估 test_loss, test_acc = model.evaluate(test_ds) print('Test accuracy:', test_acc)

对模型进行评估,计算测试集上的准确率。

  1. 对模型进行预测 predictions = model.predict(test_ds)

使用训练好的模型对测试集进行预测,得到预测结果。

  1. 绘制模型准确度和损失随时间变化的曲线 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()

绘制了模型在训练过程中准确度和损失随时间变化的曲线

import osimport numpy as npimport matplotlibpyplot as pltimport tensorflow as tffrom tensorflow import kerasfrom tensorflowkeras import layersfrom keraslayerscore import Dropout# 定义训练集和测试集路径train_dir

原文地址: https://www.cveoy.top/t/topic/gYFT 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录