英文:
A quick way to squeeze multiple times in PytTorch?
问题
有没有一种有效的方法来在PyTorch张量中多次挤压(unsqueeze)?
例如,一个张量 a 的形状是:[4,1,1,2],
import torch
import torch.nn as nn
a = torch.tensor([[1,2,3,4],[5,6,7,8]], dtype=torch.float32)
a = a.reshape(4,1,1,2)
print(a.shape)
torch.Size([4, 1, 1, 2])
我想将 a 挤压成 [4, 2],但不想手动挤压两次,例如,
a1 = a.squeeze(1).squeeze(1)
print(a1.shape)
torch.Size([4, 2])
有没有办法我不必写两次(un)squeeze(1)
或多次。谢谢。
英文:
Is there any efficient way to to squeeze (unsqueeze) multiple times in pytorch tensors?
For example a tensor a has shape: [4,1,1,2],
import torch
import torch.nn as nn
a = torch.tensor([[1,2,3,4],[5,6,7,8]], dtype=torch.float32)
a = a.reshape(4,1,1,2)
print(a.shape)
torch.Size([4, 1, 1, 2])
I would like to squeeze a to [4, 2] but without squeezing it twice manually, e.g.,
a1 = a.squeeze(1).squeeze(1)
print(a1.shape)
torch.Size([4, 2])
Is there any way that I don't have to write (un)squeeze(1)
twice/multiple times. Thanks
答案1
得分: 1
不要使用 a.squeeze(1)
。只需使用 a.squeeze()
就会得到你想要的结果。
英文:
Don't use a.squeeze(1)
. Just a.squeeze()
will give you the desired result.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论