U
    -e                     @   s   d Z ddlZddlmZ ddlZddlmZmZm	Z	 ddl
mZ ddlmZmZ dd	lmZmZ dd
lmZmZmZmZmZmZ dd Zdd ZG dd deZdS )z Bayesian Gaussian Mixture Model.    N)Real)betalndigammagammaln   )check_array)Interval
StrOptions   )BaseMixture_check_shape)_check_precision_matrix_check_precision_positivity_compute_log_det_cholesky_compute_precision_cholesky_estimate_gaussian_parameters_estimate_log_gaussian_probc                 C   s   t t| tt |  S )aV  Compute the log of the Dirichlet distribution normalization term.

    Parameters
    ----------
    dirichlet_concentration : array-like of shape (n_samples,)
        The parameters values of the Dirichlet distribution.

    Returns
    -------
    log_dirichlet_norm : float
        The log normalization of the Dirichlet distribution.
    )r   npsum)Zdirichlet_concentration r   b/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/sklearn/mixture/_bayesian_mixture.py_log_dirichlet_norm   s    r   c              	   C   sL   | | | | d t d  ttd| t|ddtjf   d  S )aD  Compute the log of the Wishart distribution normalization term.

    Parameters
    ----------
    degrees_of_freedom : array-like of shape (n_components,)
        The number of degrees of freedom on the covariance Wishart
        distributions.

    log_det_precision_chol : array-like of shape (n_components,)
         The determinant of the precision matrix for each component.

    n_features : int
        The number of features.

    Return
    ------
    log_wishart_norm : array-like of shape (n_components,)
        The log normalization of the Wishart distribution.
          ?       @Nr   )mathlogr   r   r   arangenewaxis)Zdegrees_of_freedomlog_det_precisions_chol
