...

How to classify monkeys images using convolutional neural network , Keras tuner hyper parameters , and transfer learning ? (part4)

Transfer Learning Fine-tune a Pretrained VGG16

Welcome to our comprehensive image classification tutorial series! In this tutorial playlist, consisting of five informative videos, we will guide you through the entire process of classifying monkey species in images, utilizing vgg16 transfer learning.

This is part of our TensorFlow image classification tutorial series!

Each video focuses on a specific aspect of the process, providing you with a well-rounded understanding of the subject matter. Join us as we cover data preparation, classic CNN classification, hyperparameter tuning with Keras Tuner, fine-tuning a pretrained model (VGG16), and exploring the outcome of deep neural network layers in this TensorFlow image classification tutorial, which includes vgg16 transfer learning. Get ready to dive into the world of monkey species classification and enhance your knowledge with practical examples and expert tips.

Video 1: Data Preparation Tutorial:

In the first video of our series, we will walk you through the essential steps of data preparation for monkey species classification. Discover how to download the necessary image data and explore its characteristics. Learn how to preprocess and format the data to ensure it is ready for the subsequent phases of the classification process. By the end of this tutorial, you will have a well-prepared dataset, laying the foundation for accurate and efficient classification.

Link for more info : https://eranfeit.net/how-to-classify-monkeys-images-using-convolutional-neural-network-keras-tuner-hyper-parameters-and-transfer-learning-part1/


Video 2: CNN Classification Tutorial:

Our second video focuses on the fundamental method of classifying monkey species using a Convolutional Neural Network (CNN). Join us as we guide you through the process of writing a CNN model, training it using the prepared dataset, and evaluating its performance. Gain insights into the inner workings of CNNs and witness their effectiveness in accurately classifying monkey species based on image data.

Link for more info : https://eranfeit.net/how-to-classify-monkeys-images-using-convolutional-neural-network-keras-tuner-hyper-parameters-and-transfer-learning-part2/


Video 3: Enhancing Classification with Keras Tuner:

In the third video, we take the CNN classification tutorial to the next level by incorporating Keras Tuner. Discover how to optimize the performance of your CNN model by automatically searching for the best hyperparameters. Learn how to leverage the power of Keras Tuner to fine-tune your model and achieve even more accurate results in classifying monkey species.

Link for more info : https://eranfeit.net/how-to-classify-monkeys-images-using-convolutional-neural-network-keras-tuner-hyper-parameters-and-transfer-learning-part3/

Video 4: Fine-tuning with Pretrained VGG16:

In the fourth video, we explore an alternative approach to image classification by utilizing a pretrained model, specifically VGG16. Join us as we guide you through the process of fine-tuning the VGG16 model for the task of monkey species classification. Learn how to adapt a powerful pretrained model to accurately classify monkey species and leverage its advanced features for improved results

Link for more info : https://eranfeit.net/how-to-classify-monkeys-images-using-convolutional-neural-network-keras-tuner-hyper-parameters-and-transfer-learning-part4/

Video 5: Visualizing Deep Neural Network Layers:

In our fifth and final video, we delve into the fascinating world of model interpretability by exploring the outcome of deep neural network layers. Witness what a trained network “sees” as we dissect the layers and visualize their outputs for a specific class. Gain a deeper understanding of how the network processes and interprets images, providing valuable insights into the classification process.

Link for more info : https://eranfeit.net/what-actually-sees-a-cnn-deep-neural-network-model/


Part 4: Fine-tuning with Pretrained VGG16:

🔧 Discover the power of pretrained models by fine-tuning a VGG16 model for monkey species classification.

In this part we will focus of classify the monkeys images using Transfer learning .
So basically , we will take the pre-trained VGG16 model , get rid of the last layer , and replace and retrain it to our images and required classes.

You can find the link for the video tutorial here : https://youtu.be/p9l9AgiVsqI&list=UULFTiWJJhaH6BviSWKLJUM9sg

You can find the code in this link : https://ko-fi.com/s/8fbd4679f6

