有没有办法将Tensorflow中的中间输出保存到文件中?

tha*_*ang 2 debugging save tensorflow

我有一个转发网络做了很多事情.

推理代码看起来像这样:

conv0_feature_count = 2
with tf.variable_scope('conv0') as scope:
    kernel = _variable_with_weight_decay('weights', shape=[5, 5, 1, conv0_feature_count], stddev=5e-2, wd=0.0)
    conv = tf.nn.conv2d(images, kernel, [1, 1, 1, 1], padding='SAME')
    biases = _variable_on_cpu('biases', [conv0_feature_count], tf.constant_initializer(0.0))
    bias = tf.nn.bias_add(conv, biases)
    conv0 = tf.nn.relu(bias, name=scope.name)
Run Code Online (Sandbox Code Playgroud)

依此类推,然后是最大池,等等.

我希望能够将conv0保存到文件中进行检查.我知道tf.Print会在控制台中打印这些值,但这是一个很大的张量.打印该值毫无意义.

mrr*_*rry 5

TensorFlow没有任何公共运算符可以将张量写入文件,但是如果你看一下tf.train.Saver(特别是BaseSaverBuilder.save_op()方法)的实现,你会看到它包含一个可以写一个的op的实现或更多的文件张量,用于编写检查点.

CAVEAT:以下解决方案依赖于内部实现,可能会发生变化,但适用于TensorFlow r0.10rc0.

以下代码片段将张量写入t名为的文件"/tmp/t.ckpt":

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

t = tf.matmul(tf.constant([[6, 6]]), tf.constant([[2], [-1]]))

save_op = io_ops._save(filename="/tmp/t.ckpt", tensor_names=["t"],
                       tensors=[t])

sess = tf.Session()
sess.run(save_op)  # Writes `t` to "/tmp/t.ckpt".
Run Code Online (Sandbox Code Playgroud)

要读取值,您可以使用tf.train.NewCheckpointReader()如下:

reader = tf.train.NewCheckpointReader("/tmp/t.ckpt")
print reader.get_tensor("t")  # ==> "array([[6]], dtype=int32)"
Run Code Online (Sandbox Code Playgroud)