TensorFlow
API中提供了几种比较运算符。
但是,在直接操纵张量时,没有什么等效于简洁的NumPy语法。你必须要使用个人的
comparison,
where和
assign运营商执行相同的操作。
您的NumPy示例的等效代码是这样的:
import tensorflow as tfa = 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]
打印语句当然是可选的,它们只是用来演示代码是否正确执行。



