numpy中的随机单热矩阵

mic*_*den 6 python arrays numpy

我想制作一个x形状矩阵(n_samples, n_classes),每个矩阵x[i]都是一个随机的单热矢量.这是一个缓慢的实现:

x = np.zeros((n_samples, n_classes))
J = np.random.choice(n_classes, n_samples)
for i, j in enumerate(J):
    x[i, j] = 1
Run Code Online (Sandbox Code Playgroud)

什么是更加pythonic的方式来做到这一点?

cs9*_*s95 11

使用np.eye以下方法创建单位矩阵

x = np.eye(n_classes)
Run Code Online (Sandbox Code Playgroud)

然后使用np.random.choice随机选择行:

x[np.random.choice(x.shape[0], size=n_samples)]
Run Code Online (Sandbox Code Playgroud)

作为简写,只需使用:

np.eye(n_classes)[np.random.choice(n_classes, n_samples)]
Run Code Online (Sandbox Code Playgroud)

演示:

In [90]: np.eye(5)[np.random.choice(5, 100)]
Out[90]: 
array([[ 1.,  0.,  0.,  0.,  0.],
       [ 1.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  1.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  1.],
       [ 0.,  0.,  0.,  1.,  0.],
       [ 1.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  1.,  0.],
       .... (... to 100)
Run Code Online (Sandbox Code Playgroud)