pytorch
unsqueeze()
を使う.
a = torch.rand((3, 3))
a.size() # -> [3, 3]
a = a.unsqueeze(0)
a.size() # -> [1, 3, 3]
a = a.unsqueeze(1)
a.size() # -> [3, 1, 3]
numpy
reshape
, newaxis
, expand_dims
を使う方法がある.
reshape
かnewaxis
を使えば複数同時に増やすことも可能.
reshape
はめんどくさいからnewaxis
かな〜.
a = np.random.normal(size=(3,3))
a.shape # -> [3, 3]
# reshape
b = a.reshape(1, 3, 3)
b.shape # -> [1, 3, 3]
c = a.reshape(3, 1, 3)
c.shape # -> [3, 1, 3]
d = a.reshape(1, *a.shape)
d.shape # -> [1, 3, 3]
# newaxis
b = a[np.newaxis]
b.shape # -> [1, 3, 3]
c = a[:, np.newaxis]
c.shape # -> [3, 1, 3]
# expand_dims
b = np.expand_dims(a, 0)
b.shape # -> [1, 3, 3]
c = np.expand_dims(a, 1)
c.shape # -> [3, 1, 3]