如何在张量流的某些函数中打印中间张量的值?

时间:2019-12-24 02:31:22

标签: python tensorflow jupyter-notebook

使用tensorflow时,如何在某些函数中打印一些中间张量的值?例如:

import numpy as np
import tensorflow as tf

def f(X):
    tf.set_random_seed(1) 
    W1 = tf.get_variable('W1',[4, 4, 3, 8], initializer = tf.contrib.layers.xavier_initializer(seed = 0))
    Z1 = tf.nn.conv2d(X,W1, strides = [1,1,1,1], padding = 'SAME')
    return Z1

with tf.Session() as sess:
    np.random.seed(1)
    X=tf.placeholder(tf.float32, shape=[None, 64, 64, 3])
    Z1 = f(X)
    init = tf.global_variables_initializer()
    sess.run(init)
    a = sess.run(Z1, {X: np.random.randn(2,64,64,3)})
    print("Z1 = " + str(a))

在计算W1时如何打印张量XZ1的具体值?我需要W1X的值进行调试。

PS:我正在使用 Jupyter Notebook ,TensorFlow 1.15

2 个答案:

答案 0 :(得分:0)

在tensorflow1.x中,我知道的一种方法是使用tf.enable_eager_execution,启用eager模型,然后可以像numpy一样使用tf.tensor

答案 1 :(得分:0)

有三种方法。

更改方法的参数

def f(X):
    tf.set_random_seed(1) 
    W1 = tf.get_variable('W1',[4, 4, 3, 8], initializer = tf.contrib.layers.xavier_initializer(seed = 0))
    Z1 = tf.nn.conv2d(X,W1, strides = [1,1,1,1], padding = 'SAME')    
    return Z1, W1

with tf.Session() as sess:
    np.random.seed(1)
    X=tf.placeholder(tf.float32, shape=[None, 64, 64, 3])
    W1, Z1 = f(X)
    init = tf.global_variables_initializer()
    sess.run(init)    

    w, x, a = sess.run([W1, X, Z1], {X: np.random.randn(2,64,64,3)})
    print("Z1 = " + str(a))
    print('W = ', w)
    print('X = ', x)

无需更改方法的参数

...
    X=tf.placeholder(tf.float32, shape=[None, 64, 64, 3])
    Z1 = f(X)
    init = tf.global_variables_initializer()
    sess.run(init)    
    with tf.variable_scope('',reuse=True) as scope:
      W1 = tf.get_variable('W1')
    w, x, a = sess.run([W1, X, Z1], {X: np.random.randn(2,64,64,3)})
    print("Z1 = " + str(a))
    print('W = ', w)
    print('X = ', x)

或者您可以使用渴望执行而不是图形执行。我认为这是使用TF进行调试的最佳方法,因为在执行Graph时打印/调试值比较笨拙。