NLP模型之NNLM


1、背景

語言模型就是計算句子中的詞按照組成句子的順序排列的概率,由此來判斷是不是正常句子。

傳統的語言模型,N-gram模型,基於馬爾科夫假設,下一個詞的出現僅依賴前面的一個或n個詞

對一句話S=x1,x2,x3,x4,x5,,xnS=x1,x2,x3,x4,x5,…,xn而言,它的概率:

P(S)=P(x1,x2,x3,x4,x5,,xn)

       =P(x1)P(x2|x1)P(x3|x1,x2)...P(xn|x1,x2,...,xn1)

使用假設后,變成

  P(x1)P(x2|x1)P(x3|x2)P(x4|x3)...P(xn|xn-1)      1-gram

  P(x1)P(x2|x1)P(x3|x2,x1)P(x4|x3,x2)...P(xn|xn-1,xn-2)     2-gram 

一般工程中選擇3,也就是一個詞僅與之前面的3個詞相關,就可以了,n越大計算量指數級遞增

傳統語言模型的缺點是:

A:稀疏性    一些沒出現的詞概率為0,將直接影響概率的計算,,因此采取一些平滑處理,,比如拉普拉斯平滑、線性插值

B:泛化能力弱    依賴固定的模式匹,“舒適的酒店”和“溫馨的賓館”應該是相似的概率分布,傳統語言模型學習不到

因此發展出神經網絡語言模型

 

2、神經網絡語言模型之NNLM

直接通過神經網絡對n元條件概率進行統計

輸入:前n-1個詞的one-hot表示

將輸入與一個V*M的矩陣相乘,V表示詞匯表的大小,M表示映射后的維度

得到的n-1個詞的映射后向量,每個都是1*M維,共n-1個,組合成一維的向量(n-1)*M,表示前n-1個詞組成的詞向量

接一個softmax計算得到的是預測詞的概率,輸出是1*V維的,表示在詞匯表在最大概率出現的詞,即為預測的下一個詞

這里最重要的是得到了一個V*M的映射矩陣,對每個詞來說都是乘以這個矩陣計算概率,因此這個矩陣就是詞匯表中V個詞的表示,每一行表示一個詞對應的向量

 

3、代碼

 

import tensorflow as tf import numpy as np tf.reset_default_graph() sentences = [ "i like dog Luckid", "i love coffee mi", "i hate milk hello"] word_list = " ".join(sentences).split() word_list = list(set(word_list)) word_dict = {w: i for i, w in enumerate(word_list)} number_dict = {i: w for i, w in enumerate(word_list)} n_class = len(word_dict) # NNLM Parameter
n_step = 3 # number of steps ['i like', 'i love', 'i hate']
n_hidden = 2 # number of hidden units

def make_batch(sentences): input_batch = [] target_batch = [] for sen in sentences: word = sen.split() input = [word_dict[n] for n in word[:-1]] target = word_dict[word[-1]] input_batch.append(np.eye(n_class)[input]) target_batch.append(np.eye(n_class)[target]) return input_batch, target_batch # Model
X = tf.placeholder(tf.float32, [None, n_step, n_class]) # [batch_size, number of steps, number of Vocabulary]
Y = tf.placeholder(tf.float32, [None, n_class]) input = tf.reshape(X, shape=[-1, n_step * n_class]) # [batch_size, n_step * n_class]
H = tf.Variable(tf.random_normal([n_step * n_class, n_hidden])) d = tf.Variable(tf.random_normal([n_hidden])) U = tf.Variable(tf.random_normal([n_hidden, n_class])) b = tf.Variable(tf.random_normal([n_class])) tanh = tf.nn.tanh(d + tf.matmul(input, H)) # [batch_size, n_hidden]
model = tf.matmul(tanh, U) + b # [batch_size, n_class]
 cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=model, labels=Y)) optimizer = tf.train.AdamOptimizer(0.001).minimize(cost) prediction =tf.argmax(model, 1) # Training
init = tf.global_variables_initializer() sess = tf.Session() sess.run(init) input_batch, target_batch = make_batch(sentences) for epoch in range(10000): _, loss = sess.run([optimizer, cost], feed_dict={X: input_batch, Y: target_batch}) if (epoch + 1)%1000 == 0: print('Epoch:', '%04d' % (epoch + 1), 'cost =', '{:.6f}'.format(loss)) # Predict
predict =  sess.run([prediction], feed_dict={X: input_batch}) # Test
input = [sen.split()[:n_step] for sen in sentences] print([sen.split()[:n_step] for sen in sentences], '->', [number_dict[n] for n in predict[0]])

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM