Pytorch:通过reshape智能地减少维度的方法

3

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

例如,

第一张张量:torch.Size([12, 10])变为torch.Size([120])

第二张张量: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)
    ]

2
t = t.reshape(-1, *t.shape[2:]) - undefined
2个回答

4

针对张量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])

我认为这个也可以不用tuple()。 - undefined
我觉得你可能还需要t.shape,否则看起来不错。 - undefined

1

实际上我认为有更好的方法:

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中添加的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接