我想复制以下内容numpy
代码在tensorflow
。例如,我想分配一个0
到先前值为的所有张量索引1
.
a = np.array([1, 2, 3, 1])
a[a==1] = 0
# a should be [0, 2, 3, 0]
如果我写类似的代码tensorflow
我收到以下错误。
TypeError: 'Tensor' object does not support item assignment
方括号中的条件应该是任意的,如下所示a[a<1] = 0
.
有没有办法实现这种“条件赋值”(由于缺乏更好的名称)tensorflow
?
比较运算符,例如比...更棒 https://www.tensorflow.org/api_docs/python/tf/math/greater可在 TensorFlow API 中使用。
然而,在直接操作张量时,没有什么比简洁的 NumPy 语法等效的了。你必须利用个人comparison
, where
and assign
操作员执行相同的操作。
与 NumPy 示例等效的代码如下:
import tensorflow as tf
a = tf.Variable( [1,2,3,1] )
start_op = tf.global_variables_initializer()
comparison = tf.equal( a, tf.constant( 1 ) )
conditional_assignment_op = a.assign( tf.where (comparison, tf.zeros_like(a), a) )
with tf.Session() as session:
# Equivalent to: a = np.array( [1, 2, 3, 1] )
session.run( start_op )
print( a.eval() )
# Equivalent to: a[a==1] = 0
session.run( conditional_assignment_op )
print( a.eval() )
# Output is:
# [1 2 3 1]
# [0 2 3 0]
打印语句当然是可选的,它们只是为了证明代码正确执行。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)