pytorch Use ʻ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
There is a way to use reshape
, newaxis
, ʻexpand_dims. If you use
reshape or
newaxis, you can increase more than one at the same time.
Reshape is annoying, so I wonder if it's a
new axis`.
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]
Recommended Posts