PyTorch階乗関数

Oct 01 2020

階乗を計算するためのPyTorch関数はないようです。PyTorchでこれを行う方法はありますか?トーチでポアソン分布を手動で計算しようとしています(これが存在することはわかっています:https://pytorch.org/docs/stable/generated/torch.poisson.html)そして式は分母に階乗を必要とします。

ポアソン分布: https://en.wikipedia.org/wiki/Poisson_distribution

回答

4 trsvchn Oct 01 2020 at 16:15

私はあなたがそれをtorch.jit._builtins.math.factorial BUT pytorchとして見つけることができると思いますnumpyそしてscipy(numpyとscipyの階乗)はpython'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

しかし、対照的に、scipy「主流」に加えてmath.factorial、非常に「特別な」階乗関数が含まれていますscipy.special.factorial。mathモジュールの関数とは異なり、配列で動作します。

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

組み込みmathモジュール(docs)は、指定された積分の階乗をとして返す関数を提供しますint。

import math

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

出力

120
<class 'int'>