Python 在tensorflow中获得独特面具的优雅方式?
目前在tensorflow 1.15上 我有一批序列,我想要一个布尔掩码,它将一个序列中的第一个唯一项指示为Python 在tensorflow中获得独特面具的优雅方式?,python,python-3.x,tensorflow,Python,Python 3.x,Tensorflow,目前在tensorflow 1.15上 我有一批序列,我想要一个布尔掩码,它将一个序列中的第一个唯一项指示为True。例如: sequences = tf.Tensor( [ ["1", "2", "3", "2"], ["4", "2", "5", "6"], ["7", "7", "4", "7"], ], ) 我会得到: [ [True, True, True, False], [True, True, Tr
True
。例如:
sequences = tf.Tensor(
[
["1", "2", "3", "2"],
["4", "2", "5", "6"],
["7", "7", "4", "7"],
],
)
我会得到:
[
[True, True, True, False],
[True, True, True, True],
[True, False, True, False],
],
有没有优雅的方法
tf.unique
似乎仅限于一维张量。我制作了一个自定义掩码行函数。此函数用于选择行中的第一个唯一元素并创建遮罩。此函数使用map\u fn在所有行上迭代
sequences = tf.constant([
["1", "2", "3", "2"],
["4", "2", "5", "6"],
["7", "7", "4", "7"]])
def mask_row(row):
mask = tf.map_fn(lambda x: tf.math.equal(tf.range(row.shape[-1]),
tf.cast(tf.math.reduce_min(tf.where(tf.math.equal(row, x))), tf.int32)),
row, dtype=tf.bool)
return tf.math.reduce_any(mask, axis=0)
tf.map_fn(mask_row, sequences, dtype=tf.bool)
结果
<tf.Tensor: shape=(3, 4), dtype=bool, numpy=
array([[ True, True, True, False],
[ True, True, True, True],
[ True, False, True, False]])>
< /代码>如果你认为答案是有价值的,不要忘记接受它作为答案;当然,给可能的其他答案一点空间!虽然我担心潜在的性能影响(必须检查影响,map\u fn
总是让我提心吊胆,但你的方法肯定会奏效。