引言
借用修仙小說體寫的標題,主要目的就是吸引你點進來🤭,客官來都來了,看完再走唄~
其實實作一個智能的聊天機器人🤖還是有一定難度的,博主就和大家一起盡可能實作一個智能的聊天機器人,
計劃一周🧭更新一次,如果覺得更新慢的話,就在留言里催更吧,很有可能會回應你們的催更哦,本系列文章📓會基于Pytorch實作一個Seq2Seq 帶Attention機制的聊天機器人,在本系列文章中,大家會了解到實作聊天機器人的所有知識,歡迎關注哦,
上篇文章中我們直接加載哈工大的預訓練模型得到了句子表示,但是在計算余弦相似度時發現效果一般,因此,本文來針對句子相似問題進行微調,
主要想法是將句子相似看成一個分類問題,結果就是:相似(1)/不相似(0),
本文一步一步介紹如何微調這個分類問題,并對我們上篇文章中的句子進行測驗,
使用🤗的Transformers包
pip install transformers datasets
本文需要的包通過上面的指令安裝即可,
資料集
本文使用的資料集為中文句子對資料集,期望有兩個句子,并且帶有是否相似的標簽,
博主在HuggingFace的官方資料集中沒有找到滿足要求的,因此從網上下載了一個資料集,但是過分相信該資料集,導致直接加載各種報錯,因此花費了幾個小時處理了一下資料集,使它是可用的,
資料集包含了兩個檔案:train.csv和dev.csv,其中訓練集有9萬句子對;開發集有1萬句子對,
該資料集下載地址:點這里
加載資料集到datasets中
🤗提供的datasets模塊匯入資料集用起來很方便,因此如果能將我們自己的資料集也通過該工具加載豈不是美滋滋,
下面一起來實作吧:
from datasets import load_dataset
# 加載本地資料集,指定本地路徑即可
raw_datasets = load_dataset('csv', data_files={'train': './data/train.csv','dev': './data/dev.csv'})
由于🤗引入了進度條工具,加載這些資料集的時候還會有一個進度條,等起來就不覺得久了,
尤其是在jupyter上看起來更舒服,

加載完成后,我們看下它的結構:
print(raw_datasets)
DatasetDict({
train: Dataset({
features: ['sentence1', 'sentence2', 'label'],
num_rows: 88975
})
dev: Dataset({
features: ['sentence1', 'sentence2', 'label'],
num_rows: 10000
})
})
現在我們已經加載好了原始的資料集,接下來需要對資料集中的每個句子進行分詞、轉換為ID、增加特殊標記等操作,好在🤗已經幫我們把這些封裝到了分詞器Tokenizer里面了,不用每次做一些重復作業,
下載并加載Tokenizer
與上篇文章一樣,我們還是采用哈工大的BERT資料集,這里介紹一種比較簡單的方式,可以不需要自己手動下載,不過可能你需要有網路?
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("hfl/chinese-bert-wwm-ext")
這里我們使用🤗transformers中的AutoTokenizer模塊,它會根據我們傳入的路徑自動幫我們分析需要創建什么分詞器,每個模型的分詞器是不同的,還有一個好處時,我們可以把路徑封裝成一個變數,如果需要不同的預訓練模型,只要改變該變數的內容即可,主要代碼可以不變,
這里的hfl/chinese-bert-wwm-ext代表https://huggingface.co/hfl/chinese-bert-wwm-ext
并不是隨意輸入的,像我們的代碼可以傳到github一樣,我們使用🤗做的模型也可以上傳到他們提供的模型hub,hfl是哈工大的用戶名,后面就是哈工大上傳的模型名稱,
等待片刻,下載好了之后,我們先看一下我們資料,并使用該分詞進行預處理,
dataset_train = raw_datasets['train']
dataset_train[6]
{'label': 0, 'sentence1': '為什么我每次都提前還款了最后卻不給我貸款了', 'sentence2': '30號我一次性還清可以不'}
可以通過datasets的feature屬性查看有哪些欄位:
dataset_train.features
{'label': Value(dtype='int64', id=None),
'sentence1': Value(dtype='string', id=None),
'sentence2': Value(dtype='string', id=None)}
然后我們使用加載的分詞器對這兩個句子進行處理,
inputs = tokenizer(dataset_train[6]['sentence1'],dataset_train[6]['sentence2'])
inputs
{
'input_ids': [101, 711, 784, 720, 2769, 3680, 3613, 6963, 2990, 1184, 6820, 3621, 749, 3297, 1400, 1316, 679, 5314, 2769, 6587, 3621, 749, 102, 8114, 1384, 2769, 671, 3613, 2595, 6820, 3926, 1377, 809, 679, 102],
'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
}
可以看到,已經幫我們把句子分詞并轉換為ID,同時回傳了標記型別ID和注意力掩碼,
我們也可以把input_ids轉換回文字:
tokenizer.convert_ids_to_tokens(inputs["input_ids"])
['[CLS]',
'為',
'什',
'么',
'我',
'每',
'次',
'都',
'提',
'前',
'還',
'款',
'了',
'最',
'后',
'卻',
'不',
'給',
'我',
'貸',
'款',
'了',
'[SEP]',
'30',
'號',
'我',
'一',
'次',
'性',
'還',
'清',
'可',
'以',
'不',
'[SEP]']
嗯,增加了特殊標記,
處理資料集
下面我們來看下如何處理我們的資料集,如果想一次性處理整個資料集并加載到記憶體的話,不是土豪就是天真,
官方提供的datasets.map 可以分批加載資料,而不是一次加載整個資料集,
首先需要定義一個分詞函式:
def tokenize_function(example):
'''
example可以是一個樣本,也是一個一批樣本
注意根據指定的最大長度填充是非常低效的,最好的方法是按照該批次內最大長度進行填充,
'''
return tokenizer(example['sentence1'], example['sentence2'],truncation=True)
我們可以在上面的例子中實驗這個函式:
tokenize_function(dataset_train[6])
{'input_ids': [101, 711, 784, 720, 2769, 3680, 3613, 6963, 2990, 1184, 6820, 3621, 749, 3297, 1400, 1316, 679, 5314, 2769, 6587, 3621, 749, 102, 8114, 1384, 2769, 671, 3613, 2595, 6820, 3926, 1377, 809, 679, 102], 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}
下面就可以利用map方法傳入該函式來處理整個資料集了:
# batched=True一次可以處理一批資料
tokenized_datasets = raw_datasets.map(tokenize_function, batched=True)

