Forward hook method for visualising

TypeError: Invalid shape (14, 14, 480) for image data got this error
my code is this

from google.colab.patches import cv2_imshow

!pip install efficientnet_pytorch

import cv2

import numpy as np

Load and resize the image

image_path = ‘/content/cat.jpg’

image = cv2.imread(image_path)

image = cv2.resize(image, (224,224)) # Resize to match EfficientNet input size

Convert image to float32 and normalize

image = image.astype(np.float32) / 255.0

Expand image dimensions to match model input shape

image = np.expand_dims(image, axis=0)

import matplotlib.pyplot as plt

import torch

from efficientnet_pytorch import EfficientNet

Load your pretrained EfficientNet model

model = EfficientNet.from_pretrained(‘efficientnet-b0’)

Print the model architecture to see the available modules and their names

print(model)

Alternatively, you can inspect the model’s _modules dictionary

print(model._modules)

import matplotlib.pyplot as plt

import torch

from efficientnet_pytorch import EfficientNet

Load your pretrained EfficientNet model

model = EfficientNet.from_pretrained(‘efficientnet-b0’)

Define the forward hook function to capture intermediate layer outputs

intermediate_outputs = []

def hook(module, input, output):

intermediate_outputs.append(output)

Register the forward hook on the conv6 layer

model._blocks[6]._depthwise_conv.register_forward_hook(hook)

Pass the image through the model to trigger the forward hook and capture the intermediate layer output

model(image)

Visualize the captured intermediate layer output as a feature map

feature_map = intermediate_outputs[0][0].detach().numpy()

Normalize the feature map for visualization

feature_map -= feature_map.mean()

feature_map /= feature_map.std()

feature_map *= 64

feature_map += 128

feature_map = np.clip(feature_map, 0, 255).astype(‘uint8’)

Display the intermediate layer output

plt.figure()

plt.title(‘Conv6 Layer Output’)

plt.imshow(feature_map.transpose(1, 2, 0))

plt.axis(‘off’)

plt.show()

The intermediate output in the shape [14, 14, 480] (after permutation) is not a valid image format since it has 480 channels as the error message explains.
If you want to visualize each channel separately, use a loop and index the channel dimension.