ฟังก์ชัน PyTorch Factorial

Oct 01 2020

ดูเหมือนจะไม่มีฟังก์ชัน PyTorch สำหรับการคำนวณแฟกทอเรียล มีวิธีการทำใน PyTorch หรือไม่? ฉันต้องการคำนวณการแจกแจงแบบปัวซองด้วยตนเองใน Torch (ฉันทราบว่ามีอยู่: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 แต่ pytorchเช่นเดียวกับnumpyและscipy( Factorial in numpy และ SciPy ) ใช้pythonbuiltin '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โมดูลในตัว ( เอกสาร ) จัดเตรียมฟังก์ชันที่ส่งคืนแฟกทอเรียลของอินทิกรัลที่กำหนดเป็นintไฟล์.

import math

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

เอาต์พุต

120
<class 'int'>