- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我针对特定任务对序列分类 BERT 进行了微调,我希望应用 LIME 解释来查看每个标记如何有助于分类到特定标签,因为 LIME 将分类器作为黑盒处理。我根据可用的在线代码制作了如下组合代码:
# 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")
当我运行代码时,由于 predictions.predict 输入,它永远不会给我输出,总是存在我无法理解的维度错误,我应该以最简单的形式向 explainer.explain_instance 输入什么?我应该输入('文本',[[0.9867 0.1243]])吗?或者('文本',[[0.9867 0.1243] [0.7651 0.3459] [0.3254 0.775]])或者是什么?我遇到了这个错误
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)
提前致谢
最佳答案
太复杂的例子。
您可以按照简单的方法检查为什么您不起作用(在 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)
关于python - 将 LIME 解释应用于我的微调 BERT 序列分类模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64484738/
我写了几个命令来转换数据框,但我想将我写的代码简化为四个部分。第 1,2 和 3 部分用于计算第 1、2 和 3 列(计算每列重复值的次数,并完成 0 和三列最大值之间的缺失数)。第四部分是加入前面的
我试图理解应用于函数的类型参数。 我想在下面的方法中使用通用类型,但为了我的理解使用 String 和 Int。 当我如下定义一个函数时 def myfunc[Int](f:String => I
我有一个像下面这样的 DIV: // link to some js .js 在 div 中呈现最新的文章摘要。然而,它在 Calibri
我在 GridView 中有以下列,一列是日期,另一列是美元金额。我应用了格式并将 HtmlEncode 属性设置为 false,但值仍然未格式化: 这就是这些值在 GridView 中的显示方式
假设我已经定义了这些类型: data Km = Km Float deriving (Show, Eq) data Mile = Mile Float deriving (Show, Eq
我有一个关于 value in context 的小问题。 取 Just 'a',所以在这种情况下 Maybe 类型上下文中的值是 'a' 采用[3],因此在这种情况下,[a] 类型上下文中的值为3
require(quantmod) require(PerformanceAnalytics) getSymbols('INTC') x<- monthlyReturn(INTC) rollapply
我正在使用 VBA 对“已应用字轨更改”文档进行更改。 红色段落结束标记是插入段落结束标记。(打开“跟踪更改”> 将光标放在第一段末尾 > 按 Enter > 插入新段落内容 > 格式风格不同) 我需
考虑以下代码: class A{ my_method(const B& b){ import_something_from_c(this, b.getC()); // does some
我正在为自定义 Material 分配图像。分配的图像看起来有点像素化,类似于此图像 我已经将抗锯齿设置为 4 倍。我该如何解决这个问题? 最佳答案 尝试将 Material 的 mipFilter
我将样式应用于 元素和 元素。是否可以在 上使用样式元素应用于 似乎不遵循 CSS 特异性的通常规则。这是真的吗? 示例:http://jsfiddle.net/59dpy/ 尝试将所有背景色设为红
有没有办法将垂直虚线边框应用于 没有他们(边界)合并?我说的是附图上的东西——有 3 个 这里的元素,每个元素包含 2 的。如果我申请 border-right: 1px dashed black到
当我在 CSS 中对主体应用线性渐变时,如下所示 body { background: linear-gradient(#10416b, black); } 它不会将它应用到整个网页,而是将它应用到页
当我将边框和边框半径应用于 td 时,内半径是一个直 Angular ,根本不是圆的。 最佳答案 问题很可能是背景不透明的子元素会剪掉边框的内半径。 要解决此问题,您可以在 td 上应用 overfl
基本上,我有一个小的 SVG,它使用一个组来定义一个可重用的符号。该组包括我想在 CSS 中设置动画的路径。我面临的问题是只有“原始”元素应用了 CSS,“使用过”的元素没有。 .player_arr
宽度属性在这里不起作用: td { height: 50px; width: 25px; border: 1px
我想要一个函数(例如)在两种情况下输出 Map 的所有值: Map map1 = new HashMap(); Map map2 = new HashMap(); output(map1, "1234
我被要求将我们应用中的警报对话框的外观与应用主题使用的外观相匹配。 我设法将样式应用于应用程序中的所有警报对话框,并将其用作应用程序主题的一部分,但有些情况下样式应用不正确。 例如,当警报对话框包含“
我有一个 CGPath(由 UIBezierPath 创建),我想通过应用 CGAffineTransformScale 将其缩放到我想要的任何大小。 这会影响我的绘图质量(在转换为图像时)吗?如果不
您好,我已经在 vector 上使用了一些 STL 算法,例如 find_if、count_if、sort、push_back 等。现在我想为所有容器对象( vector 、列表、映射、集合)制作一个
我是一名优秀的程序员,十分优秀!