![bert-distilbert-句子分类](https://habrastorage.org/webt/1t/0s/2u/1t0s2udwz_c-rqf3jvlxkigemhm.png)
在过去的几年中,用于自然语言处理的机器学习取得了显着的进步。模型离开了研究实验室,并成为领先的数字产品的基础。一个很好的例证就是最近宣布BERT模型已经成为Google搜索背后的主要组成部分。 Google认为,这一步骤(即在搜索引擎中引入一种理解自然语言的高级模型)代表着“过去五年中最大的突破,也是搜索引擎历史上最重要的突破之一”。
本文是使用BERT版本之一对句子进行分类的简单指南。我们研究的示例既简单又足以初次了解该模型,又足够先进以演示关键概念。
除了本文之外,还准备了可以在存储库中查看或在Colab中运行的笔记本电脑。
数据:SST2
在我们的示例中,我们将使用SST2数据集,其中包含来自电影评论的建议,每个建议都有正标签(值1)或负标签(值0):
![sst2](https://habrastorage.org/webt/zn/el/tu/zneltu_kmrm0a2l1duybrs6ust8.png)
型号:句子分类
– , ( , ) 1 ( ), 0 ( ). :
![sentiment-classifier-1.png](https://habrastorage.org/webt/f4/mk/px/f4mkpxxli5t3izoldbz2qzfucei.png)
:
, , 768. , .
![distilbert-bert-sentiment-classifier.png](https://habrastorage.org/webt/0v/2c/2f/0v2c2fzigdyzff3vqurbanyc2tk.png)
, BERT, ELMO ( NLP ): ( [CLS]).
, , . DistilBERT', . , , «» BERT', . , , BERT , [CLS] . , , . , , BERT .
transformers DistilBERT', .
![模型训练](https://habrastorage.org/webt/lx/du/gi/lxdugirbo9cgxehjoggycphulr8.png)
, . DistilBERT' 2 .
![bert-distilbert-教程句嵌入](https://habrastorage.org/webt/bb/uv/_t/bbuv_tdc97jm9upvgj1gcyefemy.png)
DistilBERT'. Scikit Learn. , , :
![伯特·迪迪伯特火车测试拆分句子嵌入](https://habrastorage.org/webt/r_/e3/mq/r_e3mqtxvjry5xoabovb7il_iec.png)
distilBERT' ( #1) , ( #2). , sklearn , , 75% ,
:
![伯特训练逻辑回归](https://habrastorage.org/webt/wn/f6/9k/wnf69kgqr5azls-edvk6gidjoui.png)
, , , .
«a visually stunning rumination on love». BERT' , . , ( [CLS] [SEP] ).
![bert-distilbert-tokenization-1](https://habrastorage.org/webt/rd/cu/me/rdcumeyavzwbbbleog8_tv1y0o8.png)
, . Word2vec .
![bert-distilbert-tokenization-2-token-ids](https://habrastorage.org/webt/-8/o5/tv/-8o5tv8c37kuyvnzvgcr9dt6vam.png)
:
tokenizer.encode("a visually stunning rumination on love", add_special_tokens=True)
DistilBERT'.
BERT, ELMO ( NLP ), :
![](https://habrastorage.org/webt/3u/i-/gl/3ui-glcku_tpcg8cjoghffb0vt0.png)
DistilBERT
DistilBERT' , BERT'. , 768 .
![伯特模型输入输出1](https://habrastorage.org/webt/oq/nf/ip/oqnfip8zglclubfblimrqvwrdz8.png)
, , ( [CLS] ). .
![伯特模型可化验输出向量cls](https://habrastorage.org/webt/vr/-x/my/vr-xmyzsavuid9mrskzpysxbvhw.png)
, , . :
![bert-distilbert句子分类示例](https://habrastorage.org/webt/jm/oy/or/jmoyorskol1nxvxarefclben_ky.png)
, .
. Colab github.
:
import numpy as np
import pandas as pd
import torch
import transformers as ppb
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import train_test_split
github, pandas:
df = pd.read_csv('https://github.com/clairett/pytorch-sentiment-classification/raw/master/data/SST2/train.tsv', delimiter='\t', header=None)
df.head() , 5 , :
df.head()
![sst2-df-head](https://habrastorage.org/webt/t2/-_/tl/t2-_tljwx7gvvwsoqs3hlt6w7ya.png)
DistilBERT
model_class, tokenizer_class, pretrained_weights = (ppb.DistilBertModel, ppb.DistilBertTokenizer, 'distilbert-base-uncased')
tokenizer = tokenizer_class.from_pretrained(pretrained_weights)
model = model_class.from_pretrained(pretrained_weights)
. , , . . ( , 2000).
tokenized = df[0].apply((lambda x: tokenizer.encode(x, add_special_tokens=True)))
.
![sst2-文本到令牌ID的例子](https://habrastorage.org/webt/le/zs/gr/lezsgrmkronylp8wh-kays3c0c8.png)
( Series/DataFrame pandas) . DistilBERT , 0 (padding). , ( , Python).
, /, BERT':
![伯特输入张量](https://habrastorage.org/webt/u7/uz/ma/u7uzma5jjkbif--qi60zgb0xyy8.png)
DistilBERT'
DistilBERT.
input_ids = torch.tensor(np.array(padded))
with torch.no_grad():
last_hidden_states = model(input_ids)
last_hidden_states DistilBERT', ( , , DistilBERT). , 2000 (.. 2000 ), 66 ( 2000 ), 278 ( DistilBERT).
![bert-distilbert-输出张量预测](https://habrastorage.org/webt/yi/bf/lp/yibflpzn_dbzi72nvns_q92gaqw.png)
BERT'
3-d . :
![伯特输出张量](https://habrastorage.org/webt/kq/cr/k1/kqcrk198-zwu5t10mtsq4pxri3i.png)
. :
![伯特输入到输出张量回顾](https://habrastorage.org/webt/ie/a4/ob/iea4ob8zt474ku1j4uw1uthupdq.png)
BERT' [CLS]. .
![伯特输出张量选择](https://habrastorage.org/webt/84/5i/pd/845ipdjygzhjk4t-k6vj4hrbmem.png)
, 3d , 2d :
features = last_hidden_states[0][:,0,:].numpy()
features 2d numpy, .
![bert输出cls感觉嵌入](https://habrastorage.org/webt/sg/e7/_i/sge7_iy7hdtmvxyk41ajpm4xt_a.png)
, BERT'
, BERT', , . 768 , .
![Logistic回归数据集功能标签](https://habrastorage.org/webt/ul/33/yn/ul33ynyfjqqgqwuk-uvwe3mty1k.png)
, . BERT' [CLS] ( #0), (. ). , – , BERT/DistilBERT
, , .
labels = df[1]
train_features, test_features, train_labels, test_labels = train_test_split(features, labels)
:
![伯特·迪迪伯特火车测试拆分句子嵌入](https://habrastorage.org/webt/r_/e3/mq/r_e3mqtxvjry5xoabovb7il_iec.png)
.
lr_clf = LogisticRegression()
lr_clf.fit(train_features, train_labels)
, .
lr_clf.score(test_features, test_labels)
, (accuracy) – 81%.
: – 96.8. DistilBERT , – , . BERT , ( downstream task). DistilBERT' 90.7. BERT' 94.9.
Colab.
就这样!第一次相识很好。下一步是转到文档,然后尝试自己动手。您还可以返回一点,从distilBERT转到BERT,看看它是如何工作的。
感谢ClémentDelangue,Victor Sanh和Huggingface团队,他们对本指南的早期版本提供了反馈。
s