n_featuresr   r   r   _log_wishart_norm+   s    "r    c                       s`  e Zd ZU dZejeddddhgeddhgdeed	dd
dgdeed	dd
dgddgdeed	dd
dgddeed	dd
dgdZe	e
d< dddddddddddddddddd fdd
Zdd Zdd Zdd Zd d! Zd"d# Zd$d% Zd&d' Zd(d) Zd*d+ Zd,d- Zd.d/ Zd0d1 Zd2d3 Zd4d5 Zd6d7 Zd8d9 Zd:d; Zd<d= Zd>d? Z  ZS )@BayesianGaussianMixturea)/  Variational Bayesian estimation of a Gaussian mixture.

    This class allows to infer an approximate posterior distribution over the
    parameters of a Gaussian mixture distribution. The effective number of
    components can be inferred from the data.

    This class implements two types of prior for the weights distribution: a
    finite mixture model with Dirichlet distribution and an infinite mixture
    model with the Dirichlet Process. In practice Dirichlet Process inference
    algorithm is approximated and uses a truncated distribution with a fixed
    maximum number of components (called the Stick-breaking representation).
    The number of components actually used almost always depends on the data.

    .. versionadded:: 0.18

    Read more in the :ref:`User Guide <bgmm>`.

    Parameters
    ----------
    n_components : int, default=1
        The number of mixture components. Depending on the data and the value
        of the `weight_concentration_prior` the model can decide to not use
        all the components by setting some component `weights_` to values very
        close to zero. The number of effective components is therefore smaller
        than n_components.

    covariance_type : {'full', 'tied', 'diag', 'spherical'}, default='full'
        String describing the type of covariance parameters to use.
        Must be one of::

            'full' (each component has its own general covariance matrix),
            'tied' (all components share the same general covariance matrix),
            'diag' (each component has its own diagonal covariance matrix),
            'spherical' (each component has its own single variance).

    tol : float, default=1e-3
        The convergence threshold. EM iterations will stop when the
        lower bound average gain on the likelihood (of the training data with
        respect to the model) is below this threshold.

    reg_covar : float, default=1e-6
        Non-negative regularization added to the diagonal of covariance.
        Allows to assure that the covariance matrices are all positive.

    max_iter : int, default=100
        The number of EM iterations to perform.

    n_init : int, default=1
        The number of initializations to perform. The result with the highest
        lower bound value on the likelihood is kept.

    init_params : {'kmeans', 'k-means++', 'random', 'random_from_data'},     default='kmeans'
        The method used to initialize the weights, the means and the
        covariances.
        String must be one of:

            'kmeans' : responsibilities are initialized using kmeans.
            'k-means++' : use the k-means++ method to initialize.
            'random' : responsibilities are initialized randomly.
            'random_from_data' : initial means are randomly selected data points.

        .. versionchanged:: v1.1
            `init_params` now accepts 'random_from_data' and 'k-means++' as
            initialization methods.

    weight_concentration_prior_type : {'dirichlet_process', 'dirichlet_distribution'},             default='dirichlet_process'
        String describing the type of the weight concentration prior.

    weight_concentration_prior : float or None, default=None
        The dirichlet concentration of each component on the weight
        distribution (Dirichlet). This is commonly called gamma in the
        literature. The higher concentration puts more mass in
        the center and will lead to more components being active, while a lower
        concentration parameter will lead to more mass at the edge of the
        mixture weights simplex. The value of the parameter must be greater
        than 0. If it is None, it's set to ``1. / n_components``.

    mean_precision_prior : float or None, default=None
        The precision prior on the mean distribution (Gaussian).
        Controls the extent of where means can be placed. Larger
        values concentrate the cluster means around `mean_prior`.
        The value of the parameter must be greater than 0.
        If it is None, it is set to 1.

    mean_prior : array-like, shape (n_features,), default=None
        The prior on the mean distribution (Gaussian).
        If it is None, it is set to the mean of X.

    degrees_of_freedom_prior : float or None, default=None
        The prior of the number of degrees of freedom on the covariance
        distributions (Wishart). If it is None, it's set to `n_features`.

    covariance_prior : float or array-like, default=None
        The prior on the covariance distribution (Wishart).
        If it is None, the emiprical covariance prior is initialized using the
        covariance of X. The shape depends on `covariance_type`::

                (n_features, n_features) if 'full',
                (n_features, n_features) if 'tied',
                (n_features)             if 'diag',
                float                    if 'spherical'

    random_state : int, RandomState instance or None, default=None
        Controls the random seed given to the method chosen to initialize the
        parameters (see `init_params`).
        In addition, it controls the generation of random samples from the
        fitted distribution (see the method `sample`).
        Pass an int for reproducible output across multiple function calls.
        See :term:`Glossary <random_state>`.

    warm_start : bool, default=False
        If 'warm_start' is True, the solution of the last fitting is used as
        initialization for the next call of fit(). This can speed up
        convergence when fit is called several times on similar problems.
        See :term:`the Glossary <warm_start>`.

    verbose : int, default=0
        Enable verbose output. If 1 then it prints the current
        initialization and each iteration step. If greater than 1 then
        it prints also the log probability and the time needed
        for each step.

    verbose_interval : int, default=10
        Number of iteration done before the next print.

    Attributes
    ----------
    weights_ : array-like of shape (n_components,)
        The weights of each mixture components.

    means_ : array-like of shape (n_components, n_features)
        The mean of each mixture component.

    covariances_ : array-like
        The covariance of each mixture component.
        The shape depends on `covariance_type`::

            (n_components,)                        if 'spherical',
            (n_features, n_features)               if 'tied',
            (n_components, n_features)             if 'diag',
            (n_components, n_features, n_features) if 'full'

    precisions_ : array-like
        The precision matrices for each component in the mixture. A precision
        matrix is the inverse of a covariance matrix. A covariance matrix is
        symmetric positive definite so the mixture of Gaussian can be
        equivalently parameterized by the precision matrices. Storing the
        precision matrices instead of the covariance matrices makes it more
        efficient to compute the log-likelihood of new samples at test time.
        The shape depends on ``covariance_type``::

            (n_components,)                        if 'spherical',
            (n_features, n_features)               if 'tied',
            (n_components, n_features)             if 'diag',
            (n_components, n_features, n_features) if 'full'

    precisions_cholesky_ : array-like
        The cholesky decomposition of the precision matrices of each mixture
        component. A precision matrix is the inverse of a covariance matrix.
        A covariance matrix is symmetric positive definite so the mixture of
        Gaussian can be equivalently parameterized by the precision matrices.
        Storing the precision matrices instead of the covariance matrices makes
        it more efficient to compute the log-likelihood of new samples at test
        time. The shape depends on ``covariance_type``::

            (n_components,)                        if 'spherical',
            (n_features, n_features)               if 'tied',
            (n_components, n_features)             if 'diag',
            (n_components, n_features, n_features) if 'full'

    converged_ : bool
        True when convergence was reached in fit(), False otherwise.

    n_iter_ : int
        Number of step used by the best fit of inference to reach the
        convergence.

    lower_bound_ : float
        Lower bound value on the model evidence (of the training data) of the
        best fit of inference.

    weight_concentration_prior_ : tuple or float
        The dirichlet concentration of each component on the weight
        distribution (Dirichlet). The type depends on
        ``weight_concentration_prior_type``::

            (float, float) if 'dirichlet_process' (Beta parameters),
            float          if 'dirichlet_distribution' (Dirichlet parameters).

        The higher concentration puts more mass in
        the center and will lead to more components being active, while a lower
        concentration parameter will lead to more mass at the edge of the
        simplex.

    weight_concentration_ : array-like of shape (n_components,)
        The dirichlet concentration of each component on the weight
        distribution (Dirichlet).

    mean_precision_prior_ : float
        The precision prior on the mean distribution (Gaussian).
        Controls the extent of where means can be placed.
        Larger values concentrate the cluster means around `mean_prior`.
        If mean_precision_prior is set to None, `mean_precision_prior_` is set
        to 1.

    mean_precision_ : array-like of shape (n_components,)
        The precision of each components on the mean distribution (Gaussian).

    mean_prior_ : array-like of shape (n_features,)
        The prior on the mean distribution (Gaussian).

    degrees_of_freedom_prior_ : float
        The prior of the number of degrees of freedom on the covariance
        distributions (Wishart).

    degrees_of_freedom_ : array-like of shape (n_components,)
        The number of degrees of freedom of each components in the model.

    covariance_prior_ : float or array-like
        The prior on the covariance distribution (Wishart).
        The shape depends on `covariance_type`::

            (n_features, n_features) if 'full',
            (n_features, n_features) if 'tied',
            (n_features)             if 'diag',
            float                    if 'spherical'

    n_features_in_ : int
        Number of features seen during :term:`fit`.

        .. versionadded:: 0.24

    feature_names_in_ : ndarray of shape (`n_features_in_`,)
        Names of features seen during :term:`fit`. Defined only when `X`
        has feature names that are all strings.

        .. versionadded:: 1.0

    See Also
    --------
    GaussianMixture : Finite Gaussian mixture fit with EM.

    References
    ----------

    .. [1] `Bishop, Christopher M. (2006). "Pattern recognition and machine
       learning". Vol. 4 No. 4. New York: Springer.
       <https://www.springer.com/kr/book/9780387310732>`_

    .. [2] `Hagai Attias. (2000). "A Variational Bayesian Framework for
       Graphical Models". In Advances in Neural Information Processing
       Systems 12.
       <https://citeseerx.ist.psu.edu/doc_view/pid/ee844fd96db7041a9681b5a18bff008912052c7e>`_

    .. [3] `Blei, David M. and Michael I. Jordan. (2006). "Variational
       inference for Dirichlet process mixtures". Bayesian analysis 1.1
       <https://www.cs.princeton.edu/courses/archive/fall11/cos597C/reading/BleiJordan2005.pdf>`_

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.mixture import BayesianGaussianMixture
    >>> X = np.array([[1, 2], [1, 4], [1, 0], [4, 2], [12, 4], [10, 7]])
    >>> bgm = BayesianGaussianMixture(n_components=2, random_state=42).fit(X)
    >>> bgm.means_
    array([[2.49... , 2.29...],
           [8.45..., 4.52... ]])
    >>> bgm.predict([[0, 0], [9, 3]])
    array([0, 1])
    	sphericaltieddiagfulldirichlet_processZdirichlet_distributionNg        Zneither)closedz
