越來越覺得基礎太重要了,要成為一個合格的演算法工程師而不是調包俠,一定要知道各個基礎模型的HOW&WHY,畢竟那些模型都是當年的SOTA,他們的思想也對之後的NLP模型影響很大。最近找到了一個還不錯的nlp-tutorial,準備抽時間過一遍基礎模型,模型的大致思想以及數學公式可能就帶過了,主要是實現上的細節。
通過神經語言模型學習詞向量,網路結構如圖:
解決了統計語言模型(n-gram model)的以下問題:
公式:
複雜度(訓練一個樣本的參數量):
其中n=n_step,E=embedding size,H=hidden size,V=vocab size
class NNLM(nn.Module): def __init__(self): super(NNLM, self).__init__() self.C = nn.Embedding(n_class, m) self.H = nn.Parameter(torch.randn(n_step * m, n_hidden).type(dtype)) self.W = nn.Parameter(torch.randn(n_step * m, n_class).type(dtype)) self.d = nn.Parameter(torch.randn(n_hidden).type(dtype)) self.U = nn.Parameter(torch.randn(n_hidden, n_class).type(dtype)) self.b = nn.Parameter(torch.randn(n_class).type(dtype))
def forward(self, X): X = self.C(X) X = X.view(-1, n_step * m) # [batch_size, n_step * emb_dim] tanh = torch.tanh(self.d + torch.mm(X, self.H)) # [batch_size, n_hidden] output = self.b + torch.mm(X, self.W) + torch.mm(tanh, self.U) # [batch_size, n_class] return output
要注意的點:
學習更高質量、且快速訓練的word vector,分別又Skip-gram和CBOW兩種結構:
提出上述簡單結構主要受NNLM後一些研究的啟發,作者發現不完全訓練模型也可以得到詞向量,因此直接去掉了隱層。
推薦閱讀: