【发布时间】:2021-09-16 16:49:46
【问题描述】:
我有一个批量张量和另一个具有维度索引的张量,可以从批量张量中选择。目前,我正在循环批处理张量,如下代码sn-p所示:
import torch
# create tensors to represent our data in torch format
batch_size = 8
batch_data = torch.rand(batch_size, 3, 240, 320)
# notice that channels_id has 8 elements, i.e., = batch_size
channels_id = torch.tensor([2, 0, 2, 1, 0, 2, 1, 0])
这就是我在 for 循环中选择尺寸然后堆叠以转换单个张量的方式:
batch_out = torch.stack([batch_i[channel_i] for batch_i, channel_i in zip(batch_data, channels_id)])
batch_out.size() # prints torch.Size([8, 240, 320])
效果很好。但是,有没有更好的 PyTorch 方法来实现同样的效果?
【问题讨论】:
-
矢量化函数在 numpy 中处理得更好。在您的情况下,可以在 numpy 中执行操作,然后转换为 Torch 张量。但缺点是你不能使用 gpu 功能。
标签: python indexing pytorch tensor