如何将引用张量类型转换为值张量类型?
我找到的唯一方法是给张量加一个零。有什么方便的方法吗?
在assign
下面是一个引用类型的张量。如何摆脱 _ref
?
import tensorflow as tf
counter = tf.Variable(0, name="counter")
zero = tf.constant(0)
one = tf.constant(1)
new_counter = tf.add(counter, one)
assign = tf.assign(counter, new_counter) # dtype=int32_ref
result = tf.add(assign, zero) # dtype=int32
result2 = tf.convert_to_tensor(assign) # dtype=int32_ref
# result3 = assign.value() # has no attribute value
最佳答案
一般来说,您应该能够使用 tf.foo_ref
任何地方的类型张量 tf.foo
预期类型张量。 TensorFlow ops 将隐式取消引用它们的输入参数(除非明确期望引用张量,例如在 tf.assign()
中)。
取消引用张量的最简单方法是使用 tf.identity()
,如下:
counter = tf.Variable(0)
assert counter.dtype == tf.int32_ref
counter_val = tf.identity(counter)
assert counter_val.dtype == tf.int32
请注意,这回答了您的问题,但可能具有令人惊讶的语义,因为 tf.identity()
不复制底层缓冲区。因此,counter
和 counter_val
在上面的示例中共享相同的缓冲区,并对 counter
进行了修改会反射(reflect)在counter_val
:
counter = tf.Variable(0)
counter_val = tf.identity(counter) # Take alias before the `assign_add` happens.
counter_update = counter.assign_add(1)
with tf.control_dependencies([counter_update]):
# Force a copy after the `assign_add` happens.
result = counter_val + 0
sess = tf.Session()
sess.run(tf.initialize_all_variables())
print sess.run(result) # ==> 1 (result has effect of `assign_add`)
关于python - 如何在 TensorFlow 中取消引用 _ref 张量类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35175032/