captum icon indicating copy to clipboard operation
captum copied to clipboard

how would it be possible to calculate the Integrated gradients for model which has embedding

Open mostafaalishahi opened this issue 6 years ago • 17 comments

Hi everyone,

I am applying the integrated gradient method on my dataset which has categorical and numerical data, in which I convert categorical data into embedding and concatenate with numerical. But the output of integrated gradients for all the categorical values are zero and for the numerical ones is calculated correctly. I have tried to do it with LayerIntegratedGradients but as far as I do not have the developer version of captum installed it failed. any suggestion?

mostafaalishahi avatar Feb 11 '20 13:02 mostafaalishahi

Hi @mostafaalishahi ! We recommend to install developer version since it is better tested and has more algorithms. There is a way to do it by using IntegratedGradients and configure embedding layer. For examples please, check out: https://captum.ai/tutorials/Multimodal_VQA_Captum_Insights or BERT tutorial.

NarineK avatar Feb 11 '20 17:02 NarineK

Thanks a bunch @NarineK for your quick response. according to your explanation and the tutorial I used LayerIntegratedGradients in order to get the values for categorical values (as I used embedding in order to convert them into vectors) and I applied IntegratedGradients in order to get the values for all the features(which categorical are zeros) and I replaced the zeors of categorical features with the output from LayerIntegratedGradients. But the outputs from LayerIntegratedGradients and IntegratedGradients are not in the same range(e.g 1e-2, 1e-4). Do you know if this is the correct way to do it?

mostafaalishahi avatar Feb 12 '20 10:02 mostafaalishahi

@mostafaalishahi, LayerIntegratedGradients and IntegratedGradients implement the same logic. They must return the same attribution.

For IntegratedGradients the inputs must be the embeddings not the indices. In order to compute the embeddings you can use our helper functions.

For the LayerIntegratedGradients, the inputs are the indices. The computation of embeddings happens internally when you hook the embedding layer. If you have both embedding indices and scalar dense features in your model you should directly use IntegratedGradients. LayerIntegratedGradients is not the right choice for that. See, multi-modal, VQA tutorial.

Maybe you can explain your model and inputs and I can help you more. I'm not sure I fully understand your question.

NarineK avatar Feb 13 '20 00:02 NarineK

@NarineK Thanks for your reply. The model that I used is as the following:

class BiRNN(nn.Module):
    def __init__(self, input_size, hidden_size, num_layers, num_classes):
        super(BiRNN, self).__init__()
        self.num_layers  = num_layers
        self.num_classes = num_classes
        self.drop = nn.Dropout(p=0.2)
        self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first = True, bidirectional = True)
        self.fc = nn.Linear(hidden_size*2, num_classes) # 2 for bidirection
        self.sigmoid = torch.nn.Sigmoid()
        self.embeds = nn.Embedding(40,5)
        
                
    def forward(self, data_categorical, data_categorical, seq_lengths, captum=True):
            embed = self.embeds(data_categorical).reshape((data_categorical.size(0), data_categorical.size(1), -1))
            x = torch.cat((embed,data_categorical),-1)
            packed_input = pack_padded_sequence(x, seq_lengths, batch_first=True, enforce_sorted=False)
            out, _ =  self.lstm(packed_input)         
            lstm_out, input_sizes = pad_packed_sequence(out, batch_first=True)        
            lstm_out = lstm_out.contiguous().view(-1, max(seq_lengths), 2, 128)
            # get backward output 
            lstm_out_bw = lstm_out[:, 0, 1, :]
            # get forward output
            lstm_out_fw = lstm_out[:, -1, 0, :]
            output = self.fc(torch.cat((lstm_out_fw, lstm_out_bw), -1))
            return output

Here is how I try to get the importance for both categorical and numerical features using 'AttributionVisualizer' ]

features = [
    TextFeature("Categorical", input_transforms=[input_text_transform], baseline_transforms=[], visualization_transform=cat_feat),
    GeneralFeature("Numerical", categories=['variable1', 'variable2','variable3','variable4','variable5', 'variable6'])
]
visualizer = AttributionVisualizer(
    models=[model],
    score_func=score_func,
    features=features,
    dataset=dataset,
    classes=[0, 1]
)

but when I run 'visualizer.render()' it does not show any output.

could you please give me some hints, whether is my approach correct or I am doing everything wrong?

mostafaalishahi avatar Feb 17 '20 17:02 mostafaalishahi

Hi @mostafaalishahi , in this definition you declared data_categorical twice and have captum argument variable that you don't use:

    def forward(self, data_categorical, data_categorical, seq_lengths, captum=True):

How are you computing the attribution ? Since you have different types of features you can use Integrated Gradients and precompute the embeddings similar to the VQA example. Is that how you did it ?

NarineK avatar Feb 18 '20 23:02 NarineK

Hi Everyone! Expanding on the question of @mostafaalishahi - is it possible to use the approach outlined in the VQA example for a model with multiple embedding layers? In my example I would like to use the Integrated Gradients approach for a tabular model, that uses a different embedding layer for each categorical variable. Thanks in advance!

dschaudt42 avatar Feb 25 '20 10:02 dschaudt42

Hi @Bitterlemon42, sure, we have examples of such cases for Bert sub-embeddings. See section: Multi-Embedding attribution https://captum.ai/tutorials/Bert_SQUAD_Interpret

Is that what you're looking for ?

NarineK avatar Feb 25 '20 17:02 NarineK

@mostafaalishahi , @Bitterlemon42 did those examples help ? Can we close this issue ?

NarineK avatar Feb 26 '20 22:02 NarineK

@NarineK exactly what I was looking for, thank you very much! From my side the issue can be closed.

dschaudt42 avatar Feb 27 '20 07:02 dschaudt42

@NarineK Thank you very much for your reply, I thought 'AttributionVisualizer' would compute the attribution, but still, I could not figure it out how to do it.

mostafaalishahi avatar Feb 27 '20 09:02 mostafaalishahi

AttributionVisualizer does not compute attributions. It visualizes pre-computed attributions.

NarineK avatar Feb 27 '20 18:02 NarineK

Dear @NarineK , Thanks for your reply. could you please confirm if the following is the correct way of doing this task?

interpretable_embedding = configure_interpretable_embedding_layer(model, "embeds")


total_attr_cat, total_attr_num = [], []
model.train()
for data,labels in test_loader:
    nonzeros = ~data.cpu().numpy().any(axis=2)
    data = torch.Tensor(data).to(device)
    nonzero_index = np.argmax(nonzeros,axis=1)        
    nonzero_index = torch.LongTensor(nonzero_index)
    seq_lengths, perm_idx = nonzero_index.sort(0, descending=True)
    data = data[perm_idx]
    labels = labels[perm_idx]
    categorical = interpretable_embedding.indices_to_embeddings(data[:, :, :11].long())
    numerical   = data[:, : ,11:]
    (attr_cat, attr_num), delta = ig.attribute((categorical,numerical), additional_forward_args= seq_lengths,target=1,return_convergence_delta=True)
    total_attr_cat.append(attr_cat.detach().cpu().numpy())
    total_attr_num.append(attr_num.detach().cpu().numpy())
    
remove_interpretable_embedding_layer(model, interpretable_embedding)

mostafaalishahi avatar Mar 02 '20 17:03 mostafaalishahi

@mostafaalishahi , It is a bit difficult for me to tell if everything is correct since, for example, I don't know why are you accessing up to 11th element in the 3rd dimension of the data or why are you accessing seq_length the way you did but in general from attribution perspective looks good. Also, why are you using target=1 ?

NarineK avatar Mar 04 '20 02:03 NarineK

@NarineK Thanks a lot, target=1 is to specify which class I am interested in, isn't it correct? seq_length is needed as an argument into the model.

mostafaalishahi avatar Mar 04 '20 16:03 mostafaalishahi

@mostafaalishahi , if you chose all of that correctly, then it should be right

NarineK avatar Mar 04 '20 16:03 NarineK

@mostafaalishahi, if this is not an issue any more can we, please, close it ?

NarineK avatar Apr 14 '20 04:04 NarineK

1

sg90 avatar Mar 31 '25 07:03 sg90