# tf.Print(
# input_, # input_: A tensor passed through this op. 输入单元
# data, # data: A list of tensors to print out when op is evaluated 输出单元
# message=None, # message: A string, prefix of the error message. 在输出data之前输出的前缀
# first_n=None,
# summarize=None, #Only print this many entries of each tensor. If None, then a maximum of 3 elements are printed per input tensor.如果需要打印矩阵,需要修改这里
# name=None
# )
# Prints a list of tensors.
#return A Tensor. Has the same type and contents as input_
#适用于在tensorflow的流数据中追踪变量,但是该函数当前在jupyter不能使用,即无法打印出来
#在pycharm下可用
# tf.while_loop(
# cond, # cond is a callable returning a boolean scalar tensor.
# body, # body is a callable returning a (possibly nested) tuple, namedtuple or list of
# tensors of the same arity (length and structure) and types as loop_vars.
# loop_vars, # loop_vars is a (possibly nested) tuple, namedtuple or list of tensors that is
# passed to both cond and body.
# cond and body both take as many arguments as there are loop_vars.
# shape_invariants=None,
# parallel_iterations=10,
# back_prop=True,
# swap_memory=False,
# name=None,
# maximum_iterations=None,
# return_same_structure=False
# )
# while(condition(tensors))
# {
# tensors = body(tensors);
# }
# 参考 https://stackoverflow.com/questions/37441140/how-to-use-tf-while-loop-in-tensorflow/37444810
# 可以理解为tf.while_loop 将 loop_vars声明为传递变量,在整个循环过程中,loop_vars一直随着数据流图移动,
# 每一步的返回值因此也必须是loop_vars
import tensorflow as tf
i =0
n = 10
with tf.Session() as sess:
def cond(i, n):
#print("in cond: ", (i, n))
i = tf.Print(i, [i], message="in cond") #注意这里需要将返回值赋值给输入单元
return i < n
def body(i, n):
i = i+1
#print("in body: ", (i, n))
print(2)
return (i, n)
a, k = tf.while_loop(cond, body, [i, n]) #不能直接使用,需要使用session运行
sess.run(tf.global_variables_initializer())
print("after while: ", sess.run([a, k]))
print("after while: ", sess.run([a, k]))
# 因为在tensorflow中采取流数据的方式,因此在运行时,无法通过print直接捕捉到数据,因此需要
# 调用额外的函数实现。
output:
2
after while: [10, 10]
in cond: [0]
in body: [0]
in cond: [1]
in body: [1]
in cond: [2]
in body: [2]
in cond: [3]
in body: [3]
in cond: [4]
in body: [4]
in cond: [5]
in body: [5]
in cond: [6]
in body: [6]
in cond: [7]
in body: [7]
in cond: [8]
in body: [8]
in cond: [9]
in body: [9]
in cond: [10]
in cond: [0]
in body: [0]
in cond: [1]
in body: [1]
in cond: [2]
in body: [2]
in cond: [3]
in body: [3]
in cond: [4]
in body: [4]
in cond: [5]
in body: [5]
in cond: [6]
in body: [6]
in cond: [7]
in body: [7]
in cond: [8]
in body: [8]
in cond: [9]
in body: [9]
in cond: [10]
after while: [10, 10]
上述代码主要为了实现跟踪变量i。可以看到如果直接使用print,则只会运行一次。
但是使用tf.Print函数可以实时的进行跟踪i的变化。。这里我主要想实现对程序进行debug,然后采用该种方式实现。