Tensorflow實戰學習(三十四)【實現Word2Vec】
卷積神經網路發展趨勢。Perceptron(感知機),1957年,Frank Resenblatt提出,始祖。Neocognitron(神經認知機),多層級神經網路,日本科學家Kunihiko fukushima,20世紀80年代提出,一定程度視覺認知功能,啟發卷積神經網路。LeNet-5,CNN之父,Yann LeCun,1997年提出,首次多層級聯卷積結構,手寫數字有效識別。2012年,Hinton學生Alex,8層卷積神經網路,ILSVRC 2012比賽冠軍。AlexNet 成功應用ReLU啟用函式、Dropout、最大覆蓋池化、LRN層、GPU加速,啟發後續技術創新,卷積神經網路研究進入快車道。
AlexNetx後,卷積神經網路,一類網路結構改進調整,一類網路深度增加。
Perceptron(1957)
Neocognitron(198x)
NIN(2013) VGG(2014)
Incepiton V1(2014) MSRANet(2014)
Incepiton V2(2015) ResNet(2015)
Incepiton V3(2015) ResNet V2(2015)
Inception ResNet V2(2016 )
2013年,顏水成教授,Network in Network首次發表,優化卷積神經網路結構,推廣1x1卷積結構。2014年,Google Incepiton Net V1,Inception Module,反覆堆疊高效卷積網路結構,ILSVRC 2014冠軍。2015年初,Incepiton V2,Batch Normalization,加速訓練過程,提升網路效能。2015年末,Inception V3,Factorization in Small Convolutions思想,分解大尺寸卷積為多個小卷積或一維卷積。
2014年,ILSVRC亞軍,VGGNet,全程3x3卷積,19層網路。季軍MSRA-Net(微軟)也是深層網路。2015年,微軟ResNet,152層網路,ILSVRC 2015冠軍,top-5錯誤率3.46%。ResNet V2,Batch Normalization,去除啟用層,用Identity Mapping或Preactivation,提升網路效能。Inception ResNet V2,融合Inception Net網路結構,和ResNet訓練極深網路殘差學習模組。
GPU計算資源,開源工具。
迴圈神經網路(RNN),NLP(Nature Language Processing,自然語言處理)最常用神經網路結構。Word2Vec,語言字詞轉化稠密向量(Dense Vector)。
Word2Vec,Word Embeddings,詞向量或詞嵌入。語言字詞轉向量形式表達(Vector Representations)模型。圖片,畫素點稠密矩陣,音訊,聲音訊號頻譜資料。
One-Hot Encoder,字詞轉離散單獨符號。一個詞對應一個向量,整篇文章對應一個稀疏矩陣。文字分類模型,Bag of Words,稀疏矩陣合併為一個向量,每個詞對應向量計數,統計詞出現次數,作為特徵。特徵編碼隨機,沒有關聯資訊,沒有字詞關係。稀疏向量需要更多資料訓練,訓練效率低,計算麻煩。
向量表達(Vector Representations),向量空間模型(Vector Space Models),字詞轉連續值向量表達,意思相近詞映射向量空量空間相近位置。向量空間模型在NLP依賴假設Distributional Hypothesis,相同語境詞語義相近。向量空間模型,分兩類,計數模型(Latent Semantic Analysis),預測模型(Neural Probabilistic Language Models)。計數模型統計語料庫相鄰詞頻率,計數統計結果轉小稠密矩陣,預測模型根據詞周圍相鄰詞推測出這個詞和空間向量。
Word2Vec,計算非常高效,從原始語料學習字詞空間向量預測模型。CBOW(Continuous Bag of Words)模式從原始語句推測目標字詞,適合小型資料。Skip-Gram從目標字詞推測原始語句,適合大型語料。意思相近詞向量空間位置接近。
預測模型(Neural Probabilistic Language Models),用最大似然方法,給定前語句h,最大化目標詞彙Wt概率。計算量大,需計算詞彙表所有單詞出現可能性。Word2Vec CBOw模型,只需訓練二元分類模型,區分真實目標詞彙、編造詞彙(噪聲)兩類。少量噪聲詞彙估計,類似蒙特卡洛模擬。
模型預測真實目標詞彙高概率,預測其他噪聲詞彙低概率,訓練學習目標最優化。編造噪聲詞彙訓練,Negative Sampling,計算loss fuction效率非常高,只需計算隨機選擇k個詞彙,訓練速度快。Noise_contrastive Estimation(NCE) Loss,TensorFlow tf.nn.nce_loss。
Word2Vec Skip-Gram模式。構造語境與目標詞彙對映關係。語境包括單詞左邊和右邊詞彙。滑窗尺寸 1。Skip-Gram模型,從目標詞彙預測語境。製造隨機詞彙作負樣本(噪聲)。預測概率分佈,正樣本儘可能大,隨機產生負樣本尺可能小。優化演算法(SGD)更新模型Word Embedding引數,概率分佈損失函式(NCE Loss)儘可能小。單詞Embedded Vector隨訓練過程調整,直到最適合語料空間位置。損失函式最小,最符合語料,預測正確單詞概率最高。
載入依賴庫。
定義下載廣西資料函式,urllib.request.urlretrieve下載資料壓縮檔案核檔案尺寸。已下載跳過。
解壓下載壓縮檔案,tf.compat.as_str 資料轉單詞列表。資料轉為17005207單詞列表。
建立vocabulary詞彙表,collections.Counter統計單詞列表單詞頻數,most_common方法取top 50000頻數單詞作vocabulary。建立dict,top 50000詞彙vocabulary放入dictionary,快速查詢。Python dict查詢複雜度O(1),效能好。全部單詞轉編號(頻數排序編號)。top50000以外單詞,認定為Unkown(未知),編號0,統計數量。遍歷單詞列表,每個單詞,判斷是否出現在dictionary,是轉編號,不是編0。返回轉換編碼(data)、單詞頻數統計count、詞彙表(dictionary)、反轉形式(reverse_dictionary)。
刪除原始單詞列表,節約記憶體。列印vocabulary最高頻詞彙、數量(包括Unknow詞彙)。“UNK”類418391個。“the”1061396個。“of”593677個。data前10單詞[‘anarchism’,’originated’,’as’,’a’,’term’,’of’,’abuse’,’first’,’used’,’against’],編號[5235,3084,12,6,195,2,3137,46,59,156]。
生成Word2Vec訓練樣本。Skip-Gram模式(從目標單詞反推語境)。定義函式generate_batch生成訓練batch資料。引數batch_size為batch大小。skip_window單詞最遠可聯絡距離,設1只能跟緊鄰兩個單詞生成樣本。num_skips單詞生成樣本個數,不能大於skip_window兩倍,batch_size是它的整數倍,確保batch包含詞彙所有樣本。
單詞序號data_index為global變數,反覆呼叫generate_batch,確保data_index可以在函式genetate_batch修改。assert確保num_skips、batch_size滿足條件。np.ndarray初始化batch、labels為陣列。定義span 單詞建立相關樣本單詞數量,包括目標單詞和前後單詞,span=2*skip_window+1。建立最大容量span deque,雙向佇列,deque append方法新增變數,只保留最後插入span個變數。
從序號data_index開始,span個單詞順序讀入buffer作初始值。buffer容量為span deque,已填滿,後續資料替換前面資料。
第一層迴圈(次數batch_size//num_skips),迴圈內目標單詞生成樣本。buffer目標單詞和所有相關單詞,定義target-skip_window,buffer第skip_window個變數為目標單詞。定義生成樣本需避免單詞列表,tagets_to_avoid,列表開始包括第skip_window個單詞(目標單詞),預測語境單詞,不包括目標單詞。
第二層迴圈(次數num_skips),迴圈語境單詞生成樣本,先產生隨機數,直到隨機數不在targets_to_avoid中,代表可用語境單詞,生成樣本,feature目標詞彙buffer[skip_window],label是buffer[target]。語境單詞使用,新增到targets_to_avoid過濾。目標單詞所有樣本生成完(num_skips個),讀入下一個單詞,拋掉buffer第一個單詞,滑窗向後移動一位,目標單詞向後移動一個,語境單詞整體後移,開始生成下一個目標單詞訓練樣本。
兩層迴圈完成,獲得batch_size個訓練樣本。返回batch、labels。
呼叫generate_batch函式測試。引數batch_size設8,num_skips設2,skip_window設1,執行generate_batch獲得batch、labels,列印。
定義訓練batch_size 128,embedding_size 128。embedding_size,單詞轉稠密向量維度,50〜1000。skip_window單詞間最遠聯絡距離設1,num_skips目標單詞提取樣本數設2.生成驗證資料valid_examples。隨機抽取頻數最高單詞,看向量空間最近單詞是否相關性高。valid_size設16抽取驗證單詞數。valid_window設100驗證單詞頻為最高100個單詞抽取。np.random.choice函式隨機抽取。num_sampled訓練負樣本噪聲單詞數量。
定義Skip_Gram Word2Vec模型網路結構。建立f.Graph,設定為預設graph。建立訓練資料inputs、labels placeholder,隨機產生valid_examples轉TensorFlow constant。with tf.device(‘/cpu:0’)限定所有計算在CPU執行。tf.random_uniform隨機生成所有單詞詞向量embeddings,單詞表大小50000,向量維度128,tf.nn.embedding_lookup查詢輸入train_inputs對應賂理embed。tf.truncated_normal初始化訓練優化目標NCE Loss的權重引數nce_weights,nce_biases初始化0。tf.nn.nce_loss計算學習詞向量embedding訓練資料loss,tf.reduce_mean彙總。
定義優化器SGD ,學習速率1.0。計算嵌入向量embeddings L2範數norm,embeddings除L2範數得標準化normalized_embeddings。tf.nn.embedding_lookup查詢驗證單詞嵌入向量,計算驗證單詞嵌入同與詞彙表所有單詞相似性。tf.global_variables_initializer初始化所有模型引數。
定義最大迭代次數10萬次,建立設定預設session,執行引數初始化。迭代中,generate_batch生成batch inputs、labels資料,建立feed_dict。session.run()執行優化器運算(引數更新)和損失計算,訓練loss累積到avegage_loss。
每2000次迴圈,計算平均loss,顯示。
每10000次迴圈,計算驗證單詞和全部單詞相似度,驗證單詞最相似8個單詞展示。
訓練模型對名詞、動詞、形容詞型別單詞相似詞彙識別非常準確。Skip-Gram Word2Vec 向量空間表達(Vetor Representations)質量非常高,近義詞在向量空間位置非常靠近。
定義視覺化Word2Vec效果函式。low_dim_embs降給到2維單詞空間向量,圖表展示單詞位置。plt.scatter(matplotlib.pyplot)顯示散點圖(單詞位置),plt.annotate展示單詞本身。plt.savefig儲存圖片到本地檔案。
sklearn.manifold.TSNe實現降維,原始128維嵌入同量降到2維,plot_sith_labels函式展示。只展示詞頻最高100個單詞視覺化結果。
距離相近單詞,語義高相似性。左上角單個字母聚集地。冠詞聚集在左邊中部。Word2Vec效能評價,視覺化觀察,Analogical Reasoning直接預測語義、語境關係。回答填空問題。大規模語料庫,引數除錯選取最適合值。
import collections
import math
import os
import random
import zipfile
import numpy as np
import urllib
import tensorflow as tf
# Step 1: Download the data.
url = 'http://mattmahoney.net/dc/'
def maybe_download(filename, expected_bytes):
if not os.path.exists(filename):
filename, _ = urllib.request.urlretrieve(url + filename, filename)
statinfo = os.stat(filename)
if statinfo.st_size == expected_bytes:
print('Found and verified', filename)
else:
print(statinfo.st_size)
raise Exception(
'Failed to verify ' + filename + '. Can you get to it with a browser?')
return filename
filename = maybe_download('text8.zip', 31344016)
# Read the data into a list of strings.
def read_data(filename):
with zipfile.ZipFile(filename) as f:
data = tf.compat.as_str(f.read(f.namelist()[0])).split()
return data
words = read_data(filename)
print('Data size', len(words))
# Step 2: Build the dictionary and replace rare words with UNK token.
vocabulary_size = 50000
def build_dataset(words):
count = [['UNK', -1]]
count.extend(collections.Counter(words).most_common(vocabulary_size - 1))
dictionary = dict()
for word, _ in count:
dictionary[word] = len(dictionary)
data = list()
unk_count = 0
for word in words:
if word in dictionary:
index = dictionary[word]
else:
index = 0 # dictionary['UNK']
unk_count += 1
data.append(index)
count[0][1] = unk_count
reverse_dictionary = dict(zip(dictionary.values(), dictionary.keys()))
return data, count, dictionary, reverse_dictionary
data, count, dictionary, reverse_dictionary = build_dataset(words)
del words # Hint to reduce memory.
print('Most common words (+UNK)', count[:5])
print('Sample data', data[:10], [reverse_dictionary[i] for i in data[:10]])
data_index = 0
# Step 3: Function to generate a training batch for the skip-gram model.
def generate_batch(batch_size, num_skips, skip_window):
global data_index
assert batch_size % num_skips == 0
assert num_skips <= 2 * skip_window
batch = np.ndarray(shape=(batch_size), dtype=np.int32)
labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32)
span = 2 * skip_window + 1 # [ skip_window target skip_window ]
buffer = collections.deque(maxlen=span)
for _ in range(span):
buffer.append(data[data_index])
data_index = (data_index + 1) % len(data)
for i in range(batch_size // num_skips):
target = skip_window # target label at the center of the buffer
targets_to_avoid = [ skip_window ]
for j in range(num_skips):
while target in targets_to_avoid:
target = random.randint(0, span - 1)
targets_to_avoid.append(target)
batch[i * num_skips + j] = buffer[skip_window]
labels[i * num_skips + j, 0] = buffer[target]
buffer.append(data[data_index])
data_index = (data_index + 1) % len(data)
return batch, labels
batch, labels = generate_batch(batch_size=8, num_skips=2, skip_window=1)
for i in range(8):
print(batch[i], reverse_dictionary[batch[i]],
'->', labels[i, 0], reverse_dictionary[labels[i, 0]])
# Step 4: Build and train a skip-gram model.
batch_size = 128
embedding_size = 128 # Dimension of the embedding vector.
skip_window = 1 # How many words to consider left and right.
num_skips = 2 # How many times to reuse an input to generate a label.
valid_size = 16 # Random set of words to evaluate similarity on.
valid_window = 100 # Only pick dev samples in the head of the distribution.
valid_examples = np.random.choice(valid_window, valid_size, replace=False)
num_sampled = 64 # Number of negative examples to sample.
graph = tf.Graph()
with graph.as_default():
# Input data.
train_inputs = tf.placeholder(tf.int32, shape=[batch_size])
train_labels = tf.placeholder(tf.int32, shape=[batch_size, 1])
valid_dataset = tf.constant(valid_examples, dtype=tf.int32)
# Ops and variables pinned to the CPU because of missing GPU implementation
with tf.device('/cpu:0'):
# Look up embeddings for inputs.
embeddings = tf.Variable(
tf.random_uniform([vocabulary_size, embedding_size], -1.0, 1.0))
embed = tf.nn.embedding_lookup(embeddings, train_inputs)
# Construct the variables for the NCE loss
nce_weights = tf.Variable(
tf.truncated_normal([vocabulary_size, embedding_size],
stddev=1.0 / math.sqrt(embedding_size)))
nce_biases = tf.Variable(tf.zeros([vocabulary_size]))
loss = tf.reduce_mean(
tf.nn.nce_loss(weights=nce_weights,
biases=nce_biases,
labels=train_labels,
inputs=embed,
num_sampled=num_sampled,
num_classes=vocabulary_size))
# Construct the SGD optimizer using a learning rate of 1.0.
optimizer = tf.train.GradientDescentOptimizer(1.0).minimize(loss)
# Compute the cosine similarity between minibatch examples and all embeddings.
norm = tf.sqrt(tf.reduce_sum(tf.square(embeddings), 1, keep_dims=True))
normalized_embeddings = embeddings / norm
valid_embeddings = tf.nn.embedding_lookup(
normalized_embeddings, valid_dataset)
similarity = tf.matmul(
valid_embeddings, normalized_embeddings, transpose_b=True)
# Add variable initializer.
init = tf.global_variables_initializer()
# Step 5: Begin training.
num_steps = 100001
with tf.Session(graph=graph) as session:
init.run()
print("Initialized")
average_loss = 0
for step in range(num_steps):
batch_inputs, batch_labels = generate_batch(
batch_size, num_skips, skip_window)
feed_dict = {train_inputs : batch_inputs, train_labels : batch_labels}
_, loss_val = session.run([optimizer, loss], feed_dict=feed_dict)
average_loss += loss_val
if step % 2000 == 0:
if step > 0:
average_loss /= 2000
# The average loss is an estimate of the loss over the last 2000 batches.
print("Average loss at step ", step, ": ", average_loss)
average_loss = 0
# Note that this is expensive (~20% slowdown if computed every 500 steps)
if step % 10000 == 0:
sim = similarity.eval()
for i in range(valid_size):
valid_word = reverse_dictionary[valid_examples[i]]
top_k = 8 # number of nearest neighbors
nearest = (-sim[i, :]).argsort()[1:top_k+1]
log_str = "Nearest to %s:" % valid_word
for k in range(top_k):
close_word = reverse_dictionary[nearest[k]]
log_str = "%s %s," % (log_str, close_word)
print(log_str)
final_embeddings = normalized_embeddings.eval()
# Step 6: Visualize the embeddings.
def plot_with_labels(low_dim_embs, labels, filename='tsne.png'):
assert low_dim_embs.shape[0] >= len(labels), "More labels than embeddings"
plt.figure(figsize=(18, 18)) #in inches
for i, label in enumerate(labels):
x, y = low_dim_embs[i,:]
plt.scatter(x, y)
plt.annotate(label,
xy=(x, y),
xytext=(5, 2),
textcoords='offset points',
ha='right',
va='bottom')
plt.savefig(filename)
#%%
try:
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000)
plot_only = 200
low_dim_embs = tsne.fit_transform(final_embeddings[:plot_only,:])
labels = [reverse_dictionary[i] for i in range(plot_only)]
plot_with_labels(low_dim_embs, labels)
except ImportError:
print("Please install sklearn, matplotlib, and scipy to visualize embeddings.")
參考資料:
《TensorFlow實戰》