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
相关推荐
结局无敌1 小时前
React Native for OpenHarmony 实战:三方库 react-native-modal-dialog 的鸿蒙化适配指南
深度学习·算法·react native·react.js·harmonyos
在所不辞兄2 小时前
为什么神经网络对对抗扰动和分布偏移往往比较脆弱,而人类感知相对更鲁棒?
人工智能·深度学习·神经网络·机器学习
szxinmai主板定制专家3 小时前
储能 EMS、微网控制器选型:RK3588、RK3576、RK3568+FPGA 怎么选?多网、多 CAN、EMC 设计权衡
人工智能·深度学习·机器学习·fpga开发·工业网关·rk3576·电力网关
鬼手点金3 小时前
Harness 工程:模型之外的竞争力
服务器·人工智能·深度学习·机器学习·bug
结局无敌4 小时前
React Native for OpenHarmony 实战:三方库 react-native-paper 的鸿蒙化适配指南
javascript·人工智能·深度学习·react native·react.js·ecmascript·harmonyos
在所不辞兄4 小时前
【神经网络干货】把指数级计算拆成四条一维路径:可分离 PI-DeepONet 如何破解高维 PDE
人工智能·深度学习·神经网络·机器学习
CV爱数码4 小时前
论文精读|FBPConvNet:先 FBP 再 U-Net,深度学习 CT 重建的起点
人工智能·深度学习·ct·重建
结局无敌4 小时前
React Native for OpenHarmony 实战:三方库 react-native-progress-steps 的鸿蒙化适配指南
javascript·人工智能·深度学习·react native·react.js·harmonyos
DongQiShanRen4 小时前
宇宙(上):分身创建——三条件触发与差异化演化
人工智能·深度学习·自然语言处理·数据挖掘
余槐i5 小时前
近期技术热点:从异常现象到根因定位的完整排查
人工智能·深度学习·机器学习