张量流中的最小RNN示例

时间:2015-12-22 13:59:30

标签: tensorflow recurrent-neural-network

尝试在张量流中实现最小玩具RNN示例。 目标是学习从输入数据到目标数据的映射,类似于这个精彩的简洁example in theanets

更新:我们到了那里。剩下的唯一部分是使它收敛(并且不那么复杂)。有人可以帮助将以下内容转换为运行代码或提供一个简单的示例吗?

import tensorflow as tf
from tensorflow.python.ops import rnn_cell

init_scale = 0.1
num_steps = 7
num_units = 7
input_data = [1, 2, 3, 4, 5, 6, 7]
target = [2, 3, 4, 5, 6, 7, 7]
#target = [1,1,1,1,1,1,1] #converges, but not what we want


batch_size = 1

with tf.Graph().as_default(), tf.Session() as session:
  # Placeholder for the inputs and target of the net
  # inputs = tf.placeholder(tf.int32, [batch_size, num_steps])
  input1 = tf.placeholder(tf.float32, [batch_size, 1])
  inputs = [input1 for _ in range(num_steps)]
  outputs = tf.placeholder(tf.float32, [batch_size, num_steps])

  gru = rnn_cell.GRUCell(num_units)
  initial_state = state = tf.zeros([batch_size, num_units])
  loss = tf.constant(0.0)

  # setup model: unroll
  for time_step in range(num_steps):
    if time_step > 0: tf.get_variable_scope().reuse_variables()
    step_ = inputs[time_step]
    output, state = gru(step_, state)
    loss += tf.reduce_sum(abs(output - target))  # all norms work equally well? NO!
  final_state = state

  optimizer = tf.train.AdamOptimizer(0.1)  # CONVERGEs sooo much better
  train = optimizer.minimize(loss)  # let the optimizer train

  numpy_state = initial_state.eval()
  session.run(tf.initialize_all_variables())
  for epoch in range(10):  # now
    for i in range(7): # feed fake 2D matrix of 1 byte at a time ;)
      feed_dict = {initial_state: numpy_state, input1: [[input_data[i]]]} # no
      numpy_state, current_loss,_ = session.run([final_state, loss,train], feed_dict=feed_dict)
    print(current_loss)  # hopefully going down, always stuck at 189, why!?

1 个答案:

答案 0 :(得分:6)

我认为您的代码存在一些问题,但这个想法是正确的。

主要问题是您使用单个张量进行输入和输出,如:  inputs = tf.placeholder(tf.int32, [batch_size, num_steps])

在TensorFlow中,RNN函数采用张量列表(因为num_steps在某些模型中可能会有所不同)。所以你应该构建这样的输入:
inputs = [tf.placeholder(tf.int32, [batch_size, 1]) for _ in xrange(num_steps)]

然后你需要注意你的输入是int32s的事实,但RNN单元用于浮点向量 - 这就是embedding_lookup的用途。

最后,您需要调整Feed以输入输入列表。

我认为ptb教程是一个合理的观察点,但是如果你想要一个开箱即用的RNN的更简单的例子,你可以看看一些rnn单元测试,例如,这里。 https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/kernel_tests/rnn_test.py#L164