import os import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers

Define the paths to the training and test sets

train_dir = 'C:/Users/28938/Desktop/shengdu/Data/train' test_dir = 'C:/Users/28938/Desktop/shengdu/Data/test'

Define the class labels

class_names = ['MEN_Coats', 'MEN_Hood', 'MEN_Suits', 'WOMEN_Dress', 'WOMEN_Hood']

Define the image dimensions and batch size

img_height = 224 img_width = 224 batch_size = 32

Load the training and test sets from the directories

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 )

Define a data augmentation pipeline

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), ])

Define the input shape for the model

input_shape = (img_height, img_width, 3)

Create the CNN model

model = keras.Sequential([ data_augmentation, layers.experimental.preprocessing.Rescaling(1./255), layers.Conv2D(16, 3, padding='same', activation='relu', input_shape=input_shape), layers.MaxPooling2D(), layers.Conv2D(32, 3, padding='same', activation='relu'), layers.MaxPooling2D(), layers.Conv2D(64, 3, padding='same', activation='relu'), layers.MaxPooling2D(), layers.Dropout(0.2), layers.Flatten(), layers.Dense(128, activation='relu'), layers.Dense(len(class_names)) ])

Compile the model

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

Print the model summary

model.summary()

Set the number of training epochs

epochs = 10

Train the model

history = model.fit(train_ds, validation_data=val_ds, epochs=epochs)

Evaluate the model on the test set

test_loss, test_acc = model.evaluate(test_ds) print('Test accuracy:', test_acc)

Make predictions on the test set

predictions = model.predict(test_ds)

Plot the training and validation accuracy and loss over time

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()

Image Classification with TensorFlow Keras: A CNN Model for Clothing Recognition

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

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