
    /iiRR                         d Z ddlZddlmZmZ ddlmZ ddlmZm	Z	 ddl
m
Z
 ddlZddlmZ ddlmZmZmZ dd	lmZ dd
lmZ ddlmZ ddlmZmZmZmZmZmZ ddl m!Z!m"Z" ddl#m$Z$m%Z% d Z& G d deee          Z'dS )zBase class for mixture models.    N)ABCMetaabstractmethod)nullcontext)IntegralReal)time)cluster)BaseEstimatorDensityMixin_fit_context)kmeans_plusplus)ConvergenceWarning)check_random_state)_convert_to_numpy_is_numpy_namespace
_logsumexp_max_precision_float_dtypeget_namespaceget_namespace_and_device)Interval
StrOptions)check_is_fittedvalidate_datac                 V    | j         |k    rt          d|d|d| j                   dS )zValidate the shape of the input parameter 'param'.

    Parameters
    ----------
    param : array

    param_shape : tuple

    name : str
    zThe parameter 'z' should have the shape of z
, but got N)shape
ValueError)paramparam_shapenames      [/var/www/html/bet.cuttalo.com/ml/venv/lib/python3.11/site-packages/sklearn/mixture/_base.py_check_shaper!      sE     {k!!jtt[[[%++/
 
 	
 "!    c                   ,   e Zd ZU dZ eeddd          g eeddd          g eeddd          g eeddd          g eeddd          g eh d          gd	gd
gdg eeddd          gd
Ze	e
d<   d Zed&d            Zd&dZed             Zd&dZ ed          d&d            Zd&dZed             Zed             Zed             Zd Zd&dZd Zd Zd'dZd&dZed&d             Zed&d!            Zd&d"Zd# Z d$ Z!d% Z"dS )(BaseMixturezBase class for mixture models.

    This abstract class specifies an interface for all mixture classes and
    provides basic common methods for mixture models.
       Nleft)closedg        r   >   kmeansrandomrandom_from_data	k-means++random_statebooleanverbose
n_componentstol	reg_covarmax_itern_initinit_paramsr,   
warm_startr.   verbose_interval_parameter_constraintsc                     || _         || _        || _        || _        || _        || _        || _        || _        |	| _        |
| _	        d S Nr/   )selfr0   r1   r2   r3   r4   r5   r,   r6   r.   r7   s              r    __init__zBaseMixture.__init__G   sT     )" &($ 0r"   c                     dS )zCheck initial parameters of the derived class.

        Parameters
        ----------
        X : array-like of shape  (n_samples, n_features)
        N r;   Xxps      r    _check_parameterszBaseMixture._check_parameters_   	     	r"   c                    t          ||          \  }}}|j        \  }}| j        dk    rqt          j        || j        f|j                  }t          j        | j        d|          	                    |          j
        }d|t          j        |          |f<   n;| j        dk    rb|                    |                    || j        f          |j        |          }||                    |d	          d
d
|j        f         z  }n| j        dk    r^|                    || j        f|j        |          }|                    || j        d          }	t#          |	          D ]\  }
}d|||
f<   ne| j        dk    rZt          j        || j        f|j                  }t%          || j        |          \  }}	d||	t          j        | j                  f<   |                     ||           d
S )a?  Initialize the model parameters.

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

        random_state : RandomState
            A random number generator instance that controls the random seed
            used for the method chosen to initialize the parameters.
        rA   r(   )dtyper%   )
