【问题标题】:Indexing 4D array with an indexing array along last two axes - NumPy / Python使用沿最后两个轴的索引数组索引 4D 数组 - NumPy / Python
【发布时间】:2019-11-18 05:57:03
【问题描述】:

我想创建一批具有多个通道的零图像,并且每个图像都有一个给定像素,值为 1。

如果图像仅按通道数索引,则以下代码可以正常工作:

num_channels = 3
im_size = 2
images = np.zeros((num_channels, im_size, im_size))

# random locations for the ones
pixels = np.random.randint(low=0, high=im_size,
                           size=(num_channels, 2))
images[np.arange(num_channels), pixels[:, 0], pixels[:, 1]] = 1

但是,如果我们也想考虑批处理,类似的代码会失败:

batch_size = 4
num_channels = 3
im_size = 2
images = np.zeros((batch_size, num_channels, im_size, im_size))

# random locations for the ones
pixels = np.random.randint(low=0, high=im_size,
                           size=(batch_size, num_channels, 2))
images[np.arange(batch_size), np.arange(num_channels), pixels[:, :, 0], pixels[:, :, 1]] = 1

给出错误

IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (4,) (3,) (4,3) (4,3) 

以下代码将使用低效的循环来完成这项工作:

batch_size = 4
num_channels = 3
im_size = 2
images = np.zeros((batch_size, num_channels, im_size, im_size))

# random locations for the ones
pixels = np.random.randint(low=0, high=im_size,
                       size=(batch_size, num_channels, 2))
for k in range(batch_size):
    images[k, np.arange(num_channels), pixels[k, :, 0], pixels[k, :, 1]] = 1

如何获得矢量化解?

【问题讨论】:

    标签: numpy indexing vectorization


    【解决方案1】:

    使用advanced-indexing 的简单矢量化将是 -

    I,J = np.arange(batch_size)[:,None],np.arange(num_channels)
    images[I, J, pixels[...,0], pixels[...,1]] = 1
    

    获得I,J 索引器的另一种更简单的方法是使用np.ogrid -

    I,J = np.ogrid[:batch_size,:num_channels]
    

    【讨论】:

    • 非常感谢!我不知道这种高级索引的东西的存在!对不起,我的名声太低了,我不能投票给你。
    猜你喜欢
    • 2022-01-09
    • 2016-04-08
    • 2021-07-20
    • 1970-01-01
    • 2012-01-29
    • 2015-02-01
    • 2015-11-12
    • 2019-01-04
    • 2019-11-20
    相关资源
    最近更新 更多