Skip to content

Remove ChiSquared Distribution in favor of helper #6994

Closed
@ricardoV94

Description

@ricardoV94

Description

It's just a Gamma(alpha=nu/2, beta=1/2). No point in having the extra code:

class ChiSquared(PositiveContinuous):
r"""
:math:`\chi^2` log-likelihood.
The pdf of this distribution is
.. math::
f(x \mid \nu) = \frac{x^{(\nu-2)/2}e^{-x/2}}{2^{\nu/2}\Gamma(\nu/2)}
.. plot::
:context: close-figs
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as st
import arviz as az
plt.style.use('arviz-darkgrid')
x = np.linspace(0, 15, 200)
for df in [1, 2, 3, 6, 9]:
pdf = st.chi2.pdf(x, df)
plt.plot(x, pdf, label=r'$\nu$ = {}'.format(df))
plt.xlabel('x', fontsize=12)
plt.ylabel('f(x)', fontsize=12)
plt.ylim(0, 0.6)
plt.legend(loc=1)
plt.show()
======== ===============================
Support :math:`x \in [0, \infty)`
Mean :math:`\nu`
Variance :math:`2 \nu`
======== ===============================
Parameters
----------
nu : tensor_like of float
Degrees of freedom (nu > 0).
"""
rv_op = chisquare
@classmethod
def dist(cls, nu, *args, **kwargs):
nu = pt.as_tensor_variable(floatX(nu))
return super().dist([nu], *args, **kwargs)
def moment(rv, size, nu):
moment = nu
if not rv_size_is_none(size):
moment = pt.full(size, moment)
return moment
def logp(value, nu):
return _logprob_helper(Gamma.dist(alpha=nu / 2, beta=0.5), value)
def logcdf(value, nu):
return _logcdf_helper(Gamma.dist(alpha=nu / 2, beta=0.5), value)

class Chisquare:
  """docs"""

  def __new__(cls, name, nu, **kwargs):
    return Gamma(name, nu/2, 1/2, **kwargs)
  
  @classmethod
  def dist(cls, nu, **kwargs):
    return Gamma.dist(nu/2, 1/2, **kwargs)

Likewise, the ChiSquareRV in PyTensor can be removed in favor of a helper that just returns the right gamma:

https://github.com/pymc-devs/pytensor/blob/3169197c54e2cab7ba27c647c760b93e12abca5e/pytensor/tensor/random/basic.py#L490-L540

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions