Chapter 15
文本相似度实例
Notebooktransformers30 cells
文本相似度实例
Step1 导入相关包
In [ ]python · cell 3
python
from transformers import AutoTokenizer, AutoModelForSequenceClassification, Trainer, TrainingArguments
from datasets import load_datasetStep2 加载数据集
In [ ]python · cell 5
python
dataset = load_dataset("json", data_files="./train_pair_1w.json", split="train")
datasetIn [ ]python · cell 6
python
dataset[0]Step3 划分数据集
In [ ]python · cell 8
python
datasets = dataset.train_test_split(test_size=0.2)
datasetsStep4 数据集预处理
In [ ]python · cell 10
python
import torch
tokenizer = AutoTokenizer.from_pretrained("hfl/chinese-macbert-base")
def process_function(examples):
tokenized_examples = tokenizer(examples["sentence1"], examples["sentence2"], max_length=128, truncation=True)
tokenized_examples["labels"] = [float(label) for label in examples["label"]]
return tokenized_examples
tokenized_datasets = datasets.map(process_function, batched=True, remove_columns=datasets["train"].column_names)
tokenized_datasetsIn [ ]python · cell 11
python
print(tokenized_datasets["train"][0])Step5 创建模型
In [ ]python · cell 13
python
from transformers import BertForSequenceClassification
model = AutoModelForSequenceClassification.from_pretrained("hfl/chinese-macbert-base", num_labels=1)Step6 创建评估函数
In [ ]python · cell 15
python
import evaluate
acc_metric = evaluate.load("./metric_accuracy.py")
f1_metirc = evaluate.load("./metric_f1.py")In [ ]python · cell 16
python
def eval_metric(eval_predict):
predictions, labels = eval_predict
predictions = [int(p > 0.5) for p in predictions]
labels = [int(l) for l in labels]
# predictions = predictions.argmax(axis=-1)
acc = acc_metric.compute(predictions=predictions, references=labels)
f1 = f1_metirc.compute(predictions=predictions, references=labels)
acc.update(f1)
return accStep7 创建TrainingArguments
In [ ]python · cell 18
python
train_args = TrainingArguments(output_dir="./cross_model", # 输出文件夹
per_device_train_batch_size=32, # 训练时的batch_size
per_device_eval_batch_size=32, # 验证时的batch_size
logging_steps=10, # log 打印的频率
eval_strategy="epoch", # 评估策略
save_strategy="epoch", # 保存策略
save_total_limit=3, # 最大保存数
learning_rate=2e-5, # 学习率
weight_decay=0.01, # weight_decay
metric_for_best_model="f1", # 设定评估指标
load_best_model_at_end=True) # 训练完成后加载最优模型
train_argsStep8 创建Trainer
In [ ]python · cell 20
python
from transformers import DataCollatorWithPadding
trainer = Trainer(model=model,
args=train_args,
tokenizer=tokenizer,
train_dataset=tokenized_datasets["train"],
eval_dataset=tokenized_datasets["test"],
data_collator=DataCollatorWithPadding(tokenizer=tokenizer),
compute_metrics=eval_metric)Step9 模型训练
In [ ]python · cell 22
python
trainer.train()Step10 模型评估
In [ ]python · cell 24
python
trainer.evaluate(tokenized_datasets["test"])Step11 模型预测
In [ ]python · cell 26
python
from transformers import pipeline, TextClassificationPipelineIn [ ]python · cell 27
python
model.config.id2label = {0: "不相似", 1: "相似"}In [ ]python · cell 28
python
pipe = pipeline("text-classification", model=model, tokenizer=tokenizer, device=0)In [ ]python · cell 29
python
result = pipe({"text": "我喜欢北京", "text_pair": "天气怎样"}, function_to_apply="none")
result["label"] = "相似" if result["score"] > 0.5 else "不相似"
resultIn [ ]python · cell 30
python
