使用TENSORFLOW训练循环神经网络语言模型

人工智能 深度学习
Language Model,即语言模型,其主要思想是,在知道前一部分的词的情况下,推断出下一个最有可能出现的词。在本文中,我们更加关注的是,如何使用RNN来推测下一个词。

读了将近一个下午的TensorFlow Recurrent Neural Network教程,翻看其在PTB上的实现,感觉晦涩难懂,因此参考了部分代码,自己写了一个简化版的Language Model,思路借鉴了Keras的LSTM text generation

代码地址:Github

转载请注明出处:Gaussic

语言模型

Language Model,即语言模型,其主要思想是,在知道前一部分的词的情况下,推断出下一个最有可能出现的词。例如,知道了 The fat cat sat on the,我们认为下一个词为mat的可能性比hat要大,因为猫更有可能坐在毯子上,而不是帽子上。

这可能被你认为是常识,但是在自然语言处理中,这个任务是可以用概率统计模型来描述的。就拿The fat cat sat on the mat来说。我们可能统计出第一个词The出现的概率p(The)p(The),The后面是fat的条件概率为p(fat|The)p(fat|The),The fat同时出现的联合概率:

  1. p(The,fat)=p(The)⋅p(fat|The)p(The,fat)=p(The)·p(fat|The) 
这个联合概率,就是The fat的合理性,即这句话的出现符不符合自然语言的评判标准,通俗点表述就是这是不是句人话。同理,根据链式规则,The fat cat的联合概率可求:
 
  1. p(The,fat,cat)=p(The)⋅p(fat|The)⋅p(cat|The,fat)p(The,fat,cat)=p(The)·p(fat|The)·p(cat|The,fat) 
在知道前面的词为The cat的情况下,下一个词为cat的概率可以推导出来:
 
  1. p(cat|The,fat)=p(The,fat,cat)p(The,fat)p(cat|The,fat)=p(The,fat,cat)p(The,fat) 
分子是The fat cat在语料库中出现的次数,分母是The fat在语料库中出现的次数。
因此,The fat cat sat on the mat整个句子的合理性同样可以推导,这个句子的合理性即为它的概率。公式化的描述如下:
 
  1. p(S)=p(w1,w2,⋅⋅⋅,wn)=p(w1)⋅p(w2|w1)⋅p(w3|w1,w2)⋅⋅⋅p(wn|w1,w2,w3,⋅⋅⋅,wn−1)p(S)=p(w1,w2,···,wn)=p(w1)·p(w2|w1)·p(w3|w1,w2)···p(wn|w1,w2,w3,···,wn−1) 
(公式后的n-1应该为下标,插件问题,下同)
 
可以看出一个问题,每当计算下一个词的条件概率,需要计算前面所有词的联合概率。这个计算量相当的庞大。并且,一个句子中大部分词同时出现的概率往往少之又少,数据稀疏非常严重,需要一个非常大的语料库来训练。
 
一个简单的优化是基于马尔科夫假设,下一个词的出现仅与前面的一个或n个词有关。
 
最简单的情况,下一个词的出现仅仅和前面一个词有关,称之为bigram。
 
  1. p(S)=p(w1,w2,⋅⋅⋅,wn)=p(w1)⋅p(w2|w1)⋅p(w3|w2)⋅p(w4|w3)⋅⋅⋅p(wn|wn−1)p(S)=p(w1,w2,···,wn)=p(w1)·p(w2|w1)·p(w3|w2)·p(w4|w3)···p(wn|wn−1) 
再复杂点,下一个词的出现仅和前面两个词有关,称之为trigram。
 
  1. p(S)=p(w1,w2,⋅⋅⋅,wn)=p(w1)⋅p(w2|w1)⋅p(w3|w1,w2)⋅p(w4|w2,w3)⋅⋅⋅p(wn|wn−2,wn−1)p(S)=p(w1,w2,···,wn)=p(w1)·p(w2|w1)·p(w3|w1,w2)·p(w4|w2,w3)···p(wn|wn−2,wn−1) 

