似乎没有计算阶乘的PyTorch函数。在PyTorch中有这样做的方法吗?我希望手动计算火炬中的泊松分布(我知道这是存在的:https://pytorch.org/docs/stable/generated/torch.poisson.html),这个公式需要分母中的阶乘。
泊松分布:分布
发布于 2020-10-01 16:15:00
我想你可以找到torch.jit._builtins.math.factorial ,但是 pytorch以及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)发布于 2020-10-01 14:32:58
内置的math模块(文档)提供了一个函数,它将给定积分的阶乘作为int返回。
import math
x = math.factorial(5)
print(x)
print(type(x))输出
120
<class 'int'>https://stackoverflow.com/questions/64157192
复制相似问题