PyTorch torch.expand 関数
Pytorch torch リファレンスマニュアルPytorch torch リファレンスマニュアル
torch.expandは PyTorch でテンソルのサイズを拡張するために使用される関数です。データを実際にコピーせず、ビューを複製する方法でテンソルを拡張します。
拡張されたテンソルはメモリ内で元のデータを共有するビューであるため、これはメモリ効率の高い操作です。
関数定義
torch.expand(*sizes) torch.expand(input, *sizes)
パラメータ:
input(Tensor): 入力テンソル。*sizes(torch.Size または int): ターゲットサイズ。サイズには1つの次元のみ -1 を指定でき、その次元を変更しないことを意味します。値が1の次元はより大きなサイズに拡張できます。
戻り値:
torch.Tensor: 拡張されたテンソルのビューを返します。
使用例
例
import torch
# 次元が1のテンソルを作成
x = torch.tensor([[1], [2], [3]])
print("元のテンソル:")
print(x)
print("形状:", x.shape)
# より大きなサイズに拡張
y = x.expand(3, 4)
print("n拡張後:")
print(y)
print("形状:", y.shape)
# 次元が1のテンソルを作成
x = torch.tensor([[1], [2], [3]])
print("元のテンソル:")
print(x)
print("形状:", x.shape)
# より大きなサイズに拡張
y = x.expand(3, 4)
print("n拡張後:")
print(y)
print("形状:", y.shape)
出力結果は次のとおりです:
原始张量:
tensor([[1],
[2],
[3]])
形状: torch.Size([3, 1])
扩展后:
tensor([[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3]])
形状: torch.Size([3, 4])
例
import torch
# -1 を使用して次元を変更しない
x = torch.tensor([1, 2, 3, 4])
# 2x4 のテンソルに拡張
y = x.expand(2, -1)
print("元:", x.shape)
print("拡張後:", y.shape)
print(y)
# -1 を使用して次元を変更しない
x = torch.tensor([1, 2, 3, 4])
# 2x4 のテンソルに拡張
y = x.expand(2, -1)
print("元:", x.shape)
print("拡張後:", y.shape)
print(y)
出力結果は次のとおりです:
原始: torch.Size([4])
扩展后: torch.Size([2, 4])
tensor([[1, 2, 3, 4],
[1, 2, 3, 4]])
例
import torch
# ブロードキャスト機構の応用シーン
# 列ベクトルを行列に拡張
column = torch.randn(5, 1)
# 行列と加算するために拡張
matrix = torch.randn(5, 10)
# ブロードキャスト:列ベクトルは自動的に拡張されます
result = matrix + column
print("列ベクトル形状:", column.shape)
print("行列形状:", matrix.shape)
print("結果形状:", result.shape)
# ブロードキャスト機構の応用シーン
# 列ベクトルを行列に拡張
column = torch.randn(5, 1)
# 行列と加算するために拡張
matrix = torch.randn(5, 10)
# ブロードキャスト:列ベクトルは自動的に拡張されます
result = matrix + column
print("列ベクトル形状:", column.shape)
print("行列形状:", matrix.shape)
print("結果形状:", result.shape)
出力結果は次のとおりです:
列向量形状: torch.Size([5, 1]) 矩阵形状: torch.Size([5, 10]) 结果形状: torch.Size([5, 10])
例
import torch
# 2Dテンソルから3Dへ拡張
x = torch.tensor([[1, 2, 3],
[4, 5, 6]])
# 3番目の次元を拡張
y = x.expand(2, 2, 3)
print("元の形状:", x.shape)
print("拡張後の形状:", y.shape)
print("n拡張後のテンソル:")
print(y)
# データが共有されていることを検証
print("n元のテンソルを変更:")
x[0, 0] = 100
print("x[0,0]:", x[0, 0])
print("y[0,0,0]:", y[0, 0, 0])
# 2Dテンソルから3Dへ拡張
x = torch.tensor([[1, 2, 3],
[4, 5, 6]])
# 3番目の次元を拡張
y = x.expand(2, 2, 3)
print("元の形状:", x.shape)
print("拡張後の形状:", y.shape)
print("n拡張後のテンソル:")
print(y)
# データが共有されていることを検証
print("n元のテンソルを変更:")
x[0, 0] = 100
print("x[0,0]:", x[0, 0])
print("y[0,0,0]:", y[0, 0, 0])
出力結果は次のとおりです:
原始形状: torch.Size([2, 3])
扩展后形状: torch.Size([2, 2, 3])
扩展后的张量:
tensor([[[1, 2, 3],
[4, 5, 6]],
[[1, 2, 3],
[4, 5, 6]]])
修改原始张量:
x[0,0]: tensor(100)
y[0,0,0]: tensor(100)
注意:torch.expand拡張できるのは、次元のサイズが1の次元のみであり、より大きなサイズに拡張できます。1より大きい次元を縮小したり、異なるサイズに拡張したりすることはできません。返されるのはビューであり、コピーではありません。