statsinference

statsinference - fit univariate distributions by maximum likelihood, pick the best one by AIC/BIC, plot fitdistrplus-style diagnostics, and simulate.

>>> import numpy as np
>>> from statsinference import StatsInference
>>> x = np.random.default_rng(1).gamma(2, 1.5, size=300)
>>> si = StatsInference(x).select(criterion="aic")
>>> si.best_dist, si.estimate
>>> si.summary(); si.plot(); si.plot_compare(top=3)
>>> sims = si.simulate(1000, seed=123)
 1"""
 2statsinference - fit univariate distributions by maximum likelihood, pick the
 3best one by AIC/BIC, plot fitdistrplus-style diagnostics, and simulate.
 4
 5>>> import numpy as np
 6>>> from statsinference import StatsInference
 7>>> x = np.random.default_rng(1).gamma(2, 1.5, size=300)
 8>>> si = StatsInference(x).select(criterion="aic")
 9>>> si.best_dist, si.estimate
10>>> si.summary(); si.plot(); si.plot_compare(top=3)
11>>> sims = si.simulate(1000, seed=123)
12"""
13
14from ._distributions import SUPPORTED
15from .inference import StatsInference
16
17__all__ = ["StatsInference", "SUPPORTED"]
18__version__ = "0.1.4"
class StatsInference:
 66class StatsInference:
 67    """Fit univariate distributions to data by maximum likelihood.
 68
 69    Parameters
 70    ----------
 71    x : array-like
 72        Non-empty numeric vector with no NaN or infinite values.
 73    densfun : optional
 74        If given, fit it straight away
 75        (same as ``StatsInference(x).fit(densfun)``).
 76    **fit_kwargs
 77        Passed on to :meth:`fit`.
 78
 79    After :meth:`fit` or :meth:`select`, the chosen fit's results are
 80    available directly on the object: ``estimate``, ``sd``, ``vcov``,
 81    ``loglik``, ``aic``, ``bic``, ``n``, ``converged``, ``dist`` (the fitted
 82    scipy distribution), and the methods ``summary()``, ``gof()``,
 83    ``plot()``, ``denscomp()``, ``cdfcomp()``, ``qqcomp()``, ``ppcomp()``.
 84    """
 85
 86    def __init__(self, x, densfun=None, **fit_kwargs):
 87        x = np.asarray(x)
 88        if x.size == 0 or not np.issubdtype(x.dtype, np.number):
 89            raise ValueError("'x' must be a non-empty numeric vector")
 90        x = x.astype(float).ravel()
 91        if not np.all(np.isfinite(x)):
 92            raise ValueError("'x' contains missing or infinite values")
 93        self.x = x
 94        self.result = None  # the chosen fit
 95        self.fits = {}  # label -> fit, for every successful fit
 96        self.failures = {}  # label -> error message
 97        self.table = None  # ranking from select()
 98        self.criterion = None
 99        if densfun is not None:
