gpt4 book ai didi

numpy - 使用沿最后两个轴的索引数组索引 4D 数组 - NumPy/Python

转载 作者:行者123 更新时间:2023-12-02 02:44:06 25 4
gpt4 key购买 nike

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

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

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

您将如何获得矢量化解决方案?

最佳答案

使用 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]

关于numpy - 使用沿最后两个轴的索引数组索引 4D 数组 - NumPy/Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56939650/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com