【问题标题】:PyTorch Factorial FunctionPyTorch 阶乘函数
【发布时间】:2021-01-17 06:48:07
【问题描述】:

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

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

【问题讨论】:

  • 谢谢,看来我可以使用 Torch 函数的组合在 Torch 中专门计算阶乘。
  • lgamma 不能满足您的需求吗? (显然,与exp 结合使用,尽管您最好将事情保持在日志形式,直到最后。)

标签: python math deep-learning pytorch torch


【解决方案1】:

内置的 math 模块 (docs) 提供了一个函数,该函数将给定积分的阶乘返回为 int

import math

x = math.factorial(5)
print(x)
print(type(x))

输出

120
<class 'int'>

【讨论】:

  • 感谢您的回复,但我知道在 Python 中计算阶乘的其他方法。我正在寻找一种专门使用 PyTorch 的方法。
  • @kjans_tbme 哦,我明白了,为我的误解道歉。据我所知,PyTorch 库中没有阶乘函数 - 除了 TorchScript (docs) 本身使内置的 math 模块和 math.factorial 可用。
【解决方案2】:

我认为你可以找到它为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)

【讨论】:

    猜你喜欢
    • 2011-01-26
    • 2019-08-06
    • 1970-01-01
    • 1970-01-01
    • 2022-06-24
    • 2016-06-10
    • 2011-07-05
    • 2015-04-16
    • 1970-01-01
    相关资源
    最近更新 更多