I am trying to implement saliency_map. I am using DenseNet121 and I fit the model. cose snippet:
for train_index, val_index in skf.split(X_train, y_train):
X_train_fold, X_val_fold = X_train[train_index], X_train[val_index]
y_train_fold, y_val_fold = y_train[train_index], y_train[val_index]
i = i 1;
print("Fold:",i)
DenseNet121 = model.fit(datagen.flow(X_train_fold, y_train_fold, batch_size=32), epochs=10, verbose=1,validation_data=(X_val_fold,y_val_fold) ,callbacks=[ es_callback])
code snippet of saliency_map:
# Function to generate saliency maps
def generate_saliency_map(model, X, y):
# Convert numpy arrays to TensorFlow tensors
X = tf.convert_to_tensor(X)
y = tf.convert_to_tensor(y)
X = tf.expand_dims(X, axis=0)
with tf.GradientTape() as tape:
tape.watch(X)
output_tensor = model(X)
output_class = tf.math.argmax(output_tensor, axis=-1)
one_hot = tf.one_hot(output_class, depth=4)
loss = tf.reduce_sum(output_tensor * one_hot, axis=-1)
grads = tape.gradient(loss, X)
saliency_map = tf.reduce_max(tf.abs(grads), axis=-1)
return saliency_map
# Generate saliency maps for a few test images
for i in range(5):
# print(X_test[i].shape)
saliency_map = generate_saliency_map(DenseNet121, X_test[i], y_test[i])
plt.imshow(saliency_map, cmap='gray')
plt.show()
Error: TypeError: 'History' object is not callable
I am attaching a picture for better understanding of the error.
CodePudding user response:
This line overwrite your previous Keras model with an History object.
DenseNet121 = model.fit(datagen.flow(X_train_fold, y_train_fold, batch_size=32), epochs=10, verbose=1,validation_data=(X_val_fold,y_val_fold) ,callbacks=[ es_callback])
If you want to store the history of the training you can declare a new variable
history = model.fit(datagen.flow(X_train_fold, y_train_fold, batch_size=32), epochs=10, verbose=1,validation_data=(X_val_fold,y_val_fold) ,callbacks=[es_callback])
CodePudding user response:
You need to use model
as argument instead of DenseNet121
in generate_saliency_map
as DenseNet121
holds the history object not the model. Something like this,
# Generate saliency maps for a few test images
for i in range(5):
# print(X_test[i].shape)
saliency_map = generate_saliency_map(model, X_test[i], y_test[i])
plt.imshow(saliency_map, cmap='gray')
plt.show()