I have imported the Vit-b32 model and fine-tuned it to perform classification task on echo images. Now I want to visualize the attention maps so that I can know on which part of the image the model is focusing for doing the classification task. But I am unable to do it and I am getting an error when I am trying to visualize the attention maps after fine-tuning the model. Below is the code:
!pip install --quiet vit-keras
from vit_keras import vit
vit_model = vit.vit_b32(
image_size = IMAGE_SIZE,
activation = 'softmax',
pretrained = True,
include_top = False,
pretrained_top = False,
classes = 3)
When I try yo visualize the attention map without any finetuning then it is working without any error:
from vit_keras import visualize
x = test_gen.next()
image = x[0]
attention_map = visualize.attention_map(model = vit_model, image = image)
# Plot results
fig, (ax1, ax2) = plt.subplots(ncols = 2)
ax1.axis('off')
ax2.axis('off')
ax1.set_title('Original')
ax2.set_title('Attention Map')
_ = ax1.imshow(image)
_ = ax2.imshow(attention_map)
Now in the below code I have added some classification layers to the model and fine-tuned it:
model = tf.keras.Sequential([
vit_model,
tf.keras.layers.Flatten(),
tf.keras.layers.BatchNormalization(),
tf.keras.layers.Dense(11, activation = tfa.activations.gelu),
tf.keras.layers.BatchNormalization(),
tf.keras.layers.Dense(3, 'softmax')
],
name = 'vision_transformer')
model.summary()
Below is the output of the above cell:
> Model: "vision_transformer"
> _________________________________________________________________ Layer (type) Output Shape Param #
> ================================================================= vit-b32 (Functional) (None, 768) 87455232
> _________________________________________________________________ flatten_1 (Flatten) (None, 768) 0
> _________________________________________________________________ batch_normalization_2 (Batch (None, 768) 3072
> _________________________________________________________________ dense_2 (Dense) (None, 11) 8459
> _________________________________________________________________ batch_normalization_3 (Batch (None, 11) 44
> _________________________________________________________________ dense_3 (Dense) (None, 3) 36
> ================================================================= Total params: 87,466,843 Trainable params: 87,465,285 Non-trainable
> params: 1,558
> _________________________________________________________________
Now I have trained the model on my own medical dataset:
learning_rate = 1e-4
optimizer = tfa.optimizers.RectifiedAdam(learning_rate = learning_rate)
model.compile(optimizer = optimizer,
loss = tf.keras.losses.CategoricalCrossentropy(label_smoothing = 0.2),
metrics = ['accuracy'])
STEP_SIZE_TRAIN = train_gen.n // train_gen.batch_size
STEP_SIZE_VALID = valid_gen.n // valid_gen.batch_size
reduce_lr = tf.keras.callbacks.ReduceLROnPlateau(monitor = 'val_accuracy',
factor = 0.2,
patience = 2,
verbose = 1,
min_delta = 1e-4,
min_lr = 1e-6,
mode = 'max')
earlystopping = tf.keras.callbacks.EarlyStopping(monitor = 'val_accuracy',
min_delta = 1e-4,
patience = 5,
mode = 'max',
restore_best_weights = True,
verbose = 1)
checkpointer = tf.keras.callbacks.ModelCheckpoint(filepath = './model.hdf5',
monitor = 'val_accuracy',
verbose = 1,
save_best_only = True,
save_weights_only = True,
mode = 'max')
callbacks = [earlystopping, reduce_lr, checkpointer]
model.fit(x = train_gen,
steps_per_epoch = STEP_SIZE_TRAIN,
validation_data = valid_gen,
validation_steps = STEP_SIZE_VALID,
epochs = EPOCHS,
callbacks = callbacks)
model.save('model.h5', save_weights_only = True)
After training when I am trying to visualize the attention map of the model, it is showing error:
from vit_keras import visualize
x = test_gen.next()
image = x[0]
attention_map = visualize.attention_map(model = model, image = image)
# Plot results
fig, (ax1, ax2) = plt.subplots(ncols = 2)
ax1.axis('off')
ax2.axis('off')
ax1.set_title('Original')
ax2.set_title('Attention Map')
_ = ax1.imshow(image)
_ = ax2.imshow(attention_map)
Below is the following error:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-13-f208f2d2b771> in <module>
4 image = x[0]
5
----> 6 attention_map = visualize.attention_map(model = model, image = image)
7
8 # Plot results
/opt/conda/lib/python3.7/site-packages/vit_keras/visualize.py in attention_map(model, image)
14 """
15 size = model.input_shape[1]
---> 16 grid_size = int(np.sqrt(model.layers[5].output_shape[0][-2] - 1))
17
18 # Prepare the input
TypeError: 'NoneType' object is not subscriptable
Please suggest some way to rectify the above error and visualize the attention maps of the fine-tuned model