
    {KgI                         d Z ddlZddlmZ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 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 ddlmZ d Z G d deee      Zy)zBase class for mixture models.    N)ABCMetaabstractmethod)IntegralReal)time)	logsumexp   )cluster)BaseEstimatorDensityMixin_fit_context)kmeans_plusplus)ConvergenceWarning)check_random_state)Interval
StrOptions)check_is_fittedc                     t        j                  |       } | j                  |k7  rt        d|d|d| j                        y)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)nparrayshape
ValueError)paramparam_shapenames      Y/home/alanp/www/video.onchill/myenv/lib/python3.12/site-packages/sklearn/mixture/_base.py_check_shaper      s?     HHUOE{{k![%++/
 	
 "    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        Zd Zed        Zd&dZ ed      d&d       Zd Zed        Zed        Zed        Zd Zd&dZd Zd Zd'dZd Zed         Zed!        Zd" Zd# Z d$ Z!d% Z"y)(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                     || _         || _        || _        || _        || _        || _        || _        || _        |	| _        |
| _	        y Nr+   )selfr,   r-   r.   r/   r0   r1   r(   r2   r*   r3   s              r   __init__zBaseMixture.__init__A   sN     )" &($ 0r   c                      y)zCheck initial parameters of the derived class.

        Parameters
        ----------
        X : array-like of shape  (n_samples, n_features)
        N r7   Xs     r   _check_parameterszBaseMixture._check_parametersY        	r   c                    |j                   \  }}| j                  dk(  rxt        j                  || j                  f      }t        j                  | j                  d|      j                  |      j                  }d|t        j                  |      |f<   n:| j                  dk(  rI|j                  || j                  f      }||j                  d      ddt        j                  f   z  }n| j                  dk(  rdt        j                  || j                  f      }|j                  || j                  d	
      }d||t        j                  | j                        f<   no| j                  dk(  r`t        j                  || j                  f      }t        || j                  |      \  }}d||t        j                  | j                        f<   | j                  |       y)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.
        r$   r!   )
n_clustersr0   r(   r%   sizeaxisNr&   F)rB   replacer'   )r(   )r   r1   r   zerosr,   r
   KMeansfitlabels_arangeuniformsumnewaxischoicer   _initialize)r7   r<   r(   	n_samples_resplabelindicess           r   _initialize_parametersz"BaseMixture._initialize_parametersc   s    ww	1x'88Y(9(9:;D#00 Q  12D9%u,-)''i9J9J-K'LDDHH!H$Q

]33D!3388Y(9(9:;D")) 1 15 * G ;<D"))D$5$5667,88Y(9(9:;D(!!)JAw
 ;<D"))D$5$5667D!r   c                      y)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:   )r7   r<   rR   s      r   rO   zBaseMixture._initialize   s     	r   c                 *    | j                  ||       | 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r7   r<   ys      r   rH   zBaseMixture.fit   s    6 	Ar   T)prefer_skip_nested_validationc                 l   | j                  |t        j                  t        j                  gd      }|j                  d   | j
                  k  r(t        d| j
                   d|j                  d          | j                  |       | j                  xr t        | d       }|r| j                  nd}t        j                   }d| _        t        | j                        }|j                  \  }}t        |      D ]>  }	| j!                  |	       |r| j#                  ||       |rt        j                   n| j$                  }
| j&                  dk(  r| j)                         }d}jd}t        d| j&                  dz         D ]o  }|
}| j+                  |      \  }}| j-                  ||       | j/                  ||      }
|
|z
  }| j1                  ||       t3        |      | j4                  k  smd	} n | j7                  |
|       |
|kD  s|t        j                   k(  s$|
}| j)                         }}|| _        A | j                  s)| j&                  dkD  rt9        j:                  d
t<               | j?                         | _         || _        | j+                  |      \  }}|jC                  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.
        r	   )dtypeensure_min_samplesr   z:Expected n_samples >= n_components but got n_components = z, n_samples = 
converged_r!   FTzBest performing initialization did not converge. Try different init parameters, or increase max_iter, tol, or check for degenerate data.rC   )"_validate_datar   float64float32r   r,   r   r=   r2   hasattrr0   infr_   r   r(   range_print_verbose_msg_init_begrU   lower_bound_r/   _get_parameters_e_step_m_step_compute_lower_bound_print_verbose_msg_iter_endabsr-   _print_verbose_msg_init_endwarningswarnr   _set_parametersn_iter_argmax)r7   r<   rZ   do_initr0   max_lower_boundr(   rP   rQ   initlower_boundbest_paramsbest_n_iter	convergedn_iterprev_lower_boundlog_prob_normlog_respchanges                      r   rX   zBaseMixture.fit_predict   s|   8 "**bjj)AVWX771:)))**.*;*;)< = wwqzl, 
 	q! F74+FG 'Q66')$*;*;<ww	1&MD,,T2++A|<%,266'$2C2CK}}!"224!	#At}}q'89F'2$.2ll1o+M8LLH-"&";";Hm"TK(+;;F44VVD6{TXX-$(	 : 00iH0Ow4N&1O"&"6"6"8K"(K&/DOC "L 4==1#4MM9 # 	[)"+
 ll1o8A&&r   c                 X    | j                  |      \  }}t        j                  |      |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.
        )_estimate_log_prob_respr   mean)r7   r<   r}   r~   s       r   ri   zBaseMixture._e_step"  s-      #'">">q"Axww}%x//r   c                      y)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:   )r7   r<   r~   s      r   rj   zBaseMixture._m_step5  s     	r   c                      y r6   r:   r7   s    r   rh   zBaseMixture._get_parametersC      r   c                      y r6   r:   )r7   paramss     r   rq   zBaseMixture._set_parametersG  r   r   c                 v    t        |        | j                  |d      }t        | j                  |      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!   rC   )r   r`   r   _estimate_weighted_log_probr;   s     r   score_sampleszBaseMixture.score_samplesK  s9     	/99!<1EEr   c                 @    | j                  |      j                         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   r   rY   s      r   scorezBaseMixture.score^  s    " !!!$))++r   c                     t        |        | j                  |d      }| j                  |      j                  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!   rC   )r   r`   r   rs   r;   s     r   predictzBaseMixture.predictq  s@     	///299q9AAr   c                     t        |        | j                  |d      }| j                  |      \  }}t        j                  |      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   )r   r`   r   r   exp)r7   r<   rQ   r~   s       r   predict_probazBaseMixture.predict_proba  sD     	/22158vvhr   c                 j   t        |        |dk  rt        d| j                  z        | j                  j                  \  }}t        | j                        }|j                  || j                        }| j                  dk(  ret        j                  t        | j                  | j                  |      D cg c]"  \  }}}|j                  ||t        |            $ c}}}      }	n| j                  dk(  rat        j                  t        | j                  |      D cg c]+  \  }}|j                  || j                  t        |            - c}}      }	nut        j                  t        | j                  | j                  |      D cg c]3  \  }}}||j!                  ||f      t        j"                  |      z  z   5 c}}}      }	t        j$                  t'        |      D 
