PyTorch-Faktorfunktion
Es scheint keine PyTorch-Funktion zum Berechnen einer Fakultät zu geben. Gibt es eine Methode, um dies in PyTorch zu tun? Ich möchte eine Poisson-Verteilung in Torch manuell berechnen (mir ist bekannt, dass dies existiert:https://pytorch.org/docs/stable/generated/torch.poisson.html) und die Formel erfordert eine Fakultät im Nenner.
Poisson-Verteilung: https://en.wikipedia.org/wiki/Poisson_distribution
Antworten
Ich denke, Sie können es als torch.jit._builtins.math.factorial ABER pytorch ebenso finden wie numpyund scipy( Faktor in numpy und scipy ) verwendet python's eingebautes 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
Im Gegensatz dazu enthält scipy"Mainstream" aber math.factorialauch die sehr "spezielle" Fakultätsfunktion scipy.special.factorial. Im Gegensatz zur Funktion des mathModuls arbeitet es mit Arrays:
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)
Das eingebaute mathModul ( docs ) bietet eine Funktion, die die Fakultät eines bestimmten Integrals als zurückgibt int.
import math
x = math.factorial(5)
print(x)
print(type(x))
Ausgabe
120
<class 'int'>