如何在 Tensorflow 运行时查看或保存一个张量?

How can I see or save one tensor at runtime in Tensorflow?

我有一个模型:

def __init__(params):
    seq2seq() {
        outputs, states = rnn.rnn(...)
    } 

def step()
    ...
    session.run(output_feed, input_feed)

模型调用者:

with tf.Session as sess:
    model = create_model(sess) (does __init__, loads checkpoint)
    inputs = ...
    outputs = model.step(sess, inputs)

如何 print/save/see "states" 是由 rnn.rnn() 编辑的 return?

我试过 tf.Print(states[-1], [states[-1]]) 它给出了张量的形状。

Tensor("model/seq2seq/Print:0", shape=TensorShape([Dimension(None), Dimension(4096)]), dtype=float32)

我已经尝试过 states[-1].eval() ,它提供了一系列错误,例如:

  Compute status: Invalid argument: 
  You must feed a value for placeholder tensor 'encoder1' with dtype int32   

我也曾尝试将 var 添加到模型中 return,但这没有用:

 def __init__():
     ...
     self.state = state 

 def step():
     output_feed.append(self.state)
     result = session.run(output_feed, input_feed)
     return result

为了在 eval 方法中查看张量的值,您不能依赖于图中的任何占位符。在这种情况下,错误消息告诉您 states[-1] 依赖于 'encoder1'

您可以调用 seesion.run 并输入占位符的值,如下所示:

session.run(states[-1], feed_dict={encoder1:[#values for encoder1 here
                                            ]})

其中 encoder1 是占位符对象。这应该 return 你 states[-1] 的值,然后你可以序列化保存。

在您的特定情况下,encoder1 可能是 rnn 中的一个内部占位符,因此您可能希望 运行 类似于:

_, state_values = session.run([output_feed, states[-1]], input_feed)

在您运行设置它的上下文中获取变量的值。