PyTorch 阶乘函数

kja*_*bme 5 python math deep-learning torch pytorch

似乎没有用于计算阶乘的 PyTorch 函数。PyTorch 有没有办法做到这一点?我希望在 Torch 中手动计算泊松分布(我知道存在这种分布:https: //pytorch.org/docs/stable/ generated /torch.poisson.html),并且该公式需要分母中的阶乘。

泊松分布: https: //en.wikipedia.org/wiki/Poisson_distribution

trs*_*chn 7

我认为你可以找到它torch.jit._builtins.math.factorial BUT pytorch以及numpyand scipynumpy 和 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)
Run Code Online (Sandbox Code Playgroud)
True
True
True
Run Code Online (Sandbox Code Playgroud)

但是,相比之下,scipy除了“主流”之外math.factorial还包含着非常“特殊”的阶乘函数scipy.special.factorial。与模块中的函数不同,math它对数组进行操作:

from scipy import special

print(special.factorial is math.factorial)
Run Code Online (Sandbox Code Playgroud)
False
Run Code Online (Sandbox Code Playgroud)
# 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)
Run Code Online (Sandbox Code Playgroud)
factorial math : 6
factorial math : 6
factorial math : 6
factorial math : 6
factorial scipy.special._basic : tensor(6., dtype=torch.float64)
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)