numpy
1.增加維度
import numpy as np
a = np.ones((3,4))
print(a.shape)
輸出a的形狀:(3,4)
現(xiàn)在變量a為二維數(shù)組,在圖形計(jì)算中有時(shí)需要將圖像處理成(length, width, channel)的形式,我們需要將a處理成三維,第三維的形狀為1,方式如下:
b = np.expand_dims(a, 2)
print(b.shape)
輸出的形狀為:(3,4,1)
2.壓縮維度
如果我們想要將b再變回二維,需要用到如下方法:
c = np.squeeze(b)
print(c.shape)
輸出的形狀為:(3,4)
我們也可以指定要壓縮的維度
c = np.squeeze(b, axis=2)
print(c.shape)
輸出為:(3,4)
Tensor
1.增加維度
import torch
a = torch.ones((3,4))
print(a.shape)
輸出的形狀為:torch.Size([3,4])
現(xiàn)在,我們要讓它增加一個(gè)維度,變成[1,3,4]
b = torch.unsqueeze(a, 0)
print(b.shape)
輸出結(jié)果為:torch.Size([1,3,4])
現(xiàn)在我們要把它再壓縮到三維:
c = torch.squeeze(b, 0)
print(c.shape)
輸出結(jié)果為:torch.Size([3,4]) 。[1]