我有一个大小为n*K
的整数矩阵。[注意:它表示从K个分布
(K列)中抽取的样本数量]
a =[[0,1,0,0,2,0],
[0,0,1,0,0,0],
[3,0,0,0,0,0],
]
[注意: 在应用程序上下文中,该矩阵基本上表示对于第i行(相似实例),我们从“分布1” (1 \in [0,..K]
) 中随机抽取了1个元素(a[0,1] = 1
),以及从分布4中随机抽取了2个元素(a[0,4] = 2
)].
我需要生成一个0-1矩阵,它代表了相同的整数矩阵,但是所有元素都被替换成1。在这种情况下,它是一个3D矩阵,大小为n*a.max()*K
,每个从分布中随机抽取的样本都会在矩阵中标记为1。[注意: 我们需要这个矩阵来与我们的K分布样本矩阵相乘]
输出结果
b = [[[0,1,0,0,1,0], # we don't care if they samples are stack
[0,0,0,0,1,0],
[0,0,0,0,0,0]], # this is the first row representation
[[0,0,1,0,0,0],
[0,0,0,0,0,0],
[0,0,0,0,0,0]], # this is the second row representation
[[1,0,0,0,0,0],
[1,0,0,0,0,0],
[1,0,0,0,0,0]], # this is the third row representation
]
如何在NumPy中实现这个功能?谢谢!
(np.arange(1, a.max()+1)[:,None] <= a[:,None]).astype('uint8')
- Michael Szczesny