numpy 中矩阵的单热表示

One-hot representation of a matrix in numpy

从值矩阵到 3d 张量中同一事物的一个热表示的 easiest/smartest 方法是什么?例如,如果矩阵是张量中 argmax 之后的索引,例如:

indices=numpy.argmax(mytensor,axis=2)

其中张量是 3D [x,y,z],索引自然是 [x,y]。现在你想转到一个 3D [x,y,z] 张量,它在 axis=2 的 maxes 位置有 1s,在任何其他地方有 0。

P.S。我知道向量到 1-hot 矩阵的答案,但这是 1-hot 张量的矩阵。

使用的完美设置之一 broadcasting -

indices[...,None] == np.arange(mytensor.shape[-1])

如果您需要 0s1s 的整数,请附加 .astype(int)