pytorch使用過程中,經(jīng)常需要對張量進(jìn)行維度校準(zhǔn)。我們簡單把一個2x2的tensor升維到1x2x2,該怎么做呢?
方法一:a[None]
import torch
a = torch.rand(2, 2)
b = a[None]
print(b.shape)
# torch.Size([1, 2, 2])
方法二:a.unsqueeze(0)
import torch
a = torch.rand(2, 2)
b = a.unsqueeze(0)
print(b.shape)
# torch.Size([1, 2, 2])
雖然方法二比方法一更繁瑣,但比方法一更加靈活。如果你想升維度2x2->2x1x2,可以:文章來源:http://www.zghlxwxcb.cn/news/detail-521839.html
b = a.unsqueeze(1)
print(b.shape)
# torch.Size([2, 1, 2])
同理,a.unsqueeze(2)
也可以升維成(2,2,1)。方法一的優(yōu)勢是,看起來更老練。文章來源地址http://www.zghlxwxcb.cn/news/detail-521839.html
到了這里,關(guān)于Pytorch張量升維的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!