广播阵列上的tf.where()

时间:2018-04-28 05:14:05

标签: python numpy tensorflow

我有两个数组(x是1D,y是2D)。我已经计算出数组“diff”,它基本上就是广播差异(x-y [:,None])。我想用大值(比如10000)替换数组“diff”中的所有零。如下所示,此操作在numpy中是微不足道的:

x=np.array([1.0,1.0,1.0])
y=np.array([[1.0,1.0,1.0],[0.0,0.0,0.0]])
diff = x - y[:, None]
diff = np.where(diff==0.0,10000,diff)

但是,我无法在Tensorflow中重现相同的行为。我尝试了以下代码块。

x = tf.placeholder(tf.float32) 
y = tf.placeholder(tf.float32)
diff = x - y[:,None]
diff_zero = tf.cast(tf.zeros_like(diff),tf.float32)
diff_big = tf.cast(tf.ones_like(diff)*100000,tf.float32)

diff = tf.where(diff==diff_zero, diff_big, diff)

sess = tf.Session()
diff_array = sess.run(diff, feed_dict={x: [1.0,1.0,1.0], y: [[1.0,1.0,1.0],[0.0,0.0,0.0]]})

任何解决方法都会受到赞赏。

1 个答案:

答案 0 :(得分:0)

我想出了怎么做。我不得不使用tf.equal()而不是" =="。以下几行代码就像numpy一样。

x = tf.placeholder(tf.float32) 
y = tf.placeholder(tf.float32)
diff = x - y[:,None]

diff_zero = tf.cast(tf.zeros_like(diff),tf.float32)
diff_big = tf.cast(tf.ones_like(diff)*100000,tf.float32)

condition = tf.equal(diff_zero, diff)
diff = tf.where(condition, diff_big, diff)
sess = tf.Session()

diff_array = sess.run(diff, feed_dict={x: [1.0,1.0,1.0], y: [[1.0,1.0,1.0],[0.0,0.0,0.0]]})