【问题标题】:Choosing random one from each row of a binary numpy matrix?从二进制 numpy 矩阵的每一行中随机选择一个?
【发布时间】:2014-02-19 15:33:20
【问题描述】:

假设我有一个二进制矩阵。我想将该矩阵转换为另一个矩阵,其中每一行都有一个,并且每一行的索引都是随机的。

例如,如果其中一行是 [0,1,0,1,0,0,1],我将其转换为 [0,0,0,1,0,0,0],我们在其中随机选择 1 的索引。

我如何在 numpy 中做到这一点?

目前我找到每一行的最大值(因为 max 函数返回一个索引)并将其设置为零。如果所有行最多有 2 个行,则它可以工作,但如果超过 2 个,则它会失败。

【问题讨论】:

  • 为什么是“Matlab”标签?你也想在 Matlab 中得到答案吗?

标签: python numpy matrix


【解决方案1】:

扩展@zhangxaochen的答案,给定一个随机二进制数组

x = np.random.random_integers(0, 1, (8, 8))

您可以使用从x 中随机抽取的 1 填充另一个数组:

y = np.zeros_like(x)
ind = [np.random.choice(np.where(row)[0]) for row in x]
y[range(x.shape[0]), ind] = 1

【讨论】:

    【解决方案2】:

    我想使用np.argsort 来获取非零元素的索引:

    In [351]: a=np.array([0,1,0,1,0,0,1])
    
    In [352]: from random import choice
         ...: idx=choice(np.where(a)[0]) #or np.nonzero instead of np.where
    
    In [353]: b=np.zeros_like(a)
         ...: b[idx]=1
         ...: b
    Out[353]: array([0, 1, 0, 0, 0, 0, 0])
    

    【讨论】:

    • 您可以将a.argsort()[-np.count_nonzero(a):] 替换为np.where(a)[0]
    猜你喜欢
    • 2011-12-30
    • 1970-01-01
    • 1970-01-01
    • 2020-08-31
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    • 2017-01-03
    • 1970-01-01
    相关资源
    最近更新 更多