Tensorflow:从恢复的RNN中恢复隐藏状态

时间:2018-04-27 14:53:28

标签: tensorflow restore rnn

我想恢复RNN并获得隐藏状态。

我做了类似的事情来保存RNN:

loc="path/to/save/rnn"
with tf.variable_scope("lstm") as scope:
    outputs, state = tf.nn.dynamic_rnn(..)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
saver = tf.train.Saver()
save_path = saver.save(sess,loc)

现在我要撤消state

graph = tf.Graph()
sess = tf.Session(graph=graph)
with graph.as_default():
      saver = tf.train.import_meta_graph(loc + '.meta', clear_devices=True)
      saver.restore(sess, loc)
      state= ...

1 个答案:

答案 0 :(得分:1)

您可以使用collectionstate张量添加到图tf.add_to_collection,这基本上是跟踪张量的关键值存储,然后使用tf.get_collection检索它。例如:

loc="path/to/save/rnn"
with tf.variable_scope("lstm") as scope:
    outputs, state = tf.nn.dynamic_rnn(..)
    tf.add_to_collection('state', state)


graph = tf.Graph()
with graph.as_default():
      saver = tf.train.import_meta_graph(loc + '.meta', clear_devices=True)
      state = tf.get_collection('state')[0]  # Note: tf.get_collection returns a list.