Generate conditioned random binary array matrix in python

jmp*_*jaz 2 python arrays random numpy matrix

what could be the most efficient way to generate a mxn binary array matrix which is contrained to the sum per column is equal 0 or 1 ?

somethin like this

[[0,0,1,0,0],
[1,1,0,0,0],
[0,0,0,0,1]
[0,0,0,0,0]]
Run Code Online (Sandbox Code Playgroud)

m and n are going to be fixed, but n is larger than 500000 so iteration methods could take a long time until an appropied matrix is found.

War*_*ser 5

您正在选择列的随机子集,然后为每列选择一个随机行。这是使用 numpy 做到这一点的一种方法。二项式分布用于选择哪些列获得 1。更改 的第二个参数numpy.random.binomial以调整具有 1 的列的密度。

In [156]: m = 5

In [157]: n = 12

In [158]: a = np.zeros((m, n), dtype=int)

In [159]: cols = np.random.binomial(1, 0.7, size=n)

In [160]: a[np.random.randint(0, m, size=cols.sum()), np.nonzero(cols)[0]] = 1

In [161]: a
Out[161]: 
array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0],
       [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
       [0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0]])
Run Code Online (Sandbox Code Playgroud)

如果你想在每一列中都有一个 1 ,这里有一个相当简洁的方法:

In [103]: m = 5

In [104]: n = 12

In [105]: a = (np.random.randint(0, m, size=n) == np.arange(m).reshape(-1, 1)).astype(int)

In [106]: a
Out[106]: 
array([[0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1],
       [0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0],
       [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0],
       [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
Run Code Online (Sandbox Code Playgroud)

np.random.randint(0, m, size=n)是随机选择的行索引,每列一个。 np.arange(m).reshape(-1, 1)是[0, 1, ..., m-1]存储在形状为 (m, 1) 的数组中的序列。当这与随机值进行比较时,广播适用,因此创建了一个形状为 (m, n) 的布尔数组。只需将其转换为整数,即可得到结果。