代码来源B站up主:你可是处女座啊(如有侵权联系立删)
视频:【手把手带你实战HuggingFace Transformers-入门篇】基础知识与环境安装_哔哩哔哩_bilibili
任务:给一段文本,一个问题,几个选项,从选项中选出最符合题意的
1、导包
略
2、导数据
c3 = DatasetDict.load_from_disk("./c3/")
c3.pop("test")# 用不到这个
c3
可以看到,一个文本有一个问题,以及1~4个选项
3、数据处理
建议先看B站的视频易理解。
我们先对原数据进行处理,对于一个文本,模型需要4个copy,每个copy对应一个选项,最终模型会给出哪个是最有可能的答案。需要注意的是tokenizer需要:1、文本列表2、问题加选项列表
因此,我们需要遍历examples["context"]中的每个文本,将文本和问题copy4份,然后由于tokenizer需要问题加选项列表,我们需要在每个问题后加上一个选项。
当然,我们还需要有一个标签告诉模型哪个是准确的答案。
tokenizer = AutoTokenizer.from_pretrained("./model/")
def process(examples):
# 先处理原数据
# tokenizer需要一个样本对应的4个copy
context = []
# tokenizer需要一个样本对应的4question+choice
question_choice = []
labels = []
for i in range(len(examples["context"])):
if len(examples["choice"][i]) > 4:
print("超过四个选项,跳过!")
continue
i_context = "\n".join(examples["context"][i])
question = examples["question"][i]
choices = examples["choice"][i]
for choice in choices:
context.append(i_context)
question_choice.append(question + " " + choice)
if len(choices) < 4:# 备选项不足4个时
for j in range(4 - len(choices)):
context.append(i_context)
question_choice.append(question + " " + "不懂")
labels.append(examples["choice"][i].index(examples["answer"][i]))
tokenizer_examples = tokenizer(context, question_choice, truncation="only_first", max_length = 128, padding = "max_length")
其中,当选项多余4个时,直接跳过;当不足4个时,加上一个"不懂"的选项以补足。
到这里话没结束,假设共n条数据,则tokenizer_examples中元素的shape是:n*4, max_length;但是labels是:n, 1; 不对应,而且模型需要输入为 bs, n, 4, max_length,因此,我还需要变换一下。
tokenizer_examples = {
key : [ value[ i : i + 4]
for i in range( 0, len(value), 4 )
]# 当前key对应的值中元素每四个为一组
for key, value in tokenizer_examples.items()# 依次遍历键值对
}
# 现在,tokenizer_examples中的k,v的v的shape是n, 4, max_length
tokenizer_examples["labels"] = labels
4、评估函数
import numpy as np
#accuracy = evaluate.load("accuracy")
# 本地加载的方式
acc_metric = evaluate.load("./metric_accuracy.py")
def compute_metric(pred):
predictions, labels = pred
predictions = np.argmax(predictions, axis=-1)
return acc_metric.compute(predictions=predictions, references=labels)
5、训练
args = TrainingArguments(
output_dir="./muliple_choice",
per_device_train_batch_size=4,
per_device_eval_batch_size=4,
num_train_epochs=3,
logging_steps=50,
evaluation_strategy ="epoch",
save_strategy="epoch",
load_best_model_at_end=True,
fp16=True
)
trainer = Trainer(
model=model,
args=args,
tokenizer=tokenizer,
train_dataset=tokenizer_c3["train"],
eval_dataset=tokenizer_c3["validation"],
compute_metrics=compute_metric
)
这里最好多训练几次。

被折叠的 条评论
为什么被折叠?



