在PyTorch中快速多次压缩的方法?

huangapple go评论94阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年6月29日 02:05:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76575694.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定