前言
在機器學習的領域中,我們經常用的資料格式就是 tensor,
有時為了格式對齊,我們需要增加維度。
- 常見使用地方:讀取時因為一層一層拆開後,要拼回去原來的資料型態 (shape)
範例程式碼
我們能使用 「.unsqueeze()」 來增加 tensor 維度,下面範例程式碼。
import torch
a = torch.tensor([1, 2])
print(a)
print(a.shape)
print(a.unsqueeze(0))
print(a.unsqueeze(0).shape)
print(a.unsqueeze(0)[0][0])
print(a.unsqueeze(0)[0][1])
print(a.unsqueeze(1))
print(a.unsqueeze(1).shape)
print(a.unsqueeze(1)[0][0])
print(a.unsqueeze(1)[1][0])
- 結果與說明
原先 a 的維度是一維兩個值 [2]
- 後來經過 a.unsqueeze(0),多了「第 0 維」變成二維
- a[0][0] = 1
- a[0][1] = 2
- a[1][0] = error
- 經過 a.unsqueeze(1),多了「第 1 維」變成二維
- a[0][0] = 1
- a[1][0] = 2
- a[0][1] = error