1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

実務でよく使うPyTorchの機能まとめ⑥|unsqueezeメソッド

Posted at

基本的な使い方

unsqueezeメソッドはPyTorchのテンソルの次元を上げる際に用いられるメソッドです。

import torch

x = torch.zeros([2, 2])
print(x.shape)

print(x.unsqueeze(dim=0).shape)
print(x.unsqueeze(dim=1).shape)
print(x.unsqueeze(dim=2).shape)

・実行結果

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

unsqueezeメソッドの活用

unsqueezeメソッドは次元の大きなテンソルにテンソルを加えるなどの処理に活用することができます。

import torch

x = torch.zeros([2, 2])
y = torch.ones([2, 5, 2])

print(x)
print(y)
print(x.shape)
print(y.shape)
print(x.unsqueeze(dim=1).shape)
print((y+x.unsqueeze(dim=1)).shape)

・実行結果

tensor([[0., 0.],
        [0., 0.]])
tensor([[[1., 1.],
         [1., 1.],
         [1., 1.],
         [1., 1.],
         [1., 1.]],

        [[1., 1.],
         [1., 1.],
         [1., 1.],
         [1., 1.],
         [1., 1.]]])
torch.Size([2, 2])
torch.Size([2, 5, 2])
torch.Size([2, 1, 2])
torch.Size([2, 5, 2])
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?