NLP
發(fā)展到現(xiàn)在忌卤,一些舊的方法了解即可,早就過時(shí)了楞泼,導(dǎo)圖上打刪除線了驰徊。當(dāng)然了,一些小的場(chǎng)景還可能使用到的堕阔。
導(dǎo)圖
Transformer安裝環(huán)境
3080
辣垒,安裝Python=3.9
,然后如下印蔬,更高版本老是出錯(cuò)。
conda install pytorch==1.12.0 torchvision==0.13.0 torchaudio==0.12.0 cudatoolkit=11.6
conda install -c huggingface transformers # -c代表源
pip install datasets # 這么好的包名被搶用了啊
pip install evaluate
pip install scikit-learn # 不是sklearn
感覺transformers
是個(gè)集大成的傻瓜神器脱衙。
極簡(jiǎn)情感二分類
用到的庫:
from transformers import (AutoModel,
AutoModelForSequenceClassification,
AutoTokenizer,
Trainer,
TrainingArguments,
EvalPrediction)
import evaluate
from datasets import load_dataset, load_from_disk
import torch
from torch import nn
from torch.utils.data import Dataset, DataLoader
分詞侥猬,也叫符號(hào)化例驹,準(zhǔn)備數(shù)據(jù),會(huì)直接到huggingface
網(wǎng)下載退唠,可能需要科學(xué)上網(wǎng):
pt_name = 'bert-base-chinese' # 中文用這個(gè)多一些
tokenizer = AutoTokenizer.from_pretrained(pt_name)
original_ds = load_dataset('seamew/ChnSentiCorp')
def f(data):
return tokenizer(text=data['text'],
padding='max_length',
truncation=True,
max_length=300,
return_tensors='pt',)
ds = original_ds.map(f, batched=True, batch_size=16, remove_columns=['text'])
train_dataset = ds['train'].shuffle()
validation_dataset = ds['validation'].shuffle()
test_dataset = ds['test']
上面也可以用Pytorch
常用的繼承Dataset
的方式鹃锈。接下來看模型,因?yàn)槭莻€(gè)二分類任務(wù)瞧预,很方便:
model = AutoModelForSequenceClassification.from_pretrained(pt_name, num_labels=2)
accuracy = evaluate.load('accuracy') # 以前的load_metric降被停用
def compute_metrics(eval_pred):
logits, labels = eval_pred
logits = logits.argmax(axis=1) # axis, not dim
return accuracy.compute(predictions=logits, references=labels)
# 測(cè)試下評(píng)估函數(shù)
eval_pred = EvalPrediction(predictions=torch.tensor([[0,1], [2,3]]),
label_ids=torch.tensor([1,1]))
compute_metrics(eval_pred)
準(zhǔn)備訓(xùn)練器屎债,這個(gè)集成封裝得太漂亮了。
args = TrainingArguments(output_dir='./output_dir',
evaluation_strategy='epoch',
num_train_epochs=1,
learning_rate=1e-4,
weight_decay=1e-2,
per_device_eval_batch_size=32,
per_device_train_batch_size=16)
trainer = Trainer(model=model,
args=args,
train_dataset=train_dataset,
eval_dataset=validation_dataset,
compute_metrics=compute_metrics)
trainer.evaluate() # 看看隨機(jī)初始化的推理垢油,應(yīng)該是55開
開始訓(xùn)練盆驹,直接能給出各種結(jié)果,而且自動(dòng)調(diào)用GPU
了滩愁。
trainer.train() # torch.optim.AdamW
trainer.save_model(output_dir='./output_dir/manual')
最后躯喇,推理測(cè)試,用之前準(zhǔn)備的測(cè)試集硝枉。如果只是看看指標(biāo)廉丽,可以:
trainer.evaluate(eval_dataset=test_dataset)
但是想得到詳細(xì)的推理結(jié)果,這里使用Pytorch
的DataLoader
來準(zhǔn)備妻味,可能有更方便的方法正压,待研究。
model.eval()
def try_gpu(i=0): # 來自limu
if torch.cuda.device_count() >= i+1:
return torch.device(f'cuda:{i}')
return torch.device('cpu')
device = try_gpu()
def collate_fn(data):
label = [i['label'] for i in data]
input_ids = [i['input_ids'] for i in data]
token_type_ids = [i['token_type_ids'] for i in data]
attention_mask = [i['attention_mask'] for i in data]
# 得到的是List, 轉(zhuǎn)成Tensor
label = torch.LongTensor(label)
input_ids = torch.LongTensor(input_ids)
token_type_ids = torch.LongTensor(token_type_ids)
attention_mask = torch.LongTensor(attention_mask)
return label, input_ids, token_type_ids, attention_mask
test_loader = DataLoader(dataset=test_dataset,
collate_fn=collate_fn,
batch_size=16)
correct, total = 0, 0
for i, (label, input_ids, token_type_ids, attention_mask) in enumerate(test_loader):
label = label.to(device)
input_ids = input_ids.to(device)
token_type_ids = token_type_ids.to(device)
attention_mask = attention_mask.to(device)
out = model(input_ids=input_ids, token_type_ids=token_type_ids, attention_mask=attention_mask)
out = out.logits.argmax(axis=1)
correct += (out==label).sum().item()
total += len(label)
acc = correct / total
print(f'{acc:.3f}')
如果只是簡(jiǎn)單看看幾句話责球,沒必要大動(dòng)干戈焦履。
sentences = ['這家的菜做得不行。', '房間挺干凈的棕诵,也沒有噪聲']
token_out = tokenizer(sentences,
padding=True,
truncation=True,
return_tensors='pt')
token_out.to(device)
out = model(**token_out)
out = out.logits.argmax(axis=1)
for i, s in enumerate(sentences):
print(s, out[i].item())
就先這么著裁良。