TensorFlow中的张量值的条件分配 [英] Conditional assignment of tensor values in TensorFlow

查看:368
本文介绍了TensorFlow中的张量值的条件分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to replicate the following numpy code in tensorflow. For example, I want to assign a 0 to all tensor indices that previously had a value of 1.

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

# a should be [0, 2, 3, 0]

如果在tensorflow中编写类似的代码,则会出现以下错误.

If I write similar code in tensorflow I get the following error.

TypeError: 'Tensor' object does not support item assignment

方括号中的条件应与a[a<1] = 0中的一样.

The condition in the square brackets should be arbitrary as in a[a<1] = 0.

是否有一种方法可以在tensorflow中实现这种条件赋值"(由于缺少更好的名称)?

Is there a way to realize this "conditional assignment" (for lack of a better name) in tensorflow?

推荐答案

多个比较运算符在TensorFlow API中可用.

Several comparison operators are available within TensorFlow API.

但是,在直接操纵张量时,没有什么等效于简洁的NumPy语法.您必须使用单独的comparisonwhereassign运算符来执行相同的操作.

However, there is nothing equivalent to the concise NumPy syntax when it comes to manipulating the tensors directly. You have to make use of individual comparison, where and assign operators to perform the same action.

您的NumPy示例的等效代码是这样的:

Equivalent code to your NumPy example is this:

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]

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

The print statements are of course optional, they are just there to demonstrate the code is performing correctly.

这篇关于TensorFlow中的张量值的条件分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