PyTorch torch.logcumsumexp 関数
torch.logcumsumexpは PyTorch で累積指数和の対数を計算するための関数です。最初に要素の指数を計算し、次に累積的に合計し、最後に対数を取るため、数値オーバーフローを回避できます。
関数定義
torch.logcumsumexp(input, dim)
パラメータの説明:
input: 入力テンソルdim: 累積和を計算する次元
使用例
例
import torch
# テンソルの作成
x = torch.tensor([1.0, 2.0, 3.0])
# 指数の累積和の対数を計算
y = torch.logcumsumexp(x, dim=0)
print(y)
# テンソルの作成
x = torch.tensor([1.0, 2.0, 3.0])
# 指数の累積和の対数を計算
y = torch.logcumsumexp(x, dim=0)
print(y)
出力結果は次のとおりです:
tensor([1.0000, 2.3133, 3.1000])
例
import torch
# 検証:log(exp(1) + exp(2)) = log(exp(1) + exp(2))
# log(e^1 + e^2) = log(e^1 + e^2) ≈ 2.3133
x = torch.tensor([1.0, 2.0])
y = torch.logcumsumexp(x, dim=0)
# 直接計算と比較
import math
direct = math.log(math.exp(1) + math.exp(2))
print("logcumsumexp:", y[1].item())
print("direct:", direct)
# 検証:log(exp(1) + exp(2)) = log(exp(1) + exp(2))
# log(e^1 + e^2) = log(e^1 + e^2) ≈ 2.3133
x = torch.tensor([1.0, 2.0])
y = torch.logcumsumexp(x, dim=0)
# 直接計算と比較
import math
direct = math.log(math.exp(1) + math.exp(2))
print("logcumsumexp:", y[1].item())
print("direct:", direct)
出力結果は次のとおりです:
logcumsumexp: 2.313261505126953 direct: 2.313261505126953
その他の拡張
Pytorch torch リファレンスマニュアル