我們來看一下回傳的資料集:
print(tokenized_datasets)
DatasetDict({
train: Dataset({
features: ['attention_mask', 'input_ids', 'label', 'sentence1', 'sentence2', 'token_type_ids'],
num_rows: 88975
})
dev: Dataset({
features: ['attention_mask', 'input_ids', 'label', 'sentence1', 'sentence2', 'token_type_ids'],
num_rows: 10000
})
})
注意由于句子已經標記化了,因此里面的原始字串不再需要了,我們可以洗掉它們(什么?你說我過河拆橋?),
tokenized_datasets = tokenized_datasets.remove_columns(
["sentence1", "sentence2"]
)
下面我們需要創建批資料,這里要注意的是,我們根據這批資料內最長的句子長度進行填充,而不是默認的最大長度512,
資料批量化
剩下的作業是根據批資料內最大長度,動態填充批內資料,
在PyTorch中,負責將批內的樣本放在一起的函式稱為整理函式(collate function)
Transformers幫我們實作了這樣的一個函式,
from transformers import DataCollatorWithPadding
data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
我們取一些樣本,來測驗這個函式,
samples = tokenized_datasets["train"][:8]
samples = {
k: v for k, v in samples.items()
}
# 查看該批次內每個樣本的長度
print([len(x) for x in samples["input_ids"]])
[27, 16, 39, 38, 25, 35, 35, 37]
現在我們就使用data_collator來創建一個批資料,并根據該批資料內最大長度(39)進行填充
batch = data_collator(samples)
{k: v.shape for k, v in batch.items()}
{'attention_mask': torch.Size([8, 39]),
'input_ids': torch.Size([8, 39]),
'labels': torch.Size([8]),
'token_type_ids': torch.Size([8, 39])}
可以看到,第二個維度都是39,
定義訓練器
訓練🤗的模型最簡單的方法是使用他們提供的訓練器(Trainer),
它主要是通過TrainingArguments來控制訓練器的引數,
from transformers import TrainingArguments
# 指定訓練程序中模型引數保存的路徑以及批大小
training_args = TrainingArguments(output_dir="saved",per_device_train_batch_size=8)
里面有很多默認的引數,可以根據自己的需要進行調整,官方檔案鏈接→這里

