Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Animal Image Classification with Transfer Learning: The Ultimate Guide

Image classification is a common and important task in the field of computer vision. Transfer learning is a technique that allows us to leverage pre-trained models on large datasets to solve similar problems with smaller datasets. In this blog post, we will explore how to perform animal image classification using transfer learning with TensorFlow and the InceptionNet model.

Transfer Learning and InceptionNet

Transfer learning is a powerful technique in machine learning, especially in the domain of image classification. It involves taking a pre-trained neural network model and fine-tuning it for a specific task. In this case, we’ll be using the InceptionNet model, which is known for its ability to classify images with high accuracy.

InceptionNet, also known as GoogleNet, is a deep convolutional neural network architecture that has shown remarkable performance on various image classification tasks. It’s known for its inception modules that allow it to capture features at different scales and resolutions within the same network.

Dataset Preparation

Before we dive into the code, you’ll need a dataset of animal images to train and test your model. You can use publicly available datasets like the CIFAR-10, and ImageNet, or create your custom dataset. For simplicity, we’ll assume you have a dataset organized into subfolders, each containing images of a specific animal class.

Also Read: Image Classification: How To Develop Single-Layer Neural Network In PyTorch

Step-by-step Guide for Code Implementation

Let’s move to the step-by-step guidance for image classification code implementation.

Step 1: Importing Libraries

Import necessary libraries used for image classification code implementation using transfer learning.

import numpy as np
import pathlib
import PIL
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt

from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.layers import Conv2D, Dense, MaxPool2D, Flatten
from tensorflow.keras.optimizers import Adam
from keras.applications.inception_v3 import InceptionV3

Step 2: Dataset Preparation

Before diving into the code, you’ll need to prepare your dataset of animal images. Organize your dataset into subfolders containing images of a specific animal class.

# Set the path to your dataset
data_dir = pathlib.Path(‘path to you dataset’)

# Names of the animal
with open('/content/name of the animals.txt') as f:
  animal_class = f.read()
animal_class = animal_class.split('\n')

# Define image size and batch size
img_height = 224
img_width = 224
batch_size = 32

Step 3: Image Preprocessing & Data Augmentation

Data augmentation is a technique used to artificially increase the size of your dataset by applying random transformations to the images during training. We’ll use TensorFlow’s ImageDataGenerator for this purpose.

train_datagen = ImageDataGenerator(
    rescale=1./255,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip=True,
    rotation_range=20,
    width_shift_range=0.2,
    height_shift_range=0.2,
    validation_split=0.2
    )

validation_datagen = ImageDataGenerator(rescale=1./255, validation_split=0.2)

train_generator = train_datagen.flow_from_directory(
        data_dir,
        target_size=(img_height, img_width),
        batch_size=batch_size,
        class_mode='categorical',
        subset='training')

validation_generator = validation_datagen.flow_from_directory(
        data_dir,
        target_size=(img_height, img_width),
        batch_size=batch_size,
        class_mode='categorical',
        subset='validation')

Step 4: Loading the Pre-trained InceptionNet Model

We’ll load the pre-trained InceptionNet model, excluding the top classification layer.

inception_model =  InceptionV3(include_top = False, input_shape = (224,224,3))

Step 5: Freezing Base Model Layers

You can choose to freeze the layers in the base model to prevent them from being updated during training. This is optional and depends on your specific use case.

for layer in inception_model.layers:
  layer.trainable = False

Step 6: Building the Transfer Learning Model

We’ll add our custom layers to the pre-trained InceptionNet model to create the transfer learning model.

Flattened_layer = Flatten()(inception_model.output)
# I have 90 categories of animals so the number of neurons in the Dense layer # is 90. You can change it according to your dataset. 
Output_layer = Dense(90, activation='softmax')(Flattened_layer)
final_model = Model(inputs=inception_model.input, outputs=output_layer)

Step 7: Compiling the Model

Compile the model with the desired optimizer and loss function.

final_model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

Step 8: Training the Model

Train the model on the training dataset. You can modify the number of epochs.

history = final_model.fit(
        train_generator,
        epochs=15,
        validation_data=validation_generator
        )

Step 9: Saving the Trained Model

Finally, save the trained model to a file for future use.

final_model.save('animal_classification_model.h5')

Step 10: Plotting the accuracy and loss

You can plot your results too. Here are my results.

import matplotlib.pyplot as plt

plt.plot(history.history['accuracy'], label='accuracy')
plt.plot(history.history['val_accuracy'], label = 'val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend(loc='lower right')

plt.plot(history.history['loss'], label='loss')
plt.plot(history.history['val_loss'], label = 'val_loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend(loc='lower right')

Step 11: Checking the predictions with some images from input data

You can plot and check model predictions on your input generator data. Here’s my results.

images, labels = validation_generator.next()

for i in range(2):
  plt.imshow(images[i])
  image =  np.expand_dims(images[i],axis=0)
  predicted_label = animal_class[np.argmax(final_model.predict(image))]
  actual_label = animal_class[np.argmax(labels[i])]
  plt.title(f"Actual: {actual_label}\n Predicted: {predicted_label}")
  plt.show()

Step 12: Checking predictions with custom data

Here you can pass an animal image URL in the function and it will print the predicted result. Here, showing the result of one Image URL.

def testing_model_from_url(url):
  img_from_url = Image.open(requests.get(url, stream=True).raw)
  new_image = img_from_url.resize((224,224))
  processed_image = np.asarray(new_image)
  if (processed_image.max())>1:
    processed_image = processed_image/255
  image =  np.expand_dims(processed_image,axis=0)
  predicted_label = animal_class[np.argmax(final_model.predict(image))]
  print(predicted_label)

testing_model_from_url('https://thumbs.dreamstime.com/b/zebra-isolated-white-background-30408343.jpg')

Output:
1/1 [==============================] – 0s 44ms/step
‘zebra’

Conclusion

In this blog post, we’ve demonstrated how to perform animal image classification using transfer learning with TensorFlow and the InceptionNet model. Transfer learning allows you to achieve high accuracy even with a limited dataset by leveraging the knowledge from a larger dataset. You can further fine-tune the model, adjust hyperparameters, and evaluate its performance on test data to ensure it meets your classification needs.

Are you struggling with image classification or other AI/ML projects? Hire AI and ML experts from CodeTrade to help you achieve your goals. Our team of experienced professionals can help you with everything from data labeling to model training and deployment.

The post Animal Image Classification with Transfer Learning: The Ultimate Guide appeared first on Custom Software Development Company.



This post first appeared on Web Development Trends 2023, please read the originial post: here

Share the post

Animal Image Classification with Transfer Learning: The Ultimate Guide

×

Subscribe to Web Development Trends 2023

Get updates delivered right to your inbox!

Thank you for your subscription

×