Função Fatorial PyTorch
Não parece haver uma função PyTorch para calcular um fatorial. Existe um método para fazer isso no PyTorch? Estou tentando calcular manualmente uma distribuição de Poisson no Torch (estou ciente de que isso existe:https://pytorch.org/docs/stable/generated/torch.poisson.html) e a fórmula requer um fatorial no denominador.
Distribuição de veneno: https://en.wikipedia.org/wiki/Poisson_distribution
Respostas
Acho que você pode encontrá-lo como torch.jit._builtins.math.factorial MAS pytorch , bem como numpye scipy( Fatorial em numpy e scipy ) usa pythono embutido de 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
Mas, em contraste, scipyalém de "mainstream" math.factorialcontém a função fatorial muito "especial" scipy.special.factorial. Ao contrário da função do mathmódulo, ele opera em matrizes:
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)
O mathmódulo integrado ( docs ) fornece uma função que retorna o fatorial de um dado integral como um int.
import math
x = math.factorial(5)
print(x)
print(type(x))
Resultado
120
<class 'int'>