如果元素之和低于某个阈值,则在张量中删除一行



如果每行元素的总和低于阈值-1,我如何删除张量中的行?例如:

tensor = tf.random.normal((3, 3))
tf.Tensor(
[[ 0.506158    0.53865975 -0.40939444]
[ 0.4917719  -0.1575156   1.2308844 ]
[ 0.08580616 -1.1503975  -2.252681  ]], shape=(3, 3), dtype=float32)

由于最后一行的和小于-1,我需要将其移除并获得张量(2,3(:

tf.Tensor(
[[ 0.506158    0.53865975 -0.40939444]
[ 0.4917719  -0.1575156   1.2308844 ]], shape=(2, 3), dtype=float32)

我知道如何使用tf.reduce_sum,但不知道如何从张量中删除行。像df.drop这样的东西会很好。

tf.boolean_mask就是您所需要的全部。

tensor = tf.constant([
[ 0.506158,    0.53865975, -0.40939444],
[ 0.4917719,  -0.1575156,   1.2308844 ],
[ 0.08580616, -1.1503975,  -2.252681  ],
])
mask = tf.reduce_sum(tensor, axis=1) > -1 
# <tf.Tensor: shape=(3,), dtype=bool, numpy=array([ True,  True, False])>
tf.boolean_mask(
tensor=tensor, 
mask=mask,
axis=0
)
# <tf.Tensor: shape=(2, 3), dtype=float32, numpy=
# array([[ 0.506158  ,  0.53865975, -0.40939444],
#        [ 0.4917719 , -0.1575156 ,  1.2308844 ]], dtype=float32)>

最新更新