在TensorFlow中条件分配张量值

chi*_*ger 15 python numpy tensorflow

我想复制以下numpy代码tensorflow.例如,我想为0之前具有值的所有张量索引分配一个1.

a = np.array([1, 2, 3, 1])
a[a==1] = 0

# a should be [0, 2, 3, 0]
Run Code Online (Sandbox Code Playgroud)

如果我写相似的代码tensorflow我得到以下错误.

TypeError: 'Tensor' object does not support item assignment
Run Code Online (Sandbox Code Playgroud)

方括号中的条件应该是任意的,如a[a<1] = 0.

有没有办法实现这种"条件分配"(缺少一个更好的名字)tensorflow

Nei*_*ter 24

TensorFlow API中提供了几个比较运算符.

但是,在直接操作张量时,没有什么能比得上简洁的NumPy语法.你必须要使用个人的comparison,whereassign运营商执行相同的操作.

您的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]
Run Code Online (Sandbox Code Playgroud)

print语句当然是可选的,它们只是用于演示代码是否正确执行.