PyTorch 팩토리얼 함수

Oct 01 2020

팩토리얼을 계산하는 PyTorch 함수가없는 것 같습니다. PyTorch에서이 작업을 수행하는 방법이 있습니까? Torch에서 Poisson 분포를 수동으로 계산하려고합니다 (이게 존재한다는 것을 알고 있습니다.https://pytorch.org/docs/stable/generated/torch.poisson.html) 및 공식에는 분모에 계승이 필요합니다.

푸 아송 분포 : https://en.wikipedia.org/wiki/Poisson_distribution

답변

4 trsvchn Oct 01 2020 at 16:15

나는 당신이 그것을 찾을 수 있다고 생각 torch.jit._builtins.math.factorial 하지만 pytorch 뿐만 아니라 numpy과 scipy( 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)
JPI93 Oct 01 2020 at 14:32

내장 math모듈 ( 문서 )은 주어진 적분의 계승을 int.

import math

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

산출

120
<class 'int'>