定義模型
萬事具備,只差模型了,我們這里使用的還是哈工大的bert預訓練模型,
加載也很簡單:
# 定義模型
from transformers import AutoModelForSequenceClassification
# 基于哈工大的bert預訓練模型
model = AutoModelForSequenceClassification.from_pretrained("hfl/chinese-bert-wwm-ext", num_labels=2)
Some weights of the model checkpoint at hfl/chinese-bert-wwm-ext were not used when initializing BertForSequenceClassification: ['cls.predictions.decoder.weight', 'cls.seq_relationship.weight', 'cls.predictions.transform.LayerNorm.weight', 'cls.seq_relationship.bias', 'cls.predictions.bias', 'cls.predictions.transform.dense.weight', 'cls.predictions.transform.dense.bias', 'cls.predictions.transform.LayerNorm.bias']
- This IS expected if you are initializing BertForSequenceClassification from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).
- This IS NOT expected if you are initializing BertForSequenceClassification from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).
Some weights of BertForSequenceClassification were not initialized from the model checkpoint at hfl/chinese-bert-wwm-ext and are newly initialized: ['classifier.weight', 'classifier.bias']
You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
下載完了之后它會列印一些提示??,由于我們要做分類任務,因此選擇AutoModelForSequenceClassification,它相當于在預訓練的BERT模型上,加了一個輸出頭,這個提示或者警告的意思是讓我們注意,這個新加的用于句子分類的輸出頭是隨機初始化的,需要你去微調,真是貼心??啊,
好了,那下面我們就來微調吧,
定義評估指標
差點忘說了,在進行訓練之前,需要先定義評估指標,因為訓練比較耗時,定義評估指標應用在開發集上,以便你可以看到一輪迭代完成之后的效果,
from datasets import load_metric
def compute_metrics(eval_preds):
metric = load_metric("accuracy")
logits, labels = eval_preds
predictions = np.argmax(logits, axis=-1)
return metric.compute(predictions=predictions, references=labels)
這里采用準確率作為評估指標,你也可以替換為f1/recall/precision等,
進行訓練
傳入要訓練的模型實體,配置的training_args和訓練資料集、驗證資料集等,
# 實體化訓練器
from transformers import Trainer
trainer = Trainer(
model,
training_args,
train_dataset=tokenized_datasets['train'],
data_collator=data_collator,
eval_dataset=tokenized_datasets["dev"],
tokenizer=tokenizer,
compute_metrics=compute_metrics
)
然后執行
trainer.train()
# 別忘記保存模型
trainer.save_model()
就可以開始訓練了,
在GeForce RTX 3090上面跑了一個小時才訓練完,
訓練完了之后,它會輸出:
Configuration saved in saved/config.json
Model weights saved in saved/pytorch_model.bin
tokenizer config file saved in saved/tokenizer_config.json
Special tokens file saved in saved/special_tokens_map.json
博主已經上傳了訓練好的模型,同時基于RoBERTa和BERT進行了微調,本文中微調的是BERT版的,
- BERT
- RoBERTa
加載微調好的模型
最后也是比較重要的一步是,我們要如何加載微調好的模型,不可能每次都訓練一次吧,
其實很簡單,報我們上面最終保存的檔案統一放到一個目錄下面,這里放到當前路徑的saved檔案下,如下所示:

下面撰寫加載代碼:
from transformers import AutoTokenizer, AutoModelForSequenceClassification
tokenizer = AutoTokenizer.from_pretrained("./saved")
model = AutoModelForSequenceClassification.from_pretrained("./saved")
model.eval()
是不是也很簡單,注意我們除了要加載未調好的模型,還要加載對應的分詞器,
進行測驗
還是采用上篇文章的測驗句子:
sentences = [
'今天的月亮又大又圓',
'十五的月亮十六圓',
'今天去看電影吧',
]
然后看前兩句話的相似度:
def compute_similarity(sentence1, sentence2):
batch = tokenizer(sentence1, sentence2, truncation=True, return_tensors="pt")
output = model(**batch)
softmax = torch.nn.Softmax(dim=1)
logits = output[0].view(1, -1, 2)
out = softmax(logits[:, -1])
result = out[0].detach().cpu().numpy()
print(f'The similarity of {sentence1} and {sentence2} is: {result[1]:.2f}')
compute_similarity(sentences[0], sentences[1])
compute_similarity(sentences[0], sentences[2])
compute_similarity(sentences[1], sentences[2])
The similarity of 今天的月亮又大又圓 and 十五的月亮十六圓 is: 0.99
The similarity of 今天的月亮又大又圓 and 今天去看電影吧 is: 0.00
The similarity of 十五的月亮十六圓 and 今天去看電影吧 is: 0.00
可以看到,我們隨意輸入的幾個句子,之間的相似度判斷還比較準確,當然,更嚴謹的做法是對測驗集使用f1/recall/precision等評估指標進行評估,
參考
- 🤗官方教程
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/302960.html
標籤:AI
上一篇:【論文翻譯】DeepWalk: Online Learning of Social Representations
