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

# Define the paths to the training and test datasets
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 size and batch size
img_height = 224
img_width = 224
batch_size = 32

# Load the training and test datasets from 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 function to plot images
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()

# Define the data augmentation layer
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 model
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))
])

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

# Print the model summary
model.summary()

# Display the first 5 images from the training dataset
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')

# Set the training parameters
epochs = 20

# Train the model
batch_size = 16
history = model.fit(train_ds, validation_data=val_ds, epochs=epochs, batch_size=batch_size)

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

# Make predictions on the test dataset
predictions = model.predict(test_ds)

# Plot the training and validation accuracy and loss
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()

This code implements an image classification model using TensorFlow and Keras. Here is a breakdown of each part:

  1. Import necessary libraries:

    • os: For file path manipulation.
    • numpy: For numerical operations.
    • matplotlib.pyplot: For plotting graphs.
    • tensorflow: For building and training the model.
    • tensorflow.keras: Keras API for TensorFlow.
    • tensorflow.keras.layers: Keras layers for building the model.
    • keras.layers.core: Additional Keras layers.
  2. Define dataset paths and class labels:

    • train_dir: Path to the training dataset directory.
    • test_dir: Path to the test dataset directory.
    • class_names: List of class labels for the images.
  3. Define image size and batch size:

    • img_height: Height of the input images.
    • img_width: Width of the input images.
    • batch_size: Number of images processed in each batch during training.
  4. Load training and test datasets:

    • keras.preprocessing.image_dataset_from_directory(): Loads images from a directory and creates a tf.data.Dataset object.
    • validation_split: Fraction of the training dataset to be used as validation data.
    • subset: Specifies whether to load the training or validation subset.
    • seed: Random seed for consistent data splitting.
    • image_size: Resizes the images to the specified size.
    • batch_size: Sets the batch size for the dataset.
  5. Define a function to plot images:

    • plotImages(): Takes an array of images and displays them in a grid.
  6. Define data augmentation layer:

    • keras.Sequential(): Creates a sequential model for data augmentation.
    • RandomFlip(): Randomly flips the images horizontally.
    • RandomRotation(): Randomly rotates the images by a specified angle.
    • RandomZoom(): Randomly zooms the images by a specified factor.
  7. Define the model input shape:

    • input_shape: Specifies the shape of the input images to the model.
  8. Create the model:

    • keras.Sequential(): Creates a sequential model.
    • layers.Conv2D(): 2D convolutional layers for extracting features from the images.
    • layers.MaxPooling2D(): Max pooling layers to downsample feature maps.
    • layers.Dropout(): Dropout layers to prevent overfitting.
    • layers.Flatten(): Flattens the feature maps before passing them to the dense layers.
    • layers.Dense(): Dense (fully connected) layers for classification.
  9. Compile the model:

    • model.compile(): Defines the optimizer, loss function, and metrics to use during training.
    • optimizer: Optimizes the model's weights during training.
    • loss: Measures the error between the model's predictions and the actual labels.
    • metrics: Measures the model's performance, e.g., accuracy.
  10. Print the model summary:

  • model.summary(): Prints the model architecture, including the number of parameters.
  1. Display example images:
  • Displays the first 5 images from the training dataset with their corresponding labels.
  1. Set training parameters:
  • epochs: Number of training epochs.
  1. Train the model:
  • model.fit(): Trains the model on the training data.
  • validation_data: Validation dataset used to monitor model performance during training.
  • epochs: Number of epochs to train for.
  • batch_size: Batch size for training.
  1. Evaluate the model:
  • model.evaluate(): Evaluates the model on the test dataset.
  • test_loss: Loss on the test dataset.
  • test_acc: Accuracy on the test dataset.
  1. Make predictions:
  • model.predict(): Generates predictions on the test dataset.
  1. Plot training and validation accuracy and loss:
  • Plots the training and validation accuracy and loss over epochs.
  • This helps visualize the model's performance during training and identify overfitting or underfitting.

This code provides a complete framework for image classification using TensorFlow and Keras. You can adapt it to your specific dataset and task by modifying the dataset paths, class labels, model architecture, and training parameters. Remember to properly prepare and organize your image dataset before running the code.

Image Classification Model using TensorFlow and Keras

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

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