微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Pytorch 如何在不改变单个过滤器的形状的情况下重塑/减少过滤器的数量

如何解决Pytorch 如何在不改变单个过滤器的形状的情况下重塑/减少过滤器的数量

使用形状的 3D 张量(过滤器的数量、高度、宽度),如何通过重塑将原始过滤器作为整个块保持在一起来减少过滤器的数量

假设新尺寸的尺寸选择为使得所有原始过滤器可以并排安装在其中一个新过滤器中。所以(4,2,2)的原始尺寸可以改造成(2,4)。

并排重塑的视觉解释,您可以看到标准重塑将改变单个过滤器形状:

pytorch reshape

我尝试了各种 pytorch 函数,例如 gatherselect_index,但没有找到以一般方式获得最终结果的方法(即适用于不同数量的过滤器和不同的过滤器尺寸) .

我认为在执行重塑后重新排列张量值会更容易,但无法获得 pytorch 重塑形式的张量:

[[[1,3,4],[5,6,7,8]],[[9,10,11,12],[13,14,15,16]]]

到:

[[[1,5,6],[3,4,13,14],[11,12,16]]]

为了完整性,重塑前的原始张量:

[[[1,2],4]],[[5,[7,10],12]],[[13,[15,16]]]

解决方法

另一种选择是构造一个部件列表并将它们连接起来

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,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,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',y)
,

您可以通过分块张量然后重新组合来实现。

<View
        style={{
          width: 36,height: 36,justifyContent: 'center',alignItems: 'center',borderRadius: 30,shadowOffset: { width: 1,height: 1 },shadowColor: '#DF3011',shadowOpacity: 1,backgroundColor: '#ffffff',borderWidth: 1,borderColor: #DF3011,elevation: 5,shadowRadius: 6,marginEnd: 11,}}
      ></View>
def side_by_side_reshape(x):
    n_pairs = x.shape[0] // 2
    filter_size = x.shape[-1]
    x = x.reshape((n_pairs,filter_size,filter_size))
    return torch.stack(list(map(lambda x: torch.hstack(x.unbind()),k)))

但我知道这并不理想,因为有 >> p = torch.arange(1,91).reshape((10,3)) >> side_by_side_reshape(p) tensor([[[ 1,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]]]) maplist 会破坏记忆。这就是我提供的,直到我弄清楚如何仅通过视图来做到这一点(所以是真正的重塑)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。