PyTorch torch.sum 関数
torch.sumPyTorch でテンソルの要素の合計を計算するための関数です。すべての要素の合計を計算することも、指定した次元に沿って計算することもできます。
これは深層学習でよく使用されるリダクション操作であり、損失計算や統計などのシーンで使用されます。
関数定義
torch.sum(input, dim, keepdim, dtype, out)
パラメータ:
input(Tensor): 入力テンソル。dim(int または tuple of int, オプション): 計算する次元。もしNoneの場合、すべての要素の合計を計算します。keepdim(bool, オプション): 次元を保持するかどうか。デフォルトはFalse。dtype(torch.dtype, オプション): 出力テンソルのデータ型。out(Tensor, オプション): 出力テンソル。
戻り値:
torch.Tensor: 計算後のテンソルを返します。
使用例
例 1: すべての要素の合計を計算
実例
import torch
# テンソルを作成
x = torch.tensor([[1, 2, 3], [4, 5, 6]])
# すべての要素の合計を計算
total = torch.sum(x)
print("テンソル:")
print(x)
print("要素の合計:", total)
# テンソルを作成
x = torch.tensor([[1, 2, 3], [4, 5, 6]])
# すべての要素の合計を計算
total = torch.sum(x)
print("テンソル:")
print(x)
print("要素の合計:", total)
出力結果は次のとおりです:
张量:
tensor([[1, 2, 3],
[4, 5, 6]])
元素之和: tensor(21)
例 2: 指定した次元に沿って合計を計算
実例
import torch
x = torch.tensor([[1, 2, 3], [4, 5, 6]])
# dim=0(列)に沿って合計を計算
sum_dim0 = torch.sum(x, dim=0)
print("dim=0 に沿った合計:", sum_dim0)
# dim=1(行)に沿って合計を計算
sum_dim1 = torch.sum(x, dim=1)
print("dim=1 に沿った合計:", sum_dim1)
x = torch.tensor([[1, 2, 3], [4, 5, 6]])
# dim=0(列)に沿って合計を計算
sum_dim0 = torch.sum(x, dim=0)
print("dim=0 に沿った合計:", sum_dim0)
# dim=1(行)に沿って合計を計算
sum_dim1 = torch.sum(x, dim=1)
print("dim=1 に沿った合計:", sum_dim1)
出力結果は次のとおりです:
沿 dim=0 求和: tensor([5, 7, 9]) 沿 dim=1 求和: tensor([ 6, 15])
例 3: keepdim を使用して次元を保持
実例
import torch
x = torch.tensor([[1, 2, 3], [4, 5, 6]])
# 次元を保持しない
sum1 = torch.sum(x, dim=0)
print("次元を保持しない:", sum1.shape)
# 次元を保持
sum2 = torch.sum(x, dim=0, keepdim=True)
print("次元を保持:", sum2.shape)
print(sum2)
x = torch.tensor([[1, 2, 3], [4, 5, 6]])
# 次元を保持しない
sum1 = torch.sum(x, dim=0)
print("次元を保持しない:", sum1.shape)
# 次元を保持
sum2 = torch.sum(x, dim=0, keepdim=True)
print("次元を保持:", sum2.shape)
print(sum2)
出力結果は次のとおりです:
不保持维度: torch.Size([3]) 保持维度: torch.Size([1, 3]) tensor([[5, 7, 9]])
例 4: ニューラルネットワークで損失を計算
実例
import torch
# 予測値と実際の値をシミュレート
predictions = torch.tensor([0.1, 0.9, 0.8, 0.3])
targets = torch.tensor([0.0, 1.0, 1.0, 0.0])
# 平均二乗誤差損失を計算
loss = torch.sum((predictions - targets) ** 2) / len(predictions)
print("MSE 損失:", loss.item())
# 予測値と実際の値をシミュレート
predictions = torch.tensor([0.1, 0.9, 0.8, 0.3])
targets = torch.tensor([0.0, 1.0, 1.0, 0.0])
# 平均二乗誤差損失を計算
loss = torch.sum((predictions - targets) ** 2) / len(predictions)
print("MSE 損失:", loss.item())
出力結果は次のとおりです:
MSE 损失: 0.07499999690771103
その他の拡張
Pytorch torch リファレンスマニュアル