TensorFlow2.4 完成 Word2vec 詞嵌入訓練

語言: CN / TW / HK

本文正在參加「金石計劃 . 瓜分6萬現金大獎」

前言

本文使用 cpu 版本的 tensorflow 2.4 ,在 shakespeare 資料的基礎上使用 Skip-Gram 演算法訓練詞嵌入。

相關概念

Word2Vec 不是一個單純的演算法,而是對最初的神經概率語言模型 NNLM 做出的改進和優化,可用於從大型資料集中學習單詞的詞嵌入。通過word2vec 學習到的單詞詞嵌入已經被成功地運用於下游的各種 NLP 任務中。

Word2Vec 是輕量級的神經網路,其模型僅僅包括輸入層、隱藏層和輸出層,模型框架根據輸入輸出的不同,主要包括 CBOW 和 Skip-Gram 模型:

  • CBOW :根據周圍的上下文詞預測中間的目標詞。周圍的上下文詞由當中間的目標詞的前面和後面的若干個單片語成,這種體系結構中單詞的順序並不重要。
  • Skip-Gram :在同一個句子中預測當前單詞前後一定範圍內的若干個目標單詞。

本文大綱

  1. 使用例子介紹 Skip-Gram 操作
  2. 獲取、處理資料
  3. 搭建、訓練模型
  4. 檢視 Word2Vec 向量

實現過程

1. 使用例子介紹 Skip-Gram 操作

(1)使用例子說明負取樣過程 我們首先用一個句子 "我是中國人"來說明相關的操作流程。

(2)先要對句子中的 token 進行拆分,儲存每個字到整數的對映關係,以及每個整數到字的對映關係。

(3)然後用整數對整個句子進行向量化,也就是用整數表示對應的字,從而形成一個包含了整數的的向量,需要注意的是這裡要特意保留 0 作為填充佔位符。

(4)sequence 模組提供可以簡化 word2vec 資料準備的功能,我們使用 skipgram 函式,在 example_sequence 中以每個單詞為中心,與前後視窗大小為 window_size 範圍內的詞生成 Skip-Gram 整數對集合。具體結果可以結合例子的輸出理解。

import io
import re
import string
import tqdm
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers

SEED = 2
AUTOTUNE = tf.data.AUTOTUNE
window_size = 2
sentence = "我是一個偉大的中國人"
tokens = list(sentence)
vocab, index = {}, 1
vocab['<pad>'] = 0
for token in tokens:
    if token not in vocab:
        vocab[token] = index
        index += 1
vocab_size = len(vocab)
inverse_vocab = {index: token for token, index in vocab.items()}
example_sequence = [vocab[word] for word in tokens]
positive_skip, _ = tf.keras.preprocessing.sequence.skipgrams( example_sequence,  vocabulary_size = vocab_size, window_size = window_size, negative_samples = 0)
positive_skip.sort()
for t, c in positive_skip:
    print(f"({t}, {c}): ({inverse_vocab[t]}, {inverse_vocab[c]})")

所有正樣本輸出:

(1, 2): (我, 是)
(1, 3): (我, 一)
(2, 1): (是, 我)
(2, 3): (是, 一)
(2, 4): (是, 個)
(3, 1): (一, 我)
(3, 2): (一, 是)
(3, 4): (一, 個)
(3, 5): (一, 偉)
(4, 2): (個, 是)
(4, 3): (個, 一)
(4, 5): (個, 偉)
(4, 6): (個, 大)
(5, 3): (偉, 一)
(5, 4): (偉, 個)
(5, 6): (偉, 大)
(5, 7): (偉, 的)
(6, 4): (大, 個)
(6, 5): (大, 偉)
(6, 7): (大, 的)
(6, 8): (大, 中)
(7, 5): (的, 偉)
(7, 6): (的, 大)
(7, 8): (的, 中)
(7, 9): (的, 國)
(8, 6): (中, 大)
(8, 7): (中, 的)
(8, 9): (中, 國)
(8, 10): (中, 人)
(9, 7): (國, 的)
(9, 8): (國, 中)
(9, 10): (國, 人)
(10, 8): (人, 中)
(10, 9): (人, 國)