array-like)covariance_typeweight_concentration_prior_typeweight_concentration_priormean_precision_prior
mean_priordegrees_of_freedom_priorcovariance_prior_parameter_constraintsr
   gMbP?gư>d   ZkmeansFr   
   )n_componentsr(   tol	reg_covarmax_itern_initinit_paramsr)   r*   r+   r,   r-   r.   random_state
warm_startverboseverbose_intervalc                   sN   t  j||||||||||d
 || _|| _|	| _|
| _|| _|| _|| _d S )N)
r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   )	super__init__r(   r)   r*   r+   r,   r-   r.   )selfr2   r(   r3   r4   r5   r6   r7   r)   r*   r+   r,   r-   r.   r8   r9   r:   r;   	__class__r   r   r=   p  s&    z BayesianGaussianMixture.__init__c                 C   s*   |    | | | | | | dS )zCheck that the parameters are well defined.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
        N)_check_weights_parameters_check_means_parameters_check_precision_parameters _checkcovariance_prior_parameter)r>   Xr   r   r   _check_parameters  s    

z)BayesianGaussianMixture._check_parametersc                 C   s$   | j dkrd| j | _n| j | _dS )z2Check the parameter of the Dirichlet distribution.N      ?)r*   r2   weight_concentration_prior_r>   r   r   r   rA     s    
z1BayesianGaussianMixture._check_weights_parametersc                 C   sl   |j \}}| jdkrd| _n| j| _| jdkr>|jdd| _n*t| jtjtj	gdd| _t
| j|fd dS )zCheck the parameters of the Gaussian distribution.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
        NrG   r   )axisFZdtypeZ	ensure_2dZmeans)shaper+   mean_precision_prior_r,   meanmean_prior_r   r   float64float32r   r>   rE   _r   r   r   r   rB     s    


 
 z/BayesianGaussianMixture._check_means_parametersc                 C   sN   |j \}}| jdkr|| _n.| j|d kr4| j| _ntd|d | jf dS )zCheck the prior parameters of the precision distribution.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
        NrG   zQThe parameter 'degrees_of_freedom_prior' should be greater than %d, but got %.3f.r
   )rL   r-   degrees_of_freedom_prior_
