以编程方式区分TensorFlow

时间:2017-05-29 23:16:34

标签: python tensorflow

在TensorFlow中,是否有一种很好的方法可以在编程上区分张量,变量和操作?例如,在重新加载模型时,这可能会出现,tf.local_variables()可以同时包含张量和变量。如果您尝试初始化张量,则会出现错误。

以下是我当前黑客的一些代码,但有更好的方法吗?部分问题是变量,张量等的类型是,例如tensorflow.python.ops.variables.Variable,但似乎tensorflow.python不再可访问(我认为它是在某些早期版本中? )。该示例仅显示变量与张量,但我还需要先区分操作和张量,并且必须使用类似的黑客。

import tensorflow as tf
vars_list = [tf.Variable(0), tf.constant(0)]
# init = tf.variables_initializer(vars_list) # -> AttributeError: 'Tensor' object has no attribute 'initializer'
var_type = type(tf.Variable(0))
init = tf.variables_initializer([v for v in vars_list if type(v) == var_type])

1 个答案:

答案 0 :(得分:1)

通常,在Python中,可以使用

isinstance(x, tf.Variable)

isinstance(x, (tf.Variable, tf.Tensor))