Skip to content

Implement tensor.special.logit helper #645

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Mar 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion pytensor/tensor/special.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from pytensor.link.c.op import COp
from pytensor.tensor.basic import as_tensor_variable
from pytensor.tensor.elemwise import get_normalized_batch_axes
from pytensor.tensor.math import gamma, gammaln, neg, sum
from pytensor.tensor.math import gamma, gammaln, log, neg, sum


class SoftmaxGrad(COp):
Expand Down Expand Up @@ -780,6 +780,14 @@ def factorial(n):
return gamma(n + 1)


def logit(x):
"""
Logit function.

"""
return log(x / (1 - x))


def beta(a, b):
"""
Beta function.
Expand All @@ -801,6 +809,7 @@ def betaln(a, b):
"log_softmax",
"poch",
"factorial",
"logit",
"beta",
"betaln",
]
14 changes: 14 additions & 0 deletions tests/tensor/test_special.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from scipy.special import beta as scipy_beta
from scipy.special import factorial as scipy_factorial
from scipy.special import log_softmax as scipy_log_softmax
from scipy.special import logit as scipy_logit
from scipy.special import poch as scipy_poch
from scipy.special import softmax as scipy_softmax

Expand All @@ -18,6 +19,7 @@
betaln,
factorial,
log_softmax,
logit,
poch,
softmax,
)
Expand Down Expand Up @@ -206,6 +208,18 @@ def test_factorial(n):
)


def test_logit():
x = vector("x")
actual_fn = function([x], logit(x), allow_input_downcast=True)

x_test = np.linspace(0, 1)
actual = actual_fn(x_test)
expected = scipy_logit(x_test)
np.testing.assert_allclose(
actual, expected, rtol=1e-7 if config.floatX == "float64" else 1e-5
)


def test_beta():
_a, _b = vectors("a", "b")
actual_fn = function([_a, _b], beta(_a, _b))
Expand Down