學習筆記TF034:實現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實踐》
歡迎付費咨詢(150元每小時),我的微信:qingxingfengzi
學習筆記TF034:實現Word2Vec