(5)skipgram 函式通過在給定的 window_size 上視窗上進行滑動來返回所有正樣本對,但是我們在進行模型訓練的時候還需要負樣本,要生成 skip-gram 負樣本,就需要從詞彙表中對單詞進行隨機取樣。使用 log_uniform_candidate_sampler 函式對視窗中給定 target 進行 num_ns 個負取樣。我們可以在一個目標詞 target 上呼叫負取樣函式,並將上下文 context 出現的詞作為 true_classes ,以避免在負取樣時被取樣到。但是這裡需要注意的是,雖然理論上負取樣中 true_classes 是不被取樣的,但是由於 log_uniform_candidate_sampler 中實現的負取樣演算法不同,所以還是可能會被取樣到,想要了解具體的情況,我們可以檢視 http://github.com/tensorflow/tensorflow/issues/49490 。

(6)在較小的資料集中一般將 num_ns 設定為 [5, 20] 範圍內的整數,而在較大的資料集一般設定為 [2, 5] 範圍內整數。

target_word, context_word = positive_skip[0]
num_ns = 3
context_class = tf.expand_dims( tf.constant([context_word], dtype="int64"), 1)
negative_sampling, _, _ = tf.random.log_uniform_candidate_sampler( true_classes=context_class,   num_true=1,  num_sampled=num_ns,  unique=True,  range_max=vocab_size, seed=SEED,  name="negative_sampling"  )

(7)我們選用了一個正樣本 (我, 是) 來為其生成對應的負取樣樣本,目標詞為“我”,該樣本的標籤類別定義為“是”,使用函式 log_uniform_candidate_sampler 就會以“我”為目標,再去在詞典中隨機取樣一個不存在於 true_classes 的字作為負取樣的標籤類別, 如下我們生成了三個樣本類別,可以分別組成(我,一)、(我,個)、(我,我)三個負樣本。

(8)對於一個給定的正樣本 skip-gram 對,每個樣本對都是 (target_word, context_word) 的形式,我們現在又生成了 3 個負取樣,將 1 個正樣本 和 3 負樣本組合到一個張量中。對於正樣本標籤標記為 1 和負樣本標籤標記為 0 。

squeezed_context_class = tf.squeeze(context_class, 1)
context = tf.concat([squeezed_context_class, negative_sampling], 0)
label = tf.constant([1] + [0]*num_ns, dtype="int64")
target = target_word
print(f"target_index    : {target}")
print(f"target_word     : {inverse_vocab[target_word]}")
print(f"context_indices : {context}")
print(f"context_words   : {[inverse_vocab[c.numpy()] for c in context]}")
print(f"label           : {label}")

結果為:

target_index    : 1
target_word     : 我
context_indices : [2 3 4 1]
context_words   : ['是', '一', '個', '我']
label           : [1 0 0 0]

2. 獲取、處理資料

(1)這裡我們使用 tensorflow 的內建函式從網路上下載 shakespeare 文字資料,裡面儲存的都是莎士比亞的作品。

(2)我們使用內建的 TextVectorization 函式對資料進行預處理,並且將出現的所有的詞都對映層對應的整數,並且保證每個樣本的長度不超過 10

(3)將所有的資料都轉化成對應的整數表示,並且設定每個 batcc_size 為 1024 。

path_to_file = tf.keras.utils.get_file('shakespeare.txt', 'http://storage.googleapis.com/download.tensorflow.org/data/shakespeare.txt')
text_ds = tf.data.TextLineDataset(path_to_file).filter(lambda x: tf.cast(tf.strings.length(x), bool))
def custom_standardization(input_data):
    lowercase = tf.strings.lower(input_data)
    return tf.strings.regex_replace(lowercase,  '[%s]' % re.escape(string.punctuation), '')
