Applying LIME interpretation on my fine-tuned BERT for sequence classification model?

4.1k views Asked by At

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:

# 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 "License");
# 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 "AS IS" 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):
    """A single training/test example for simple sequence classification."""

    def __init__(self, guid, text_a, text_b=None, label=None):
        """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.
        """
        self.guid = guid
        self.text_a = text_a
        self.text_b = text_b
        self.label = label


class InputFeatures(object):
    """A single set of features of data."""

    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):
    """Base class for data converters for sequence classification data sets."""

    def get_train_examples(self, data_dir):
        """Gets a collection of `InputExample`s for the train set."""
        raise NotImplementedError()

    def get_dev_examples(self, data_dir):
        """Gets a collection of `InputExample`s for the dev set."""
        raise NotImplementedError()

    def get_labels(self):
        """Gets the list of labels for this data set."""
        raise NotImplementedError()

    @classmethod
    def _read_tsv(cls, input_file, quotechar=None):
        """Reads a tab separated value file."""
        with open(input_file, "r", encoding='utf-8') as f:
            reader = csv.reader(f, delimiter="\t", quotechar=quotechar)
            lines = []
            for line in reader:
                lines.append(line)
            return lines



class SemEvalProcessor(DataProcessor):

    def get_train_examples(self, data_dir):
        """See base class."""
        logger.info("LOOKING AT {}".format(data_dir))
        return self._create_examples(
            self._read_tsv(data_dir), "train")

    def get_dev_examples(self, data_dir):
        """See base class."""
        return self._create_examples(
            self._read_tsv(data_dir), "dev")

    def get_test_examples(self, data_dir):
        logger.info("LOOKING AT {}".format(data_dir))
        return self._create_examples(
            self._read_tsv(data_dir), "test")

    def get_labels(self):
        """See base class."""
        return ["0", "1"]

    def create_examples(self, line, set_type='test'):
        examples = []
        if set_type == 'test':
          guid = "%s" % (set_type)
          text_a = line
          text_b = None
          label = "0"
          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):
      """Loads a data file into a list of `InputBatch`s."""
      if label_list:
          label_map = {label : i for i, label in enumerate(label_list)}
      else:
          label_map = {"0": 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 "- 3"
          _truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)
      else:
          # Account for [CLS] and [SEP] with "- 2"
          if len(tokens_a) > 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 "type_ids" 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 "sentence vector". Note that this only makes sense because
      # the entire model is fine-tuned.
      tokens = ["[CLS]"] + tokens_a + ["[SEP]"]
      segment_ids = [0] * len(tokens)

      if tokens_b:
          tokens += tokens_b + ["[SEP]"]
          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("*** Example ***")
      logger.info("guid: %s" % (example.guid))
      logger.info("tokens: %s" % " ".join(
              [str(x) for x in tokens]))
      logger.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
      logger.info("input_mask: %s" % " ".join([str(x) for x in input_mask]))
      logger.info(
              "segment_ids: %s" % " ".join([str(x) for x in segment_ids]))
      logger.info("label: %s (id = %d)" % (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):
      """Truncates a sequence pair in place to the maximum length."""

      # 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 <= max_length:
              break
          if len(tokens_a) > 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 < 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("***** Running prediction *****")
        #logger.info("  test_example = %", test_example)
        logger.info("  Batch size = %d", 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="Predicting"):
          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("logits,logits.shape",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("results_array",results_array.shape)  
      return np.array(logits)
  
    
if __name__ == "__main__":
    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("--data_path",
                        type=str,
                        help="The path of the input data file. The data should be in the .tsv format.")
    parser.add_argument("--bert_model", default='bert-base-uncased', type=str,
                        help="Bert pre-trained model selected in the list: bert-base-uncased, "
                             "bert-large-uncased, bert-base-cased, bert-large-cased, bert-base-multilingual-uncased, "
                             "bert-base-multilingual-cased, bert-base-chinese.")
    parser.add_argument("--task_name",
                        default='SEMEVAL',
                        type=str,
                        help="The name of the task.")
    parser.add_argument("--output_dir",
                        default='results/bert_output.tsv',
                        type=str,
                        help="The output results file.")
    parser.add_argument("--model_path",
                        default='results/semeval_output/pytorch_model_task.bin',
                        type=str,
                        help="The path to the trained model file.")

    ## Other parameters
    parser.add_argument("--max_seq_length",
                        default=128,
                        type=int,
                        help="The maximum total input sequence length after WordPiece tokenization. \n"
                             "Sequences longer than this will be truncated, and sequences shorter \n"
                             "than this will be padded.")
    parser.add_argument("--do_lower_case",
                        action='store_true',
                        default=True,
                        help="Set this flag if you are using an uncased model.")
    parser.add_argument("--predict_batch_size",
                        default=16,
                        type=int,
                        help="Total batch size for prediction.")
    parser.add_argument("--no_cuda",
                        action='store_true',
                        help="Whether not to use CUDA when available")
    parser.add_argument("--local_rank",
                        type=int,
                        default=-1,
                        help="local_rank for distributed training on gpus")
    parser.add_argument('--fp16',
                        action='store_true',
                        help="Whether to use 16-bit float precision instead of 32-bit")

    args = parser.parse_args()

    processors = {
        "semeval": SemEvalProcessor,
    }

    num_labels_task = {
        "semeval": 2,
    }

    if args.local_rank == -1 or args.no_cuda:
        device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")
        n_gpu = torch.cuda.device_count()
    else:
        torch.cuda.set_device(args.local_rank)
        device = torch.device("cuda", 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("device: {} n_gpu: {}, distributed training: {}, 16-bits training: {}".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("Task not found: %s" % (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 = "models/mrpc"
    #bert_model_class = "bert"
    #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("Applying LIME")
    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("Fininsh Applying LIME")

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

Traceback (most recent call last):
  File "/content/drive/My Drive/BERT CODE/Try_LIME.py", line 442, in <module>
    exp = explainer.explain_instance(example, predictions.predict)
  File "/usr/local/lib/python3.6/dist-packages/lime/lime_text.py", line 415, in explain_instance
    distance_metric=distance_metric)
  File "/usr/local/lib/python3.6/dist-packages/lime/lime_text.py", line 482, in __data_labels_distances
    labels = classifier_fn(inverse_data)
  File "/content/drive/My Drive/BERT CODE/Try_LIME.py", line 273, in predict
    logits = F.softmax(logits, dim = 1)
  File "/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py", line 1498, in softmax
    ret = input.softmax(dim)
IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1)

thanks in advance

1

There are 1 answers

0
Eric On

too complicated example.

You can follow the simple one while checking why your does not work (in jupyter-lab)

import numpy as np
import lime
import torch
import torch.nn.functional as F
from lime.lime_text import LimeTextExplainer

from transformers import AutoTokenizer, AutoModelForSequenceClassification

filename_model = 'ProsusAI/finbert'
tokenizer = AutoTokenizer.from_pretrained(filename_model)
model = AutoModelForSequenceClassification.from_pretrained(filename_model)
class_names = ['positive','negative', 'neutral']

def predictor(texts):
    outputs = model(**tokenizer(texts, return_tensors="pt", padding=True))
    tensor_logits = outputs[0]
    probas = F.softmax(tensor_logits).detach().numpy()
    return probas

text = 'Building more bypasses will help the environment by reducing pollution and traffic jams in towns and cities.'
print(tokenizer(text, return_tensors='pt', padding=True))

explainer = LimeTextExplainer(class_names=class_names)
exp = explainer.explain_instance(text, predictor, num_features=20, num_samples=2000)
exp.show_in_notebook(text=text)

enter image description here