PyTorch torch.expand_as 関数
torch.expand_asPyTorch において、テンソルを別のテンソルと同じサイズに拡張するために使用される関数です。これはtorch.expandの便利なバージョンで、参照テンソルのサイズを自動的に使用して拡張します。
関数定義
torch.expand_as(other)
パラメータ:
other(Tensor): 参照テンソル。現在のテンソルはこのテンソルと同じサイズに拡張されます。
戻り値:
torch.Tensor: 拡張されたテンソルのビューを返します。
使用例
例
import torch
# ベクトルを作成
x = torch.tensor([1, 2, 3, 4])
# ターゲット行列を作成
other = torch.randn(3, 4)
# x を other と同じ形状に拡張する
y = x.expand_as(other)
print("元のベクトルの形状:", x.shape)
print("参照テンソルの形状:", other.shape)
print("拡張後の形状:", y.shape)
print("n拡張後のテンソル:")
print(y)
# ベクトルを作成
x = torch.tensor([1, 2, 3, 4])
# ターゲット行列を作成
other = torch.randn(3, 4)
# x を other と同じ形状に拡張する
y = x.expand_as(other)
print("元のベクトルの形状:", x.shape)
print("参照テンソルの形状:", other.shape)
print("拡張後の形状:", y.shape)
print("n拡張後のテンソル:")
print(y)
出力結果は次のとおりです:
原始向量形状: torch.Size([4])
参考张量形状: torch.Size([3, 4])
扩展后形状: torch.Size([3, 4])
扩展后的张量:
tensor([[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4]])
例
import torch
# 列ベクトルを作成
x = torch.tensor([[1], [2], [3]])
# ターゲットの3Dテンソルを作成
other = torch.randn(3, 4, 5)
# x を other と同じ形状に拡張する
y = x.expand_as(other)
print("元の列ベクトルの形状:", x.shape)
print("参照テンソルの形状:", other.shape)
print("拡張後の形状:", y.shape)
# 列ベクトルを作成
x = torch.tensor([[1], [2], [3]])
# ターゲットの3Dテンソルを作成
other = torch.randn(3, 4, 5)
# x を other と同じ形状に拡張する
y = x.expand_as(other)
print("元の列ベクトルの形状:", x.shape)
print("参照テンソルの形状:", other.shape)
print("拡張後の形状:", y.shape)
出力結果は次のとおりです:
原始列向量形状: torch.Size([3, 1]) 参考张量形状: torch.Size([3, 4, 5]) 扩展后形状: torch.Size([3, 4, 5])
例
import torch
# ニューラルネットワークでの適用例
# バイアスベクトルを特徴マップにブロードキャストする必要があると仮定します
bias = torch.tensor([0.1, 0.2, 0.3]) # 3チャンネルのバイアス
# 畳み込み出力の特徴マップを模擬します (batch, channel, height, width)
feature_map = torch.randn(8, 3, 32, 32)
# バイアスを特徴マップと同じ形状に拡張する
bias_expanded = bias.expand_as(feature_map)
print("バイアスの形状:", bias.shape)
print("特徴マップの形状:", feature_map.shape)
print("拡張後のバイアスの形状:", bias_expanded.shape)
# バイアスを加算する
output = feature_map + bias_expanded
print("nバイアス加算後の出力形状:", output.shape)
# ニューラルネットワークでの適用例
# バイアスベクトルを特徴マップにブロードキャストする必要があると仮定します
bias = torch.tensor([0.1, 0.2, 0.3]) # 3チャンネルのバイアス
# 畳み込み出力の特徴マップを模擬します (batch, channel, height, width)
feature_map = torch.randn(8, 3, 32, 32)
# バイアスを特徴マップと同じ形状に拡張する
bias_expanded = bias.expand_as(feature_map)
print("バイアスの形状:", bias.shape)
print("特徴マップの形状:", feature_map.shape)
print("拡張後のバイアスの形状:", bias_expanded.shape)
# バイアスを加算する
output = feature_map + bias_expanded
print("nバイアス加算後の出力形状:", output.shape)
出力結果は次のとおりです:
偏置形状: torch.Size([3]) 特征图形状: torch.Size([8, 3, 32, 32]) 扩展后偏置形状: torch.Size([8, 3, 32, 32]) 加上偏置后的输出形状: torch.Size([8, 3, 32, 32])
注意:torch.expand_asサイズが1の次元のみをより大きなサイズに拡張できます。otherテンソルのサイズは拡張後のサイズと互換性がある必要があります(つまり、現在のテンソルの次元はブロードキャストによってターゲットサイズに拡張できる必要があります)。返されるのはビューであり、コピーではありません。
その他の拡張
Pytorch torch リファレンスマニュアル