Hàm thừa số PyTorch

Oct 01 2020

Dường như không có hàm PyTorch để tính giai thừa. Có phương pháp nào để làm điều này trong PyTorch không? Tôi đang tìm cách tính toán phân phối Poisson trong Torch theo cách thủ công (tôi biết rằng điều này tồn tại:https://pytorch.org/docs/stable/generated/torch.poisson.html) và công thức yêu cầu một giai thừa ở mẫu số.

Phân phối Poisson: https://en.wikipedia.org/wiki/Poisson_distribution

Trả lời

4 trsvchn Oct 01 2020 at 16:15

Tôi nghĩ bạn có thể tìm thấy nó torch.jit._builtins.math.factorial NHƯNG pytorch cũng như numpyvà scipy( Giai thừa trong numpy và scipy ) sử dụng pythonnội trang của 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

Nhưng, ngược lại, scipyngoài "chủ đạo" math.factorialchứa hàm giai thừa rất "đặc biệt" scipy.special.factorial. Không giống như hàm từ mathmô-đun, nó hoạt động trên các mảng:

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

mathMô-đun tích hợp sẵn ( docs ) cung cấp một hàm trả về giai thừa của một tích phân đã cho dưới dạng một int.

import math

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

Đầu ra

120
<class 'int'>