Participer au site avec un Tip
Rechercher
 

Améliorations / Corrections

Vous avez des améliorations (ou des corrections) à proposer pour ce document : je vous remerçie par avance de m'en faire part, cela m'aide à améliorer le site.

Emplacement :

Description des améliorations :

Vous êtes un professionnel et vous avez besoin d'une formation ? Machine Learning
avec Scikit-Learn
Voir le programme détaillé
Module « scipy.stats »

Classe « rv_discrete »

Informations générales

Héritage

builtins.object
    rv_generic
        rv_discrete

Définition

class rv_discrete(rv_generic):

help(rv_discrete)

A generic discrete random variable class meant for subclassing.

`rv_discrete` is a base class to construct specific distribution classes
and instances for discrete random variables. It can also be used
to construct an arbitrary distribution defined by a list of support
points and corresponding probabilities.

Parameters
----------
a : float, optional
    Lower bound of the support of the distribution, default: 0
b : float, optional
    Upper bound of the support of the distribution, default: plus infinity
moment_tol : float, optional
    The tolerance for the generic calculation of moments.
values : tuple of two array_like, optional
    ``(xk, pk)`` where ``xk`` are integers and ``pk`` are the non-zero
    probabilities between 0 and 1 with ``sum(pk) = 1``. ``xk``
    and ``pk`` must have the same shape, and ``xk`` must be unique.
inc : integer, optional
    Increment for the support of the distribution.
    Default is 1. (other values have not been tested)
badvalue : float, optional
    The value in a result arrays that indicates a value that for which
    some argument restriction is violated, default is np.nan.
name : str, optional
    The name of the instance. This string is used to construct the default
    example for distributions.
longname : str, optional
    This string is used as part of the first line of the docstring returned
    when a subclass has no docstring of its own. Note: `longname` exists
    for backwards compatibility, do not use for new subclasses.
shapes : str, optional
    The shape of the distribution. For example "m, n" for a distribution
    that takes two integers as the two shape arguments for all its methods
    If not provided, shape parameters will be inferred from
    the signatures of the private methods, ``_pmf`` and ``_cdf`` of
    the instance.
seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
    If `seed` is None (or `np.random`), the `numpy.random.RandomState`
    singleton is used.
    If `seed` is an int, a new ``RandomState`` instance is used,
    seeded with `seed`.
    If `seed` is already a ``Generator`` or ``RandomState`` instance then
    that instance is used.

Methods
-------
rvs
pmf
logpmf
cdf
logcdf
sf
logsf
ppf
isf
moment
stats
entropy
expect
median
mean
std
var
interval
__call__
support

Notes
-----
This class is similar to `rv_continuous`. Whether a shape parameter is
valid is decided by an ``_argcheck`` method (which defaults to checking
that its arguments are strictly positive.)
The main differences are as follows.

- The support of the distribution is a set of integers.
- Instead of the probability density function, ``pdf`` (and the
  corresponding private ``_pdf``), this class defines the
  *probability mass function*, `pmf` (and the corresponding
  private ``_pmf``.)
- There is no ``scale`` parameter.
- The default implementations of methods (e.g. ``_cdf``) are not designed
  for distributions with support that is unbounded below (i.e.
  ``a=-np.inf``), so they must be overridden.

To create a new discrete distribution, we would do the following:

>>> from scipy.stats import rv_discrete
>>> class poisson_gen(rv_discrete):
...     "Poisson distribution"
...     def _pmf(self, k, mu):
...         return exp(-mu) * mu**k / factorial(k)

and create an instance::

>>> poisson = poisson_gen(name="poisson")

Note that above we defined the Poisson distribution in the standard form.
Shifting the distribution can be done by providing the ``loc`` parameter
to the methods of the instance. For example, ``poisson.pmf(x, mu, loc)``
delegates the work to ``poisson._pmf(x-loc, mu)``.

**Discrete distributions from a list of probabilities**

Alternatively, you can construct an arbitrary discrete rv defined
on a finite set of values ``xk`` with ``Prob{X=xk} = pk`` by using the
``values`` keyword argument to the `rv_discrete` constructor.

**Deepcopying / Pickling**

If a distribution or frozen distribution is deepcopied (pickled/unpickled,
etc.), any underlying random number generator is deepcopied with it. An
implication is that if a distribution relies on the singleton RandomState
before copying, it will rely on a copy of that random state after copying,
and ``np.random.seed`` will no longer control the state.

Examples
--------
Custom made discrete distribution:

>>> import numpy as np
>>> from scipy import stats
>>> xk = np.arange(7)
>>> pk = (0.1, 0.2, 0.3, 0.1, 0.1, 0.0, 0.2)
>>> custm = stats.rv_discrete(name='custm', values=(xk, pk))
>>>
>>> import matplotlib.pyplot as plt
>>> fig, ax = plt.subplots(1, 1)
>>> ax.plot(xk, custm.pmf(xk), 'ro', ms=12, mec='r')
>>> ax.vlines(xk, 0, custm.pmf(xk), colors='r', lw=4)
>>> plt.show()

Random number generation:

>>> R = custm.rvs(size=100)

Constructeur(s)

Signature du constructeur Description
__new__(cls, a=0, b=inf, name=None, badvalue=None, moment_tol=1e-08, values=None, inc=1, longname=None, shapes=None, seed=None)
__init__(self, a=0, b=inf, name=None, badvalue=None, moment_tol=1e-08, values=None, inc=1, longname=None, shapes=None, seed=None)

Liste des propriétés

Nom de la propriétéDescription
random_stateGet or set the generator object for generating random variates. [extrait de random_state.__doc__]

Liste des opérateurs

Opérateurs hérités de la classe object

__eq__, __ge__, __gt__, __le__, __lt__, __ne__

Liste des méthodes

Toutes les méthodes Méthodes d'instance Méthodes statiques Méthodes dépréciées
Signature de la méthodeDescription
__getstate__(self)
cdf(self, k, *args, **kwds) Cumulative distribution function of the given RV. [extrait de cdf.__doc__]
expect(self, func=None, args=(), loc=0, lb=None, ub=None, conditional=False, maxcount=1000, tolerance=1e-10, chunksize=32)
isf(self, q, *args, **kwds) Inverse survival function (inverse of `sf`) at q of the given RV. [extrait de isf.__doc__]
logcdf(self, k, *args, **kwds) Log of the cumulative distribution function at k of the given RV. [extrait de logcdf.__doc__]
logpmf(self, k, *args, **kwds) Log of the probability mass function at k of the given RV. [extrait de logpmf.__doc__]
logsf(self, k, *args, **kwds) Log of the survival function of the given RV. [extrait de logsf.__doc__]
pmf(self, k, *args, **kwds) Probability mass function at k of the given RV. [extrait de pmf.__doc__]
ppf(self, q, *args, **kwds) Percent point function (inverse of `cdf`) at q of the given RV. [extrait de ppf.__doc__]
rvs(self, *args, **kwargs) Random variates of given type. [extrait de rvs.__doc__]
sf(self, k, *args, **kwds) Survival function (1 - `cdf`) at k of the given RV. [extrait de sf.__doc__]

Méthodes héritées de la classe rv_generic

__call__, __init_subclass__, __setstate__, __subclasshook__, entropy, freeze, interval, mean, median, moment, nnlf, stats, std, support, var

Méthodes héritées de la classe object

__delattr__, __dir__, __format__, __getattribute__, __hash__, __reduce__, __reduce_ex__, __repr__, __setattr__, __sizeof__, __str__

Vous êtes un professionnel et vous avez besoin d'une formation ? RAG (Retrieval-Augmented Generation)
et Fine Tuning d'un LLM
Voir le programme détaillé