n_clustersr4   r,   r)   sizerF   deviceaxisNr*   F)rI   replacer+   )r,   )r   r   r5   npzerosr0   rF   r	   KMeansfitlabels_arangeasarrayuniformsumnewaxischoice	enumerater   _initialize)r;   r@   r,   rA   _rK   	n_samplesresplabelindicescolindexs               r    _initialize_parametersz"BaseMixture._initialize_parametersi   s6    1r:::Avw	1x''8Y(9:!'JJJD#0   Q  12D9%%u,--))::$$9d6G*H$IIg   D
 BFF4aF((BJ77DD!33388D-.agf   D #)) 15 *  G (00 % %
U#$UCZ  %,,8Y(9:!'JJJD(!)  JAw
 ;<D")D$56667D!!!!!r"   c                     dS )zInitialize the model parameters of the derived class.

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

        resp : array-like of shape (n_samples, n_components)
        Nr>   )r;   r@   r^   s      r    r[   zBaseMixture._initialize   s	     	r"   c                 2    |                      ||           | S )a  Estimate model parameters with the EM algorithm.

        The method fits the model ``n_init`` times and sets the parameters with
        which the model has the largest likelihood or lower bound. Within each
        trial, the method iterates between E-step and M-step for ``max_iter``
        times until the change of likelihood or lower bound is less than
        ``tol``, otherwise, a ``ConvergenceWarning`` is raised.
        If ``warm_start`` is ``True``, then ``n_init`` is ignored and a single
        initialization is performed upon the first call. Upon consecutive
        calls, training starts where it left off.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            List of n_features-dimensional data points. Each row
            corresponds to a single data point.

        y : Ignored
            Not used, present for API consistency by convention.

        Returns
        -------
        self : object
            The fitted mixture.
        )fit_predict)r;   r@   ys      r    rR   zBaseMixture.fit   s    6 	Ar"   T)prefer_skip_nested_validationc                    t          |          \  }}t          | ||j        |j        gd          }|j        d         | j        k     r%t          d| j         d|j        d                    |                     ||           | j        ot          | d           }|r| j
        nd}|j         }g }d	| _        t          | j                  }	|j        \  }
}t          |          D ]c}|                     |           |r|                     ||	|           |r|j         n| j        }g }| j        dk    r|                                 }d}gd	}t          d| j        dz             D ]}|}|                     ||          \  }}|                     |||           |                     ||          }|                    |           ||z
  }|                     ||           t5          |          | j        k     rd
} n|                     ||           ||k    s||j         k    r!|}|                                 }|}|}|| _        e| j        s%| j        dk    rt;          j        dt>                     |                      ||           || _!        || _        || _"        |                     ||          \  }}|#                    |d          S )a  Estimate model parameters using X and predict the labels for X.

        The method fits the model ``n_init`` times and sets the parameters with
        which the model has the largest likelihood or lower bound. Within each
        trial, the method iterates between E-step and M-step for `max_iter`
        times until the change of likelihood or lower bound is less than
        `tol`, otherwise, a :class:`~sklearn.exceptions.ConvergenceWarning` is
        raised. After fitting, it predicts the most probable label for the
        input data points.

        .. versionadded:: 0.20

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            List of n_features-dimensional data points. Each row
            corresponds to a single data point.

        y : Ignored
            Not used, present for API consistency by convention.

        Returns
        -------
        labels : array, shape (n_samples,)
            Component labels.
           )rF   ensure_min_samplesr   z:Expected n_samples >= n_components but got n_components = z, n_samples = rE   
