如何解决PyTorch阶乘函数
似乎没有用于计算阶乘的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
以及numpy
和scipy
(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__,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__,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'>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。