def Gram_CAM_heatmap(image:torch.Tensor, model:SiameseNetwork=None, sub_network:int=None,
image_size:tuple=None, figname:str=None, figsize:tuple=(3,3)):
'''
Calculates the heatmap for Gram-CAM procedure
code
Parameters
----------
image: requested image
model: Similarity model (Siamese network)
sub_network: requested sub_network 1 or 2
image_size: image size
figname: figure name (optional)
fisize: figure size (optional)
Returns
-------
heatmap
'''
# pull the gradients out of the model
gradients = model.get_activations_gradient(sub_network=1)
# pool the gradients across the channels
pooled_gradients = torch.mean(gradients, dim=[0, 2, 3])
# get the activations of the last convolutional layer
activations = model.get_activations(image).detach()
# weight the channels by corresponding gradients
for i in range(activations.shape[1]):
activations[:, i, :, :] *= pooled_gradients[i]
# average the channels of the activations
heatmap = torch.mean(activations, dim=1).squeeze()
# relu on top of the heatmap
# expression (2) in https://arxiv.org/pdf/1610.02391.pdf
heatmap = torch.where(heatmap > 0, heatmap, 0)
# normalize the heatmap
heatmap /= torch.max(heatmap)
# Reshape & Convert Tensor to numpy
heatmap = heatmap.squeeze()
heatmap = heatmap.detach().cpu().numpy()
# Resize Heatmap
heatmap = cv2.resize(heatmap, image_size)
# Convert to [0,255]
heatmap = np.uint8(255 * heatmap)
if figname is not None:
plt.figure(figsize=figsize);
fig = plt.imshow(heatmap);
fig.axes.get_xaxis().set_visible(False)
fig.axes.get_yaxis().set_visible(False)
plt.savefig(figname, dpi=300, format='png',
bbox_inches='tight', pad_inches=0.1,
facecolor='auto', edgecolor='auto',
backend=None,
)
return heatmap
Yes, you can use this function to compute a heatmap for a single-channel image, but you might need to make a few adjustments depending on how the Siamese network you're using is handling single-channel input images. Typically, models like ResNet expect 3-channel (RGB) images, so you'll need to ensure that you properly adjust the input shape.
Here are some considerations and steps you might take to adapt the function for single-channel images:
Input Channel Adjustment: If your model (i.e., the feature extraction part of your Siamese network) requires a 3-channel image, you might need to convert your single-channel image to a 3-channel image by duplicating the single channel across the RGB channels.
python
if image.shape[0] == 1: # Check if the image has a single channel
image = image.repeat(3, 1, 1) # Convert to 3-channel by repeating
Model Adaptation: Ensure that the initial convolution layer of your ResNet-based model is capable of accepting single-channel input directly, or that you've adjusted the weights to accommodate for single-channel input. In custom models, this can often be resolved by changing the first layer's input channel to 1 and readjusting the weights accordingly.
Check Model Outputs: Double-check how the SiameseNetwork class is structured and ensure that the methods like get_activations and get_activations_gradient are correctly handling single-channel data.
Visualization: No additional steps are usually necessary for visualization in matplotlib or cv2 for single-channel images, as these inherently handle grayscale data.
By ensuring these adaptations, your function should work appropriately with single-channel images. If you're leveraging the model's internal functionality (like ResNet), verify that it either supports single-channel by default, or that you have implemented necessary changes to support single-channel inputs.
def Gram_CAM_heatmap(image:torch.Tensor, model:SiameseNetwork=None, sub_network:int=None,
image_size:tuple=None, figname:str=None, figsize:tuple=(3,3)):
'''
Calculates the heatmap for Gram-CAM procedure
code
Parameters
----------
image: requested image
model: Similarity model (Siamese network)
sub_network: requested sub_network 1 or 2
image_size: image size
figname: figure name (optional)
fisize: figure size (optional)
Returns
-------
heatmap
'''
# pull the gradients out of the model
gradients = model.get_activations_gradient(sub_network=1)
# pool the gradients across the channels
pooled_gradients = torch.mean(gradients, dim=[0, 2, 3])
# get the activations of the last convolutional layer
activations = model.get_activations(image).detach()
# weight the channels by corresponding gradients
for i in range(activations.shape[1]):
activations[:, i, :, :] *= pooled_gradients[i]
# average the channels of the activations
heatmap = torch.mean(activations, dim=1).squeeze()
# relu on top of the heatmap
# expression (2) in https://arxiv.org/pdf/1610.02391.pdf
heatmap = torch.where(heatmap > 0, heatmap, 0)
# normalize the heatmap
heatmap /= torch.max(heatmap)
# Reshape & Convert Tensor to numpy
heatmap = heatmap.squeeze()
heatmap = heatmap.detach().cpu().numpy()
# Resize Heatmap
heatmap = cv2.resize(heatmap, image_size)
# Convert to [0,255]
heatmap = np.uint8(255 * heatmap)
if figname is not None:
plt.figure(figsize=figsize);
fig = plt.imshow(heatmap);
fig.axes.get_xaxis().set_visible(False)
fig.axes.get_yaxis().set_visible(False)
plt.savefig(figname, dpi=300, format='png',
bbox_inches='tight', pad_inches=0.1,
facecolor='auto', edgecolor='auto',
backend=None,
)
return heatmap