【发布时间】:2021-02-04 15:41:29
【问题描述】:
如果我有一个 N 维张量,我想创建另一个值 0 和 1 的张量(具有相同的形状),其中 1 与原始张量中某个维度上的最大元素的位置相同。
我的一个限制是我只想获得沿该轴的第一个最大元素,以防有重复项。
为简单起见,我将使用更少的维度。
>>> x = tf.constant([[7, 2, 3],
[5, 0, 1],
[3, 8, 2]], dtype=tf.float32)
>>> tf.reduce_max(x, axis=-1)
tf.Tensor([7. 5. 8.], shape=(3,), dtype=float32)
我想要的是:
tf.Tensor([1. 0. 0.],
[1. 0. 0.],
[0. 1. 0.], shape=(3,3), dtype=float32)
我尝试过的(发现是错误的):
>>> tf.cast(tf.equal(x, tf.reduce_max(x, axis=-1, keepdims=True)), dtype=tf.float32)
# works fine when there are no duplicates
tf.Tensor([[1. 0. 0.]
[1. 0. 0.]
[0. 1. 0.]], shape=(3, 3), dtype=float32)
>>> y = tf.zeros([3,3])
>>> tf.cast(tf.equal(y, tf.reduce_max(y, axis=-1, keepdims=True)), dtype=tf.float32)
# fails when there are multiple identical values across dimension
tf.Tensor([[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]], shape=(3, 3), dtype=float32)
编辑:已解决
tf.cast(tf.equal(tf.argsort(tf.argsort(x, 1, direction='DESCENDING'), 1), 0), tf.float32)
【问题讨论】: