Ron Cohen
Ron Cohen

Reputation: 2925

Subtract columns in Tensorflow tensor

In Tensorflow, I want to subtract one column in a 2D tensor from the other column. I looked at using tf.split() or tf.slice() to split into 2 tensors and then subtract, but this seemed unnecessarily complex. My current approach is to multiply one column by -1 and then reduce_sum the columns:

input = tf.constant(
        [[5.8, 3.0],
         [4.0, 6.0],
         [7.0, 9.0]])
oneMinusOne = tf.constant([1., -1.])
temp = tf.mul(input, oneMinusOne)
delta = tf.reduce_sum(temp, 1)

Still seems needlessly complex. Is there a simpler way of doing this?

Upvotes: 0

Views: 1701

Answers (1)

keveman
keveman

Reputation: 8487

Lot of numpy's array indexing work as expected in TensorFlow. The following works :

input = tf.constant(
    [[5.8, 3.0],
     [4.0, 6.0],
     [7.0, 9.0]])
sess = tf.InteractiveSession()
ans = input[:, :1] - input[:, 1:]
print(ans.eval())

array([[ 2.80000019],
   [-2.        ],
   [-2.        ]], dtype=float32)

Upvotes: 1

Related Questions