Fonction factorielle PyTorch
Il ne semble pas y avoir de fonction PyTorch pour calculer une factorielle. Existe-t-il une méthode pour faire cela dans PyTorch? Je cherche à calculer manuellement une distribution de Poisson dans Torch (je suis conscient que cela existe:https://pytorch.org/docs/stable/generated/torch.poisson.html) et la formule nécessite une factorielle dans le dénominateur.
Distribution de Poisson: https://en.wikipedia.org/wiki/Poisson_distribution
Réponses
Je pense que vous pouvez le trouver aussi bien torch.jit._builtins.math.factorial MAIS pytorch que numpyet scipy( Factorial en numpy et scipy ) utilise pythonla fonction intégrée 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
Mais, en revanche, scipyen plus de "mainstream" math.factorialcontient la fonction factorielle très "spéciale" scipy.special.factorial. Contrairement à la fonction du mathmodule, il fonctionne sur des tableaux:
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)
Le mathmodule intégré ( docs ) fournit une fonction qui renvoie la factorielle d'une intégrale donnée sous la forme d'un int.
import math
x = math.factorial(5)
print(x)
print(type(x))
Production
120
<class 'int'>