Funkcja czynnikowa PyTorcha

Oct 01 2020

Wydaje się, że nie ma funkcji PyTorch do obliczania silni. Czy istnieje metoda, aby to zrobić w PyTorch? Chcę ręcznie obliczyć rozkład Poissona w Torch (wiem, że istnieje:https://pytorch.org/docs/stable/generated/torch.poisson.html), a wzór wymaga silni w mianowniku.

Rozkład Poissona: https://en.wikipedia.org/wiki/Poisson_distribution

Odpowiedzi

4 trsvchn Oct 01 2020 at 16:15

Myślę, że można go znaleźć jako torch.jit._builtins.math.factorial ALE pytorch , jak numpyi scipy( Silnia w numpy i scipy ) wykorzystuje pythonwbudowane „s 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

Ale dla kontrastu, scipyoprócz „głównego nurtu” math.factorialzawiera bardzo „specjalną” funkcję silni scipy.special.factorial. W przeciwieństwie do funkcji z mathmodułu działa na tablicach:

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

Wbudowany mathmoduł ( docs ) udostępnia funkcję, która zwraca silnię danej całki jako int.

import math

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

Wynik

120
<class 'int'>