🎥 TensorFlow Image Classification Tutorial With Keras CNN: Image Classification Tutorial Series: Five Parts 🐵
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.
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. 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/
Video 2: CNN Classification Tutorial:
🔍 In this tutorial we will learn how to classify monkey species using Convolutional Neural Networks (CNN).
We will Discover the process of building, training, and evaluating a CNN model to achieve very good results in monkey species identification.
And last we will you a transfer learning to classify the images differently.
This is the link for part 2: https://youtu.be/FfmE3WWKDgE&list=UULFTiWJJhaH6BviSWKLJUM9sg
You can find more tutorials here : https://eranfeit.net/blog/
You can find the full code here : https://ko-fi.com/s/8fbd4679f6
Introduction
This tutorial shows how to build a complete TensorFlow Keras pipeline for multi-class image classification.
You will define a compact CNN, prepare data with real-time augmentation, train with validation, and persist the best model to disk.
You will also evaluate accuracy and visualize performance across epochs to understand generalization.
The example is configured for ten classes and uses practical callbacks to stabilize results.
All code blocks are ready to copy, run, and adapt to your dataset.
Data Pipeline And Augmentation
This part sets global parameters, prepares directories, and builds training and validation generators with augmentation.
It also computes steps per epoch and defines a checkpoint to save the best model by validation accuracy.
### Install TensorFlow if it is not installed yet. # pip install tensorflow ### Import TensorFlow and Keras utilities for modeling and data processing. import tensorflow as tf ### Import image utilities for potential single-image operations. from tensorflow.keras.preprocessing import image ### Import ImageDataGenerator to stream and augment images from folders. from tensorflow.keras.preprocessing.image import ImageDataGenerator ### Import useful callbacks to control training and save best checkpoints. from tensorflow.keras.callbacks import EarlyStopping , ModelCheckpoint ### Import NumPy for numeric operations and simple math. import numpy as np ### Import time for optional timing or logging. import time ### Import matplotlib for plotting learning curves. import matplotlib.pyplot as plt ### Set the base resolution for image resizing. IMG=200 ### Build a tuple used by generators to resize to the target resolution. IMG_SIZE = [IMG, IMG] ### Define the number of classes in the dataset. numOfClasses = 10 ### Choose a batch size that balances speed and stability. batchSize = 32 ### Set the number of training epochs. EPOCHS = 30 ### Point to the training images directory organized by class subfolders. trainMyImagesFolder = "C:/Python-cannot-upload-to-GitHub/10-Monkey-Species/training/training" ### Point to the validation images directory organized by class subfolders. testMyImagesFolder = "C:/Python-cannot-upload-to-GitHub/10-Monkey-Species/validation/validation" ### Create a training generator with rescaling and rich augmentation to improve generalization. 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) ### Stream training images from folders, shuffle them, and resize to the target size. training_set = train_datagen.flow_from_directory(trainMyImagesFolder, shuffle=True, target_size=IMG_SIZE, batch_size=batchSize, class_mode = 'categorical') ### Create a validation generator with only rescaling to measure unbiased generalization. test_datagen = ImageDataGenerator(rescale = 1. / 255) ### Stream validation images without shuffling for stable evaluation and predictions. 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 proper evaluation each epoch. validationSteps =np.ceil (test_set.samples / batchSize) ### Choose a file path to store the best performing model weights or H5 file. best_model_file = "C:/Python-cannot-upload-to-GitHub/10-Monkey-Species/myCnnMonkeyModel.h5" ### Configure a checkpoint to save the model with the highest validation accuracy. bestModel = ModelCheckpoint(best_model_file, monitor='val_accuracy', verbose=1, save_best_only=True)
You can find the full code here : https://ko-fi.com/s/8fbd4679f6
You now have a clean data pipeline with on-the-fly augmentation and reproducible evaluation.
The checkpoint will keep the best model based on validation accuracy.
CNN Architecture And Compilation
This part defines a compact convolutional neural network and compiles it with categorical cross-entropy and Adam optimizer.
The architecture uses stacked Conv2D and MaxPooling2D layers, followed by dropout regularization and dense layers.
### Build a Sequential CNN with increasing filters for feature extraction. model = tf.keras.models.Sequential ([ ### First convolution extracts low-level features with ReLU activation. tf.keras.layers.Conv2D(32,(3,3), activation='relu', input_shape=(IMG,IMG,3)), ### Max pooling reduces spatial size and provides translation invariance. tf.keras.layers.MaxPooling2D(2,2), ### Second convolution deepens feature maps at the same filter count. tf.keras.layers.Conv2D(32,(3,3), activation='relu'), ### Pooling again to compress features and control overfitting. tf.keras.layers.MaxPooling2D(2,2), ### Third convolution increases filters to learn richer patterns. tf.keras.layers.Conv2D(64,(3,3), activation='relu'), ### Pooling to reduce dimensions and computation. tf.keras.layers.MaxPooling2D(2,2), ### Fourth convolution continues feature extraction at higher capacity. tf.keras.layers.Conv2D(64,(3,3), activation='relu'), ### Pooling prepares for flattening into dense layers. tf.keras.layers.MaxPooling2D(2,2), ### Flatten converts 3D feature maps to a 1D vector for dense layers. tf.keras.layers.Flatten(), ### Dropout randomly deactivates neurons to reduce overfitting. tf.keras.layers.Dropout(0.5), ### Dense layer learns non-linear combinations of features. tf.keras.layers.Dense(512, activation='relu'), ### Output layer uses softmax for multi-class probabilities. tf.keras.layers.Dense(numOfClasses, activation='softmax') ]) ### Print a model summary to verify layer shapes and parameter counts. print(model.summary()) ### Compile the model with categorical cross-entropy, Adam optimizer, and accuracy metric. model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
You can find the full code here : https://ko-fi.com/s/8fbd4679f6
Your CNN is compiled and ready to train on ten classes.
Dropout and pooling layers help control overfitting and stabilize learning.
Training, Evaluation, And Accuracy Plots
This part trains the model with validation, evaluates its performance, and plots training versus validation accuracy to assess generalization.
The best model is saved automatically by the checkpoint configured earlier.
### Fit the model using augmented training data and validation monitoring. history = model.fit ( training_set, validation_data = test_set, epochs = EPOCHS, steps_per_epoch = stepsPerEpochs, validation_steps = validationSteps, verbose=1, callbacks=[bestModel]) ### Evaluate the final model on the validation generator to report metrics. valResults = model.evaluate(test_set) ### Print the numeric results for quick inspection. print(valResults) ### Print the metric names to interpret the results order. print(model.metrics_names) ### Extract accuracy and loss curves from the training history. acc = history.history['accuracy'] ### Extract the validation accuracy curve for comparison. val_acc = history.history['val_accuracy'] ### Extract training loss over epochs. loss = history.history['loss'] ### Extract validation loss over epochs. val_loss = history.history['val_loss'] ### Build a simple range for the number of completed epochs. actualEpochs = range(len(acc)) ### Print the number of epochs to confirm training progression. print("Actual Epochs : "+ str(actualEpochs)) ### Plot training and validation accuracy to visualize learning and generalization. plt.plot(actualEpochs, acc , 'r', label='Training accuracy') ### Add the validation accuracy curve to the same figure. plt.plot(actualEpochs, val_acc , 'b', label='Validation accuracy') ### Label the x-axis with epoch count. plt.xlabel('Epoch') ### Label the y-axis with accuracy percentage. plt.ylabel('Accuracy') ### Add a descriptive title to the chart. plt.title('Training and validation accuracy') ### Display the plot on screen. plt.show()
You can find the full code here : https://ko-fi.com/s/8fbd4679f6
You have trained and evaluated a multi-class classifier with TensorFlow Keras.
You have accuracy curves to diagnose overfitting, underfitting, or stable convergence.
Your best model is saved for later inference or fine-tuning.
Test the model :
Model Loading And Batch Prediction Pipeline.
This section loads the saved transfer learning model, builds a test generator from a directory structure, and produces class predictions for the entire set.
You will also extract the predicted class index for each image to enable later label mapping.
### Import the Keras function to load a pre-trained or fine-tuned model from disk. from keras.models import load_model ### Import TensorFlow to access Keras preprocessing utilities and ensure compatibility. import tensorflow as tf ### Import the image utilities to handle image loading and related helpers if needed. from tensorflow.keras.preprocessing import image ### Import ImageDataGenerator to build batched pipelines directly from folders. from tensorflow.keras.preprocessing.image import ImageDataGenerator ### Import EarlyStopping and ModelCheckpoint in case you extend training or fine-tuning later. from tensorflow.keras.callbacks import EarlyStopping , ModelCheckpoint ### Import NumPy for numerical operations and working with model outputs. import numpy as np ### Import time for optional timing and performance measurements. import time ### Import Matplotlib for visualizing images and predictions later in the workflow. import matplotlib.pyplot as plt ### Import random to sample random images for visualization. import random ### Import glob to list image files across subdirectories easily. import glob ### Define a base image size for resizing all inputs to a common resolution. # Parameters IMG=200 ### Create a size tuple that Keras will expect for target_size in generators. IMG_SIZE = [IMG,IMG] ### Set the number of classes in your model for clarity and potential assertions. NumOfClasses = 10 ### Define a batch size to control memory and throughput during inference. BatchSize = 32 ### Preserve alternative model paths used in previous experiments for reproducibility if needed. #best_model_file = "C:/Python-cannot-upload-to-GitHub/10-Monkey-Species/myCnnMonkeyModel.h5" #best_model_file = "C:/Python-cannot-upload-to-GitHub/10-Monkey-Species/myCnnMonkeyModelHyperParam.h5" #best_model_file = "C:/Python-cannot-upload-to-GitHub/10-Monkey-Species/myCnnMonkeyModelHyperBandParam.h5" ### Choose the best performing transfer learning model saved as an H5 file. best_model_file = "C:/Python-cannot-upload-to-GitHub/10-Monkey-Species/myTransferLearningMonkeyModel.h5" ### Load the Keras model from disk so it is ready for inference. model = load_model(best_model_file) ### Point to the validation folder structured as subdirectories per class. testMyImagesFolder = "C:/Python-cannot-upload-to-GitHub/10-Monkey-Species/validation/validation" ### Create an ImageDataGenerator that rescales pixel values to the [0,1] range. test_datageb = ImageDataGenerator(rescale = 1. /255) ### Build a non-shuffled generator so indices align with file ordering for later comparisons. test_set = test_datageb.flow_from_directory(testMyImagesFolder, shuffle=False, # dont forget target_size = IMG_SIZE, batch_size = BatchSize, class_mode = 'categorical') ### Run batched inference across the entire validation set to get class probabilities per image. predictions = model.predict(test_set) ### The next two debug lines were used during development to inspect output types and arrays. #print(type(predictions)) #print(predictions) ### Convert probability vectors to predicted class indices using argmax across classes. predictionsResults = np.argmax(predictions, axis=1) ### Display the predicted class index for each image to confirm successful inference. print(predictionsResults)
You can find the full code here : https://ko-fi.com/s/8fbd4679f6
You loaded a trained Keras transfer learning model, created a deterministic validation generator, and produced predicted class indices for every image.
These indices are now ready to be translated into human-readable labels.
Label Mapping And Visual Evaluation.
This section reads a labels file with Pandas, cleans the text, maps indices to class names, and displays random images in a grid showing predicted and real labels.
You also get a quick count of correct predictions across the sampled grid for a fast quality signal.
### Import Pandas for reading and cleaning the label mapping file. # lets copy the code from the first tutorial # lets read the monkey_lables.txt file columns = ["Label","Latin Name","Common Name","Train Images","Validation Images"] ### Bring Pandas into the namespace to handle CSV parsing and DataFrame operations. import pandas as pd ### Load the label file, name the columns, and skip the header row if present in the file. df = pd.read_csv("C:/Python-cannot-upload-to-GitHub/10-Monkey-Species/monkey_labels.txt",names=columns,skiprows=1) ### Normalize spacing for the label column to ensure consistent indexing. df['Label'] = df['Label'].str.strip() ### Remove stray tab characters from Latin names that might appear in the source file. df['Latin Name'] = df['Latin Name'].replace("\t","") ### Trim whitespace from Latin names for clean display. df['Latin Name'] = df['Latin Name'].str.strip() ### Trim whitespace from common names for clean display. df['Common Name'] = df['Common Name'].str.strip() ### Use the label column as the DataFrame index to enable direct dictionary-style access. df= df.set_index("Label") ### Print the cleaned DataFrame to verify label integrity and names. print(df) ### Extract a Series mapping from label index to the common name for quick lookups. #lets create a short pandas list of the lables and the common monkey name: monkeyDic = df["Common Name"] ### Print the mapping as a sanity check. print(monkeyDic) ### Define a function that samples random images, compares predictions to ground truth, and plots results. # lets see the images randomly and compare the real label with the predicted label def compareResults(): ### Collect all JPG file paths recursively from the validation directory. image_files = glob.glob(testMyImagesFolder + '/*/*.jpg') ### Choose the number of grid rows for visualization. nrows = 5 ### Choose the number of grid columns for visualization. ncols = 6 ### Compute the total number of images to show. picnum = nrows * ncols ### Create a Matplotlib figure with a grid of subplots sized for readability. fig , ax = plt.subplots(nrows , ncols , figsize=(3*ncols , 3*nrows)) ### Initialize a counter for correctly predicted images within the grid. correct = 0 ### Iterate over the grid positions and fill each with a random image and its labels. for i in range(picnum) : ### Pick a random image path from the pool. x = random.choice(image_files) ### Find the index of that path so we can align with predictions and true classes. xi = image_files.index(x) # get the position of the random image ### Read the image into memory for display. img1 = plt.imread(x) ### Translate the numeric prediction to a common name via the mapping. pred1 = monkeyDic[predictionsResults[xi]] ### Optionally trim the name for compact plotting. pred1 = pred1[:7] ### Translate the true class index to a common name for comparison. real1 = monkeyDic[test_set.classes[xi]] ### Optionally trim the name for compact plotting. real1 = real1[:7] ### Tally correctness for quick accuracy estimation over the sampled grid. if (pred1 == real1 ): correct = correct + 1 ### Build a title string that shows both predicted and real labels. name = 'predicted : {} \nreal: {}'.format(pred1,real1) ### Display the image in the current subplot. plt.imshow(img1) ### Set the subplot title to the label comparison. plt.title(name) ### Move to the next subplot cell and hide axes for a cleaner gallery look. sp = plt.subplot(nrows,ncols, i+1 ) sp.axis('off') # no grid ### Print a quick summary showing how many of the sampled images were correct. print(" ======================================================= ") print("Total : {} correct {} : ".format(picnum , correct)) ### Render the full grid window. plt.show() ### Execute the visualization and comparison routine. # run the function compareResults()
You can find the full code here : https://ko-fi.com/s/8fbd4679f6
You parsed and cleaned label metadata, created a convenient index → name mapping, and built a visual gallery that overlays predicted and true labels.
This delivers instant qualitative feedback plus a quick accuracy count across a random sample
Connect :
☕ Buy me a coffee — https://ko-fi.com/eranfeit
🖥️ Email : feitgemel@gmail.com
🤝 Fiverr : https://www.fiverr.com/s/mB3Pbb
Enjoy,
Eran