...

CNN Feature Visualization with Activation Maximization in Keras (VGG16)

CNN Feature Visualization with Activation Maximization

CNN Feature Visualization with Activation Maximization

This post shows how to visualize what a convolutional neural network “imagines” for a target class using Activation Maximization.
We will generate a synthetic image that maximally activates the “Persian cat” neuron of a pre-trained VGG16 model.
The method helps you interpret CNNs, validate model behavior, and create compelling teaching visuals.
We will use TensorFlow Keras, tf-keras-vis, and OpenCV in a clean, reproducible pipeline.
Our primary SEO focus is CNN feature visualization, which balances demand and competition while matching readers’ intent.

You can find the link for the video tutorial here : https://www.youtube.com/watch?v=5J_b_GxnUBU

You can find the full code here : https://ko-fi.com/s/d62d70033b

You can find more similar tutorials in my blog posts page here : https://eranfeit.net/blog/

Here is the Code :

Environment and Model Setup

In this part you install or upgrade dependencies, import libraries, load the VGG16 model with ImageNet weights, print the architecture, and prepare a model_modifier that switches the final activation to linear for optimization.


Keeping include_top=True preserves the classifier so we can directly maximize a class score.

### Ensure the visualization toolkit and TensorFlow are available and up to date. # pip install --upgrade tf-keras-vis tensorflow  ### Import NumPy for array handling. import numpy as np  ### Import TensorFlow for deep learning operations. import tensorflow as tf  ### Import the pre-trained VGG16 model and alias for readability. from tensorflow.keras.applications.vgg16 import VGG16 as Vgg16Model  ### Load VGG16 with ImageNet weights and keep the classification head for class scoring. model = Vgg16Model(weights='imagenet', include_top=True)  ### Print the model summary to confirm architecture and parameter counts. print (model.summary())  ### Prepare a function that modifies the model before visualization. ### We change the final softmax to linear to expose raw logits for maximization. # define a function to modify the model # we will change the softmax to a linear function def model_modifier(modl):     ### Set the last layer activation to linear to make optimization well behaved.     modl.layers[-1].activation = tf.keras.activations.linear  # All the layers except the last one will have activation=linear 

You can find the full code here : https://ko-fi.com/s/d62d70033b

You verified the environment, loaded a pre-trained classifier, and ensured the output activation is suitable for activation maximization.
This prepares the model for stable optimization toward a specific class.

Build the Activation Maximization Pipeline

Here you create the ActivationMaximization object, define a loss that targets the “Persian cat” class index, run the optimizer, and convert the resulting image to uint8 for display and saving.
Progress printing helps monitor the iterations.

### Import the activation maximization utility that performs gradient-based optimization on the input. # create an object instance of Acticvation maximization class from tf_keras_vis.activation_maximization import ActivationMaximization  ### Instantiate the visualizer with our model and the modifier. ### clone=True duplicates the model so the original instance remains unchanged. activation_maximization = ActivationMaximization(model,                                                 model_modifier,                                                 clone=True)  # clone means , duplicate the model and not update the current one  ### Define a loss that returns the logit for the target ImageNet class. ### We will maximize the score for the Persian cat class. # Now , We will define a loss function that maximize a specific class. # leats maximize the class of "Persian cat" , class no. 283 # https://deeplearning.cms.waikato.ac.nz/user-guide/class-maps/IMAGENET/ def loss(output):     ### Return the score for class index 283 which corresponds to Persian cat.     return output[:, 283]  ### Import a callback to print progress at intervals. from tf_keras_vis.utils.callbacks import Print  ### Run activation maximization to synthesize an image that maximizes the target class score. ### The callback prints status every 50 iterations for transparency. # visual the class activation = activation_maximization(loss,                                     callbacks=[Print(interval=50)]    )  ### Retrieve the synthesized image from the result list and convert to 8-bit for rendering. #lets grab the image after running the process image = activation[0].astype(np.uint8) 

You can find the full code here : https://ko-fi.com/s/d62d70033b

You targeted a specific class with a simple loss and let tf-keras-vis optimize a canvas image toward high activation.
The output is a synthetic image reflecting what the network associates with the Persian cat concept.

Post-processing and Display with OpenCV

Finally, you convert color space from RGB to BGR for OpenCV, upscale the visualization for clarity, and display it in a window.
This makes the result presentation-ready for notebooks, slides, or blog images.

### Import OpenCV for color conversion, resizing, and display. # show the image using OpenCv import cv2  ### Convert the image from RGB to BGR because OpenCV expects BGR by default. # change the image from RGB to BGR imageCV = cv2.cvtColor(image , cv2.COLOR_RGB2BGR)  ### Define the upscaling percentage to view more detail comfortably. # enlarge the image scale_percent = 200  ### Compute the new width using the chosen scale. w = int(imageCV.shape[1]* scale_percent / 100)  ### Compute the new height using the chosen scale. h = int(imageCV.shape[0]* scale_percent / 100)  ### Package the target dimensions for the resize function. dim = (w, h)  ### Resize the image using an area-based interpolator for smooth scaling. resized = cv2.resize(imageCV, dim , interpolation=cv2.INTER_AREA)  ### Display the synthesized class visualization in a window titled "Persian Cat". cv2.imshow("Persian Cat",resized )  ### Keep the window open until a key is pressed. cv2.waitKey(0) 

You can find the full code here : https://ko-fi.com/s/d62d70033b

You prepared the synthesized image for display and scaled it to highlight fine textures.
Your activation maximization pipeline is complete and ready to reuse for any ImageNet class.

CNN Feature Visualization with Activation Maximization
CNN Feature Visualization with Activation Maximization
CNN Feature Visualization with Activation Maximization

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