这样的条件概率虽然好求,但是会丢失大量的前面的词的信息,有时会对结果产生不良影响。因此如何选择一个有效的n,使得既能简化计算,又能保留大部分的上下文信息。

以上均是传统语言模型的描述。如果不太深究细节,我们的任务就是,知道前面n个词,来计算下一个词出现的概率。并且使用语言模型来生成新的文本。

在本文中,我们更加关注的是,如何使用RNN来推测下一个词。

数据准备
 
TensorFlow的官方文档使用的是Mikolov准备好的PTB数据集。我们可以将其下载并解压出来:
 
  1. $ wget http://www.fit.vutbr.cz/~imikolov/rnnlm/simple-examples.tgz 
  2. $ tar xvf simple-examples.tgz 
部分数据如下,不常用的词转换成了<unk>标记,数字转换成了N:
 
  1. we 're talking about years ago before anyone heard of asbestos having any questionable properties 
  2. there is no asbestos in our products now 
  3. neither <unk> nor the researchers who studied the workers were aware of any research on smokers of the kent cigarettes 
  4. we have no useful information on whether users are at risk said james a. <unk> of boston 's <unk> cancer institute 
  5. the total of N deaths from malignant <unk> lung cancer and <unk> was far higher than expected the researchers said 
读取文件中的数据,将换行符转换为<eos>,然后转换为词的list:
 
  1. def _read_words(filename): 
  2.     with open(filename, 'r', encoding='utf-8'as f: 
  3.         return f.read().replace('\n''<eos>').split() 
  1. f = _read_words('simple-examples/data/ptb.train.txt'
  2. print(f[:20]) 
得到:
 
  1. ['aer''banknote''berlitz''calloway''centrust''cluett''fromstein''gitano''guterman''hydro-quebec''ipo''kia''memotec''mlx''nahb''punts''rake''regatta''rubens''sim'
构建词汇表,词与id互转:
 
  1. def _build_vocab(filename): 
  2.     data = _read_words(filename) 
  3.  
  4.     counter = Counter(data) 
  5.     count_pairs = sorted(counter.items(), key=lambda x: -x[1]) 
  6.  
  7.     words, _ = list(zip(*count_pairs)) 
  8.     word_to_id = dict(zip(words, range(len(words)))) 
  9.  
  10.     return words, word_to_id 
  1. words, words_to_id = _build_vocab('simple-examples/data/ptb.train.txt'
  2. print(words[:10]) 
  3. print(list(map(lambda x: words_to_id[x], words[:10]))) 
输出:
 
  1. ('the''<unk>''<eos>''N''of''to''a''in''and'"'s"
  2. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 
将一个文件转换为id表示:
 
  1. def _file_to_word_ids(filename, word_to_id): 
  2.     data = _read_words(filename) 
  3.     return [word_to_id[x] for x in data if x in word_to_id] 
  1. words_in_file = _file_to_word_ids('simple-examples/data/ptb.train.txt', words_to_id) 
  2. print(words_in_file[:20]) 
词汇表已根据词频进行排序,由于第一句话非英文,所以id靠后。
 
  1. [9980, 9988, 9981, 9989, 9970, 9998, 9971, 9979, 9992, 9997, 9982, 9972, 9993, 9991, 9978, 9983, 9974, 9986, 9999, 9990] 
将一句话从id列表转换回词:
 
  1. def to_words(sentence, words): 
  2.     return list(map(lambda x: words[x], sentence)) 
将以上函数整合:
 
  1. def ptb_raw_data(data_path=None): 
  2.     train_path = os.path.join(data_path, 'ptb.train.txt'
  3.     valid_path = os.path.join(data_path, 'ptb.valid.txt'
  4.     test_path = os.path.join(data_path, 'ptb.test.txt'
  5.  
  6.     words, word_to_id = _build_vocab(train_path) 
  7.     train_data = _file_to_word_ids(train_path, word_to_id) 
  8.     valid_data = _file_to_word_ids(valid_path, word_to_id) 
  9.     test_data = _file_to_word_ids(test_path, word_to_id) 
  10.  
  11.     return train_data, valid_data, test_data, words, word_to_id 
以上部分和官方的例子有一定的相似之处。接下来的处理和官方存在很大的不同,主要参考了Keras例程处理文档的操作:
 
  1. def ptb_producer(raw_data, batch_size=64, num_steps=20, stride=1): 
  2.     data_len = len(raw_data) 
  3.  
  4.     sentences = [] 
  5.     next_words = [] 
  6.     for i in range(0, data_len - num_steps, stride): 
  7.         sentences.append(raw_data[i:(i + num_steps)]) 
  8.         next_words.append(raw_data[i + num_steps]) 
  9.  
  10.     sentences = np.array(sentences) 
  11.     next_words = np.array(next_words) 
  12.  
  13.     batch_len = len(sentences) // batch_size 
  14.     x = np.reshape(sentences[:(batch_len * batch_size)], \ 
  15.         [batch_len, batch_size, -1]) 
  16.  
  17.     y = np.reshape(next_words[:(batch_len * batch_size)], \ 
  18.         [batch_len, batch_size]) 
  19.  
  20.     return x, y 
参数解析:
  •     raw_data: 即ptb_raw_data()函数产生的数据
  •     batch_size: 神经网络使用随机梯度下降,数据按多个批次输出,此为每个批次的数据量
  •     num_steps: 每个句子的长度,相当于之前描述的n的大小,这在循环神经网络中又称为时序的长度。
  •     stride: 取数据的步长,决定数据量的大小。

代码解析:

这个函数将一个原始数据list转换为多个批次的数据,即[batch_len, batch_size, num_steps]。

首先,程序每一次取了num_steps个词作为一个句子,即x,以这num_steps个词后面的一个词作为它的下一个预测,即为y。这样,我们首先把原始数据整理成了batch_len * batch_size个x和y的表示,类似于已知x求y的分类问题。

为了满足随机梯度下降的需要,我们还需要把数据整理成一个个小的批次,每次喂一个批次的数据给TensorFlow来更新权重,这样,数据就整理为[batch_len, batch_size, num_steps]的格式。

打印部分数据: 

  1. train_data, valid_data, test_data, words, word_to_id = ptb_raw_data('simple-examples/data'
  2. x_train, y_train = ptb_producer(train_data) 
  3. print(x_train.shape) 
  4. print(y_train.shape) 
输出:
 
  1. (14524, 64, 20) 
  2. (14524, 64) 
可见我们得到了14524个批次的数据,每个批次的训练集维度为[64, 20]。
 
  1. print(' '.join(to_words(x_train[100, 3], words))) 
第100个批次的第3句话为:
 
  1. despite steady sales growth <eos> magna recently cut its quarterly dividend in half and the company 's class a shares 
  1. print(words[np.argmax(y_train[100, 3])]) 
它的下一个词为:
 
  1. the 
 
构建模型
 
配置项
 
  1. class LMConfig(object): 
  2.     """language model 配置项""" 
  3.     batch_size = 64       # 每一批数据的大小 
  4.     num_steps = 20        # 每一个句子的长度 
  5.     stride = 3            # 取数据时的步长 
  6.  
  7.     embedding_dim = 64    # 词向量维度 
  8.     hidden_dim = 128      # RNN隐藏层维度 
  9.     num_layers = 2        # RNN层数 
  10.  
  11.     learning_rate = 0.05  # 学习率 
  12.     dropout = 0.2         # 每一层后的丢弃概率 
读取输入
 
让模型可以按批次的读取数据。
 
  1. class PTBInput(object): 
  2.     """按批次读取数据""" 
  3.     def __init__(self, config, data): 
  4.         self.batch_size = config.batch_size 
  5.         self.num_steps = config.num_steps 
  6.         self.vocab_size = config.vocab_size # 词汇表大小 
  7.  
  8.         self.input_data, self.targets = ptb_producer(data, 
  9.             self.batch_size, self.num_steps) 
  10.  
  11.         self.batch_len = self.input_data.shape[0] # 总批次 
  12.         self.cur_batch = 0  # 当前批次 
  13.  
  14.     def next_batch(self): 
  15.         """读取下一批次""" 
  16.         x = self.input_data[self.cur_batch] 
  17.         y = self.targets[self.cur_batch] 
  18.  
  19.         # 转换为one-hot编码 
  20.         y_ = np.zeros((y.shape[0], self.vocab_size), dtype=np.bool) 
  21.         for i in range(y.shape[0]): 
  22.             y_[i][y[i]] = 1 
  23.  
  24.         # 如果到最后一个批次,则回到最开头 
  25.         self.cur_batch = (self.cur_batch +1) % self.batch_len 
  26.  
  27.         return x, y_ 
模型
 
  1. class PTBModel(object): 
  2.     def __init__(self, config, is_training=True): 
  3.  
  4.         self.num_steps = config.num_steps 
  5.         self.vocab_size = config.vocab_size 
  6.  
  7.         self.embedding_dim = config.embedding_dim 
  8.         self.hidden_dim = config.hidden_dim 
  9.         self.num_layers = config.num_layers 
  10.         self.rnn_model = config.rnn_model 
  11.  
  12.         self.learning_rate = config.learning_rate 
  13.         self.dropout = config.dropout 
  14.  
  15.         self.placeholders()  # 输入占位符 
  16.         self.rnn()           # rnn 模型构建 
  17.         self.cost()          # 代价函数 
  18.         self.optimize()      # 优化器 
  19.         self.error()         # 错误率 
  20.  
  21.  
  22.     def placeholders(self): 
  23.         """输入数据的占位符""" 
  24.         self._inputs = tf.placeholder(tf.int32, [None, self.num_steps]) 
  25.         self._targets = tf.placeholder(tf.int32, [None, self.vocab_size]) 
  26.  
  27.  
  28.     def input_embedding(self): 
  29.         """将输入转换为词向量表示""" 
  30.         with tf.device("/cpu:0"): 
  31.             embedding = tf.get_variable( 
  32.                 "embedding", [self.vocab_size, 
  33.                     self.embedding_dim], dtype=tf.float32) 
  34.             _inputs = tf.nn.embedding_lookup(embedding, self._inputs) 
  35.  
  36.         return _inputs 
  37.  
  38.  
  39.     def rnn(self): 
  40.         """rnn模型构建""" 
  41.         def lstm_cell():  # 基本的lstm cell 
  42.             return tf.contrib.rnn.BasicLSTMCell(self.hidden_dim, 
  43.                 state_is_tuple=True
  44.  
  45.         def gru_cell():   # gru cell,速度更快 
  46.             return tf.contrib.rnn.GRUCell(self.hidden_dim) 
  47.  
  48.         def dropout_cell():    # 在每个cell后添加dropout 
  49.             if (self.rnn_model == 'lstm'): 
  50.                 cell = lstm_cell() 
  51.             else
  52.                 cell = gru_cell() 
  53.             return tf.contrib.rnn.DropoutWrapper(cell, 
  54.                 output_keep_prob=self.dropout) 
  55.  
  56.         cells = [dropout_cell() for _ in range(self.num_layers)] 
  57.         cell = tf.contrib.rnn.MultiRNNCell(cells, state_is_tuple=True)  # 多层rnn 
  58.  
  59.         _inputs = self.input_embedding() 
  60.         _outputs, _ = tf.nn.dynamic_rnn(cell=cell, 
  61.             inputs=_inputs, dtype=tf.float32) 
  62.  
  63.         # _outputs的shape为 [batch_size, num_steps, hidden_dim] 
  64.         last = _outputs[:, -1, :]  # 只需要最后一个输出 
  65.  
  66.         # dense 和 softmax 用于分类,以找出各词的概率 
  67.         logits = tf.layers.dense(inputs=last, units=self.vocab_size)    
  68.         prediction = tf.nn.softmax(logits)   
  69.  
  70.         self._logits = logits 
  71.         self._pred = prediction 
  72.  
  73.     def cost(self): 
  74.         """计算交叉熵代价函数""" 
  75.         cross_entropy = tf.nn.softmax_cross_entropy_with_logits( 
  76.             logits=self._logits, labels=self._targets) 
  77.         cost = tf.reduce_mean(cross_entropy) 
  78.         self.cost = cost 
  79.  
  80.     def optimize(self): 
  81.         """使用adam优化器""" 
  82.         optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate) 
  83.         self.optim = optimizer.minimize(self.cost) 
  84.  
  85.     def error(self): 
  86.         """计算错误率""" 
  87.         mistakes = tf.not_equal( 
  88.             tf.argmax(self._targets, 1), tf.argmax(self._pred, 1)) 
  89.         self.errors = tf.reduce_mean(tf.cast(mistakes, tf.float32)) 
训练
 
  1. def run_epoch(num_epochs=10): 
  2.     config = LMConfig()   # 载入配置项 
  3.  
  4.     # 载入源数据,这里只需要训练集 
  5.     train_data, _, _, words, word_to_id = \ 
  6.         ptb_raw_data('simple-examples/data'
  7.     config.vocab_size = len(words) 
  8.  
  9.     # 数据分批 
  10.     input_train = PTBInput(config, train_data) 
  11.     batch_len = input_train.batch_len 
  12.  
  13.     # 构建模型 
  14.     model = PTBModel(config) 
  15.  
  16.     # 创建session,初始化变量 
  17.     sess = tf.Session() 
  18.     sess.run(tf.global_variables_initializer()) 
  19.  
  20.     print('Start training...'
  21.     for epoch in range(num_epochs):  # 迭代轮次 
  22.         for i in range(batch_len):   # 经过多少个batch 
  23.             x_batch, y_batch = input_train.next_batch() 
  24.  
  25.             # 取一个批次的数据,运行优化 
  26.             feed_dict = {model._inputs: x_batch, model._targets: y_batch} 
  27.             sess.run(model.optim, feed_dict=feed_dict) 
  28.  
  29.             # 每500个batch,输出一次中间结果 
  30.             if i % 500 == 0: 
  31.                 cost = sess.run(model.cost, feed_dict=feed_dict) 
  32.  
  33.                 msg = "Epoch: {0:>3}, batch: {1:>6}, Loss: {2:>6.3}" 
  34.                 print(msg.format(epoch + 1, i + 1, cost)) 
  35.  
  36.                 # 输出部分预测结果 
  37.                 pred = sess.run(model._pred, feed_dict=feed_dict) 
  38.                 word_ids = sess.run(tf.argmax(pred, 1)) 
  39.                 print('Predicted:'' '.join(words[w] for w in word_ids)) 
  40.                 true_ids = np.argmax(y_batch, 1) 
  41.                 print('True:'' '.join(words[w] for w in true_ids)) 
  42.  
  43.     print('Finish training...'
  44.     sess.close() 

需要经过多次的训练才能得到一个较为合理的结果。 

 

责任编辑:庞桂玉 来源: 36大数据
相关推荐

2017-03-27 16:18:30

神经网络TensorFlow人工智能

2017-08-29 13:50:03

TensorFlow深度学习神经网络

2018-08-27 17:05:48

tensorflow神经网络图像处理

2017-09-28 16:15:12

神经网络训练多层

2022-12-05 10:08:59

2017-08-22 16:20:01

深度学习TensorFlow

2018-02-27 09:32:13

神经网络自然语言初探

2017-12-22 08:47:41

神经网络AND运算

2018-03-22 13:34:59

TensorFlow神经网络

2023-05-06 12:47:41

2023-01-11 07:28:49

TensorFlow分类模型

2019-01-05 08:40:17

VGG神经网络

2018-07-29 06:46:07

神经网络RNN循环神经网络

2022-10-19 07:42:41

图像识别神经网络

2018-12-14 08:02:55

神经网络机器学习二值模型

2019-07-24 05:36:32

神经网络语言模型NNLM

2017-07-19 11:39:25

深度学习人工智能boosting

2017-11-24 08:00:06

深度学习TensorFlow预测股票

2017-08-10 15:31:57

Apache Spar TensorFlow

2023-08-21 10:48:25

点赞
收藏

51CTO技术栈公众号