最簡單的BERT模型調用方法

  • 2020 年 2 月 14 日
  • 筆記

本文地址:https://github.com/qhduan/bert-model

BERT Models

注達到本文效果基本要求Tensorflow 2.0

也許,是最簡單的BERT預加載模型。

當然,實現起來是有一些tricky的,而且tokenizer並不是真正的bert的tokenizer,中文大部分不會有太大問題,英文的話實際上因為考慮BPE,所以肯定是不行的。

本項目重點在於,實際上我們是可以通過非常非常簡單的幾行代碼,就能實現一個幾乎達到SOTA的模型的。

BERT分類模型(pool模式)

返回一個1×768的張量,相當於句子的固定長度Embedding

根據一個實際Chinese GLUE的測試樣例:COLAB DEMO

import tensorflow_hub as hub    # 注意這裡最後是 pool.tar.gz  model = hub.KerasLayer('https://code.aliyun.com/qhduan/chinese_roberta_wwm_ext_L-12_H-768_A-12/raw/master/pool.tar.gz')    # y.shape == (1, 768)  y = model([['我愛你']])

一個非常簡單的分類例子(classifier.py):

import os  # 讓TFHUB顯示下載進度  os.environ['TFHUB_DOWNLOAD_PROGRESS'] = "1"  import tensorflow as tf  import tensorflow_hub as hub    x = [      ['我愛你'],      ['我恨你'],      ['愛你'],      ['恨你'],      ['愛'],      ['恨'],  ]  y = [      1, 0, 1, 0, 1, 0  ]    tx = tf.constant(x)  ty = tf.constant(tf.keras.utils.to_categorical(y, 2))    # 注意這裡最後是 pool.tar.gz  model = tf.keras.Sequential([    hub.KerasLayer('https://code.aliyun.com/qhduan/chinese_roberta_wwm_ext_L-12_H-768_A-12/raw/master/pool.tar.gz', trainable=False),    tf.keras.layers.Dense(2, activation='softmax')  ])    model.compile(loss='categorical_crossentropy')  model.fit(tx, ty, epochs=10, batch_size=2)  logits = model.predict(tx)  pred = logits.argmax(-1).tolist()    print(pred)  print(y)

BERT序列模型(SEQ)

返回一個序列的Embedding的模型

import tensorflow_hub as hub    # 注意這裡最後是 seq.tar.gz  model = hub.KerasLayer('https://code.aliyun.com/qhduan/chinese_roberta_wwm_ext_L-12_H-768_A-12/raw/master/seq.tar.gz')    # y.shape == (1, 5, 768)  # [CLS], 我, 愛, 你, [SEP],所以一共5個符號  y = model([['我愛你']])

BERT預測模型(PRED)

例如使用mask預測缺字

import tensorflow_hub as hub    # 注意這裡最後是 pred.tar.gz  model = hub.KerasLayer('https://code.aliyun.com/qhduan/chinese_roberta_wwm_ext_L-12_H-768_A-12/raw/master/pred.tar.gz')    # y.shape == (1, 5, 21128)  y = model([['我[MASK]你']])    index2word = {k: v.strip() for k, v in enumerate(open('vocab.txt'))}    # 我 愛 你  r = [index2word[i] for i in y.numpy().argmax(-1).flatten()][1:-1]

模型引用

REPO地址:https://github.com/qhduan/bert-model

Roberta和WMM來自ymcui