https://www.bilibili.com/video/BV1K5411t7MD?p=5
https://www.youtube.com/channel/UCoRX98PLOsaN8PtekB9kWrw/videos
深入BERT实战(PyTorch) by ChrisMcCormickAI
这是ChrisMcCormickAI在油管bert,8集系列第二篇WordPiece Embeddings的pytorch的讲解的代码,在油管视频下有下载地址,如果不能翻墙的可以留下邮箱我全部看完整理后发给你。

文章目录

  • 加载模型
  • 查看Bert中的词汇
  • 单字符
  • Subwords vs. Whole-words
  • 开始子词和中间子词
  • 对于姓名来说
  • 对于数字来说

加载模型

安装huggingface实现

!pip install pytorch-pretrained-bertimport torch
from pytorch_pretrained_bert import BertTokenizer# 加载预训练模型
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')

查看Bert中的词汇

检索整个“tokens”列表,并将它们写入文本文件,可以仔细阅读它们。

with open("vocabulary.txt", 'w', encoding='utf-8') as f:# For each token... 得到每个单词for token in tokenizer.vocab.keys():# Write it out and escape any unicode characters.# 写并且转义为Unicode字符f.write(token + '\n')
  • 打印出来可以得到

  • 前999个词序是保留位置,它们的形式类似于[unused957]

  • 1 - [PAD] 截断
    101 - [UNK] 未知字符
    102 - [CLS] 句首,表示分类任务
    103 - [SEP] BERT中分隔两个输入的句子
    104 - [MASK] MASK机制

  • 第1000-1996行似乎是单个字符的转储。

  • 它们似乎没有按频率排序(例如,字母表中的字母都是按顺序排列的)。

  • 第一个单词是1997位置的The

  • 从这里开始,这些词似乎是按频率排序的。
    前18个单词是完整的单词,第2016位是##s,可能是最常见的子单词。
    最后一个完整单词是29612位的 “necessitated”

单字符

下面的代码打印出词汇表中的所有单字符的token,以及前面带’##'的所有单字符的token。

结果发现这些都是匹配集——每个独立角色都有一个“##”版本。有997个单字符标记。

下面的单元格遍历词汇表,取出所有单个字符标记。

one_chars = []
one_chars_hashes = []# For each token in the vocabulary... 遍历所有单字符
for token in tokenizer.vocab.keys():# Record any single-character tokens.记录下来if len(token) == 1:one_chars.append(token)# Record single-character tokens preceded by the two hashes.# 记录##单字符elif len(token) == 3 and token[0:2] == '##':one_chars_hashes.append(token)

打印单字符的

print('Number of single character tokens:', len(one_chars), '\n')# Print all of the single characters, 40 per row.# For every batch of 40 tokens...
for i in range(0, len(one_chars), 40):# Limit the end index so we don't go past the end of the list.end = min(i + 40, len(one_chars) + 1)# Print out the tokens, separated by a space.print(' '.join(one_chars[i:end]))

打印##单字符的

print('Number of single character tokens with hashes:', len(one_chars_hashes), '\n')# Print all of the single characters, 40 per row.按每行40打印# Strip the hash marks, since they just clutter the display.去除##
tokens = [token.replace('##', '') for token in one_chars_hashes]# For every batch of 40 tokens...每批40
for i in range(0, len(tokens), 40):# Limit the end index so we don't go past the end of the list.限制结束位置end = min(i + 40, len(tokens) + 1)# Print out the tokens, separated by a space.print(' '.join(tokens[i:end]))
Number of single character tokens: 997 ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ [ \ ] ^ _ ` a b
c d e f g h i j k l m n o p q r s t u v w x y z { | } ~ ¡ ¢ £ ¤ ¥ ¦ § ¨ © ª « ¬
® ° ± ² ³ ´ µ ¶ · ¹ º » ¼ ½ ¾ ¿ × ß æ ð ÷ ø þ đ ħ ı ł ŋ œ ƒ ɐ ɑ ɒ ɔ ɕ ə ɛ ɡ ɣ ɨ
ɪ ɫ ɬ ɯ ɲ ɴ ɹ ɾ ʀ ʁ ʂ ʃ ʉ ʊ ʋ ʌ ʎ ʐ ʑ ʒ ʔ ʰ ʲ ʳ ʷ ʸ ʻ ʼ ʾ ʿ ˈ ː ˡ ˢ ˣ ˤ α β γ δ
ε ζ η θ ι κ λ μ ν ξ ο π ρ ς σ τ υ φ χ ψ ω а б в г д е ж з и к л м н о п р с т у
ф х ц ч ш щ ъ ы ь э ю я ђ є і ј љ њ ћ ӏ ա բ գ դ ե թ ի լ կ հ մ յ ն ո պ ս վ տ ր ւ
ք ־ א ב ג ד ה ו ז ח ט י ך כ ל ם מ ן נ ס ע ף פ ץ צ ק ר ש ת ، ء ا ب ة ت ث ج ح خ د
ذ ر ز س ش ص ض ط ظ ع غ ـ ف ق ك ل م ن ه و ى ي ٹ پ چ ک گ ں ھ ہ ی ے अ आ उ ए क ख ग च
ज ट ड ण त थ द ध न प ब भ म य र ल व श ष स ह ा ि ी ो । ॥ ং অ আ ই উ এ ও ক খ গ চ ছ জ
ট ড ণ ত থ দ ধ ন প ব ভ ম য র ল শ ষ স হ া ি ী ে க ச ட த ந ன ப ம ய ர ல ள வ ா ி ு ே
ை ನ ರ ಾ ක ය ර ල ව ා ก ง ต ท น พ ม ย ร ล ว ส อ า เ ་ ། ག ང ད ན པ བ མ འ ར ལ ས မ ა
ბ გ დ ე ვ თ ი კ ლ მ ნ ო რ ს ტ უ ᄀ ᄂ ᄃ ᄅ ᄆ ᄇ ᄉ ᄊ ᄋ ᄌ ᄎ ᄏ ᄐ ᄑ ᄒ ᅡ ᅢ ᅥ ᅦ ᅧ ᅩ ᅪ ᅭ ᅮ
ᅯ ᅲ ᅳ ᅴ ᅵ ᆨ ᆫ ᆯ ᆷ ᆸ ᆼ ᴬ ᴮ ᴰ ᴵ ᴺ ᵀ ᵃ ᵇ ᵈ ᵉ ᵍ ᵏ ᵐ ᵒ ᵖ ᵗ ᵘ ᵢ ᵣ ᵤ ᵥ ᶜ ᶠ ‐ ‑ ‒ – — ―
‖ ‘ ’ ‚ “ ” „ † ‡ • … ‰ ′ ″ › ‿ ⁄ ⁰ ⁱ ⁴ ⁵ ⁶ ⁷ ⁸ ⁹ ⁺ ⁻ ⁿ ₀ ₁ ₂ ₃ ₄ ₅ ₆ ₇ ₈ ₉ ₊ ₍
₎ ₐ ₑ ₒ ₓ ₕ ₖ ₗ ₘ ₙ ₚ ₛ ₜ ₤ ₩ € ₱ ₹ ℓ № ℝ ™ ⅓ ⅔ ← ↑ → ↓ ↔ ↦ ⇄ ⇌ ⇒ ∂ ∅ ∆ ∇ ∈ − ∗
∘ √ ∞ ∧ ∨ ∩ ∪ ≈ ≡ ≤ ≥ ⊂ ⊆ ⊕ ⊗ ⋅ ─ │ ■ ▪ ● ★ ☆ ☉ ♠ ♣ ♥ ♦ ♭ ♯ ⟨ ⟩ ⱼ ⺩ ⺼ ⽥ 、 。 〈 〉
《 》 「 」 『 』 〜 あ い う え お か き く け こ さ し す せ そ た ち っ つ て と な に ぬ ね の は ひ ふ へ ほ ま み
む め も や ゆ よ ら り る れ ろ を ん ァ ア ィ イ ウ ェ エ オ カ キ ク ケ コ サ シ ス セ タ チ ッ ツ テ ト ナ ニ ノ ハ
ヒ フ ヘ ホ マ ミ ム メ モ ャ ュ ョ ラ リ ル レ ロ ワ ン ・ ー 一 三 上 下 不 世 中 主 久 之 也 事 二 五 井 京 人 亻 仁
介 代 仮 伊 会 佐 侍 保 信 健 元 光 八 公 内 出 分 前 劉 力 加 勝 北 区 十 千 南 博 原 口 古 史 司 合 吉 同 名 和 囗 四
国 國 土 地 坂 城 堂 場 士 夏 外 大 天 太 夫 奈 女 子 学 宀 宇 安 宗 定 宣 宮 家 宿 寺 將 小 尚 山 岡 島 崎 川 州 巿 帝
平 年 幸 广 弘 張 彳 後 御 德 心 忄 志 忠 愛 成 我 戦 戸 手 扌 政 文 新 方 日 明 星 春 昭 智 曲 書 月 有 朝 木 本 李 村
東 松 林 森 楊 樹 橋 歌 止 正 武 比 氏 民 水 氵 氷 永 江 沢 河 治 法 海 清 漢 瀬 火 版 犬 王 生 田 男 疒 発 白 的 皇 目
相 省 真 石 示 社 神 福 禾 秀 秋 空 立 章 竹 糹 美 義 耳 良 艹 花 英 華 葉 藤 行 街 西 見 訁 語 谷 貝 貴 車 軍 辶 道 郎
郡 部 都 里 野 金 鈴 镇 長 門 間 阝 阿 陳 陽 雄 青 面 風 食 香 馬 高 龍 龸 fi fl ! ( ) , - . / : ? ~

上面两段代码及 ##+单字符单字符 结果一样

# return True
print('Are the two sets identical?', set(one_chars) == set(tokens))

Subwords vs. Whole-words

打印一些词汇的统计数据。

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as npsns.set(style='darkgrid')# Increase the plot size and font size.
sns.set(font_scale=1.5)
plt.rcParams["figure.figsize"] = (10,5)# Measure the length of every token in the vocab. 加载每个单词
token_lengths = [len(token) for token in tokenizer.vocab.keys()]# Plot the number of tokens of each length.
sns.countplot(token_lengths)
plt.title('Vocab Token Lengths')
plt.xlabel('Token Length')
plt.ylabel('# of Tokens')print('Maximum token length:', max(token_lengths))


统计一下,’##'开头的tokens。

num_subwords = 0subword_lengths = []# For each token in the vocabulary...
for token in tokenizer.vocab.keys():# If it's a subword...if len(token) >= 2 and token[0:2] == '##':# Tally all subwordsnum_subwords += 1# Measure the sub word length (without the hashes)length = len(token) - 2# Record the lengths.subword_lengths.append(length)

相对于完整词汇表占据的数量

vocab_size = len(tokenizer.vocab.keys())print('Number of subwords: {:,} of {:,}'.format(num_subwords, vocab_size))# Calculate the percentage of words that are '##' subwords.
prcnt = float(num_subwords) / vocab_size * 100.0print('%.1f%%' % prcnt)
Number of subwords: 5,828 of 30,522
19.1%

作图统计的结果

sns.countplot(subword_lengths)
plt.title('Subword Token Lengths (w/o "##")')
plt.xlabel('Subword Length')
plt.ylabel('# of ## Subwords')


可以自行查看下错误拼写的例子

'misspelled' in tokenizer.vocab # Right
'mispelled' in tokenizer.vocab # Wrong
'government' in tokenizer.vocab # Right
'goverment' in tokenizer.vocab # Wrong
'beginning' in tokenizer.vocab # Right
'begining' in tokenizer.vocab # Wrong
'separate' in tokenizer.vocab # Right
'seperate' in tokenizer.vocab # Wrong

对于缩写来说

"can't" in tokenizer.vocab    # False
"cant" in tokenizer.vocab    # False

开始子词和中间子词

对于单个字符,既有单个字符,也有对应每个字符的“##”版本。子词也是如此吗?

# For each token in the vocabulary...
for token in tokenizer.vocab.keys():# If it's a subword...if len(token) >= 2 and token[0:2] == '##':if not token[2:] in tokenizer.vocab:print('Did not find a token for', token[2:])break

可以查看到第一个返回的##ly在词表中,但是ly不在词表中

Did not find a token for ly'##ly' in tokenizer.vocab    # True
'ly' in tokenizer.vocab    # False

对于姓名来说

下载数据

!pip install wgetimport wget
import random print('Beginning file download with wget module')url = 'http://www.gutenberg.org/files/3201/files/NAMES.TXT'
wget.download(url, 'first-names.txt')

编码,小写化,输出长度

# Read them in.
with open('first-names.txt', 'rb') as f:names_encoded = f.readlines()names = []# Decode the names, convert to lowercase, and strip newlines.
for name in names_encoded:try:names.append(name.rstrip().lower().decode('utf-8'))except:continueprint('Number of names: {:,}'.format(len(names)))
print('Example:', random.choice(names))

查看有多少个姓名是在BERT的词表中

num_names = 0# For each name in our list...
for name in names:# If it's in the vocab...if name in tokenizer.vocab:# Tally it.num_names += 1print('{:,} names in the vocabulary'.format(num_names))

对于数字来说

# Count how many numbers are in the vocabulary. 统计词汇表中有多少数字
count = 0# For each token in the vocabulary...
for token in tokenizer.vocab.keys():# Tally if it's a number.if token.isdigit():count += 1# Any numbers >= 10,000?if len(token) > 4:print(token)print('Vocab includes {:,} numbers.'.format(count))

计算一下在1600-2021中有几个数字在

# Count how many dates between 1600 and 2021 are included.
count = 0
for i in range(1600, 2021):if str(i) in tokenizer.vocab:count += 1print('Vocab includes {:,} of 421 dates from 1600 - 2021'.format(count))

深入Bert实战(Pytorch)----WordPiece Embeddings相关推荐

  1. 深入Bert实战(Pytorch)----fine-Tuning 2

    深入Bert实战(Pytorch)----fine-Tuning 2 https://www.bilibili.com/video/BV1K5411t7MD?p=5 https://www.youtu ...

  2. [NLP]基于IMDB影评情感分析之BERT实战-测试集上92.24%

    系列文章目录 深度学习NLP(一)之Attention Model; 深度学习NLP(二)之Self-attention, Muti-attention和Transformer; 深度学习NLP(三) ...

  3. BERT 的 PyTorch 实现(超详细)

    B站视频讲解 本文主要介绍一下如何使用 PyTorch 复现BERT.请先花上 10 分钟阅读我的这篇文章 BERT详解(附带ELMo.GPT介绍),再来看本文,方能达到醍醐灌顶,事半功倍的效果 准备 ...

  4. 最强NLP模型BERT喜迎PyTorch版!谷歌官方推荐,也会支持中文

    郭一璞 夏乙 发自 凹非寺  量子位 报道 | 公众号 QbitAI 谷歌的最强NLP模型BERT发布以来,一直非常受关注,上周开源的官方TensorFlow实现在GitHub上已经收获了近6000星 ...

  5. Bert实战--文本分类(一)

    使用Bert预训练模型进行文本分类 bert做文本分类,简单来说就是将每句话的第一个位置加入了特殊分类嵌入[CLS].而该[CLS]包含了整个句子的信息,它的最终隐藏状态(即,Transformer的 ...

  6. BERT实战(1):使用DistilBERT作为词嵌入进行文本情感分类,与其它词向量(FastText,Word2vec,Glove)进行对比

    这次根据一篇教程Jay Alammar: A Visual Guide to Using BERT for the First Time学习下如何在Pytorch框架下使用BERT. 主要参考了中文翻 ...

  7. 深度学习-nlp系列(2)文本分类(Bert)pytorch

    对于 Bert 来说,用于文本分类是最常见的,并且准确率也很高.本文将会对 bert 用于文本分类来做详细的介绍. 预训练模型 对于不同的数据,需要导入不同的预训练模型. 预训练模型下载地址:Mode ...

  8. 广告行业中那些趣事系列2:BERT实战NLP文本分类任务(附github源码)

    微信公众号:数据拾光者.愿结交更多的小伙伴,一同走人生路. 摘要:上一篇广告中那些趣事系列1:广告统一兴趣建模流程,我们了解了如何为广告主圈人群以及如何刻画用户的兴趣度.要想给用户打标签,我们需要构建 ...

  9. 文本分类实战----数据处理篇----embeddings与vocab中词汇不相覆盖问题的处理办法

    上一篇文章我们讲了一些数据处理的方法.这一篇我们来对数据进行一些分析,帮助我们更好的理解数据的基础上,为后面的工作做一些基础.也希望有一些积累,在后面遇到相似的任务事可以举一反三. 好了,话不多说,我 ...

  10. bert中文文本情感分类 微博评论挖掘之Bert实战应用案例-文本情感分类

    Bert模型全称Bidirectional Encoder Representations from Transformers,主要分为两个部分:1训练语言模型(language model)的预训练 ...

最新文章

  1. GridSearchCV 与 RandomizedSearchCV 调参
  2. 《python核心编程第二版》第5章习题
  3. 百度母婴技术团队—基于Reactjs实现webapp #1
  4. 《疯狂Java讲义》5
  5. BeanDefinition的载入和解析
  6. (2) ebj学习:hello world入门案例
  7. 考研生的努力程度是有多恐怖!
  8. 华为魔术手机拆机图解_华为P9进水不显示维修案例
  9. Solution 7: 判断两链表是否相交
  10. 4 初学入门_2020年最新版,如何挑选入门级,进阶级和专业级网球拍(12月更新)...
  11. Failed to find provider null for user 0; expected to find a valid ContentProvider for this authority
  12. 路由器刷固件——斐讯路由器FIR300M刷OpenWrt固件教程
  13. 冒泡排序 BubbleSort
  14. 在计算机中打开word2010三种方法,打开word的软件电脑 怎么在电脑上打开word
  15. UWP 如何访问本地代理
  16. 岁月划过生命线(从阿里到微店)
  17. 癌症最新研究进展(2021年10月)
  18. 云流化云渲染技术在vr看房/装修领域是怎样实现的?
  19. BUAA_4:Kevin·Feng的正确@姿势
  20. 互联网创业赚钱规则,彻底释放自己的价值吧!丨国仁网络

热门文章

  1. android 摄像头黑屏,5+app 安卓调用摄像头黑屏 苹果可以
  2. 阅读“变形计”:一场偶然与非偶然的相遇
  3. android背景置灰,android view置灰(哀悼日)
  4. android NDK 基础普及
  5. 又一个程序猿的奋斗史——第二章 实习
  6. QQ游戏大厅产品体验报告
  7. 大数据处理的基本流程是什么?
  8. win10计算机安全模式怎么,Win10进入安全模式的多种方法
  9. 免费备案查询API,支持通过主办单位名称查询备案信息
  10. Method类及相关类解读