繁体   English   中英

Pytorch:通过重塑来减少尺寸的更智能方法

[英]Pytorch: smarter way to reduce dimension by reshape

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

例如,

第一个张量: 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) ,

能适应不同Tensors的形状吗?


测试用例:

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)

我不确定添加了哪个版本的火炬。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM