Pytorch:通过重塑来减少尺寸的更聪明的方法

Pytorch: smarter way to reduce dimension by reshape

我想通过乘以前两个维度的形状来重塑张量。

例如,

1st_tensor: torch.Size([12, 10])torch.Size([120])

2nd_tensor:torch.Size([12, 10, 5, 4])torch.Size([120, 5, 4])

即前两个维度合并为一个,其他维度保持不变

有没有比

更聪明的方法

1st_tensor.reshape(-1,)

2nd_tensor.reshape(-1,5,4),

那个可以适应不同张量的形状?


测试用例:

import torch
tests = [
    torch.rand(11, 11), 
    torch.rand(12, 15351, 6, 4),
    torch.rand(13, 65000, 8)
    ]

对于张量t,你可以使用:

t.reshape((-1,)+t.shape[2:])

这使用 -1 来展平前两个维度,然后使用 t.shape[2:] 使其他维度与原始张量相同。

举个例子:

>>> tests = [
...     torch.rand(11, 11),
...     torch.rand(12, 15351, 6, 4),
...     torch.rand(13, 65000, 8)
...     ]
>>> tests[0].reshape((-1,)+tests[0].shape[2:]).shape
torch.Size([121])
>>> tests[1].reshape((-1,)+tests[1].shape[2:]).shape
torch.Size([184212, 6, 4])
>>> tests[2].reshape((-1,)+tests[2].shape[2:]).shape
torch.Size([845000, 8])

其实我觉得还有更好的办法:

import torch

tests = [
    torch.rand(11, 11), 
    torch.rand(12, 15351, 6, 4),
    torch.rand(13, 65000, 8)
    ]

for test in tests:
    print(test.flatten(0, 1).shape)

我不确定添加的是哪个版本的 torch。