ValueErrorrR   r   r   r   rC     s    


z3BayesianGaussianMixture._check_precision_parametersc                 C   s  |j \}}| jdkrdtt|jtt|jtj|dddtj|ddd d| j | _	n| jdkrt
| jtjtjgdd| _	t| j	||fd	| j  t| j	| j nR| jd
krt
| jtjtjgdd| _	t| j	|fd	| j  t| j	| j n| j| _	dS )zCheck the `covariance_prior_`.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
        Nr   r
   )rJ   Zddofr%   r#   r$   r"   )r%   r#   FrK   z%s covariance_priorr$   )rL   r.   r   Z
atleast_2dZcovTvarrN   r(   covariance_prior_r   rP   rQ   r   r   r   rR   r   r   r   rD     sD    


 
 
 
 z8BayesianGaussianMixture._checkcovariance_prior_parameterc                 C   s@   t ||| j| j\}}}| | | || | ||| dS )zInitialization of the mixture parameters.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)

        resp : array-like of shape (n_samples, n_components)
        N)r   r4   r(   _estimate_weights_estimate_means_estimate_precisions)r>   rE   respnkxkskr   r   r   _initialize   s    	   

z#BayesianGaussianMixture._initializec              
   C   sT   | j dkrDd| | jtt|ddd ddd df f| _n| j| | _dS )zEstimate the parameters of the Dirichlet distribution.

        Parameters
        ----------
        nk : array-like of shape (n_components,)
        r&   rG   Nr   )r)   rH   r   hstackcumsumweight_concentration_)r>   r^   r   r   r   rZ     s    
