gpt4 book ai didi

python - PyTorch 阶乘函数

转载 作者:行者123 更新时间:2023-12-04 01:13:14 30 4
gpt4 key购买 nike

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

最佳答案

我想你可以找到它作为torch.jit._builtins.math.factorial 但是 pytorch以及 numpyscipy ( Factorial in numpy and 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)

关于python - PyTorch 阶乘函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64157192/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com