Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

軸の増やし方

More than 1 year has passed since last update.

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を使う方法がある.
reshapenewaxisを使えば複数同時に増やすことも可能.
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]
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away