Python Numpy:查找以两个不同数组中的值为条件的标记(来自R)

Python Numpy:查找以两个不同数组中的值为条件的标记(来自R),python,arrays,r,numpy,Python,Arrays,R,Numpy,我有一个由3D ndarray表示的卷,X,其值介于0和255之间,还有另一个3D ndarray,Y,它是第一个数组的任意掩码,其值为0或1 我想找到50个体素的随机样本的标记,这些体素在X中大于零,即“图像”,在Y中等于1,即“遮罩” 我在R的工作经验如下: idx <- sample(which(X>0 & Y==1), 50) idx 0&Y==1),50) 也许R的优势在于我可以线性索引3D数组,因为在numpy中只使用一个索引就可以得到一个2D矩阵 我想它可能

我有一个由3D ndarray表示的卷,
X
,其值介于0和255之间,还有另一个3D ndarray,
Y
,它是第一个数组的任意掩码,其值为0或1

我想找到50个体素的随机样本的标记,这些体素在X中大于零,即“图像”,在Y中等于1,即“遮罩”

我在R的工作经验如下:

idx <- sample(which(X>0 & Y==1), 50)
idx 0&Y==1),50)
也许R的优势在于我可以线性索引3D数组,因为在numpy中只使用一个索引就可以得到一个2D矩阵

我想它可能涉及到
numpy.random.choice
,但我似乎不能有条件地使用它,更不用说有条件地使用两个不同的数组了。有没有其他方法可以替代呢?

这里有一种方法-

N = 50 # number of samples needed (50 for your actual case)

# Get mask based on conditionals
mask = (X>0) & (Y==1)

# Get corresponding linear indices (easier to random sample in next step)
idx = np.flatnonzero(mask)

# Get random sample
rand_idx = np.random.choice(idx, N)

# Format into three columnar output (each col for each dim/axis)
out = np.c_[np.unravel_index(rand_idx, X.shape)]
如果需要不替换的随机样本,请使用带有可选参数的
np.random.choice()

样本运行-

In [34]: np.random.seed(0)
    ...: X = np.random.randint(0,4,(2,3,4))
    ...: Y = np.random.randint(0,2,(2,3,4))

In [35]: N = 5 # number of samples needed (50 for your actual case)
    ...: mask = (X>0) & (Y==1)
    ...: idx = np.flatnonzero(mask)
    ...: rand_idx = np.random.choice(idx, N)
    ...: out = np.c_[np.unravel_index(rand_idx, X.shape)]

In [37]: mask
Out[37]: 
array([[[False,  True,  True, False],
        [ True, False,  True, False],
        [ True, False,  True,  True]],

       [[False,  True,  True, False],
        [False, False, False,  True],
        [ True,  True,  True,  True]]], dtype=bool)

In [38]: out
Out[38]: 
array([[1, 0, 1],
       [0, 0, 1],
       [0, 0, 2],
       [1, 1, 3],
       [1, 1, 3]])
将输出
out
mask
True
值的位置相关联,以进行快速验证


如果您不想为了获得线性索引而进行展平,而直接获得每个维度/轴的索引,我们可以这样做-

i0,i1,i2 = np.where(mask)
rand_idx = np.random.choice(len(i0), N)
out = np.c_[i0,i1,i2][rand_idx]
为了提高性能,首先索引,然后在最后一步连接到
np.c
-

out = np.c_[i0[rand_idx], i1[rand_idx], i2[rand_idx]]

谢谢顺便说一句,在您的回答中,[34]:行中的
表示什么?这是您的环境的一些提示功能吗?我的只是有>>>@ElijahRockers是的,我在IPython控制台上。