How to debug the gradcam model implementation #157674
Unanswered
cruelsummer1
asked this question in
Programming Help
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
error at line "pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2))"
below is the whole codes.
! mkdir ~/.kaggle
from google.colab import drive
drive.mount('/content/drive')
!cp /content/drive/MyDrive/kaggle.json ~/.kaggle/
! chmod 600 ~/.kaggle/kaggle.json
! kaggle datasets download francismon/curated-colon-dataset-for-deep-learning
! unzip curated-colon-dataset-for-deep-learning.zip
import tensorflow as tf
from tensorflow import keras
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import cv2
import tensorflow.keras.backend as K
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Conv2D
#!pip install --upgrade tensorflow
print(tf.version)
Define class labels
species = ['Normal', 'Polyps']
Load your model
model = tf.keras.models.load_model('/content/drive/MyDrive/InceptionV3_medical_image_classifier.keras')
Now model.inputs and model.output are defined!# ❗ Call the model once to build its graph
img_path = '/content/test/2_polyps/test_polyps_ (137).jpg'
Preprocess image
img = Image.open(img_path).convert("RGB")
img_resized = img.resize((299, 299))
pixels = np.asarray(img_resized, dtype='float32') /255.0
input_tensor = np.expand_dims(pixels, axis=0) #To match the model's expected input shape
#input_tensor = tf.convert_to_tensor(input_tensor) # Make sure it's a Tensor
_ = model.predict(input_tensor) # Force model to build and make prediction
Make prediction
preds = model.predict(input_tensor)
print(species[np.argmax(preds[0])])
predicted_class = np.argmax(preds[0])
print("Predicted class:", species[predicted_class])
Find the InceptionV3 layer within your model
inception_v3_layer = model.get_layer('inception_v3')
Check model configuration
print(model.get_config())
for layer in inception_v3_layer.layers:
print(layer.name)
for layer in reversed(inception_v3_layer.layers):
if 'conv' in layer.name or 'mixed' in layer.name:
print(f"Selected layer: {layer.name}")#As soon as it finds one, it selects that layer as the target_layer and stops (break).
target_layer = layer
break
#Safety check
if inception_v3_layer is None:
raise ValueError("No Conv2D layer found in the InceptionV3 sub-model")
model.summary() # Check for 'mixed10' or similar
last_conv_layer = target_layer
with tf.GradientTape() as tape:
Compute heatmap
heatmap = tf.reduce_mean(tf.multiply(pooled_grads, last_conv_layer_out), axis=-1)
heatmap = np.maximum(heatmap, 0)
heatmap /= np.max(heatmap)
Resize and overlay
heatmap = cv2.resize(heatmap, (299, 299))
raw_img = Image.open(img_path).resize((299, 299))
heatmap_colored = cv2.applyColorMap(np.uint8(255 * heatmap), cv2.COLORMAP_JET)
superimposed = cv2.addWeighted(np.array(raw_img), 0.6, heatmap_colored, 0.4, 0)
Display
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.imshow(raw_img)
plt.title("Original")
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(superimposed)
plt.title("Grad-CAM")
plt.axis('off')
plt.show()
Beta Was this translation helpful? Give feedback.
All reactions