NLP-transformer-分词库用法

NLP-transformer-分词库用法

 

参考文档: https://blog.csdn.net/orangerfun/article/details/124089467

1 pip install transformer

2 下载专有的vocab.txt词典

  这个词典用于 把 单词-> id -> 词向量

  https://github.com/google-research/bert

  

 

 

 

3 实例化分词实例

1 from transformers import BertTokenizer
2 import torch
3 
4 token = r"vocab.txt"
5 
6 bert_tokenizer = BertTokenizer(vocab_file=token)
View Code

4 分词任务

# 1 分词任务
res = bert_tokenizer.tokenize("山海关总兵官吴三桂")
print(res)

['山', '海', '关', '总', '兵', '官', '吴', '三', '桂']

 

5 转为id

# 2 转化为id
# 接受一个词或字列表
idres = bert_tokenizer.convert_tokens_to_ids("山海关总兵官吴三桂")
print(idres)
idres = bert_tokenizer.convert_tokens_to_ids(res)
print(idres)
# 一个字时候是否是准的? 准确id
idres = bert_tokenizer.convert_tokens_to_ids("山")
print(idres)

6 转文字
# id转字
wordres = bert_tokenizer.convert_ids_to_tokens([2255, 3862, 1068, 2600, 1070, 2135, 1426, 676, 3424])
# 可以成功转为对应汉字
print(wordres)
# 来看看 前面误操作的 100 能转为什么
wordres = bert_tokenizer.convert_ids_to_tokens(100)
print(wordres)
View Code

7 使用回调函数 实现批量等工程级别操作

  • text: 需要被编码的文本,可以是一维或二维list        最好是一维的
  • padding: 是否需要padding,可选如下几个值
  • truncation: 是否要进行截断
    True or 'longest_first',保留由max_length指定的长度,或者当max_length没有指定时,截取保留模型最大能接受的长度,对于sentence pair,截取长度最大的句子
    False or 'do_not_truncate (default) 不截取
    only_first,截取到max_length, 但是只截取sentence pair中的第一个句子
    'only_second',同理,只截取pair中第二个句子
    max_length,句子最大长度,和padding及truncation相关

合理动态padding问题

注意 :因为需要添加 句子头和尾

['[CLS]', '我', '爱', '北', '京', '天', '[SEP]']

[101, 2769, 4263, 1266,  776, 1921,  102]
所以如果最大长度max_length,句子最大长度 设置为7的话, 注意5个位置来存实际的内容。

当max_length=10时候,填充为

{'input_ids': tensor([[ 101, 2769, 4263, 1266, 776, 1921, 2128, 7305, 102, 0],
[ 101, 2408, 1767, 1391, 4156, 7883, 102, 0, 0, 0]]),      在 标志位后面添加000

本质: 输出为 输入model的长度 词列表。

最大长度max_length即输入model的最大长度。
examples = [["我爱北京天安门", "广场吃炸鸡"],["苏德战争","俄罗"]]
res = bert_tokenizer(examples,
                padding="max_length",
                truncation=True,
                max_length=10,
                return_tensors="pt",
                return_length=True)
print(res)

{'input_ids': tensor([[ 101, 2769, 4263, 1266,  776,  102, 2408, 1767, 1391,  102],
        [ 101, 5722, 2548, 2773,  751,  102,  915, 5384,  102,    0]]), 'token_type_ids': tensor([[0, 0, 0, 0, 0, 0, 1, 1, 1, 1],
        [0, 0, 0, 0, 0, 0, 1, 1, 1, 0]]), 'length': tensor([10,  9]), 'attention_mask': tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 0]])}
View Code

 

posted on 2023-03-03 09:48  lexn  阅读(81)  评论(0编辑  收藏  举报

导航