&	z)BayesianGaussianMixture._estimate_weightsc                 C   sH   | j | | _| j | j |ddtjf |  | jddtjf  | _dS )zEstimate the parameters of the Gaussian distribution.

        Parameters
        ----------
        nk : array-like of shape (n_components,)

        xk : array-like of shape (n_components, n_features)
        N)rM   mean_precision_rO   r   r   means_)r>   r^   r_   r   r   r   r[   &  s    	 z'BayesianGaussianMixture._estimate_meansc                 C   s8   | j | j| j| jd| j ||| t| j| j| _dS )a  Estimate the precisions parameters of the precision distribution.

        Parameters
        ----------
        nk : array-like of shape (n_components,)

        xk : array-like of shape (n_components, n_features)

        sk : array-like
            The shape depends of `covariance_type`:
            'full' : (n_components, n_features, n_features)
            'tied' : (n_features, n_features)
            'diag' : (n_components, n_features)
            'spherical' : (n_components,)
        rV   N)_estimate_wishart_full_estimate_wishart_tied_estimate_wishart_diag_estimate_wishart_sphericalr(   r   covariances_precisions_cholesky_)r>   r^   r_   r`   r   r   r   r\   4  s       z,BayesianGaussianMixture._estimate_precisionsc                 C   s   |j \}}| j| | _t| j||f| _t| jD ]R}|| | j }| j	|| ||   || | j
 | j|  t||  | j|< q4|  j| jddtjtjf   _dS )aR  Estimate the full Wishart distribution parameters.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)

        nk : array-like of shape (n_components,)

        xk : array-like of shape (n_components, n_features)

        sk : array-like of shape (n_components, n_features, n_features)
        N)rL   rT   degrees_of_freedom_r   emptyr2   rm   rangerO   rY   rM   rg   outerr   )r>   r^   r_   r`   rS   r   kdiffr   r   r   ri   O  s$    



z.BayesianGaussianMixture._estimate_wishart_fullc                 C   s|   |j \}}| j| | j  | _|| j }| j||  | j  | j| j t	|| j
 |j |  | _|  j| j  _dS )aD  Estimate the tied Wishart distribution parameters.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)

        nk : array-like of shape (n_components,)

        xk : array-like of shape (n_components, n_features)

        sk : array-like of shape (n_features, n_features)
        N)rL   rT   r   r2   ro   rO   rY   rM   r   dotrg   rW   rm   r>   r^   r_   r`   rS   r   rt   r   r   r   rj   s  s    

	z.BayesianGaussianMixture._estimate_wishart_tiedc                 C   s   |j \}}| j| | _|| j }| j|ddtjf || j| j ddtjf t	|    | _
|  j
| jddtjf   _
dS )aF  Estimate the diag Wishart distribution parameters.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)

        nk : array-like of shape (n_components,)

        xk : array-like of shape (n_components, n_features)

        sk : array-like of shape (n_components, n_features)
        N)rL   rT   ro   rO   rY   r   r   rM   rg   squarerm   rv   r   r   r   rk     s    

z.BayesianGaussianMixture._estimate_wishart_diagc              	   C   sb   |j \}}| j| | _|| j }| j||| j| j tt	|d    | _
|  j
| j  _
dS )a@  Estimate the spherical Wishart distribution parameters.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)

        nk : array-like of shape (n_components,)

        xk : array-like of shape (n_components, n_features)

        sk : array-like of shape (n_components,)
        r
   N)rL   rT   ro   rO   rY   rM   rg   r   rN   rw   rm   rv   r   r   r   rl     s    

z3BayesianGaussianMixture._estimate_wishart_sphericalc                 C   sP   |j \}}t|t|| j| j\}}}| | | || | ||| dS )a*  M step.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)

        log_resp : array-like of shape (n_samples, n_components)
            Logarithm of the posterior probabilities (or responsibilities) of
            the point of each sample in X.
        N)	rL   r   r   expr4   r(   rZ   r[   r\   )r>   rE   log_respZ	n_samplesrS   r^   r_   r`   r   r   r   _m_step  s    
   

