Remove a set of tensors from a tensor in Tensorflow

Viewed 8018

I'm looking for an easy way to remove a set of tensors from a current tensor in Tensorflow and I'm having a difficult reasonable solution.

For example, let's say that I have the below current tensor:

a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')

And that I want to remove, say, two items from this tensor (2.0 and 5.0).

What would be the best way to transform this tensor into [1.0, 3.0, 4.0, 6.0] after it has been created?

Many thanks in advance.

2 Answers

You can call tf.unstack to obtain a list of sub-tensors. Then you can modify the list and call tf.stack to construct a tensor from the list. For example, the following code removes the [2.0, 5.0] column from a:

a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
a_vecs = tf.unstack(a, axis=1)
del a_vecs[1]
a_new = tf.stack(a_vecs, 1)

Another way to do this would be either making use of split or slice function. This would be useful especially if tensor is huge.

Method 1: Making use of split function.

a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
split1, split2, split3 = tf.split(a, [1, 1, 1], 1)
a_new = tf.concat([split1, split3], 1)

Method 2: Making use of slice function.

slice1 = tf.slice(a, [0, 0], [2, 1])
slice2 = tf.slice(a, [0, 2], [2, 1])
a_new = tf.concat([slice1, slice2], 1)

In both the cases, a_new will have

[[ 1.  3.]
 [ 4.  6.]]
Related