首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Numpy:在两个不同的数组中查找以值为条件的指示符(来自R)

Numpy:在两个不同的数组中查找以值为条件的指示符(来自R)
EN

Stack Overflow用户
提问于 2017-12-07 20:53:19
回答 1查看 71关注 0票数 1

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

我想找出一个随机样本的50个体素,在X中大于零,在‘图像’,等于1在Y,‘面具’。

我在R方面的经验如下:

代码语言:javascript
运行
复制
idx <- sample(which(X>0 & Y==1), 50)

也许R的优点是我可以对3D数组进行线性索引,因为在numpy中只使用一个索引就可以得到一个2D矩阵。

我想它可能涉及到numpy.random.choice,但似乎我不能有条件地使用它,更不用说在两个不同的数组上设置条件了。还有别的方法我应该用吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-12-07 21:05:00

有一种方法-

代码语言:javascript
运行
复制
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()和可选的arg replace=False

样本运行-

代码语言:javascript
运行
复制
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]])

将输出outTrue值在mask中的位置关联起来,以进行快速验证。

如果你不想为了得到线性指数而变平,直接得到每个暗/轴的指数,我们可以这样做-

代码语言:javascript
运行
复制
i0,i1,i2 = np.where(mask)
rand_idx = np.random.choice(len(i0), N)
out = np.c_[i0,i1,i2][rand_idx]

为了提高性能,首先索引,然后在最后一步与np.c_连接-

代码语言:javascript
运行
复制
out = np.c_[i0[rand_idx], i1[rand_idx], i2[rand_idx]]
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47703598

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档