如何在Tensorflow`自定义估算器中打印张量进行调试?

时间:2018-03-16 09:09:49

标签: tensorflow

在low-level-api中,我们可以使用

import tensorflow as tf

FLAGS = tf.app.flags.FLAGS


def yichu_dssm_model_fn(
        features,  # This is batch_features from input_fn
        labels,  # This is batch_labels from input_fn
        mode,  # An instance of tf.estimator.ModeKeys
        params):
    # word_id sequence in content
    content_input = tf.feature_column.input_layer(features, params['feature_columns'])
    content_embedding_matrix = tf.get_variable(name='content_embedding_matrix',
                                               shape=[FLAGS.max_vocab_size, FLAGS.word_vec_dim])
    content_embedding = tf.nn.embedding_lookup(content_embedding_matrix, content_input)
    content_embedding = tf.reshape(content_embedding, shape=[-1, FLAGS.max_text_len, FLAGS.word_vec_dim, 1])
    content_conv = tf.layers.Conv2D(filters=100, kernel_size=[3, FLAGS.word_vec_dim])

    content_conv_tensor = content_conv(content_embedding)
    """
      in low-level-api, we can use `print(session.run(content_conv_tensor))` to get the real data to debug.
      But in custom estimator, how to debug these tensors?
    """

获取用于调试的真实数据。但在自定义估算器中,如何调试这些张量?

以下是生动样本的摘要:

{{1}}

3 个答案:

答案 0 :(得分:1)

您可以使用tf.Print。它为图形添加了操作,可在执行时将张量内容打印到标准错误。

content_conv_tensor = tf.Print(content_conv_tensor, [content_conv_tensor], 'content_conv_tensor: ')

答案 1 :(得分:0)

sess = tf.InteractiveSession() test = sess.run(features) print('features:') print(test)

尽管这会导致错误,但仍会打印出张量值。打印后立即发生错误,因此您只能将其用于检查张量值。

答案 2 :(得分:0)

tf.Print已过时,请使用tf.print,但使用起来并不容易

最好的选择是日志挂钩

hook =  \
    tf.train.LoggingTensorHook({"var is:": var_to_print},
                               every_n_iter=10)
return tf.estimator.EstimatorSpec(mode, loss=loss, 
                                  train_op=train_op,
                                  training_hooks=[hook])