如果每行中元素的總和低于閾值 -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這樣的東西會很好。
uj5u.com熱心網友回復:
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)>
uj5u.com熱心網友回復:
您可以使用tf.where提取元素總和大于 -1 的行的索引,然后使用tf.gather洗掉其他行。
import tensorflow as tf
tf.random.set_seed(0)
x = tf.random.normal((3, 3))
# <tf.Tensor: shape=(3, 3), dtype=float32, numpy=
# array([[ 1.5110626 , 0.42292204, -0.41969493],
# [-1.0360372 , -1.2368279 , 0.47027302],
# [-0.01397489, 1.1888583 , 0.60253334]], dtype=float32)>
x = tf.gather(x, indices=tf.squeeze(tf.where(tf.reduce_sum(x, axis=1) > -1)), axis=0)
# <tf.Tensor: shape=(2, 3), dtype=float32, numpy=
# array([[ 1.5110626 , 0.42292204, -0.41969493],
# [-0.01397489, 1.1888583 , 0.60253334]], dtype=float32)>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/391940.html