vocab_size = 4096
sequence_length = 10
vectorize_layer = layers.TextVectorization(
                        standardize=custom_standardization,
                        max_tokens=vocab_size,
                        output_mode='int',
                        output_sequence_length=sequence_length)
vectorize_layer.adapt(text_ds.batch(1024))
inverse_vocab = vectorize_layer.get_vocabulary()
text_vector_ds = text_ds.batch(1024).prefetch(AUTOTUNE).map(vectorize_layer).unbatch()
sequences = list(text_vector_ds.as_numpy_iterator())

擷取部分進行列印:

for seq in sequences[:5]:
    print(f"{seq} => {[inverse_vocab[i] for i in seq]}")

結果為:

 [ 89 270   0   0   0   0   0   0   0   0] => ['first', 'citizen', '', '', '', '', '', '', '', '']
[138  36 982 144 673 125  16 106   0   0] => ['before', 'we', 'proceed', 'any', 'further', 'hear', 'me', 'speak', '', '']
[34  0  0  0  0  0  0  0  0  0] => ['all', '', '', '', '', '', '', '', '', '']
[106 106   0   0   0   0   0   0   0   0] => ['speak', 'speak', '', '', '', '', '', '', '', '']
[ 89 270   0   0   0   0   0   0   0   0] => ['first', 'citizen', '', '', '', '', '', '', '', '']

(4)我們將上面所使用到的步驟都串聯起來,可以組織形成生成訓練資料的函式,裡面包括了正取樣和負取樣操作。另外可以使用 make_sampling_table 函式生成基於詞頻的取樣概率表,對應到詞典中第 i 個最常見的詞的概率,為平衡期起見,對於越經常出現的詞,取樣到的概率越低。

(5)這裡呼叫 generate_training_data 函式可以生成訓練資料,target 的維度為 (64901,) ,contexts 和 labels 的維度為 (64901, 5) 。

(6)要對大量的訓練樣本執行高效的批處理,可以使用 Dataset 相關的 API ,使用 shuffle 可以從快取的 BUFFER_SIZE 大小的樣本集中隨機選擇一個,使用 batch 表示我們每個 batch 的大小設定為 BATCH_SIZE ,使用 cache 為了保證在載入資料的時候不會出現 I/O 不會阻塞,我們在從磁碟載入完資料之後,使用 cache 會將資料儲存在記憶體中,確保在訓練模型過程中資料的獲取不會成為訓練速度的瓶頸。如果說要儲存的資料量太大,可以使用 cache 建立磁碟快取提高資料的讀取效率。我們使用 prefetch 在訓練過程中可以並行執行資料的預獲取。

(7)最終每個樣本最終的形態為 ((target_word, context_word),label) 。

def generate_training_data(sequences, window_size, num_ns, vocab_size, seed):
    targets, contexts, labels = [], [], []
    sampling_table = tf.keras.preprocessing.sequence.make_sampling_table(vocab_size)
    for sequence in tqdm.tqdm(sequences):
        positive_skip, _ = tf.keras.preprocessing.sequence.skipgrams(
                              sequence,
                              vocabulary_size=vocab_size,
                              sampling_table=sampling_table,
                              window_size=window_size,
                              negative_samples=0)
        for target_word, context_word in positive_skip:
            context_class = tf.expand_dims(
                              tf.constant([context_word], dtype="int64"), 1)
            negative_sampling, _, _ = tf.random.log_uniform_candidate_sampler(
                              true_classes=context_class,
                              num_true=1,
                              num_sampled=num_ns,
                              unique=True,
                              range_max=vocab_size,
                              seed=seed,
                              name="negative_sampling")
            context = tf.concat([tf.squeeze(context_class,1), negative_sampling], 0)
            label = tf.constant([1] + [0]*num_ns, dtype="int64")
            targets.append(target_word)
            contexts.append(context)
            labels.append(label)
    return targets, contexts, labels