cg c]!  \  }
}t        j(                  ||
t              # c}}
      }|	|fS c c}}}w c c}}w c c}}}w c c}}
w )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.fulltiedrA   )r]   )r   r   r,   means_r   r   r(   multinomialweights_covariance_typer   vstackzipcovariances_multivariate_normalintstandard_normalsqrtconcatenate	enumerater   )r7   rP   rQ   
n_featuresrngn_samples_compr   
covariancesampler<   jrZ   s               r   r   zBaseMixture.sample  s     	q=$'+'8'8: 
 )): !2!23DMMB6)		 7:T%6%6772z6 ++D*c&kJ7A !!V+		 +.dkk>*J*Jv ++D$2C2CS[Q*JA 		
 7:T%6%67	72z6 ))
/C)Dggj)**7		A NN<En<UV<Uyq&RWWVQc*<UV
 1v= Ws   6'H0H"
8H()&H/
c                 F    | j                  |      | j                         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)
        )_estimate_log_prob_estimate_log_weightsr;   s     r   r   z'BaseMixture._estimate_weighted_log_prob  s#     &&q)D,F,F,HHHr   c                      y)zEstimate log-weights in EM algorithm, E[ log pi ] in VB algorithm.

        Returns
        -------
        log_weight : array, shape (n_components, )
        Nr:   r   s    r   r   z!BaseMixture._estimate_log_weights  r>   r   c                      y)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                     | j                  |      }t        |d      }t        j                  d      5  ||ddt        j                  f   z
  }ddd       ||fS # 1 sw Y   |fS xY w)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
        r!   rC   ignore)underN)r   r   r   errstaterM   )r7   r<   weighted_log_probr}   r~   s        r   r   z#BaseMixture._estimate_log_prob_resp  sj    & !<<Q?!"3!<[[x((=BJJ+GGH ) h&& ) h&&s   AA(c                     | j                   dk(  rt        d|z         y| j                   dk\  r/t        d|z         t               | _        | j                  | _        yy)(Print verbose message on initialization.r!   zInitialization %dr	   N)r*   printr   _init_prev_time_iter_prev_time)r7   r0   s     r   rf   z'BaseMixture._print_verbose_msg_init_beg  sS    <<1%./\\Q%./#'6D #'#7#7D  r   c                     || j                   z  dk(  r^| j                  dk(  rt        d|z         y| j                  dk\  r0t               }t        d||| j                  z
  |fz         || _        yyy)r   r   r!   z  Iteration %dr	   z0  Iteration %d	 time lapse %.5fs	 ll change %.5fN)r3   r*   r   r   r   )r7   r{   diff_llcur_times       r   rl   z'BaseMixture._print_verbose_msg_iter_end  s|    D)))Q.||q &/0"6Hx$*>*>>HI (0$ # /r   c           	          |rdnd}| j                   dk(  rt        d| d       y
| j                   dk\  r/t               | j                  z
  }t        d| d|dd	|dd       y
y
)z.Print verbose message on the end of iteration.rz   zdid not converger!   zInitialization .r	   z. time lapse z.5fzs	 lower bound N)r*   r   r   r   )r7   lbinit_has_convergedconverged_msgts        r   rn   z'BaseMixture._print_verbose_msg_init_end+  sw    '9?Q<<1OM?!45\\Q---A!-aW Es81 r   r6   )r!   )#__name__
__module____qualname____doc__r   r   r   r   r4   dict__annotations__r8   r   r=   rU   rO   rH   r   rX   ri   rj   rh   rq   r   r   r   r   r   r   r   r   r   rf   rl   rn   r:   r   r   r    r    +   s    "(AtFCDsD89tS$v>?h4?@Haf=>LM
 (( k;%h4GH$D 10  )"V 	 	< 5g' 6g'R0&      F&,&B$ &<|I    '480
r   r    )	metaclass)r   ro   abcr   r   numbersr   r   r   numpyr   scipy.specialr    r
   baser   r   r   r   
exceptionsr   utilsr   utils._param_validationr   r   utils.validationr   r   r    r:   r   r   <module>r      sK    $  ' "   #  < < % + & : .
&J, Jr   