PyTorch torch.unflatten 関数
torch.unflattenは PyTorch で次元を展開するために使用される関数です。テンソル内の既存の次元を複数の次元に展開し、テンソルの形状を再構築するために使用します。
関数定義
torch.unflatten(input, dim, sizes)
パラメータの説明:
input: 入力テンソルdim: 展開する次元インデックスsizes: 展開後のサイズタプル
使用例
例
import torch
# 1次元テンソルを作成
x = torch.arange(12)
# 3x4 行列に展開
y = torch.unflatten(x, dim=0, sizes=(3, 4))
print(y.shape)
print(y)
# 1次元テンソルを作成
x = torch.arange(12)
# 3x4 行列に展開
y = torch.unflatten(x, dim=0, sizes=(3, 4))
print(y.shape)
print(y)
出力結果:
torch.Size([3, 4])
tensor([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
例
import torch
# フラット化したテンソルを作成
x = torch.randn(24)
# 2x3x4 の3次元テンソルに展開
y = torch.unflatten(x, dim=0, sizes=(2, 3, 4))
print(y.shape)
# フラット化したテンソルを作成
x = torch.randn(24)
# 2x3x4 の3次元テンソルに展開
y = torch.unflatten(x, dim=0, sizes=(2, 3, 4))
print(y.shape)
出力結果:
torch.Size([2, 3, 4])
例
import torch
# フラット化したテンソルを作成
x = torch.randn(12)
# 名前で次元を指定できます
x = x.rename('N')
y = torch.unflatten(x, dim='N', sizes=(3, 4))
print(y.shape)
# フラット化したテンソルを作成
x = torch.randn(12)
# 名前で次元を指定できます
x = x.rename('N')
y = torch.unflatten(x, dim='N', sizes=(3, 4))
print(y.shape)
出力結果:
torch.Size([3, 4])
その他の拡張
PyTorch torch リファレンスマニュアル