zBayesianGaussianMixture._m_stepc                 C   s   | j dkrft| jd | jd  }t| jd }t| jd }|| tdt|| d d f S t| jtt| j S d S )Nr&   r   r
   rb   )r)   r   rf   r   rd   re   r   )r>   Zdigamma_sumZ	digamma_aZ	digamma_br   r   r   _estimate_log_weights  s    


z-BayesianGaussianMixture._estimate_log_weightsc              
   C   s   |j \}}t|| j| j| jd| t| j  }|td tt	d| jt
d|d d tjf   d }|d||| j    S )Nr   r   r   )rL   r   rh   rn   r(   r   r   ro   r   r   r   r   rg   )r>   rE   rS   r   Z	log_gaussZ
log_lambdar   r   r   _estimate_log_prob  s$    
   z*BayesianGaussianMixture._estimate_log_probc                 C   s   | j j\}t| j| j|d| t| j  }| jdkrT| jt	t
| j|| }ntt
| j||}| jdkrtt| jd | jd  }n
t| j}tt||  | | d| tt| j  S )a  Estimate the lower bound of the model.

        The lower bound on the likelihood (of the training data with respect to
        the model) is used to detect the convergence and has to increase at
        each iteration.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)

        log_resp : array, shape (n_samples, n_components)
            Logarithm of the posterior probabilities (or responsibilities) of
            the point of each sample in X.

        log_prob_norm : float
            Logarithm of the probability of each sample in X.

        Returns
        -------
        lower_bound : float
        r   r#   r&   r   r
   )rO   rL   r   rn   r(   r   r   ro   r2   rP   r    r   r)   r   rf   r   rx   rg   )r>   ry   Zlog_prob_normr   r   Zlog_wishartZlog_norm_weightr   r   r   _compute_lower_bound
  sH    
  
    

z,BayesianGaussianMixture._compute_lower_boundc                 C   s   | j | j| j| j| j| jfS )N)rf   rg   rh   ro   rm   rn   rI   r   r   r   _get_parametersE  s    z'BayesianGaussianMixture._get_parametersc              	   C   s   |\| _ | _| _| _| _| _| jdkr| j d | j d  }| j d | }| j d | tdt	|d d f | _
|  j
t| j
  _
n| j t| j  | _
| jdkrtdd | jD | _n,| jdkrt| j| jj| _n| jd	 | _d S )
Nr&   r   r
   rb   r%   c                 S   s   g | ]}t ||jqS r   )r   ru   rW   ).0Z	prec_cholr   r   r   
<listcomp>m  s   z;BayesianGaussianMixture._set_parameters.<locals>.<listcomp>r#   r   )rf   rg   rh   ro   rm   rn   r)   r   rd   ZcumprodZweights_r   r(   arrayZprecisions_ru   rW   )r>   paramsZweight_dirichlet_sumtmpr   r   r   _set_parametersO  sD    


 z'BayesianGaussianMixture._set_parameters) __name__
__module____qualname____doc__r   r/   r	   r   r   dict__annotations__r=   rF   rA   rB   rC   rD   ra   rZ   r[   r\   ri   rj   rk   rl   rz   r{   r|   r}   r~   r   __classcell__r   r   r?   r   r!   J   sn   
  
*)$";
r!   )r   r   numbersr   numpyr   Zscipy.specialr   r   r   utilsr   Zutils._param_validationr   r	   _baser   r   Z_gaussian_mixturer   r   r   r   r   r   r   r    r!   r   r   r   r   <module>   s    
