title: Applying LIME interpretation on my fine-tuned BERT for sequence classification model?
body: <p>I fine tuned BERT For Sequence Classification on task specific, I wand to apply LIME interpretation to see how each token contribute to be classified to specific label as LIME handle the classifier as black box. I made a combined code from available online codes as following:</p>
  <pre><code># coding=utf-8
  # Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team.
  # Copyright (c) 2018, NVIDIA CORPORATION.  All rights reserved.
  #
  # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
  # you may not use this file except in compliance with the License.
  # You may obtain a copy of the License at
  #
  #     http://www.apache.org/licenses/LICENSE-2.0
  #
  # Unless required by applicable law or agreed to in writing, software
  # distributed under the License is distributed on an &quot;AS IS&quot; BASIS,
  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  # See the License for the specific language governing permissions and
  # limitations under the License.
  
  #This code is a modification of the original run_examples.py script from the repository 'https://#github.com/wanghm92/pytorch-pretrained-BERT'. Modified for research purposes by Andraž P.
  
  import logging
  import csv
  import argparse
  
  import numpy as np
  import torch
  from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler
  from torch.utils.data.distributed import DistributedSampler
  
  from pytorch_pretrained_bert.modeling import BertForSequenceClassification
  from pytorch_pretrained_bert.tokenization import BertTokenizer
  
  from tqdm import tqdm
  
  logging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s -   %(message)s',
                      datefmt = '%m/%d/%Y %H:%M:%S',
                      level = logging.INFO)
  logger = logging.getLogger(__name__)
  
  
  class InputExample(object):
      &quot;&quot;&quot;A single training/test example for simple sequence classification.&quot;&quot;&quot;
  
      def __init__(self, guid, text_a, text_b=None, label=None):
          &quot;&quot;&quot;Constructs a InputExample.
  
          Args:
              guid: Unique id for the example.
              text_a: string. The untokenized text of the first sequence. For single
              sequence tasks, only this sequence must be specified.
              text_b: (Optional) string. The untokenized text of the second sequence.
              Only must be specified for sequence pair tasks.
              label: (Optional) string. The label of the example. This should be
              specified for train and dev examples, but not for test examples.
          &quot;&quot;&quot;
          self.guid = guid
          self.text_a = text_a
          self.text_b = text_b
          self.label = label
  
  
  class InputFeatures(object):
      &quot;&quot;&quot;A single set of features of data.&quot;&quot;&quot;
  
      def __init__(self, input_ids, input_mask, segment_ids, label_id):
          self.input_ids = input_ids
          self.input_mask = input_mask
          self.segment_ids = segment_ids
          self.label_id = label_id
  
  
  class DataProcessor(object):
      &quot;&quot;&quot;Base class for data converters for sequence classification data sets.&quot;&quot;&quot;
  
      def get_train_examples(self, data_dir):
          &quot;&quot;&quot;Gets a collection of `InputExample`s for the train set.&quot;&quot;&quot;
          raise NotImplementedError()
  
      def get_dev_examples(self, data_dir):
          &quot;&quot;&quot;Gets a collection of `InputExample`s for the dev set.&quot;&quot;&quot;
          raise NotImplementedError()
  
      def get_labels(self):
          &quot;&quot;&quot;Gets the list of labels for this data set.&quot;&quot;&quot;
          raise NotImplementedError()
  
      @classmethod
      def _read_tsv(cls, input_file, quotechar=None):
          &quot;&quot;&quot;Reads a tab separated value file.&quot;&quot;&quot;
          with open(input_file, &quot;r&quot;, encoding='utf-8') as f:
              reader = csv.reader(f, delimiter=&quot;\t&quot;, quotechar=quotechar)
              lines = []
              for line in reader:
                  lines.append(line)
              return lines
  
  
  
  class SemEvalProcessor(DataProcessor):
  
      def get_train_examples(self, data_dir):
          &quot;&quot;&quot;See base class.&quot;&quot;&quot;
          logger.info(&quot;LOOKING AT {}&quot;.format(data_dir))
          return self._create_examples(
              self._read_tsv(data_dir), &quot;train&quot;)
  
      def get_dev_examples(self, data_dir):
          &quot;&quot;&quot;See base class.&quot;&quot;&quot;
          return self._create_examples(
              self._read_tsv(data_dir), &quot;dev&quot;)
  
      def get_test_examples(self, data_dir):
          logger.info(&quot;LOOKING AT {}&quot;.format(data_dir))
          return self._create_examples(
              self._read_tsv(data_dir), &quot;test&quot;)
  
      def get_labels(self):
          &quot;&quot;&quot;See base class.&quot;&quot;&quot;
          return [&quot;0&quot;, &quot;1&quot;]
  
      def create_examples(self, line, set_type='test'):
          examples = []
          if set_type == 'test':
            guid = &quot;%s&quot; % (set_type)
            text_a = line
            text_b = None
            label = &quot;0&quot;
            examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
          return examples[0]
  
  
  class Predictions:
  
    def convert_examples_to_features(self,example, label_list, max_seq_length, tokenizer):
        &quot;&quot;&quot;Loads a data file into a list of `InputBatch`s.&quot;&quot;&quot;
        if label_list:
            label_map = {label : i for i, label in enumerate(label_list)}
        else:
            label_map = {&quot;0&quot;: i for i in range(1)}
  
        features = []
        tokens_a = tokenizer.tokenize(example.text_a)
  
        tokens_b = None
        if example.text_b:
            tokens_b = tokenizer.tokenize(example.text_b)
            # Modifies `tokens_a` and `tokens_b` in place so that the total
            # length is less than the specified length.
            # Account for [CLS], [SEP], [SEP] with &quot;- 3&quot;
            _truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)
        else:
            # Account for [CLS] and [SEP] with &quot;- 2&quot;
            if len(tokens_a) &gt; max_seq_length - 2:
                tokens_a = tokens_a[:(max_seq_length - 2)]
  
        # The convention in BERT is:
        # (a) For sequence pairs:
        #  tokens:   [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
        #  type_ids: 0   0  0    0    0     0       0 0    1  1  1  1   1 1
        # (b) For single sequences:
        #  tokens:   [CLS] the dog is hairy . [SEP]
        #  type_ids: 0   0   0   0  0     0 0
        #
        # Where &quot;type_ids&quot; are used to indicate whether this is the first
        # sequence or the second sequence. The embedding vectors for `type=0` and
        # `type=1` were learned during pre-training and are added to the wordpiece
        # embedding vector (and position vector). This is not *strictly* necessary
        # since the [SEP] token unambigiously separates the sequences, but it makes
        # it easier for the model to learn the concept of sequences.
        #
        # For classification tasks, the first vector (corresponding to [CLS]) is
        # used as as the &quot;sentence vector&quot;. Note that this only makes sense because
        # the entire model is fine-tuned.
        tokens = [&quot;[CLS]&quot;] + tokens_a + [&quot;[SEP]&quot;]
        segment_ids = [0] * len(tokens)
  
        if tokens_b:
            tokens += tokens_b + [&quot;[SEP]&quot;]
            segment_ids += [1] * (len(tokens_b) + 1)
  
        input_ids = tokenizer.convert_tokens_to_ids(tokens)
  
        # The mask has 1 for real tokens and 0 for padding tokens. Only real
        # tokens are attended to.
        input_mask = [1] * len(input_ids)
  
        # Zero-pad up to the sequence length.
        padding = [0] * (max_seq_length - len(input_ids))
        input_ids += padding
        input_mask += padding
        segment_ids += padding
  
        assert len(input_ids) == max_seq_length
        assert len(input_mask) == max_seq_length
        assert len(segment_ids) == max_seq_length
  
        label_id = label_map[example.label]
      
        logger.info(&quot;*** Example ***&quot;)
        logger.info(&quot;guid: %s&quot; % (example.guid))
        logger.info(&quot;tokens: %s&quot; % &quot; &quot;.join(
                [str(x) for x in tokens]))
        logger.info(&quot;input_ids: %s&quot; % &quot; &quot;.join([str(x) for x in input_ids]))
        logger.info(&quot;input_mask: %s&quot; % &quot; &quot;.join([str(x) for x in input_mask]))
        logger.info(
                &quot;segment_ids: %s&quot; % &quot; &quot;.join([str(x) for x in segment_ids]))
        logger.info(&quot;label: %s (id = %d)&quot; % (example.label, label_id))
  
        features.append(
                InputFeatures(input_ids=input_ids,
                              input_mask=input_mask,
                              segment_ids=segment_ids,
                              label_id=label_id))
        return features
  
  
    def _truncate_seq_pair(tokens_a, tokens_b, max_length):
        &quot;&quot;&quot;Truncates a sequence pair in place to the maximum length.&quot;&quot;&quot;
  
        # This is a simple heuristic which will always truncate the longer sequence
        # one token at a time. This makes more sense than truncating an equal percent
        # of tokens from each, since if one sequence is very short then each token
        # that's truncated likely contains more information than a longer sequence.
        while True:
            total_length = len(tokens_a) + len(tokens_b)
            if total_length &lt;= max_length:
                break
            if len(tokens_a) &gt; len(tokens_b):
                tokens_a.pop()
            else:
                tokens_b.pop()
  
    #def accuracy(out, labels):
    #    outputs = np.argmax(out, axis=1)
    #    return np.sum(outputs == labels)
  
    #def warmup_linear(x, warmup=0.002):
    #    if x &lt; warmup:
    #        return x/warmup
    #    return 1.0 - x
  
  
    def predict(self, text): 
        examples = []
        print(text)
        for example in text:
          test_example = processor.create_examples(example)
          test_features = self.convert_examples_to_features(test_example, None, args.max_seq_length, tokenizer)
          examples.append(test_features)
          logger.info(&quot;***** Running prediction *****&quot;)
          #logger.info(&quot;  test_example = %&quot;, test_example)
          logger.info(&quot;  Batch size = %d&quot;, args.predict_batch_size)
          all_input_ids = torch.tensor([f.input_ids for f in test_features], dtype=torch.long)
          all_input_mask = torch.tensor([f.input_mask for f in test_features], dtype=torch.long)
          all_segment_ids = torch.tensor([f.segment_ids for f in test_features], dtype=torch.long)
          all_label_ids = torch.tensor([f.label_id for f in test_features], dtype=torch.long)
          test_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_label_ids) 
          # Run prediction for full data
          test_sampler = SequentialSampler(test_data)
          test_dataloader = DataLoader(test_data, sampler=test_sampler, batch_size=args.predict_batch_size)
          model.eval()
        all_preds = []
        all_ids = []
        results=[]
        for input_ids, input_mask, segment_ids, label_ids in tqdm(test_dataloader, desc=&quot;Predicting&quot;):
            input_ids = input_ids.to(device)
            input_mask = input_mask.to(device)
            segment_ids = segment_ids.to(device)
  
            with torch.no_grad():
                outputs = model(input_ids, segment_ids, input_mask)
            logits = outputs[0]
            print(&quot;logits,logits.shape&quot;,logits)
            #preds = np.argmax(logits).tolist()
            logits = F.softmax(logits, dim = 1)
            results.append(logits.cpu().detach().numpy()[0])
            #logits = logits.detach().cpu().numpy()[0]
            input_ids = input_ids.to('cpu').numpy().tolist()
            #all_preds.extend(preds)
            all_ids.extend(input_ids)
            results_array = np.array(results)
            logger.info(&quot;results_array&quot;,results_array.shape)  
        return np.array(logits)
    
      
  if __name__ == &quot;__main__&quot;:
      import pandas as pd
      import numpy as np
      import torch
      import torch.nn.functional as F
      from lime.lime_text import LimeTextExplainer
      import logging
      parser = argparse.ArgumentParser()
      ## Required parameters
      parser.add_argument(&quot;--data_path&quot;,
                          type=str,
                          help=&quot;The path of the input data file. The data should be in the .tsv format.&quot;)
      parser.add_argument(&quot;--bert_model&quot;, default='bert-base-uncased', type=str,
                          help=&quot;Bert pre-trained model selected in the list: bert-base-uncased, &quot;
                               &quot;bert-large-uncased, bert-base-cased, bert-large-cased, bert-base-multilingual-uncased, &quot;
                               &quot;bert-base-multilingual-cased, bert-base-chinese.&quot;)
      parser.add_argument(&quot;--task_name&quot;,
                          default='SEMEVAL',
                          type=str,
                          help=&quot;The name of the task.&quot;)
      parser.add_argument(&quot;--output_dir&quot;,
                          default='results/bert_output.tsv',
                          type=str,
                          help=&quot;The output results file.&quot;)
      parser.add_argument(&quot;--model_path&quot;,
                          default='results/semeval_output/pytorch_model_task.bin',
                          type=str,
                          help=&quot;The path to the trained model file.&quot;)
  
      ## Other parameters
      parser.add_argument(&quot;--max_seq_length&quot;,
                          default=128,
                          type=int,
                          help=&quot;The maximum total input sequence length after WordPiece tokenization. \n&quot;
                               &quot;Sequences longer than this will be truncated, and sequences shorter \n&quot;
                               &quot;than this will be padded.&quot;)
      parser.add_argument(&quot;--do_lower_case&quot;,
                          action='store_true',
                          default=True,
                          help=&quot;Set this flag if you are using an uncased model.&quot;)
      parser.add_argument(&quot;--predict_batch_size&quot;,
                          default=16,
                          type=int,
                          help=&quot;Total batch size for prediction.&quot;)
      parser.add_argument(&quot;--no_cuda&quot;,
                          action='store_true',
                          help=&quot;Whether not to use CUDA when available&quot;)
      parser.add_argument(&quot;--local_rank&quot;,
                          type=int,
                          default=-1,
                          help=&quot;local_rank for distributed training on gpus&quot;)
      parser.add_argument('--fp16',
                          action='store_true',
                          help=&quot;Whether to use 16-bit float precision instead of 32-bit&quot;)
  
      args = parser.parse_args()
  
      processors = {
          &quot;semeval&quot;: SemEvalProcessor,
      }
  
      num_labels_task = {
          &quot;semeval&quot;: 2,
      }
  
      if args.local_rank == -1 or args.no_cuda:
          device = torch.device(&quot;cuda&quot; if torch.cuda.is_available() and not args.no_cuda else &quot;cpu&quot;)
          n_gpu = torch.cuda.device_count()
      else:
          torch.cuda.set_device(args.local_rank)
          device = torch.device(&quot;cuda&quot;, args.local_rank)
          n_gpu = 1
          # Initializes the distributed backend which will take care of sychronizing nodes/GPUs
          torch.distributed.init_process_group(backend='nccl')
      logger.info(&quot;device: {} n_gpu: {}, distributed training: {}, 16-bits training: {}&quot;.format(
          device, n_gpu, bool(args.local_rank != -1), args.fp16))
  
      task_name = args.task_name.lower()
  
      if task_name not in processors:
          raise ValueError(&quot;Task not found: %s&quot; % (task_name))
     
      processor = processors[task_name]()
      num_labels = num_labels_task[task_name]
       #label_list = processor.get_labels()
      # loading a tokenizer
      tokenizer = BertTokenizer.from_pretrained(args.bert_model, do_lower_case=args.do_lower_case)
      # Lodaing a model
      model_state_dict = torch.load(args.model_path)
      model = BertForSequenceClassification.from_pretrained(args.bert_model, state_dict=model_state_dict,
                                                                num_labels=num_labels)
      model.to(device)
      predictions = Predictions()
      #model_path = &quot;models/mrpc&quot;
      #bert_model_class = &quot;bert&quot;
      #prediction = Prediction(bert_model_class, model_path,
      #                           lower_case = True, seq_length = 512)
      label_names = [0, 1]
      train_df = pd.read_csv(args.data_path, sep = '\t')
      #test_examples = processor.get_test_examples(texts)
      # guids = [example.guid for example in test_examples]
      #resultpredict=predict(test_examples)
      logger.info(&quot;Applying LIME&quot;)
      explainer = LimeTextExplainer(class_names=label_names)
      train_ls = train_df['text'].tolist()
      train_ls=train_ls[0]
      example=train_ls
      print(type(predictions.predict))
      for example in train_ls:
          print('example train_ls',example)
          exp = explainer.explain_instance(example, predictions.predict)
          words = exp.as_list()
      logger.info(&quot;Fininsh Applying LIME&quot;)
  </code></pre>
  <p>when I run the code, it never gives me the output because of the predictions.predict input, there is always dimension error that I could not figure, what should I input to the explainer.explain_instance in its simplest form?
  should I input ('text',[[0.9867 0.1243]])?
  or
  ('text',[[0.9867 0.1243] [0.7651 0.3459] [0.3254 0.775]])
  or what?
  I got this error</p>
  <pre><code>Traceback (most recent call last):
    File &quot;/content/drive/My Drive/BERT CODE/Try_LIME.py&quot;, line 442, in &lt;module&gt;
      exp = explainer.explain_instance(example, predictions.predict)
    File &quot;/usr/local/lib/python3.6/dist-packages/lime/lime_text.py&quot;, line 415, in explain_instance
      distance_metric=distance_metric)
    File &quot;/usr/local/lib/python3.6/dist-packages/lime/lime_text.py&quot;, line 482, in __data_labels_distances
      labels = classifier_fn(inverse_data)
    File &quot;/content/drive/My Drive/BERT CODE/Try_LIME.py&quot;, line 273, in predict
      logits = F.softmax(logits, dim = 1)
    File &quot;/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py&quot;, line 1498, in softmax
      ret = input.softmax(dim)
  IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1)
  </code></pre>
  <p>thanks in advance</p>