How can each row write a hit into its own selected column?

put_along_axis writes values at the indices assigned to each slice and mutates its destination.

numpy.put_along_axis in practice

Two samples belong to classes two and zero. Starting with zeros makes every untouched cell meaningful when writing their one-hot labels.

import numpy as np
a=np.zeros((2,3),dtype=int)
np.put_along_axis(a,np.array([[2],[0]]),1,axis=1)
a

Result [[0, 0, 1], [1, 0, 0]]

中文

如何把每行的命中标记写回对应列?

put_along_axis 按各切片的索引向目标数组写值,修改发生在原数组上。

numpy.put_along_axis 算例

两条样本分别属于类别 2 和 0,可从全零矩阵写出两行独热标签。先建立完整的零背景,未被选中的位置才有明确意义。

import numpy as np
a=np.zeros((2,3),dtype=int)
np.put_along_axis(a,np.array([[2],[0]]),1,axis=1)
a

结果 [[0, 0, 1], [1, 0, 0]]

References / 参考来源

Keep reading / 继续阅读