PyTorch torch.add 関数
torch.addは、PyTorch で要素ごとの加算を実行するための関数です。2つのテンソル、またはテンソルとスカラーを加算します。
これは最も基本的な数学演算の1つであり、深層学習のさまざまな計算シーンで使用されます。
関数定義
torch.add(input, other, alpha=1, out=None)
パラメータ:
input(Tensor): 最初の入力テンソル。other(Tensor または float): 2番目の入力テンソルまたはスカラー。alpha(float, オプション): スケーリング係数、otherこの値を掛けてからinput加算します。デフォルトは1です。out(Tensor, オプション): 出力テンソル。
戻り値:
torch.Tensor: 加算後のテンソルを返します。
使用例
例1: 2つのテンソルの加算
例
import torch
# 2つのテンソルを作成
a = torch.tensor([1, 2, 3])
b = torch.tensor([4, 5, 6])
# 加算
c = torch.add(a, b)
print(c)
# 2つのテンソルを作成
a = torch.tensor([1, 2, 3])
b = torch.tensor([4, 5, 6])
# 加算
c = torch.add(a, b)
print(c)
出力結果は:
tensor([5, 7, 9])
例2: テンソルとスカラーの加算
例
import torch
# テンソルを作成
a = torch.tensor([1, 2, 3])
# スカラーを加算
b = torch.add(a, 10)
print(b)
# テンソルを作成
a = torch.tensor([1, 2, 3])
# スカラーを加算
b = torch.add(a, 10)
print(b)
出力結果は:
tensor([11, 12, 13])
例3: alphaパラメータを使用
例
import torch
# 2つのテンソルを作成
a = torch.tensor([1.0, 2.0, 3.0])
b = torch.tensor([1.0, 2.0, 3.0])
# a + 2 * b を計算
c = torch.add(a, b, alpha=2)
print(c)
# 2つのテンソルを作成
a = torch.tensor([1.0, 2.0, 3.0])
b = torch.tensor([1.0, 2.0, 3.0])
# a + 2 * b を計算
c = torch.add(a, b, alpha=2)
print(c)
出力結果は:
tensor([3., 6., 9.])
alphaパラメータは、特定のアルゴリズムを実装する際に役立ちます。例えば、計算などに使用します。input + alpha * other。
例4: ブロードキャスト機構
例
import torch
# 異なる形状のテンソルの加算(ブロードキャスト)
a = torch.tensor([[1, 2, 3], [4, 5, 6]])
b = torch.tensor([1, 2, 3])
c = torch.add(a, b)
print(c)
# 異なる形状のテンソルの加算(ブロードキャスト)
a = torch.tensor([[1, 2, 3], [4, 5, 6]])
b = torch.tensor([1, 2, 3])
c = torch.add(a, b)
print(c)
出力結果は:
tensor([[2, 4, 6],
[5, 7, 9])
PyTorchはブロードキャスト機構をサポートしており、異なる形状のテンソルを演算できます。
加算演算子を使用
使用するほか、torch.add()関数を使わずに直接使用できる+演算子もあります。両者の効果は同じです:
例
import torch
a = torch.tensor([1, 2, 3])
b = torch.tensor([4, 5, 6])
# 2つの方法は同等
c1 = torch.add(a, b)
c2 = a + b
print(c1)
print(c2)
print(torch.equal(c1, c2))
a = torch.tensor([1, 2, 3])
b = torch.tensor([4, 5, 6])
# 2つの方法は同等
c1 = torch.add(a, b)
c2 = a + b
print(c1)
print(c2)
print(torch.equal(c1, c2))
その他の拡張
Pytorch torch リファレンスマニュアル