Función factorial PyTorch

Oct 01 2020

No parece haber una función de PyTorch para calcular un factorial. ¿Existe algún método para hacer esto en PyTorch? Estoy buscando calcular manualmente una distribución de Poisson en Torch (soy consciente de que esto existe:https://pytorch.org/docs/stable/generated/torch.poisson.html) y la fórmula requiere un factorial en el denominador.

Distribución de veneno: https://en.wikipedia.org/wiki/Poisson_distribution

Respuestas

4 trsvchn Oct 01 2020 at 16:15

Creo que puedes encontrarlo como torch.jit._builtins.math.factorial PERO pytorch así como numpyy scipy( Factorial en numpy y scipy ) usa pythonel builtin 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

Pero, en contraste, scipyademás de "mainstream" math.factorialcontiene la función factorial muy "especial" scipy.special.factorial. A diferencia de la función del mathmódulo, opera en matrices:

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

El mathmódulo integrado ( docs ) proporciona una función que devuelve el factorial de una integral dada como un int.

import math

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

Salida

120
<class 'int'>