python - 如何在 TensorFlow 中取消引用 _ref 张量类型?

标签 python reference tensorflow dereference

如何将引用张量类型转换为值张量类型?

我找到的唯一方法是给张量加一个零。有什么方便的方法吗?

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() 不复制底层缓冲区。因此,countercounter_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/

相关文章:

reference - 为什么对泛型函数中特征的引用必须实现 `Sized` ?

我可以用一个函数交换两个矩阵,只交换其基地址,而不逐个元素交换吗?

python - 如何重新训练自定义图像的 mobilenet 模型

python - 如何修复错误:invalid literal for int() with base 10: 'Luck' ?

Python 3.6.x PyInstaller 给出错误 "No module named ' PyQt5.sip'”

python - 当变量引用同一个对象时,它是如何调用的,为什么python有这个特性?

tensorflow - 值错误 : Operation u'tpu_140462710602256/VarIsInitializedOp' has been marked as not fetchable

python - 更新 SQLAlchemy 关系

python - xlwt 模块 - 保存 xls unicode 错误

c++ - 当设备设置为 CPU 时,为什么 TensorFlow 使用我的 GPU