Link for my blog : https://eranfeit.net/blog/


Introduction.

This tutorial shows how to build a multi-class image classifier with TensorFlow Keras using VGG16 for transfer learning.
You will set up data augmentation, load images from folders, freeze the pre-trained backbone, add a custom classification head, train the model, save the best checkpoint, and visualize accuracy metrics.


The goal is to provide a clean, copy-paste-ready pipeline that you can adapt to your own dataset with minimal changes.
The example targets a 10-class problem and demonstrates sensible defaults for batch size, epochs, and image size.
By the end, you will have a reproducible script you can run and extend for new projects.

Data Pipeline and Configuration.

This part prepares imports, global parameters, and the image data loaders with augmentation.
It builds robust ImageDataGenerator objects for training and validation, and computes steps per epoch from dataset sizes.

Short summary before the code.
We import required libraries, define image size, classes, batch size, epochs, and patience, and create directory-based data loaders with augmentation for the training set and rescaling for the validation set.
We also compute steps_per_epoch and validation_steps based on dataset sizes.

### Import Dense and Flatten layers for building the final classification head. from keras.layers import Dense , Flatten #-> for the last layers  ### Import the functional Model API to assemble inputs and outputs. from keras.models import Model  ### Import the VGG16 architecture pre-trained on ImageNet. from keras.applications.vgg16 import VGG16  ### Import preprocessing utility for VGG16 if needed for custom pipelines. from keras.applications.vgg16 import preprocess_input  ### Import useful training callbacks like EarlyStopping and ModelCheckpoint. from tensorflow.keras.callbacks import EarlyStopping , ModelCheckpoint  ### Import ImageDataGenerator to stream images from directories with augmentation. from keras.preprocessing.image import ImageDataGenerator  ### Import Sequential in case you build sequential models later. from keras.models import Sequential  ### Import NumPy for numerical operations. import numpy as np   ### Import glob for file pattern matching if needed. from glob import glob   ### Import matplotlib for training curve visualization. import matplotlib.pyplot as plt   ### Import time for optional timing of operations. import time  ### Define a base image edge length. IMG=200  ### Create a height-width tuple for model input. IMG_SIZE = [IMG, IMG]  ### Set the number of output classes for softmax. numOfClasses = 10  ### Choose a reasonable batch size for training. batchSize = 32  ### Set the maximum number of training epochs. EPOCHS = 30  ### Define patience for early stopping if you add it later. PATIENCE=5  ### Define the training images root folder organized by class subfolders. trainMyImagesFolder = "C:/Python-cannot-upload-to-GitHub/10-Monkey-Species/training/training"  ### Define the validation images root folder organized by class subfolders. testMyImagesFolder = "C:/Python-cannot-upload-to-GitHub/10-Monkey-Species/validation/validation"  ### Create a training data generator with pixel rescaling and strong augmentations. train_datagen = ImageDataGenerator(rescale = 1. / 255,                                      rotation_range = 20 ,                                     width_shift_range = 0.2 ,                                     height_shift_range = 0.2 ,                                     shear_range = 0.2 ,                                     zoom_range = 0.2 ,                                     horizontal_flip = True)  ### Build the training iterator that reads images from directories by class. training_set = train_datagen.flow_from_directory(trainMyImagesFolder,                                                 shuffle=True,                                                 target_size=IMG_SIZE,                                                 batch_size=batchSize,                                                 class_mode = 'categorical')  ### Create a validation data generator with only rescaling to measure generalization. test_datagen = ImageDataGenerator(rescale = 1. / 255)  ### Build the validation iterator without shuffling to keep evaluation stable. test_set = test_datagen.flow_from_directory(testMyImagesFolder,                                                 shuffle=False, #### important                                                 target_size=IMG_SIZE,                                                 batch_size=batchSize,                                                 class_mode = 'categorical')  ### Compute steps per epoch as the ceiling of samples divided by batch size. stepsPerEpochs = np.ceil (training_set.samples / batchSize) # round the result up  ### Compute validation steps similarly for the validation iterator. validationSteps =np.ceil (test_set.samples / batchSize)  