100            self.fit(densfun, **fit_kwargs)
101
102    # -------------------------------------------------------------- fitting
103    def fit(
104        self,
105        densfun,
106        start=None,
107        fixed=None,
108        lower=None,
109        upper=None,
110        method="L-BFGS-B",
111        cdf=None,
112        discrete=None,
113        label=None,
114    ):
115        """Fit one distribution; it becomes the current result.
116
117        ``densfun`` is a supported name (see ``SUPPORTED``), a scipy
118        distribution such as ``scipy.stats.gamma``, or a density function
119        ``f(x, **params[, log=])`` (then ``start`` is required).
120
121        start, fixed, lower, upper : dict, optional
122            Keyed by parameter name. ``fixed`` holds parameters that are not
123            estimated (R's ``...``). Not allowed: ``start`` for "normal",
124            which is fitted in closed form.
125        method : any ``scipy.optimize.minimize`` method.
126        cdf, discrete : only for a density function (numeric CDF otherwise).
127        label : name under which the fit is stored in ``self.fits``.
128        """
129        f = _SingleFit(
130            self.x,
131            densfun,
132            start=start,
133            fixed=fixed,
134            lower=lower,
135            upper=upper,
136            method=method,
137            cdf=cdf,
138            discrete=discrete,
139        )
140        self.fits[label or f.name] = f
141        self.result = f
142        return self
143
144    def select(
145        self,
146        distributions=None,
147        criterion="aic",
148        verbose=1,
149        progress=True,
150        options=None,
151    ):
152        """Fit several distributions and keep the best by AIC or BIC.
153
154        Parameters
155        ----------
156        distributions : list, optional
157            Names from ``SUPPORTED`` and/or scipy distribution objects.
158            Default: every named distribution whose support fits the data
159            (count distributions for non-negative integers, otherwise the
160            continuous ones; positive-only and (0, 1) ones only when the
161            data allow them).
162        criterion : {"aic", "bic"}
163        verbose : int
164            0 = silent, 1 = print the ranking at the end,
165            2 = also print each fit (or failure) as it happens.
166        progress : bool
167            Show a progress bar (tqdm if installed, else a counter).
168        options : dict, optional
169            Per-distribution keyword arguments for :meth:`fit`, keyed by
170            label, e.g. ``{"t": {"fixed": {"df": 5}}}``.
171
172        Returns
173        -------
174        self, with ``result`` set to the best fit, ``table`` holding the
175        ranking (criterion, delta, Akaike/Schwarz weights) and ``fits``
176        holding every successful fit.
177        """
178        criterion = criterion.lower()
179        if criterion not in ("aic", "bic"):
180            raise ValueError("criterion must be 'aic' or 'bic'")
181        options = options or {}
182
183        if distributions is None:
184            # Never mix count and continuous models: their likelihoods
185            # (probabilities vs densities) are not comparable by AIC/BIC.
186            pool = (
187                sorted(_COUNT)
188                if _is_count_data(self.x)
189                else [d for d in SUPPORTED if d not in _COUNT]
190            )
191            candidates = [d for d in pool if _supports(d, self.x)]
192        else:
193            candidates = list(distributions)
194        if not candidates:
195            raise ValueError("no candidate distributions to fit")
196
197        labels = []
198        for d in candidates:
199            if isinstance(d, str):
200                key = _ALIASES.get(d.strip().lower(), d.strip().lower())
201                labels.append(key)
202            else:
203                labels.append(getattr(d, "name", str(d)))
204
205        bar = _Progress(len(candidates), progress)
206        self.failures = {}
207        fitted = {}
208        try:
209            for d, lab in zip(candidates, labels):
210                if (
211                    isinstance(d, str)
212                    and lab in _DISTS
213                    and not _supports(lab, self.x)
214                ):
215                    self.failures[lab] = (
216                        "data outside the distribution's support"
217                    )
218                else:
219                    try:
220                        with warnings.catch_warnings():
221                            warnings.simplefilter("ignore")
222                            f = _SingleFit(self.x, d, **options.get(lab, {}))
223                        if not np.isfinite(f.loglik):
224                            raise RuntimeError("non-finite log-likelihood")
225                        fitted[lab] = f
226                        if verbose >= 2:
227                            crit = getattr(f, criterion)
228                            flag = "" if f.converged else "   (not converged)"
229                            self._say(
230                                f"  {lab:<20} loglik = {f.loglik:12.4f}   "
231                                f"{criterion.upper()} = {crit:12.4f}{flag}",
232                                bar,
233                            )
234                    except Exception as e:  # keep going, record why
235                        self.failures[lab] = f"{type(e).__name__}: {e}"
236                        if verbose >= 2:
237                            self._say(
238                                f"  {lab:<20} failed: {self.failures[lab]}", bar
239                            )
240                bar.update(lab)
241        finally:
242            bar.close()
243
244        if not fitted:
245            raise RuntimeError(f"every fit failed: {self.failures}")
246
247        self.fits.update(fitted)
248        self.criterion = criterion
249        self.table = self._rank(fitted, criterion)
250        best = min(fitted, key=lambda k: getattr(fitted[k], criterion))
251        self.result = fitted[best]
252
253        if verbose >= 1:
254            print(self._format_table())
255            if self.failures:
256                print(
257                    "Skipped / failed: "
258                    + "; ".join(f"{k} ({v})" for k, v in self.failures.items())
259                )
260            print(f"Best by {criterion.upper()}: {best}")
261        return self
262
263    @staticmethod
264    def _say(msg, bar):
265        if bar.bar is not None:
266            bar.bar.write(msg)
267        else:
268            print("\r" + msg if bar.enabled else msg)
269
270    @staticmethod
271    def _rank(fitted, criterion):
272        rows = []
273        for lab, f in fitted.items():
274            g = f.gof()
275            rows.append(
276                {
277                    "distribution": lab,
278                    "k": f.k,
279                    "loglik": f.loglik,
280                    "aic": f.aic,
281                    "bic": f.bic,
282                    "ks": g.get("ks"),
283                    "converged": f.converged,
284                }
285            )
286        rows.sort(key=lambda r: r[criterion])
287        best = rows[0][criterion]
288        w = np.array([np.exp(-0.5 * (r[criterion] - best)) for r in rows])
289        w /= w.sum()
290        for r, wi in zip(rows, w):
291            r["delta"] = r[criterion] - best
292            r["weight"] = float(wi)
293        cols = [
294            "distribution",
295            "k",
296            "loglik",
297            "aic",
298            "bic",
299            "delta",
300            "weight",
301            "ks",
302            "converged",
303        ]
304        rows = [{c: r[c] for c in cols} for r in rows]
305        try:
306            import pandas as pd
307
308            return pd.DataFrame(rows).set_index("distribution")
309        except ImportError:
310            return rows
311
312    def _format_table(self):
313        rows = (
314            self.table.reset_index().to_dict("records")
315            if hasattr(self.table, "reset_index")
316            else self.table
317        )
318        head = (
319            f"{'distribution':<20}{'k':>3}{'loglik':>12}{'AIC':>12}{'BIC':>12}"
320            f"{'delta':>10}{'weight':>9}"
321        )
322        out = [head, "-" * len(head)]
323        for r in rows:
324            out.append(
325                f"{r['distribution']:<20}{r['k']:>3}{r['loglik']:>12.3f}"
326                f"{r['aic']:>12.3f}{r['bic']:>12.3f}{r['delta']:>10.3f}"
327                f"{r['weight']:>9.3f}{'' if r['converged'] else '  *'}"
328            )
329        if any(not r["converged"] for r in rows):
330            out.append("* optimizer did not report convergence")
331        return "\n".join(out)
332
333    # ------------------------------------------------------------- results
334    @property
335    def best_dist(self):
336        """Name of the chosen distribution (None before fitting)."""
337        return None if self.result is None else self.result.name
338
339    def simulate(self, size=None, seed=None, dist=None):
340        """Simulate from the fitted distribution.
341
342        Parameters
343        ----------
344        size : int or tuple of ints, optional
345            Output shape; None returns a single draw.
346        seed : int, numpy.random.Generator or None
347            For reproducible draws.
348        dist : str, optional
349            Label of another stored fit (see ``self.fits``); default is the
350            chosen one (``best_dist``).
351
352        Example
353        -------
354        >>> si = StatsInference(x).select(verbose=0)
355        >>> sims = si.simulate(1000, seed=123)
356        """
357        if dist is None:
358            if self.result is None:
359                raise AttributeError("call fit() or select() before simulate()")
360            f = self.result
361        else:
362            key = (
363                _ALIASES.get(dist.strip().lower(), dist.strip().lower())
364                if dist not in self.fits
365                else dist
366            )
367            if key not in self.fits:
368                raise KeyError(
369                    f"no fit named '{dist}'; available: {list(self.fits)}"
370                )
371            f = self.fits[key]
372        return f.simulate(size=size, seed=seed)
373
374    def __getattr__(self, name):
375        # Delegate estimate, sd, aic, summary(), plot(), ... to the chosen fit.
376        result = self.__dict__.get("result")
377        if result is None:
378            raise AttributeError(
379                f"'{name}' is not available yet: call fit() or select() first"
380            )
381        return getattr(result, name)
382
383    def compare(self, labels=None, sort_by=None):
384        """GOF table (loglik, AIC, BIC, KS, CvM, AD) for the given fits."""
385        labels = labels or list(self.fits)
386        return _compare_table(
387            [self.fits[k] for k in labels],
388            labels,
389            sort_by=sort_by or self.criterion or "aic",
390        )
391
392    def plot_compare(self, labels=None, top=None, **kwargs):
393        """Overlay several fits on the four diagnostic panels.
394
395        By default the ``top`` best (3 if ``select()`` was run) are shown.
396        """
397        if labels is None:
398            if self.table is not None:
399                order = (
400                    list(self.table.index)
401                    if hasattr(self.table, "index")
402                    else [r["distribution"] for r in self.table]
403                )
404                labels = order[: top or 3]
405            else:
406                labels = list(self.fits)[:top] if top else list(self.fits)
407        return _plot_fits(
408            [self.fits[k] for k in labels], labels=labels, **kwargs
409        )
410
411    def __repr__(self):
412        if self.result is None:
413            return f"<StatsInference n={self.x.size}, not fitted>"
414        return f"<StatsInference n={self.x.size}, {self.result!r}>"

