对于形状的3D张量(滤镜的数量,高度,宽度),如何通过重塑来减少滤镜的数量,从而将原始滤镜保持在一起作为整个块?
假设新的大小具有选择的尺寸,使得整数个原始过滤器可以并排适合于其中一个新过滤器。因此,可以将(4,2,2)的原始大小重塑为(2,2,4)。
对并排重塑的视觉解释,您可以看到标准重塑将改变各个滤镜形状:

我尝试过各种pytorch函数,比如gather和select_index,但没有找到一种通用的方式(即适用于不同数量的滤镜和不同大小的滤镜)。
我认为在执行重塑之后重新排列张量值会更容易,但无法获得pytorch重塑形式的张量:
[[[1,2,3,4],
[5,6,7,8]],
[[9,10,11,12],
[13,14,15,16]]]至:
[[[1,2,5,6],
[3,4,7,8]],
[[9,10,13,14],
[11,12,15,16]]]为了完整性,在重塑之前,原始张量:
[[[1,2],
[3,4]],
[[5,6],
[7,8]],
[[9,10],
[11,12]],
[[13,14],
[15,16]]]发布于 2020-12-19 03:59:39
另一种选择是构造一个部件列表,并将它们连接起来
x = torch.arange(4).reshape(4, 1, 1).repeat(1, 2, 2)
y = torch.cat([x[i::2] for i in range(2)], dim=2)
print('Before\n', x)
print('After\n', y)这给了我们
Before
tensor([[[0, 0],
[0, 0]],
[[1, 1],
[1, 1]],
[[2, 2],
[2, 2]],
[[3, 3],
[3, 3]]])
After
tensor([[[0, 0, 1, 1],
[0, 0, 1, 1]],
[[2, 2, 3, 3],
[2, 2, 3, 3]]])或者更一般地说,我们可以编写一个函数,该函数沿源维度获取多组邻居,并沿着目标维度将它们连接在一起
def group_neighbors(x, group_size, src_dim, dst_dim):
assert x.shape[src_dim] % group_size == 0
return torch.cat([x[[slice(None)] * (src_dim) + [slice(i, None, group_size)] + [slice(None)] * (len(x.shape) - (src_dim + 2))] for i in range(group_size)], dim=dst_dim)
x = torch.arange(4).reshape(4, 1, 1).repeat(1, 2, 2)
# read as "take neighbors in groups of 2 from dimension 0 and concatenate them in dimension 2"
y = group_neighbors(x, group_size=2, src_dim=0, dst_dim=2)
print('Before\n', x)
print('After\n', y)发布于 2020-12-19 03:07:02
你可以通过分块张量,然后重新组合来实现。
def side_by_side_reshape(x):
n_pairs = x.shape[0] // 2
filter_size = x.shape[-1]
x = x.reshape((n_pairs, 2, filter_size, filter_size))
return torch.stack(list(map(lambda x: torch.hstack(x.unbind()), k)))>> p = torch.arange(1, 91).reshape((10, 3, 3))
>> side_by_side_reshape(p)
tensor([[[ 1, 2, 3, 10, 11, 12],
[ 4, 5, 6, 13, 14, 15],
[ 7, 8, 9, 16, 17, 18]],
[[19, 20, 21, 28, 29, 30],
[22, 23, 24, 31, 32, 33],
[25, 26, 27, 34, 35, 36]],
[[37, 38, 39, 46, 47, 48],
[40, 41, 42, 49, 50, 51],
[43, 44, 45, 52, 53, 54]],
[[55, 56, 57, 64, 65, 66],
[58, 59, 60, 67, 68, 69],
[61, 62, 63, 70, 71, 72]],
[[73, 74, 75, 82, 83, 84],
[76, 77, 78, 85, 86, 87],
[79, 80, 81, 88, 89, 90]]])但我知道这并不理想,因为有map、list和unbind,它们会扰乱内存。这就是我所提供的,直到我弄清楚如何只通过视图来做(所以是真正的重塑)
https://stackoverflow.com/questions/65361912
复制相似问题