PyTorch torch.broadcast_tensors関数
torch.broadcast_tensorsPyTorch で複数のテンソルをブロードキャストするための関数です。入力テンソルを同じ形状にブロードキャストし、要素ごとに演算できる一連のテンソルを返します。ブロードキャスト規則は NumPy のブロードキャスト機構に従います。
関数定義
torch.broadcast_tensors(*tensors)
使用例
実例
import torch
# 異なる形状のテンソルのブロードキャスト
x = torch.tensor([[1, 2, 3]]) # 形状 (1, 3)
y = torch.tensor([[1], [2], [3]]) # 形状 (3, 1)
a, b = torch.broadcast_tensors(x, y)
print("ブロードキャスト後の x の形状:", a.shape)
print("ブロードキャスト後の y の形状:", b.shape)
print("ブロードキャスト後の x:")
print(a)
print("ブロードキャスト後の y:")
print(b)
print("要素ごとの加算:")
print(a + b)
# 複数のテンソル
x1 = torch.randn(3, 1, 5)
x2 = torch.randn(1, 4, 5)
x3 = torch.randn(3, 4, 1)
r1, r2, r3 = torch.broadcast_tensors(x1, x2, x3)
print("ブロードキャスト後の形状:", r1.shape)
# 異なる形状のテンソルのブロードキャスト
x = torch.tensor([[1, 2, 3]]) # 形状 (1, 3)
y = torch.tensor([[1], [2], [3]]) # 形状 (3, 1)
a, b = torch.broadcast_tensors(x, y)
print("ブロードキャスト後の x の形状:", a.shape)
print("ブロードキャスト後の y の形状:", b.shape)
print("ブロードキャスト後の x:")
print(a)
print("ブロードキャスト後の y:")
print(b)
print("要素ごとの加算:")
print(a + b)
# 複数のテンソル
x1 = torch.randn(3, 1, 5)
x2 = torch.randn(1, 4, 5)
x3 = torch.randn(3, 4, 1)
r1, r2, r3 = torch.broadcast_tensors(x1, x2, x3)
print("ブロードキャスト後の形状:", r1.shape)
その他の拡張
Pytorch torch リファレンスマニュアル