PyTorch 似乎没有计算阶乘的函数。 PyTorch 有没有办法做到这一点?我希望在 Torch 中手动计算泊松分布(我知道存在这种分布:https://pytorch.org/docs/stable/ generated/torch.poisson.html)并且该公式需要分母中的阶乘。
我认为你可以找到它
torch.jit._builtins.math.factorial
BUT pytorch
以及 numpy
和 scipy
(numpy 和 scipy 中的阶乘)使用 python
的内置 math.factorial
:
import math
import numpy as np
import scipy as sp
import torch
print(torch.jit._builtins.math.factorial is math.factorial)
print(np.math.factorial is math.factorial)
print(sp.math.factorial is math.factorial)
True
True
True
但是,相比之下,
scipy
除了“主流”math.factorial
之外,还包含非常“特殊”的阶乘函数scipy.special.factorial
。与 math
模块中的函数不同,它在数组上运行:
from scipy import special
print(special.factorial is math.factorial)
False
# the all known factorial functions
factorials = (
math.factorial,
torch.jit._builtins.math.factorial,
np.math.factorial,
sp.math.factorial,
special.factorial,
)
# Let's run some tests
tnsr = torch.tensor(3)
for fn in factorials:
try:
out = fn(tnsr)
except Exception as err:
print(fn.__name__, fn.__module__, ':', err)
else:
print(fn.__name__, fn.__module__, ':', out)
factorial math : 6
factorial math : 6
factorial math : 6
factorial math : 6
factorial scipy.special._basic : tensor(6., dtype=torch.float64)
tnsr = torch.tensor([1, 2, 3])
for fn in factorials:
try:
out = fn(tnsr)
except Exception as err:
print(fn.__name__, fn.__module__, ':', err)
else:
print(fn.__name__, fn.__module__, ':', out)
factorial math : only integer tensors of a single element can be converted to an index
factorial math : only integer tensors of a single element can be converted to an index
factorial math : only integer tensors of a single element can be converted to an index
factorial math : only integer tensors of a single element can be converted to an index
factorial scipy.special._basic : tensor([1., 2., 6.], dtype=torch.float64)
内置
math
模块 (docs) 提供了一个函数,该函数将给定积分的阶乘返回为 int
。
import math
x = math.factorial(5)
print(x)
print(type(x))
输出
120
<class 'int'>
torch.lgamma
计算伽玛的对数,等于 (x-1)!
import torch
def log_factorial(x):
return torch.lgamma(x + 1)
def factorial(x):
return torch.exp(log_factorial(x))