You can find the code in this link : https://ko-fi.com/s/8fbd4679f6

Your data pipeline is ready with robust augmentations and consistent rescaling.
The iterators stream batches efficiently and report sample counts that drive steps_per_epoch and validation_steps.

Model Building, Training, Checkpointing, and Charts.

This part configures VGG16 as a frozen feature extractor, adds a Flatten layer and a Dense softmax head, compiles and trains the model with a checkpoint callback, and finally plots training curves.

Short summary before the code.
We load VGG16 without the top, freeze all backbone layers, attach a Flatten and softmax head, compile with categorical cross-entropy, train with ModelCheckpoint enabled, and visualize accuracy over epochs.

### Initialize the VGG16 convolutional base with ImageNet weights and no top classification layers. myVgg = VGG16(input_shape=IMG_SIZE+ [3],             weights='imagenet',             include_top=False) # False means , remove the last fully coneccted layers  ### Optionally inspect the model architecture for debugging and confirmation. #print(myVgg.summary())  ### Freeze all layers in the VGG16 base to use it as a fixed feature extractor. for layer in myVgg.layers:     layer.trainable = False  ### Flatten the convolutional feature maps to a 1D vector for classification. PlusFlattenLayer = Flatten()(myVgg.output)  ### Add the final classification layer with softmax over the defined number of classes. lastPredictionLayer = Dense(numOfClasses, activation='softmax')(PlusFlattenLayer)  ### Assemble the full model by connecting VGG16 inputs to the new classification head. model = Model(inputs=myVgg.input , outputs=lastPredictionLayer)  ### Print a summary to verify layer counts, output shapes, and parameter sizes. print(model.summary())  ### Compile the model with categorical cross-entropy, Adam optimizer, and accuracy metric. model.compile(loss='categorical_crossentropy',             optimizer='Adam',             metrics=['accuracy'] )  ### Define a file path for saving the best model based on validation accuracy. best_model_file = "C:/Python-cannot-upload-to-GitHub/10-Monkey-Species/myTransferLearningMonkeyModel.h5"  ### Configure ModelCheckpoint to keep only the best performing weights during training. bestModel = ModelCheckpoint(best_model_file, monitor='val_accuracy', verbose=1, save_best_only=True)  ### Train the model on the training iterator and validate on the test iterator while saving the best checkpoint. history = model.fit( training_set,                     validation_data = test_set,                     epochs=EPOCHS,                     steps_per_epoch=stepsPerEpochs,                     validation_steps=validationSteps,                     verbose=1,                     callbacks=[bestModel])  ### Retrieve accuracy and loss histories for both training and validation sets. acc = history.history['accuracy'] val_acc = history.history['val_accuracy'] loss = history.history['loss'] val_loss = history.history['val_loss']  ### Create a range object representing actual epoch indices for plotting. actualEpochs = range(len(acc))  ### Print the epoch indices for quick inspection. print("Actual Epochs : "+ str(actualEpochs))  ### Plot training accuracy and validation accuracy across epochs to visualize learning progress. plt.plot(actualEpochs, acc , 'r', label='Training accuracy') plt.plot(actualEpochs, val_acc , 'b', label='Validation accuracy') plt.xlabel('Epoch') plt.ylabel('Accuracy') plt.title('Training and validation accuracy')  ### Render the plot window so you can view the curves. plt.show() 

You can find the code in this link : https://ko-fi.com/s/8fbd4679f6

The model uses VGG16 features and a lightweight classifier head to achieve strong performance with limited data.
The checkpoint ensures you persist the best weights, and the plot makes it easy to spot overfitting or convergence issues.

Connect :

☕ Buy me a coffee — https://ko-fi.com/eranfeit

🖥️ Email : feitgemel@gmail.com

🌐 https://eranfeit.net

🤝 Fiverr : https://www.fiverr.com/s/mB3Pbb

Enjoy,

Eran

error: Content is protected !!
Eran Feit