converged_r%   FTzBest performing initialization did not converge. Try different init parameters, or increase max_iter, tol, or check for degenerate data.rL   )$r   r   float64float32r   r0   r   rB   r6   hasattrr4   infrl   r   r,   range_print_verbose_msg_init_begrc   lower_bound_r3   _get_parameters_e_step_m_step_compute_lower_boundappend_print_verbose_msg_iter_endabsr1   _print_verbose_msg_init_endwarningswarnr   _set_parametersn_iter_lower_bounds_argmax)r;   r@   rg   rA   r\   do_initr4   max_lower_boundbest_lower_boundsr,   r]   initlower_boundcurrent_lower_boundsbest_paramsbest_n_iter	convergedn_iterprev_lower_boundlog_prob_normlog_respchanges                         r    rf   zBaseMixture.fit_predict   sC   8 a  A$"*bj)AVWXXX71:))),*.*;, , wqz, ,  
 	qR((( F74+F+FG '.Q6')$*;<<w	1&MM $	0 $	0D,,T222 D++A|+CCC%,C26''$2CK#% }!!"2244!	#At}q'899  F'2$.2ll1l.D.D+M8LLHL444"&";";Hm"T"TK(//<<<(+;;F44VVDDD6{{TX--$(	 . 00iHHH00Ow4N4N&1O"&"6"6"8"8K"(K(<%&/DO
  	4=1#4#4M9 #   	[R000"+.
 ll1l,,8yyy***r"   c                     t          ||          \  }}|                     ||          \  }}|                    |          |fS )a  E step.

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

        Returns
        -------
        log_prob_norm : float
            Mean of the logarithms of the probabilities of each sample in X

        log_responsibility : array, shape (n_samples, n_components)
            Logarithm of the posterior probabilities (or responsibilities) of
            the point of each sample in X.
        rE   )r   _estimate_log_prob_respmean)r;   r@   rA   r\   r   r   s         r    ru   zBaseMixture._e_step:  sN      aB'''A"&">">qR">"H"Hxww}%%x//r"   c                     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.
        Nr>   )r;   r@   r   s      r    rv   zBaseMixture._m_stepN  s	     	r"   c                     d S r:   r>   )r;   s    r    rt   zBaseMixture._get_parameters\      r"   c                     d S r:   r>   )r;   paramss     r    r~   zBaseMixture._set_parameters`  r   r"   c                     t          |            t          | |d          }t          |                     |          d          S )a  Compute the log-likelihood of each sample.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            List of n_features-dimensional data points. Each row
            corresponds to a single data point.

        Returns
        -------
        log_prob : array, shape (n_samples,)
            Log-likelihood of each sample in `X` under the current model.
        Fresetr%   rL   )r   r   r   _estimate_weighted_log_prob)r;   r@   s     r    score_sampleszBaseMixture.score_samplesd  sG     	$///$::1==AFFFFr"   c                     t          |          \  }}t          |                    |                     |                              S )a  Compute the per-sample average log-likelihood of the given data X.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_dimensions)
            List of n_features-dimensional data points. Each row
            corresponds to a single data point.

        y : Ignored
            Not used, present for API consistency by convention.

        Returns
        -------
        log_likelihood : float
            Log-likelihood of `X` under the Gaussian mixture model.
        )r   floatr   r   )r;   r@   rg   rA   r\   s        r    scorezBaseMixture.scorew  s=    " a  ARWWT//2233444r"   c                     t          |            t          |          \  }}t          | |d          }|                    |                     |          d          S )a  Predict the labels for the data samples in X using trained model.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            List of n_features-dimensional data points. Each row
            corresponds to a single data point.

        Returns
        -------
        labels : array, shape (n_samples,)
            Component labels.
        Fr   r%   rL   )r   r   r   r   r   )r;   r@   rA   r\   s       r    predictzBaseMixture.predict  s[     	a  A$///yy99!<<1yEEEr"   c                     t          |            t          | |d          }t          |          \  }}|                     ||          \  }}|                    |          S )a  Evaluate the components' density for each sample.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            List of n_features-dimensional data points. Each row
            corresponds to a single data point.

        Returns
        -------
        resp : array, shape (n_samples, n_components)
            Density of each Gaussian component for each sample in X.
        Fr   rE   )r   r   r   r   exp)r;   r@   rA   r\   r   s        r    predict_probazBaseMixture.predict_proba  se     	$///a  A2212<<8vvhr"   c           
      
   	
 t                      t           j                  \  
}|dk     rt          d j        z             j        j        \  }t           j                  		                    |t           j
        
                     j        dk    rVt          j        	fdt          t           j        
          t           j        
                    D                       }n j        dk    rDt          j        	 
fdt          t           j        
                    D                       }nVt          j        	fdt          t           j        
          t           j        
                    D                       }
                    
fdt#          t%                              D                       }t'          
	          }
                    ||
          |fS )ay  Generate random samples from the fitted Gaussian distribution.

        Parameters
        ----------
        n_samples : int, default=1
            Number of samples to generate.

        Returns
        -------
        X : array, shape (n_samples, n_features)
            Randomly generated sample.

        y : array, shape (nsamples,)
            Component labels.
        r%   zNInvalid value for 'n_samples': %d . The sampling requires at least one sample.fullc           	      `    g | ]*\  }}}                     ||t          |                    +S r>   )multivariate_normalint).0r   
covariancesamplerngs       r    
<listcomp>z&BaseMixture.sample.<locals>.<listcomp>  sG       2z6 ++D*c&kkJJ  r"   tiedc           	          g | ]<\  }}                     |t          j                  t          |                    =S r>   )r   r   covariances_r   )r   r   r   r   r;   rA   s      r    r   z&BaseMixture.sample.<locals>.<listcomp>  sZ        'v ++/0A2FFF   r"   c                 x    g | ]6\  }}}|                     |f           t          j        |          z  z   7S )rH   )standard_normalrO   sqrt)r   r   r   r   
n_featuresr   s       r    r   z&BaseMixture.sample.<locals>.<listcomp>  sa     	 	 	 3z6 ))
/C)DDgj))**	 	 	r"   c                 r    g | ]3}                     t          |                   |j                   4S )rJ   )r   r   int64)r   idevice_n_samples_comprA   s     r    r   z&BaseMixture.sample.<locals>.<listcomp>  sL        N1-..'RR  r"   )rA   rK   rJ   )r   r   means_r   r0   r   r   r,   multinomialr   weights_covariance_typerO   vstackzipr   concatrq   lenr   rU   )r;   r]   r\   r@   rg   max_float_dtyper   r   r   r   rA   s   `     @@@@@r    r   zBaseMixture.sample  st     	1$+>>Awq==$'+'8:  
 ): !233(;;
 
 6))	   69)$+r::)$*;R@@&7 7  	 	AA !V++	      +.)$+r::N+ +	  	 	AA 		 	 	 	 	 7:)$+r::)$*;R@@&7 7		 	 	 A II     s>2233  
 
 57KKKzz!?7zCCQFFr"   c                 ^    |                      ||          |                     |          z   S )a  Estimate the weighted log-probabilities, log P(X | Z) + log weights.

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

        Returns
        -------
        weighted_log_prob : array, shape (n_samples, n_component)
        rE   )_estimate_log_prob_estimate_log_weightsr?   s      r    r   z'BaseMixture._estimate_weighted_log_prob  s4     &&qR&0043M3MQS3M3T3TTTr"   c                     dS )zEstimate log-weights in EM algorithm, E[ log pi ] in VB algorithm.

        Returns
        -------
        log_weight : array, shape (n_components, )
        Nr>   )r;   rA   s     r    r   z!BaseMixture._estimate_log_weights  rC   r"   c                     dS )a9  Estimate the log-probabilities log P(X | Z).

        Compute the log-probabilities per each component for each sample.

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

        Returns
        -------
        log_prob : array, shape (n_samples, n_component)
        Nr>   r?   s      r    r   zBaseMixture._estimate_log_prob  s	     	r"   c                 D   t          ||          \  }}|                     ||          }t          |d|          }t          |          rt	          j        d          nt                      }|5  ||dd|j        f         z
  }ddd           n# 1 swxY w Y   ||fS )a@  Estimate log probabilities and responsibilities for each sample.

        Compute the log probabilities, weighted log probabilities per
        component and responsibilities for each sample in X with respect to
        the current state of the model.

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

        Returns
        -------
        log_prob_norm : array, shape (n_samples,)
            log p(X)

        log_responsibilities : array, shape (n_samples, n_components)
            logarithm of the responsibilities
        rE   r%   )rM   rA   ignore)underN)r   r   r   r   rO   errstater   rX   )r;   r@   rA   r\   weighted_log_probr   context_managerr   s           r    r   z#BaseMixture._estimate_log_prob_resp&  s	   & aB'''A <<Q2<FF"#41DDD ,?r+B+BUBKh'''' 	  	H 	H(=BJ+GGH	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H h&&s   2BBBc                     | j         dk    rt          d|z             dS | j         dk    r3t          d|z             t                      | _        | j        | _        dS dS )(Print verbose message on initialization.r%   zInitialization %drj   N)r.   printr   _init_prev_time_iter_prev_time)r;   r4   s     r    rr   z'BaseMixture._print_verbose_msg_init_begF  so    <1%./////\Q%.///#'66D #'#7D    r"   c                     || j         z  dk    r^| j        dk    rt          d|z             dS | j        dk    r6t                      }t          d||| j        z
  |fz             || _        dS dS dS )r   r   r%   z  Iteration %drj   z0  Iteration %d	 time lapse %.5fs	 ll change %.5fN)r7   r.   r   r   r   )r;   r   diff_llcur_times       r    ry   z'BaseMixture._print_verbose_msg_iter_endO  s    D))Q..|q  &/00000""66Hx$*>>HI   (0$$$ /. #"r"   c           	          |rdnd}| j         dk    rt          d| d           d
