How can I drop rows in a tensor if the sum of the elements in each row is lower than the threshold -1? For example:
JavaScript
x
6
1
tensor = tf.random.normal((3, 3))
2
tf.Tensor(
3
[[ 0.506158 0.53865975 -0.40939444]
4
[ 0.4917719 -0.1575156 1.2308844 ]
5
[ 0.08580616 -1.1503975 -2.252681 ]], shape=(3, 3), dtype=float32)
6
Since the sum of the last row is smaller than -1, I need to remove it and get the tensor (2, 3):
JavaScript
1
4
1
tf.Tensor(
2
[[ 0.506158 0.53865975 -0.40939444]
3
[ 0.4917719 -0.1575156 1.2308844 ]], shape=(2, 3), dtype=float32)
4
I know how to use tf.reduce_sum, but I do not know how to delete rows from a tensor. Something like df.drop
would be nice.
Advertisement
Answer
tf.boolean_mask
is all you need.
JavaScript
1
19
19
1
tensor = tf.constant([
2
[ 0.506158, 0.53865975, -0.40939444],
3
[ 0.4917719, -0.1575156, 1.2308844 ],
4
[ 0.08580616, -1.1503975, -2.252681 ],
5
])
6
7
mask = tf.reduce_sum(tensor, axis=1) > -1
8
# <tf.Tensor: shape=(3,), dtype=bool, numpy=array([ True, True, False])>
9
10
tf.boolean_mask(
11
tensor=tensor,
12
mask=mask,
13
axis=0
14
)
15
# <tf.Tensor: shape=(2, 3), dtype=float32, numpy=
16
# array([[ 0.506158 , 0.53865975, -0.40939444],
17
# [ 0.4917719 , -0.1575156 , 1.2308844 ]], dtype=float32)>
18
19