Fit univariate distributions to data by maximum likelihood.

Parameters

x : array-like Non-empty numeric vector with no NaN or infinite values. densfun : optional If given, fit it straight away (same as StatsInference(x).fit(densfun)). **fit_kwargs Passed on to fit().

After fit() or select(), the chosen fit's results are available directly on the object: estimate, sd, vcov, loglik, aic, bic, n, converged, dist (the fitted scipy distribution), and the methods summary(), gof(), plot(), denscomp(), cdfcomp(), qqcomp(), ppcomp().

StatsInference(x, densfun=None, **fit_kwargs)
 86    def __init__(self, x, densfun=None, **fit_kwargs):
 87        x = np.asarray(x)
 88        if x.size == 0 or not np.issubdtype(x.dtype, np.number):
 89            raise ValueError("'x' must be a non-empty numeric vector")
 90        x = x.astype(float).ravel()
 91        if not np.all(np.isfinite(x)):
 92            raise ValueError("'x' contains missing or infinite values")
 93        self.x = x
 94        self.result = None  # the chosen fit
 95        self.fits = {}  # label -> fit, for every successful fit
 96        self.failures = {}  # label -> error message
 97        self.table = None  # ranking from select()
 98        self.criterion = None
 99        if densfun is not None:
100            self.fit(densfun, **fit_kwargs)
x
result
fits
failures
table
criterion
def fit( self, densfun, start=None, fixed=None, lower=None, upper=None, method='L-BFGS-B', cdf=None, discrete=None, label=None):
103    def fit(
104        self,
105        densfun,
106        start=None,
107        fixed=None,
108        lower=None,
109        upper=None,
110        method="L-BFGS-B",
111        cdf=None,
112        discrete=None,
113        label=None,
114    ):
115        """Fit one distribution; it becomes the current result.
116
117        ``densfun`` is a supported name (see ``SUPPORTED``), a scipy
118        distribution such as ``scipy.stats.gamma``, or a density function
119        ``f(x, **params[, log=])`` (then ``start`` is required).
120
121        start, fixed, lower, upper : dict, optional
122            Keyed by parameter name. ``fixed`` holds parameters that are not
123            estimated (R's ``...``). Not allowed: ``start`` for "normal",
124            which is fitted in closed form.
125        method : any ``scipy.optimize.minimize`` method.
126        cdf, discrete : only for a density function (numeric CDF otherwise).
127        label : name under which the fit is stored in ``self.fits``.
128        """
129        f = _SingleFit(
130            self.x,
131            densfun,
132            start=start,
133            fixed=fixed,
134            lower=lower,
135            upper=upper,
136            method=method,
137            cdf=cdf,
138            discrete=discrete,
139        )
140        self.fits[label or f.name] = f
141        self.result = f
142        return self

