创建一个numpy数组,其中0和1在随机位置,但在给定的子轴上至少有一个或多个'1'

nx7onnlm  于 2023-08-05  发布在  其他
关注(0)|答案(1)|浏览(62)

我正在寻找一个numpy数组随机初始化0和1,我发现下面的问题here,描述了基本的随机数组和如何控制的尺寸。但是,我需要数组在嵌套轴的每个子数组上至少有一个“1”。参见示例:

import numpy as np    
size = (3, 5, 5)
proba_0 = 0.7
n_positions = np.random.choice([0,1], size=size, p=[proba_0, 1-proba_0])
print(n_positions)

[[[0 1 1 0 0]
  [0 0 0 0 0]
  [0 0 0 1 1]
  [1 0 0 0 0]
  [0 1 0 0 0]]

 [[0 1 1 1 1]
  [0 0 1 1 0]
  [1 0 0 1 1]
  [0 0 1 0 0]
  [0 1 0 1 1]]

 [[0 0 0 0 1]
  [0 0 1 0 1]
  [0 0 0 0 1]
  [0 0 0 1 0]
  [0 0 0 0 0]]]

字符串
这里的问题是,在这个数组n_positions[0][1]中的以下位置,数据只填充了零。我需要在轴2上的每一行中至少有一个'1'。我可以增加1发生的概率,但这并不能消除风险。
我可以用一个循环或一个理解来实现这一点,使用一个方法,让numpy生成一个1-5之间的随机数,然后用零填充,但它非常慢。我希望有一个更numpy友好的方法内置实现这一点?

zed5wv10

zed5wv101#

一个解决方案(如果您只想填充最后一个轴。如果你想对所有的轴都这样做,那么你需要对所有的轴重复它,我猜)

def fillLastAxis(arr):
    # Position in all but last axes of rows that need a 1
    pos=~arr.any(axis=-1) # True on rows coords that miss a 1
    # Number of 1 to generate
    num=pos.sum()
    # Index (along the last axis, of the missing 1)
    idx=np.random.randint(0, arr.shape[-1], num)
    # Just add a one at this pos
    arr[pos, idx]=1

字符串
测试:

size = (3, 5, 5)
proba_0 = 0.7
n_positions = np.random.choice([0,1], size=size, p=[proba_0, 1-proba_0])
print("==== Before ====")
print(n_positions)
fillLastAxis(n_positions)
print("==== After ====")
print(n_positions)


展会

==== Before ====
[[[1 0 1 1 1]
  [1 0 0 0 1]
  [0 1 0 0 0]
  [0 0 0 0 0]
  [1 0 1 0 1]]

 [[0 0 1 0 1]
  [0 0 0 0 0]
  [0 0 0 0 1]
  [0 1 1 0 1]
  [0 0 0 0 0]]

 [[0 0 0 0 1]
  [0 0 0 1 1]
  [1 1 1 0 1]
  [0 1 0 0 0]
  [0 1 0 0 1]]]
==== After ====
[[[1 0 1 1 1]
  [1 0 0 0 1]
  [0 1 0 0 0]
  [0 1 0 0 0]
  [1 0 1 0 1]]

 [[0 0 1 0 1]
  [0 0 1 0 0]
  [0 0 0 0 1]
  [0 1 1 0 1]
  [0 0 0 1 0]]

 [[0 0 0 0 1]
  [0 0 0 1 1]
  [1 1 1 0 1]
  [0 1 0 0 0]
  [0 1 0 0 1]]]


可以看到,平面0的第3行和平面1的第1行之前缺少1。然后有一个(在位置1和2)。
具有更高的维度(用更多的轴进行测试,并降低这只是运气的概率)。这一次我强迫种子,这样你就可以在家里测试,并检查结果,而不需要我打印整个数组,因为你有相同的。

size = (3, 6, 4, 5)
proba_0 = 0.5
np.random.seed(12)
n_positions = np.random.choice([0,1], size=size, p=[proba_0, 1-proba_0])
print("==== Before ====")
print(n_positions)
fillLastAxis(n_positions)
print("==== After ====")
print(n_positions)


如果我是正确的,结果中有3行全0([0,2,1,:][2,0,3,:][2,4,3,:])。它们后面都是随机的1。

相关问题