HuggingFace学习笔记--利用API实现简单的NLP任务

目录

1--中文分类

1-1--使用预训练模型推理

1-2--基于预训练模型实现下游任务

2--中文填空

3--中文句子关系推断


1--中文分类

1-1--使用预训练模型推理

代码实例:

python 复制代码
import torch
from datasets import load_dataset
from transformers import BertTokenizer, BertModel

# 定义全局分词工具
tokenizer = BertTokenizer.from_pretrained('bert-base-chinese')

# 定义数据集
class Dataset(torch.utils.data.Dataset):
    def __init__(self, split):
        self.dataset = load_dataset(path = 'lansinuote/ChnSentiCorp', split = split) # 加载数据集

    def __len__(self):
        return len(self.dataset)

    def __getitem__(self, i):
        text = self.dataset[i]['text']
        label = self.dataset[i]['label']
        return text, label

# 自定义数据的处理(加载)方式
def my_collate_fn(data): # data 的类型与 dataset 的返回值相同,本例中dataset返回一个列表[text, label]
    # 根据dataset的返回结果,取出对应的text和label
    sents = [i[0] for i in data]
    labels = [i[1] for i in data]

    # 使用全局的分词工具进行编码
    data = tokenizer.batch_encode_plus(batch_text_or_text_pairs = sents,
                                        truncation = True,
                                        padding = 'max_length',
                                        max_length = 500,
                                        return_tensors = 'pt',
                                        return_length = True)
    input_ids = data['input_ids']
    attention_mask = data['attention_mask']
    token_type_ids = data['token_type_ids']
    labels = torch.LongTensor(labels)
    return input_ids, attention_mask, token_type_ids, labels

def main():
    dataset = Dataset('train') # 初始化训练集
    # print(len(dataset), dataset[0])
    
    # 定义dataloader
    loader = torch.utils.data.DataLoader(dataset = dataset,
                                        batch_size = 16,
                                        collate_fn = my_collate_fn,
                                        shuffle = True,
                                        drop_last = True)
    
    # 遍历dataloader加载数据
    for i, (input_ids, attention_mask, token_type_ids, labels) in enumerate(loader):
        break
    print(len(loader))
    print(input_ids.shape, attention_mask.shape, token_type_ids.shape, labels) # 打印一个样本
    
    # 加载预训练模型
    model = BertModel.from_pretrained('bert-base-chinese')
    for param in model.parameters(): # 不进行梯度计算和反向传播
        param.requires_grad_(False)
    # 调用预训练模型推理一个样本    
    output = model(input_ids = input_ids, attention_mask = attention_mask, token_type_ids = token_type_ids)
    print(output.last_hidden_state.shape) # 打印最后一个隐层输出特征的维度

if __name__ == "__main__":
    main()
    print("All done!")

输出结果:

python 复制代码
# dataloader单个样本:
torch.Size([16, 500]) 
torch.Size([16, 500]) 
torch.Size([16, 500]) 
tensor([1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1])
# 最后一个隐层的输出特征:
torch.Size([16, 500, 768])

1-2--基于预训练模型实现下游任务

利用预训练 bert 模型最后一个隐层的[cls] token的特征进行中文分类;

代码:

python 复制代码
import torch
from datasets import load_dataset
from transformers import BertTokenizer, BertModel, AdamW

# 定义全局分词工具
tokenizer = BertTokenizer.from_pretrained('bert-base-chinese')

# 定义数据集
class Dataset(torch.utils.data.Dataset):
    def __init__(self, split):
        self.dataset = load_dataset(path = 'lansinuote/ChnSentiCorp', split = split) # 加载数据集

    def __len__(self):
        return len(self.dataset)

    def __getitem__(self, i):
        text = self.dataset[i]['text']
        label = self.dataset[i]['label']
        return text, label

# 自定义数据的处理(加载)方式
def my_collate_fn(data): # data 的类型与 dataset 的返回值相同,本例中dataset返回一个列表[text, label]
    # 根据dataset的返回结果,取出对应的text和label
    sents = [i[0] for i in data]
    labels = [i[1] for i in data]

    # 使用全局的分词工具进行编码
    data = tokenizer.batch_encode_plus(batch_text_or_text_pairs = sents,
                                        truncation = True,
                                        padding = 'max_length',
                                        max_length = 500,
                                        return_tensors = 'pt',
                                        return_length = True)
    input_ids = data['input_ids']
    attention_mask = data['attention_mask']
    token_type_ids = data['token_type_ids']
    labels = torch.LongTensor(labels)
    return input_ids, attention_mask, token_type_ids, labels

# 定义下游任务模型
class Model(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.pretrained_model = BertModel.from_pretrained('bert-base-chinese') # 加载预训练模型
        self.fc = torch.nn.Linear(768, 2)
        
        # 固定预训练模型
        for param in self.pretrained_model.parameters():
            param.requires_grad = False

    def forward(self, input_ids, attention_mask, token_type_ids):
        with torch.no_grad():
            output = self.pretrained_model(input_ids=input_ids,
                       attention_mask=attention_mask,
                       token_type_ids=token_type_ids)

        output = self.fc(output.last_hidden_state[:, 0]) # 利用最后一个隐层的[cls]token特征进行分类

        output = output.softmax(dim=1)

        return output

# 定义测试函数
def test(model, dataset):
    model.eval()
    correct = 0
    total = 0
    # 定义加载测试集的dataloader
    loader_test = torch.utils.data.DataLoader(dataset = dataset,
                                              batch_size = 32,
                                              collate_fn = my_collate_fn,
                                              shuffle = True,
                                              drop_last = True)
    for idx, (input_ids, attention_mask, token_type_ids, labels) in enumerate(loader_test):
        if idx == 5: # 测试5个batch
            break
        print(idx)
        with torch.no_grad():
            input_ids = input_ids.cuda()
            attention_mask = attention_mask.cuda()
            token_type_ids = token_type_ids.cuda()
            labels = labels.cuda()
            output = model(input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids)

        output = output.argmax(dim=1)
        correct += (output == labels).sum().item()
        total += len(labels)
    print("Acc: ", correct / total) # 打印5个batch的总体准确率

def main():
    dataset = Dataset('train') # 初始化训练集
    # print(len(dataset), dataset[0])
    
    # 定义dataloader
    loader = torch.utils.data.DataLoader(dataset = dataset,
                                        batch_size = 16,
                                        num_workers = 8,
                                        collate_fn = my_collate_fn,
                                        shuffle = True,
                                        drop_last = True)
    # 初始化模型
    model = Model()
    model = model.cuda() # 使用GPU

    # 初始化优化器和损失函数
    optimizer = AdamW(model.parameters(), lr=5e-4)
    criterion = torch.nn.CrossEntropyLoss().cuda()
    
    # 训练模型
    model.train()
    for idx, (input_ids, attention_mask, token_type_ids, labels) in enumerate(loader): # 遍历加载数据
        input_ids = input_ids.cuda()
        attention_mask = attention_mask.cuda()
        token_type_ids = token_type_ids.cuda()
        labels = labels.cuda()
        output = model(input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids)
        loss = criterion(output, labels)
        loss.backward()
        optimizer.step()
        optimizer.zero_grad()

        if idx % 5 == 0: # 每5个batch打印当前准确率和损失
            output = output.argmax(dim=1)
            accuracy = (output == labels).sum().item() / len(labels)
            print(idx, loss.item(), accuracy)
        if idx == 300: # 使用300个batch进行训练
            break
        
    # 测试模型
    test(model, Dataset('validation'))

if __name__ == "__main__":
    main()

部分输出结果:

python 复制代码
...
260 0.5995925664901733 0.75
265 0.3791050910949707 1.0
270 0.42692136764526367 0.9375
275 0.4765201210975647 0.875
280 0.4071955382823944 0.9375
285 0.4194560945034027 0.875
290 0.449373722076416 0.9375
295 0.38813596963882446 1.0
300 0.5164415240287781 0.875
Acc:  0.89375

2--中文填空

对训练数据的第15个词进行 mask 掉,预测第15个词;

利用 bert 模型提取特征,对最后一个隐层的第15个token特征进行分类;

分类用的是一个简单的线性层,其维度为(768, token.vocab_size),其中token.vocab_sized的大小为21128,即预测21128个词的分类分数,再与真实标签进行损失计算;

代码:

python 复制代码
import torch
from datasets import load_dataset, load_from_disk
from transformers import BertTokenizer, BertModel, AdamW

# 定义全局分词工具
token = BertTokenizer.from_pretrained('bert-base-chinese')

# 定义数据集
class Dataset(torch.utils.data.Dataset):
    def __init__(self, split):
        dataset = load_dataset(path = 'lansinuote/ChnSentiCorp', split = split)
        # dataset = load_from_disk('./data/ChnSentiCorp')
        # dataset = dataset[split]

        def f(data):
            return len(data['text']) > 30
        self.dataset = dataset.filter(f) # 筛选数据集

    def __len__(self):
        return len(self.dataset)

    def __getitem__(self, i):
        text = self.dataset[i]['text']

        return text
        
def collate_fn(data):
    # batch编码
    data = token.batch_encode_plus(batch_text_or_text_pairs = data,
                                   truncation = True,
                                   padding = 'max_length',
                                   max_length = 30, # padding到30个词
                                   return_tensors = 'pt', # 返回pytorch格式
                                   return_length = True)

    input_ids = data['input_ids']
    attention_mask = data['attention_mask']
    token_type_ids = data['token_type_ids']

    # 把第15个词固定替换为mask
    labels = input_ids[:, 15].reshape(-1).clone() # 记录真实标签
    input_ids[:, 15] = token.get_vocab()[token.mask_token]

    return input_ids, attention_mask, token_type_ids, labels

# 定义下游任务模型
class Model(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.decoder = torch.nn.Linear(768, token.vocab_size, bias=False) # token.vocab_size为21128,预测21128个词的分类分数
        self.bias = torch.nn.Parameter(torch.zeros(token.vocab_size))
        self.decoder.bias = self.bias
        self.pretrained = BertModel.from_pretrained('bert-base-chinese')
        
        # 固定预训练模型
        for param in self.pretrained.parameters():
            param.requires_grad = False

    def forward(self, input_ids, attention_mask, token_type_ids):
        # 使用bert模型提取特征
        with torch.no_grad():
            output = self.pretrained(input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids)

        output = self.decoder(output.last_hidden_state[:, 15])
        return output

# 测试
def test(model):
    model.eval()
    correct = 0
    total = 0

    loader_test = torch.utils.data.DataLoader(dataset = Dataset('test'), 
                                              batch_size = 32, 
                                              collate_fn = collate_fn, 
                                              shuffle = True, 
                                              drop_last = True)

    for idx, (input_ids, attention_mask, token_type_ids, labels) in enumerate(loader_test):
        input_ids = input_ids.cuda()
        attention_mask = attention_mask.cuda()
        token_type_ids = token_type_ids.cuda()
        labels = labels.cuda()
        
        if idx == 15: # 测试15个batch
            break
        with torch.no_grad():
            output = model(input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids)

        output = output.argmax(dim=1)
        correct += (output == labels).sum().item()
        total += len(labels)
        print(token.decode(input_ids[0])) # 打印测试数据
        print("真实标签: ", token.decode(labels[0]), "预测标签: ", token.decode(labels[0]))

    print("Acc: ", correct / total)


def main():
    # 初始化训练集
    dataset = Dataset('train')
    # 定义dataloader
    loader = torch.utils.data.DataLoader(dataset = dataset,
                                            batch_size = 16,
                                            collate_fn = collate_fn,
                                            shuffle = True,
                                            drop_last = True)
    # 初始化模型
    model = Model().cuda()
    
    # 训练
    optimizer = AdamW(model.parameters(), lr=5e-4)
    criterion = torch.nn.CrossEntropyLoss().cuda()
    model.train()
    
    for epoch in range(5):
        for idx, (input_ids, attention_mask, token_type_ids, labels) in enumerate(loader):
            input_ids = input_ids.cuda()
            attention_mask = attention_mask.cuda()
            token_type_ids = token_type_ids.cuda()
            labels = labels.cuda()
            output = model(input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids)
            loss = criterion(output, labels)
            loss.backward()
            optimizer.step()
            optimizer.zero_grad()

            if idx % 50 == 0:
                output = output.argmax(dim=1)
                accuracy = (output == labels).sum().item() / len(labels)
                print(epoch, idx, loss.item(), accuracy)
    # 测试模型            
    test(model)

if __name__ == "__main__":
    main()

部分输出结果:

python 复制代码
4 300 0.633719801902771 1.0
4 350 0.8078413605690002 0.75
4 400 0.7607380747795105 0.75
4 450 1.2219955921173096 0.875
4 500 0.7912384867668152 0.8125
4 550 0.4526982307434082 0.875
Filter: 100%|██████████████████████████████████████████████████| 1200/1200 [00:00<00:00, 152215.71 examples/s]
[CLS] 1. 有 急 事 出 去 , 要 们 童 叫 出 租 [MASK] , 他 们 就 叫 酒 店 里 的 黑 车 , 价 [SEP]
真实标签:  车 预测标签:  车
[CLS] 酒 店 特 别 提 示 [ 2008 / 02 / 29 - 2008 [MASK] 08 / 30 ] 酒 店 对 面 立 交 桥 改 造 [SEP]
真实标签:  / 预测标签:  /
[CLS] 不 知 大 陆 观 众 有 多 少 看 过 台 湾 的 [MASK] 生 活 智 慧 王 [UNK] 节 目 , 里 面 介 绍 [SEP]
真实标签:  [ U N K ] 预测标签:  [ U N K ]
[CLS] 性 价 比 极 高 , 我 在 苏 宁 买 4699 , [MASK] 东 才 4399. 功 能 很 全 , 用 起 来 很 [SEP]
真实标签:  东 预测标签:  东
[CLS] 服 务 态 度 极 其 差 , 前 台 接 待 好 象 [MASK] 有 受 过 培 训 , 连 基 本 的 礼 貌 都 [SEP]
真实标签:  没 预测标签:  没
[CLS] 自 己 马 上 就 有 宝 宝 了 , 期 待 着 宝 [MASK] 降 临 人 世 , 所 以 提 前 看 看 家 教 [SEP]
真实标签:  宝 预测标签:  宝
[CLS] 《 阴 阳 师. 晴 明 取 瘤 》 这 本 书 买 [MASK] 来 放 在 书 架 上 好 段 日 子 , 我 都 [SEP]
真实标签:  回 预测标签:  回
[CLS] 出 差 入 住 的 酒 店, 订 了 个 三 人 间 [MASK] 房 间 没 空 调, 冷 得 要 死, 而 且 [SEP]
真实标签:  . 预测标签:  .
[CLS] 2007 年 9 月 11 日 256 元 住 普 通 标 间 , [MASK] 街 ( 其 它 房 型 已 无 ) 。 我 是 喜 [SEP]
真实标签:  临 预测标签:  临
[CLS] 1 、 作 为 便 携 本 , 重 了 一 点 , 厚 [MASK] 一 些 2 、 屏 幕 确 实 太 小 了 , 上 [SEP]
真实标签:  了 预测标签:  了
[CLS] 官 方 给 的 [UNK] 碟 子 和 驱 动 真 是 让 人 [MASK] 郁 闷 , 拿 到 还 是 自 己 重 新 装 的 [SEP]
真实标签:  很 预测标签:  很
[CLS] 外 观 设 计 别 出 心 裁 ! 配 置 均 衡 性 [MASK] 比 高 , 比 [UNK] 系 列 又 有 进 步 。 散 [SEP]
真实标签:  价 预测标签:  价
[CLS] 酒 店 的 位 置 很 好, 距 离 火 车 站 非 [MASK] 近. 总 提 感 觉 酒 店 的 性 价 比 不 [SEP]
真实标签:  常 预测标签:  常
[CLS] 虽 然 只 是 刚 刚 开 始 阅 读 , 但 是 已 [MASK] 给 我 带 来 很 多 思 想 冲 击 了 。 一 [SEP]
真实标签:  经 预测标签:  经
[CLS] 于 丹 的 < < 论 语 心 得 > > 简 直 就 [MASK] 胡 说 八 道 。 除 了 《 论 语 》 之 外 [SEP]
真实标签:  是 预测标签:  是
Acc:  0.7229166666666667

3--中文句子关系推断

代码:

python 复制代码
import torch
import random
from datasets import load_dataset, load_from_disk
from transformers import BertTokenizer, BertModel, AdamW

# 定义全局分词工具
token = BertTokenizer.from_pretrained('bert-base-chinese')

# 定义数据集
class Dataset(torch.utils.data.Dataset):
    def __init__(self, split):
        # dataset = load_dataset(path='lansinuote/ChnSentiCorp', split=split)
        dataset = load_from_disk('./data/ChnSentiCorp')
        dataset = dataset[split]

        def f(data):
            return len(data['text']) > 40

        self.dataset = dataset.filter(f)

    def __len__(self):
        return len(self.dataset)

    def __getitem__(self, i):
        text = self.dataset[i]['text']

        # 切分一句话为前半句和后半句
        sentence1 = text[:20]
        sentence2 = text[20:40]
        label = 0 # label为0表示为同一句

        # 有一半的概率把后半句替换为一句无关的话
        if random.randint(0, 1) == 0:
            j = random.randint(0, len(self.dataset) - 1)
            sentence2 = self.dataset[j]['text'][20:40]
            label = 1

        return sentence1, sentence2, label

def collate_fn(data):
    sents = [i[:2] for i in data]
    labels = [i[2] for i in data]

    # 编码
    data = token.batch_encode_plus(batch_text_or_text_pairs = sents,
                                   truncation = True,
                                   padding = 'max_length',
                                   max_length = 45,
                                   return_tensors = 'pt',
                                   return_length = True,
                                   add_special_tokens = True)

    input_ids = data['input_ids']
    attention_mask = data['attention_mask']
    token_type_ids = data['token_type_ids']
    labels = torch.LongTensor(labels)

    return input_ids, attention_mask, token_type_ids, labels

# 定义下游任务模型
class Model(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.fc = torch.nn.Linear(768, 2) # 二分类
        self.pretrained = BertModel.from_pretrained('bert-base-chinese')
        
        # 固定预训练模型
        for param in self.pretrained.parameters():
            param.requires_grad = False

    def forward(self, input_ids, attention_mask, token_type_ids):
        with torch.no_grad():
            output = self.pretrained(input_ids = input_ids, attention_mask = attention_mask, token_type_ids = token_type_ids)

        output = self.fc(output.last_hidden_state[:, 0])
        output = output.softmax(dim=1)
        return output
 
def main():
    model = Model().cuda()
    optimizer = AdamW(model.parameters(), lr=5e-4)
    criterion = torch.nn.CrossEntropyLoss().cuda() 
    
    # dataloader
    loader = torch.utils.data.DataLoader(dataset = Dataset('train'),
                                        batch_size = 8,
                                        collate_fn = collate_fn,
                                        shuffle = True,
                                        drop_last = True)  
    # 训练
    model.train()
    
    for idx, (input_ids, attention_mask, token_type_ids, labels) in enumerate(loader):
        input_ids = input_ids.cuda()
        attention_mask = attention_mask.cuda()
        token_type_ids = token_type_ids.cuda()
        labels = labels.cuda()
        output = model(input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids)

        loss = criterion(output, labels)
        loss.backward()
        optimizer.step()
        optimizer.zero_grad()

        if idx % 5 == 0: # 每5个batch打印
            output = output.argmax(dim=1)
            accuracy = (output == labels).sum().item() / len(labels)
            print(idx, loss.item(), accuracy)

        if idx == 300: # 训练300个batch
            break
    
    # 测试
    test(model)

# 定义测试函数
def test(model):
    model.eval()
    correct = 0
    total = 0
    loader_test = torch.utils.data.DataLoader(dataset = Dataset('test'),
                                              batch_size = 32,
                                              collate_fn = collate_fn,
                                              shuffle = True,
                                              drop_last = True)

    for idx, (input_ids, attention_mask, token_type_ids, labels) in enumerate(loader_test):
        input_ids = input_ids.cuda()
        attention_mask = attention_mask.cuda()
        token_type_ids = token_type_ids.cuda()
        labels = labels.cuda()
        if idx == 5: # 测试5个batch
            break
        with torch.no_grad():
            output = model(input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids)

        pred = output.argmax(dim=1)
        correct += (pred == labels).sum().item()
        total += len(labels)

    print('acc:', correct / total)
    
if __name__ == "__main__":
    main()

部分运行结果:

python 复制代码
240 0.39283961057662964 0.875
245 0.7069525122642517 0.5
250 0.41953372955322266 0.875
255 0.5032698512077332 0.75
260 0.6422066688537598 0.75
265 0.5467717051506042 0.75
270 0.4452913701534271 0.875
275 0.5998544096946716 0.625
280 0.4301206171512604 0.875
285 0.5177156329154968 0.75
290 0.3987200856208801 0.875
295 0.33609679341316223 1.0
300 0.3723036050796509 0.875
acc: 0.925
相关推荐
lixy57919 分钟前
深度学习3.7 softmax回归的简洁实现
人工智能·深度学习·回归
多巴胺与内啡肽.2 小时前
深度学习--自然语言处理统计语言与神经语言模型
深度学习·语言模型·自然语言处理
深度之眼3 小时前
2025时间序列都有哪些创新点可做——总结篇
人工智能·深度学习·机器学习·时间序列
不吃香菜?5 小时前
PyTorch 实现食物图像分类实战:从数据处理到模型训练
人工智能·深度学习
Light605 小时前
智启未来:深度解析Python Transformers库及其应用场景
开发语言·python·深度学习·自然语言处理·预训练模型·transformers库 |·|应用场景
数据智能老司机6 小时前
构建具备自主性的人工智能系统——在生成式人工智能系统中构建信任
深度学习·llm·aigc
谦行7 小时前
工欲善其事,必先利其器—— PyTorch 深度学习基础操作
pytorch·深度学习·ai编程
xwz小王子7 小时前
Nature Communications 面向形状可编程磁性软材料的数据驱动设计方法—基于随机设计探索与神经网络的协同优化框架
深度学习
生信碱移8 小时前
大语言模型时代,单细胞注释也需要集思广益(mLLMCelltype)
人工智能·经验分享·深度学习·语言模型·自然语言处理·数据挖掘·数据可视化
硅谷秋水9 小时前
通过模仿学习实现机器人灵巧操作:综述(上)
人工智能·深度学习·机器学习·计算机视觉·语言模型·机器人