文章目录
一、NNLM简单介绍
NNLM:Neural Network Language Model,神经网络语言模型。源自Bengio等人于2001年发表在NIPS上的《A Neural Probabilistic Language Model一文。
利用神经网络计算词向量的方法,根据(w{t-n+1}...w{t-1})来预测(w{t})是什么单词,即用前(n-1)个单词来预测第(n)个单词。
二、NNLM词语预测代码
1. 导入包
torch库——又称PyTorach,是一个以Python优先的深度学习框架,一个开源的Python机器学习库,用于自然语言处理等应用程序。
torch.nn包——nn全称为neural network,意思是神经网络,是torch中构建神经网络的模块。
torch.optim包——这个包里面有很多的优化算法,比如我们常用的随机梯度下降算法,添加动量的随机梯度下降算法。
import torch
import torch.nn as nn
import torch.optim as optim
2. 文本数据处理
输入三句短文本,"i like dog", "i love coffee", "i hate milk",作为模型预测的资料。
dtype = torch.FloatTensor
sentences = ["i like dog", "i love coffee", "i hate milk"]
word_list = " ".join(sentences).split() # 提取句子中所有词语
#print(word_list)
word_list = list(set(word_list)) # 去除重复元素,得到词汇表
#print("去重后的word_list:", word_list)
word_dict = {w: i for i, w in enumerate(word_list)} # 按照词汇表生成相应的词典 {‘word’:0,...}
number_dict = {i: w for i, w in enumerate(word_list)} # 将每个索引对应于相应的单词{0:'word',...}
n_class = len(word_dict) # 单词的总数,也是分类数
torch.FloatTensor——FloatTensor用于生成浮点类型的张量。 torch.FloatTensor()默认生成32位浮点数,dtype 为 torch.float32 或 torch.float。
enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
3. 自定义mini-batch迭代器
自定义函数:def make_batch(sentences),make_batch(sentences)函数是一个mini-batch迭代器,实现数据的输入输出,函数以sentences列表作为输入, 最终函数将输入数据集input_batch和输出数据集target_batch返回为结果。详见代码注释。