S | j         dk    r3t                      | j        z
  }t          d| d|dd	|dd           d
S d
S )z.Print verbose message on the end of iteration.r   zdid not converger%   zInitialization .rj   z. time lapse z.5fzs	 lower bound N)r.   r   r   r   )r;   lbinit_has_convergedconverged_msgts        r    r{   z'BaseMixture._print_verbose_msg_init_end\  s    '9Q?Q<14M44455555\Q--A-  aT         r"   r:   )r%   )#__name__
__module____qualname____doc__r   r   r   r   r8   dict__annotations__r<   r   rB   rc   r[   rR   r   rf   ru   rv   rt   r~   r   r   r   r   r   r   r   r   r   rr   ry   r{   r>   r"   r    r$   r$   1   s
          "(AtFCCCDsD8889htS$v>>>?Xh4???@8Haf===>JLLLMM
 (( k;%Xh4GGGH$ $D   1 1 10    ^5" 5" 5" 5"n 	 	 ^	   < \555m+ m+ m+ 65m+^0 0 0 0(   ^   ^   ^G G G&5 5 5 5(F F F&     (KG KG KG KGZU U U U    ^    ^' ' ' '@8 8 80 0 0
 
 
 
 
r"   r$   )	metaclass)(r   r|   abcr   r   
contextlibr   numbersr   r   r   numpyrO   sklearnr	   sklearn.baser
   r   r   sklearn.clusterr   sklearn.exceptionsr   sklearn.utilsr   sklearn.utils._array_apir   r   r   r   r   r   sklearn.utils._param_validationr   r   sklearn.utils.validationr   r   r!   r$   r>   r"   r    <module>r      s   $ $
  ' ' ' ' ' ' ' ' " " " " " " " " " " " " " "                 B B B B B B B B B B + + + + + + 1 1 1 1 1 1 , , , , , ,                A @ @ @ @ @ @ @ C C C C C C C C
 
 
$u u u u u, u u u u u ur"   