1. 程式人生 > >Numpy , Tensor , Variable 增刪一個值為1的維度

Numpy , Tensor , Variable 增刪一個值為1的維度

1.Numpy.array

  • 給 2-d Array(H, W) 增加一個值為 1 的維度成為 3-d Array(H, W, 1)

彩色影象numpy中以 (H, W, C) 形狀(channel-last)的 3-d Array 儲存; 而 灰度影象 則以 (H, W) 形狀的 2-d Array 儲存, 經常需要為其增加一個值為 1 的維度, 成為 3-d Array(H, W, 1)

import numpy as np

in:
a = np.ones((3,3))
print(a.shape) 
b1 = np.expand_dims(a,2)
print(b1.shape)

out:
(2, 2)
(2, 2, 1)

note:
b2 = np.expand_dims(a, 0) # (1, 2, 2)
b3 = np.expand_dims(a, 1) # (2, 2, 1)
  • 刪去n-d Array 中值為1 的維度

在顯示、儲存影象矩陣時,往往需要刪去值為1的維度:

in:
a = np.ones((2,2,1))
print(a.shape)
b = np.squeeze(a)
print(b.shape)

out:
(2, 2, 1)
(2, 2)

2.torch.Tensor

  • 給 2-d Tensor(H, W) 增加一個值為 1 的維度成為 3-d Tensor(1, H, W)

彩色影象Pytorch 中以 (C, H, W) 形狀(channel-first)的 3-d tensor

儲存; 而 灰度影象 則以 (H, W) 形狀的 2-d tensor 儲存, 經常需要為其增加一個值為 1 的維度, 成為 3-d tensor (H, W, 1)

in:
import torch as t
a = np.ones((2,2))
a = t.Tensor(a)
print(a.shape)

b = t.unsqueeze(a, 0)
print(b.shape)

out:
torch.Size([2, 2])
torch.Size([1, 2, 2])
  • 刪去n-d Array 中值為1 的維度
in:
import torch as t
a = np.ones((2,2,1))
a = t.Tensor(a)
print(a.shape)

b = t.squeeze(a)
print(b.shape)

out:
torch.Size([2, 2, 1])
torch.Size([2, 2])

3.torch.Variable

Pytorch 中為支援自動求導, Tenosr 被封裝成 VariableVariable 增刪維度使用的函式與 Tensor 一致。