targets, contexts, labels = generate_training_data( sequences=sequences, window_size=2,  num_ns=4, vocab_size=vocab_size, seed=SEED)
targets = np.array(targets)
contexts = np.array(contexts)
labels = np.array(labels)
BATCH_SIZE = 1024
BUFFER_SIZE = 10000
dataset = tf.data.Dataset.from_tensor_slices(((targets, contexts), labels))
dataset = dataset.shuffle(BUFFER_SIZE).batch(BATCH_SIZE, drop_remainder=True)
dataset = dataset.cache().prefetch(buffer_size=AUTOTUNE)

3. 搭建、訓練模型

(1)第一層是 target Embedding 層,我們為目標單詞初始化詞嵌入,設定詞嵌入向量的維度為 128 ,也就是說這一層的引數總共有 (vocab_size * embedding_dim) 個,輸入長度為 1 。

(2)第二層是 context Embedding 層,我們為上下文單詞初始化詞嵌入,我們仍然設定詞嵌入向量的維度為 128 ,這一層的引數也有 (vocab_size * embedding_dim) 個,輸入長度為 num_ns+1 。

(3)第三層是點積計算層,用於計算訓練對中 target 和 context 嵌入的點積。

(4)我們選擇 Adam 優化器來進行優化,選用 CategoricalCrossentropy 作為損失函式,選用 accuracy 作為評估指標,使用訓練資料來完成 20 個 eopch 的訓練。

class Word2Vec(tf.keras.Model):
    def __init__(self, vocab_size, embedding_dim):
        super(Word2Vec, self).__init__()
        self.target_embedding = layers.Embedding(vocab_size,
                                          embedding_dim,
                                          input_length=1,
                                          name="w2v_embedding")
        self.context_embedding = layers.Embedding(vocab_size,
                                       embedding_dim,
                                       input_length=num_ns+1)
    def call(self, pair):
        target, context = pair
        if len(target.shape) == 2:
            target = tf.squeeze(target, axis=1)
        word_emb = self.target_embedding(target)
        context_emb = self.context_embedding(context)
        dots = tf.einsum('be,bce->bc', word_emb, context_emb)
        return dots

embedding_dim = 128
word2vec = Word2Vec(vocab_size, embedding_dim)
word2vec.compile(optimizer='adam',  loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True), metrics=['accuracy'])
word2vec.fit(dataset, epochs=20)

過程如下:

Epoch 1/20
63/63 [==============================] - 1s 14ms/step - loss: 1.6082 - accuracy: 0.2321
Epoch 2/20
63/63 [==============================] - 1s 14ms/step - loss: 1.5888 - accuracy: 0.5527
...
Epoch 19/20
63/63 [==============================] - 1s 13ms/step - loss: 0.5041 - accuracy: 0.8852
Epoch 20/20
63/63 [==============================] - 1s 13ms/step - loss: 0.4737 - accuracy: 0.8945

4. 檢視 Word2Vec 向量

我們已經訓練好所有的詞向量,可以檢視前三個單詞對應的詞嵌入,不過因為第一個是一個填充字元,我們直接跳過了,所以只顯示了兩個單詞的結果。

weights = word2vec.get_layer('w2v_embedding').get_weights()[0]
vocab = vectorize_layer.get_vocabulary()
for index, word in enumerate(vocab[:3]):
    if index == 0:
        continue  
    vec = weights[index]
    print(word, "||",' '.join([str(x) for x in vec]) + "")

輸出:

[UNK] || -0.033048704 -0.13244359 0.011660721 0.04466736 0.016815167 -0.0021747486 -0.22271504 -0.19703679 -0.23452276 0.11212586 -0.016061027 0.17981936 0.07774545 0.024562761 -0.17993309 -0.18202212 -0.13211365 -0.0836222 0.14589612 0.10907205 0.14628777 -0.10057361 -0.20254703 -0.012516517 -0.026788604 0.10540704 0.10908849 0.2110478 0.09297589 -0.20392798 0.3033481 -0.06899316 -0.11218286 0.08671802 -0.032792106 0.015512758 -0.11241121 0.03193802 -0.07420188 0.058226038 0.09341678 0.0020246594 0.11772731 0.22016191 -0.019723132 -0.124759704 0.15371098 -0.032143503 -0.16924457 0.07010268 -0.27322608 -0.04762394 0.1720905 -0.27821517 -0.021202642 0.022981782 0.017429957 -0.018919267 0.0821674 0.14892177 0.032966584 0.016503694 -0.024588188 -0.15450846 0.25163063 -0.09960359 -0.08205034 -0.059559997 -0.2328465 -0.017229442 -0.11387295 0.027335169 -0.21991524 -0.25220546 -0.057238836 0.062819794 -0.07596143 0.1036019 -0.11330178 0.041029476 -0.0036062107 -0.09850497 0.026396573 0.040283844 0.09707356 -0.108100675 0.14983237 0.094585866 -0.11460251 0.159306 -0.18871744 -0.0021350821 0.21181738 -0.11000824 0.026631303 0.0043079373 -0.10093511 -0.057986196 -0.13534115 -0.05459506 0.067853846 -0.09538108 -0.1882101 0.15350497 -0.1521072 -0.01917603 -0.2464314 0.07098584 -0.085702434 -0.083315894 0.01850418 -0.019426668 0.215964 -0.04208141 0.18032664 -0.067350626 0.29129744 0.07231988 0.2200896 0.04984232 -0.2129336 -0.005486685 0.0047443025 -0.06323578 0.10223014 -0.14854044 -0.09165846 0.14745502
the || 0.012899147 -0.11042492 -0.2028403 0.20705906 -0.14402795 -0.012134922 -0.008227022 -0.19896115 -0.18482314 -0.31812677 -0.050654292 0.063769065 0.013379926 -0.04029531 -0.19954327 0.020137483 -0.035291195 -0.03429038 0.07547649 0.04313068 -0.05675204 0.34193155 -0.13978302 0.033053987 -0.0038114514 8.5749794e-05 0.15582523 0.11737131 0.1599838 -0.14866571 -0.19313708 -0.0936122 0.12842192 -0.037015382 -0.05241146 -0.00085232017 -0.04838702 -0.17497984 0.13466156 0.17985387 0.032516308 0.028982501 -0.08578549 0.014078035 0.11176433 -0.08876962 -0.12424359 -0.00049041177 -0.07127252 0.13457641 -0.17463619 0.038635027 -0.23191011 -0.13592774 -0.01954393 -0.28888118 0.0130044455 0.10935221 -0.10274326 0.16326426 0.24069212 -0.068884164 -0.042140033 -0.08411051 0.14803806 -0.08204498 0.13407354 -0.08042538 0.032217037 -0.2666482 -0.17485079 0.37256253 -0.02551431 -0.25904474 -0.002844959 0.1672513 0.035283662 -0.11897226 0.14446032 0.08866355 -0.024791516 -0.22040974 0.0137709975 -0.16484109 0.18097405 0.07075867 0.13830985 0.025787655 0.017255543 -0.0387513 0.07857641 0.20455246 -0.02442122 -0.18393797 -0.0361829 -0.12946953 -0.15860991 -0.10650375 -0.251683 -0.1709236 0.12092594 0.20731401 0.035180748 -0.09422942 0.1373039 0.121121824 -0.09530268 -0.15685256 -0.14398256 -0.068801016 0.0666081 0.13958378 0.0868633 -0.036316663 0.10832365 -0.21385072 0.15025891 0.2161903 0.2097545 -0.0487211 -0.18837014 -0.16750671 0.032201447 0.03347862 0.09050423 -0.20007794 0.11616628 0.005944925