Fit one distribution; it becomes the current result.

densfun is a supported name (see SUPPORTED), a scipy distribution such as scipy.stats.gamma, or a density function f(x, **params[, log=]) (then start is required).

start, fixed, lower, upper : dict, optional Keyed by parameter name. fixed holds parameters that are not estimated (R's ...). Not allowed: start for "normal", which is fitted in closed form. method : any scipy.optimize.minimize method. cdf, discrete : only for a density function (numeric CDF otherwise). label : name under which the fit is stored in self.fits.

def select( self, distributions=None, criterion='aic', verbose=1, progress=True, options=None):
144    def select(
145        self,
146        distributions=None,
147        criterion="aic",
148        verbose=1,
149        progress=True,
150        options=None,
151    ):
152        """Fit several distributions and keep the best by AIC or BIC.
153
154        Parameters
155        ----------
156        distributions : list, optional
157            Names from ``SUPPORTED`` and/or scipy distribution objects.
158            Default: every named distribution whose support fits the data
159            (count distributions for non-negative integers, otherwise the
160            continuous ones; positive-only and (0, 1) ones only when the
161            data allow them).
162        criterion : {"aic", "bic"}
163        verbose : int
164            0 = silent, 1 = print the ranking at the end,
165            2 = also print each fit (or failure) as it happens.
166        progress : bool
167            Show a progress bar (tqdm if installed, else a counter).
168        options : dict, optional
169            Per-distribution keyword arguments for :meth:`fit`, keyed by
170            label, e.g. ``{"t": {"fixed": {"df": 5}}}``.
171
172        Returns
173        -------
174        self, with ``result`` set to the best fit, ``table`` holding the
175        ranking (criterion, delta, Akaike/Schwarz weights) and ``fits``
176        holding every successful fit.
177        """
178        criterion = criterion.lower()
179        if criterion not in ("aic", "bic"):
180            raise ValueError("criterion must be 'aic' or 'bic'")
181        options = options or {}
182
183        if distributions is None:
184            # Never mix count and continuous models: their likelihoods
185            # (probabilities vs densities) are not comparable by AIC/BIC.
186            pool = (
187                sorted(_COUNT)
188                if _is_count_data(self.x)
189                else [d for d in SUPPORTED if d not in _COUNT]
190            )
191            candidates = [d for d in pool if _supports(d, self.x)]
192        else:
193            candidates = list(distributions)
194        if not candidates:
195            raise ValueError("no candidate distributions to fit")
196
197        labels = []
198        for d in candidates:
199            if isinstance(d, str):
200                key = _ALIASES.get(d.strip().lower(), d.strip().lower())
201                labels.append(key)
202            else:
203                labels.append(getattr(d, "name", str(d)))
204
205        bar = _Progress(len(candidates), progress)
206        self.failures = {}
207        fitted = {}
208        try:
209            for d, lab in zip(candidates, labels):
210                if (
211                    isinstance(d, str)
212                    and lab in _DISTS
213                    and not _supports(lab, self.x)
214                ):
215                    self.failures[lab] = (
216                        "data outside the distribution's support"
217                    )
218                else:
219                    try:
220                        with warnings.catch_warnings():
221                            warnings.simplefilter("ignore")
222                            f = _SingleFit(self.x, d, **options.get(lab, {}))
223                        if not np.isfinite(f.loglik):
224                            raise RuntimeError("non-finite log-likelihood")
225                        fitted[lab] = f
226                        if verbose >= 2:
227                            crit = getattr(f, criterion)
228                            flag = "" if f.converged else "   (not converged)"
229                            self._say(
230                                f"  {lab:<20} loglik = {f.loglik:12.4f}   "
231                                f"{criterion.upper()} = {crit:12.4f}{flag}",
232                                bar,
233                            )
234                    except Exception as e:  # keep going, record why
235                        self.failures[lab] = f"{type(e).__name__}: {e}"
236                        if verbose >= 2:
237                            self._say(
238                                f"  {lab:<20} failed: {self.failures[lab]}", bar
239                            )
240                bar.update(lab)
241        finally:
242            bar.close()
243
244        if not fitted:
245            raise RuntimeError(f"every fit failed: {self.failures}")
246
247        self.fits.update(fitted)
248        self.criterion = criterion
249        self.table = self._rank(fitted, criterion)
250        best = min(fitted, key=lambda k: getattr(fitted[k], criterion))
251        self.result = fitted[best]
252
253        if verbose >= 1:
254            print(self._format_table())
255            if self.failures:
256                print(
257                    "Skipped / failed: "
258                    + "; ".join(f"{k} ({v})" for k, v in self.failures.items())
259                )
260            print(f"Best by {criterion.upper()}: {best}")
261        return self

Fit several distributions and keep the best by AIC or BIC.

Parameters

distributions : list, optional Names from SUPPORTED and/or scipy distribution objects. Default: every named distribution whose support fits the data (count distributions for non-negative integers, otherwise the continuous ones; positive-only and (0, 1) ones only when the data allow them). criterion : {"aic", "bic"} verbose : int 0 = silent, 1 = print the ranking at the end, 2 = also print each fit (or failure) as it happens. progress : bool Show a progress bar (tqdm if installed, else a counter). options : dict, optional Per-distribution keyword arguments for fit(), keyed by label, e.g. {"t": {"fixed": {"df": 5}}}.

Returns

self, with result set to the best fit, table holding the ranking (criterion, delta, Akaike/Schwarz weights) and fits holding every successful fit.

best_dist
334    @property
335    def best_dist(self):
336        """Name of the chosen distribution (None before fitting)."""
337        return None if self.result is None else self.result.name

Name of the chosen distribution (None before fitting).

def simulate(self, size=None, seed=None, dist=None):
339    def simulate(self, size=None, seed=None, dist=None):
340        """Simulate from the fitted distribution.
341
342        Parameters
343        ----------
344        size : int or tuple of ints, optional
345            Output shape; None returns a single draw.
346        seed : int, numpy.random.Generator or None
347            For reproducible draws.
348        dist : str, optional
349            Label of another stored fit (see ``self.fits``); default is the
350            chosen one (``best_dist``).
351
352        Example
353        -------
354        >>> si = StatsInference(x).select(verbose=0)
355        >>> sims = si.simulate(1000, seed=123)
356        """
357        if dist is None:
358            if self.result is None:
359                raise AttributeError("call fit() or select() before simulate()")
360            f = self.result
361        else:
362            key = (
363                _ALIASES.get(dist.strip().lower(), dist.strip().lower())
364                if dist not in self.fits
365                else dist
366            )
367            if key not in self.fits:
368                raise KeyError(
369                    f"no fit named '{dist}'; available: {list(self.fits)}"
370                )
371            f = self.fits[key]
372        return f.simulate(size=size, seed=seed)

Simulate from the fitted distribution.

Parameters

size : int or tuple of ints, optional Output shape; None returns a single draw. seed : int, numpy.random.Generator or None For reproducible draws. dist : str, optional Label of another stored fit (see self.fits); default is the chosen one (best_dist).

Example

>>> si = StatsInference(x).select(verbose=0)
>>> sims = si.simulate(1000, seed=123)
def compare(self, labels=None, sort_by=None):
383    def compare(self, labels=None, sort_by=None):
384        """GOF table (loglik, AIC, BIC, KS, CvM, AD) for the given fits."""
385        labels = labels or list(self.fits)
386        return _compare_table(
387            [self.fits[k] for k in labels],
388            labels,
389            sort_by=sort_by or self.criterion or "aic",
390        )

GOF table (loglik, AIC, BIC, KS, CvM, AD) for the given fits.

def plot_compare(self, labels=None, top=None, **kwargs):
392    def plot_compare(self, labels=None, top=None, **kwargs):
393        """Overlay several fits on the four diagnostic panels.
394
395        By default the ``top`` best (3 if ``select()`` was run) are shown.
396        """
397        if labels is None:
398            if self.table is not None:
399                order = (
400                    list(self.table.index)
401                    if hasattr(self.table, "index")
402                    else [r["distribution"] for r in self.table]
403                )
404                labels = order[: top or 3]
405            else:
406                labels = list(self.fits)[:top] if top else list(self.fits)
407        return _plot_fits(
408            [self.fits[k] for k in labels], labels=labels, **kwargs
409        )

Overlay several fits on the four diagnostic panels.

By default the top best (3 if select() was run) are shown.

SUPPORTED = ('beta', 'cauchy', 'chi-squared', 'exponential', 'f', 'gamma', 'geometric', 'logistic', 'lognormal', 'negative binomial', 'normal', 'poisson', 't', 'weibull')