# 深度学习笔记(6)Hugginface -Transformer

深度学习笔记(6)Hugginface -Transformer

一、工具包

1.安装transformer

pip install transformers

安装完成后,你可以通过以下代码在Python中导入transformers来验证安装是否成功:

import transformers
print(transformers.__version__)

然后用一段代码测试一下

import warnings
warnings.filterwarnings("ignore")
from transformers import pipeline#用人家设计好的流程完成一些简单的任务
classifier = pipeline("sentiment-analysis")
classifier(
    [
        "I've been waiting for a HuggingFace course my whole life.",
        "I hate this so much!",
    ]
)

结果如下就是加载成功

[{'label': 'POSITIVE', 'score': 0.9598049521446228},
 {'label': 'NEGATIVE', 'score': 0.9994558691978455}]

基本流程如下
在这里插入图片描述
1.输入文本
2.分词,ipput IDs是分词器得到的结果,把每个词都转换成了唯一的ID。这里我们要指定对应的分词器,转换成list
3.输入到模型中得到预测结果。
4.后处理

二、 Tokenizer

Tokenizer要做的事:

  • 分词,分字以及特殊字符(起始,终止,间隔,分类等特殊字符可以自己设计的)
  • 对每一个token映射得到一个ID(每个词都会对应一个唯一的ID)
  • 还有一些辅助信息也可以得到,比如当前词属于哪个句子(还有一些MASK,表示是否事原来的词还是特殊字符等)
from transformers import AutoTokenizer#自动判断,这段代码基本可以不用改,它会根据你后面引用的模型来看
checkpoint = "distilbert-base-uncased-finetuned-sst-2-english"#根据这个模型所对应的来加载,模型去Hugginface的官网去找,可以根据对应的名字去搜索
tokenizer = AutoTokenizer.from_pretrained(checkpoint)

然后进行输入


raw_inputs = [
    "I've been waiting for a this course my whole life.",#指定的两句话
    "I hate this so much!",
]
inputs = tokenizer(raw_inputs, padding=True, truncation=True, return_tensors="pt")
print(inputs)

这几个参数是什么意思呢,第一个是padding,因为两个句子长度不一样,所以需要把这两句话作成长度一样的,padding=true默认是按长度长那个算,比如第一句5个,第二句10个,那就会把第一个补0.
truncation截断,这里可以自己指定,就是最大的字数都长度。比如最大长度为8,那I’ve been waiting for a this course my whole life就只能留下I’ve been waiting for a this course my
return_tensors 选择底层是啥pt就是pytorch,tensorflow就分tf

运行结果如下

{'input_ids': tensor([[ 101, 1045, 1005, 2310, 2042, 3403, 2005, 1037, 2023, 2607, 2026, 2878,
         2166, 1012,  102],
        [ 101, 1045, 5223, 2023, 2061, 2172,  999,  102,    0,    0,    0,    0,
            0,    0,    0]]), 'attention_mask': tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0]])}

  [[ 101, 1045, 1005, 2310, 2042, 3403, 2005, 1037, 2023, 2607, 2026, 2878,
2166, 1012, 102],是第一个
   第二个是 [ 101, 1045, 5223, 2023, 2061, 2172, 999, 102, 0, 0, 0, 0,
0, 0, 0] ,按理说第二个只有 6个单词,为啥有8个呢,因为存在一些特殊字符,101和102是特殊字符cls和sep sep之后都是补0的,也就是没意义的东西。
   'attention_mask中为1的是 作attention的时候要去算的,为1的就是要去算的,为0就是不去算的,比如第二句话后面补0的都是没意义的,所以没必要算。不会参与到selfattention中。

tokenizer.decode([ 101, 1045, 1005, 2310, 2042, 3403, 2005, 1037, 2023, 2607, 2026, 2878,2166, 1012,  102])             

解码看下编码的是啥

"[CLS] i've been waiting for a this course my whole life. [SEP]"

三、 模型加载

from transformers import AutoModel#还是一样自动选模型

checkpoint = "distilbert-base-uncased-finetuned-sst-2-english"#模型的名字
model = AutoModel.from_pretrained(checkpoint)#从预训练中直接选择
model#打印出来观察下
DistilBertModel(
  (embeddings): Embeddings(
    (word_embeddings): Embedding(30522, 768, padding_idx=0)
    (position_embeddings): Embedding(512, 768)
    (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)
    (dropout): Dropout(p=0.1, inplace=False)
  )
  (transformer): Transformer(
    (layer): ModuleList(
      (0-5): 6 x TransformerBlock(
        (attention): MultiHeadSelfAttention(
          (dropout): Dropout(p=0.1, inplace=False)
          (q_lin): Linear(in_features=768, out_features=768, bias=True)
          (k_lin): Linear(in_features=768, out_features=768, bias=True)
          (v_lin): Linear(in_features=768, out_features=768, bias=True)
          (out_lin): Linear(in_features=768, out_features=768, bias=True)
        )
        (sa_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)
        (ffn): FFN(
          (dropout): Dropout(p=0.1, inplace=False)
          (lin1): Linear(in_features=768, out_features=3072, bias=True)
          (lin2): Linear(in_features=3072, out_features=768, bias=True)
          (activation): GELUActivation()
        )
        (output_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)
      )
    )
  )
)
outputs = model(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值