如何使用Tensorflow訓練‘Word2Vec’演算法?


Tensorflow是谷歌提供的機器學習框架。它是一個開源框架,與Python結合使用,可以實現演算法、深度學習應用等等。它用於研究和生產目的。它具有最佳化技術,有助於快速執行復雜的數學運算。

這是因為它使用了NumPy和多維陣列。這些多維陣列也稱為“張量”。該框架支援與深度神經網路一起工作。它具有高度的可擴充套件性,並附帶許多流行的資料集。它使用GPU計算並自動管理資源。

可以使用以下程式碼行在Windows上安裝“tensorflow”包:

pip install tensorflow

張量是TensorFlow中使用的資料結構。它有助於連線資料流圖中的邊。這個資料流圖被稱為“資料流圖”。張量只不過是多維陣列或列表。

下面的程式碼使用維基百科的一篇文章來訓練模型。它有助於理解詞嵌入。詞嵌入是指能夠捕捉文件中特定詞的上下文、它與其他詞的關係、它的句法相似性等等的表示。它們以向量的形式存在。這些詞向量可以使用Word2Vec技術學習。

以下是一個例子:

示例

from __future__ import division, print_function, absolute_import

import collections
import os
import random
import urllib
import zipfile

import numpy as np
import tensorflow as tf

learning_rate = 0.11
batch_size = 128
num_steps = 3000000
display_step = 10000
eval_step = 200000

eval_words = ['eleven', 'the', 'going', 'good', 'american', 'new york']

embedding_size = 200 # Dimension of embedding vector.
max_vocabulary_size = 50000 # Total words in the vocabulary.
min_occurrence = 10 # Remove words that don’t appear at least n times.
skip_window = 3 # How many words to consider from left and right.
num_skips = 2 # How many times to reuse the input to generate a label.
num_sampled = 64 # Number of negative examples that need to be sampled.

url = 'http://mattmahoney.net/dc/text8.zip'
data_path = 'text8.zip'
if not os.path.exists(data_path):
   print("Downloading the dataset... (It may take some time)")
   filename, _ = urllib.request.urlretrieve(url, data_path)
   print("Th data has been downloaded")
with zipfile.ZipFile(data_path) as f:
   text_words = f.read(f.namelist()[0]).lower().split()
count = [('RARE', −1)]

count.extend(collections.Counter(text_words).most_common(max_vocabulary_size − 1))

for i in range(len(count) − 1, −1, −1):
   if count[i][1] < min_occurrence:
      count.pop(i)
   else:
      break
vocabulary_size = len(count)
word2id = dict()
for i, (word, _)in enumerate(count):
   word2id[word] = i

data = list()
unk_count = 0
for word in text_words:
   index = word2id.get(word, 0)
   if index == 0:
      unk_count += 1
   data.append(index)
count[0] = ('RARE', unk_count)
id2word = dict(zip(word2id.values(), word2id.keys()))

print("Word count is :", len(text_words))
print("Unique words:", len(set(text_words)))
print("Vocabulary size:", vocabulary_size)
print("Most common words:", count[:8])

程式碼來源 https://github.com/aymericdamien/TensorFlow-Examples/blob/master/tensorflow_v2/notebooks/2_BasicModels/word2vec.ipynb

輸出

Word count is : 17005207
Unique words: 253854
Vocabulary size: 47135
Most common words: [('RARE', 444176), (b'the', 1061396), (b'of', 593677), (b'and', 416629), (b'one', 411764), (b'in', 372201), (b'a', 325873), (b'to', 316376)]

解釋

  • 匯入併為所需的包設定別名。

  • 定義學習引數、評估引數和word2vec引數。

  • 載入並解壓縮資料。

  • 將稀有詞分配標籤“−1”。

  • 迭代資料檔案中的單詞,並在控制檯上顯示單詞總數、詞彙量大小和常用詞。

更新於:2021年1月19日

瀏覽量:152

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.