使用LSTM-ptb模型tensorflow示例预测下一个单词



我正在尝试使用tensorflow LSTM模型来进行下一个单词的预测。

正如这个相关问题中所描述的(没有公认的答案),这个例子包含了提取下一个单词概率的伪代码:

lstm = rnn_cell.BasicLSTMCell(lstm_size)
# Initial state of the LSTM memory.
state = tf.zeros([batch_size, lstm.state_size])
loss = 0.0
for current_batch_of_words in words_in_dataset:
  # The value of state is updated after processing each batch of words.
  output, state = lstm(current_batch_of_words, state)
  # The LSTM output can be used to make next word predictions
  logits = tf.matmul(output, softmax_w) + softmax_b
  probabilities = tf.nn.softmax(logits)
  loss += loss_function(probabilities, target_words)

我对如何解释概率向量感到困惑。我修改了ptb_word_lm.py中PTBModel__init__函数,以存储概率和logits:

class PTBModel(object):
  """The PTB model."""
  def __init__(self, is_training, config):
    # General definition of LSTM (unrolled)
    # identical to tensorflow example ...     
    # omitted for brevity ...

    # computing the logits (also from example code)
    logits = tf.nn.xw_plus_b(output,
                             tf.get_variable("softmax_w", [size, vocab_size]),
                             tf.get_variable("softmax_b", [vocab_size]))
    loss = seq2seq.sequence_loss_by_example([logits],
                                            [tf.reshape(self._targets, [-1])],
                                            [tf.ones([batch_size * num_steps])],
                                            vocab_size)
    self._cost = cost = tf.reduce_sum(loss) / batch_size
    self._final_state = states[-1]
    # my addition: storing the probabilities and logits
    self.probabilities = tf.nn.softmax(logits)
    self.logits = logits
    # more model definition ...

然后在run_epoch功能中打印一些关于它们的信息:

def run_epoch(session, m, data, eval_op, verbose=True):
  """Runs the model on the given data."""
  # first part of function unchanged from example
  for step, (x, y) in enumerate(reader.ptb_iterator(data, m.batch_size,
                                                    m.num_steps)):
    # evaluate proobability and logit tensors too:
    cost, state, probs, logits, _ = session.run([m.cost, m.final_state, m.probabilities, m.logits, eval_op],
                                 {m.input_data: x,
                                  m.targets: y,
                                  m.initial_state: state})
    costs += cost
    iters += m.num_steps
    if verbose and step % (epoch_size // 10) == 10:
      print("%.3f perplexity: %.3f speed: %.0f wps, n_iters: %s" %
            (step * 1.0 / epoch_size, np.exp(costs / iters),
             iters * m.batch_size / (time.time() - start_time), iters))
      chosen_word = np.argmax(probs, 1)
      print("Probabilities shape: %s, Logits shape: %s" % 
            (probs.shape, logits.shape) )
      print(chosen_word)
      print("Batch size: %s, Num steps: %s" % (m.batch_size, m.num_steps))
  return np.exp(costs / iters)

这会产生这样的输出:

0.000 perplexity: 741.577 speed: 230 wps, n_iters: 220
(20, 10000) (20, 10000)
[ 14   1   6 589   1   5   0  87   6   5   3   5   2   2   2   2   6   2  6   1]
Batch size: 1, Num steps: 20

我希望probs向量是一组概率,词汇表中的每个单词都有一个概率(例如形状为(1, vocab_size)),这意味着我可以像另一个问题中建议的那样使用np.argmax(probs, 1)来获得预测单词。

然而,向量的第一个维度实际上等于展开的LSTM中的步骤数(如果使用小配置设置,则为20),我不知道该怎么办。要访问预测单词,我是否只需要使用最后一个值(因为它是最后一步的输出)?或者我还缺少什么?

我试图通过查看seq2seq.sequence_loss_by_example的实现来理解预测是如何进行和评估的,它必须执行此评估,但最终调用了gen_nn_ops._sparse_softmax_cross_entropy_with_logits,它似乎没有包含在github repo中,所以我不确定还能从哪里看。

我对tensorflow和LSTM都很陌生,所以我们非常感谢您的帮助!

output张量包含每个时间步长的LSTM单元输出的连接(请参阅此处的定义)。因此,您可以通过取chosen_word[-1](或chosen_word[sequence_length - 1],如果序列已被填充以匹配展开的LSTM)来找到下一个单词的预测。

tf.nn.sparse_softmax_cross_entropy_with_logits()操作以不同的名称记录在公共API中。由于技术原因,它调用了一个生成的包装器函数,该函数没有出现在GitHub存储库中。op的实现是在C++中实现的。

我也在实现seq2seq模型。

因此,让我试着用我的理解来解释:

LSTM模型的输出是大小为[batch_sizesize]的2D张量的列表(长度num_steps)。

代码行:

output = tf.reshape(tf.concat(1, outputs), [-1, size])

将产生新的输出,该输出是大小为[batch_sizexnum_stepssize]的2D张量。

对于您的情况,batch_size=1和num_steps=20-->输出形状为[20size]。

代码行:

logits = tf.nn.xw_plus_b(output, tf.get_variable("softmax_w", [size, vocab_size]), tf.get_variable("softmax_b", [vocab_size]))

<=>输出[batch_size x num_steps,size]xsoftmax_w[size,vocab_size]将输出batch_sizexnum_stepsvocab_size]大小的logits
对于您的情况,大小为20logitsvocab_size]-->probs张量的大小与logits的大小相同,由[20vocab_size]决定。

代码行:

chosen_word = np.argmax(probs, 1)

将输出大小为[201]的chosen_word张量,每个值都是当前单词的下一个预测单词索引。

代码行:

loss = seq2seq.sequence_loss_by_example([logits], [tf.reshape(self._targets, [-1])], [tf.ones([batch_size * num_steps])])

是计算batch_size序列的softmax交叉熵损失。

相关内容

最新更新