`L i%dZddlZddlmZddlZddlmZmZm Z ddl m Z ddl m Z mZdd lmZmZdd lmZmZmZmZmZmZd Zd ZGd deZy)z Bayesian Gaussian Mixture Model.N)Real)betalndigammagammaln) 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|ttj|tjt|z S)aVCompute 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. )rnpsum)dirichlet_concentrations g/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sklearn/mixture/_bayesian_mixture.py_log_dirichlet_normrs4 26612 3bff'(7 c ||z||zdztjdzztjt d|tj |ddtj fz zdz S)aDCompute 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)mathlogrrrarangenewaxis)degrees_of_freedomlog_det_precisions_chol n_featuress r_log_wishart_normr%+st, 44 z )C /$((3- ? @ && C- *0Eam0TTU V    rceZdZUdZiej ehdgeddhgdeedddgdeedddgdd gdeedddgdd eedddgd Ze e d <d d dddd ddddddddddddfd Z dZ dZ dZdZdZdZdZdZdZd Zd!Zd"Zd#Zd$Zd%Zd&Zd'Zd(Zd)ZxZS)*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 `. 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 `. 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 `. 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 of the best fit of inference was reached, 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. lower_bounds_ : array-like of shape (`n_iter_`,) The list of lower bound values on the model evidence from each iteration 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. `_ .. [2] `Hagai Attias. (2000). "A Variational Bayesian Framework for Graphical Models". In Advances in Neural Information Processing Systems 12. `_ .. [3] `Blei, David M. and Michael I. Jordan. (2006). "Variational inference for Dirichlet process mixtures". Bayesian analysis 1.1 `_ 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]) >diagfulltied sphericaldirichlet_processdirichlet_distributionNgneither)closedz array-like)covariance_typeweight_concentration_prior_typeweight_concentration_priormean_precision_prior mean_priordegrees_of_freedom_priorcovariance_prior_parameter_constraintsr r)gMbP?gư>dkmeansFr ) n_componentsr0tol reg_covarmax_itern_init init_paramsr1r2r3r4r5r6 random_state warm_startverboseverbose_intervalc t||||||||||| ||_||_| |_| |_| |_| |_| |_y)N) r;r<r=r>r?r@rArBrCrD) super__init__r0r1r2r3r4r5r6)selfr;r0r<r=r>r?r@r1r2r3r4r5r6rArBrCrD __class__s rrGz BayesianGaussianMixture.__init__ssn* %#%!-   //N,*D'$8!$(@% 0rc|j|j||j||j|y)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)rHXs r_check_parametersz)BayesianGaussianMixture._check_parameterss: &&( $$Q' ((+ --a0rch|jd|jz |_y|j|_y)z2Check the parameter of the Dirichlet distribution.N?)r2r;weight_concentration_prior_rHs rrKz1BayesianGaussianMixture._check_weights_parameterss/  * * 2/2T5F5F/FD ,/3/N/ND ,rcZ|j\}}|jd|_n|j|_|j|j d|_yt |jtjtjgd|_t|j |fdy)zCheck the parameters of the Gaussian distribution. Parameters ---------- X : array-like of shape (n_samples, n_features) NrRr)axisFdtype ensure_2dmeans) shaper3mean_precision_prior_r4mean mean_prior_rrfloat64float32r rHrO_r$s rrLz/BayesianGaussianMixture._check_means_parameterss :  $ $ ,),D &)-)B)BD & ?? " vv1v~D * BJJ'?5 D  ))J=' Brc|j\}}|j||_y|j|dz kDr|j|_ytd|dz |jfz)zCheck the prior parameters of the precision distribution. Parameters ---------- X : array-like of shape (n_samples, n_features) NrRzQThe parameter 'degrees_of_freedom_prior' should be greater than %d, but got %.3f.r )r[r5degrees_of_freedom_prior_ ValueErrorras rrMz3BayesianGaussianMixture._check_precision_parameterssp :  ( ( 0-7D *  * *Z#-= =-1-J-JD *;>4#@#@AB rc|j\}}|jtjtj|j tjtj|j tj |ddtj |ddjd|j|_ y|jdvrt|jtjtjgd|_ t|j||fd |jzt|j|jy|jd k(rt|jtjtjgd|_ t|j|fd |jzt|j|jy|j|_ y) zCheck the `covariance_prior_`. Parameters ---------- X : array-like of shape (n_samples, n_features) Nrr )rVddofr)r*r(r+)r)r*FrWz%s covariance_priorr()r[r6r atleast_2dcovTvarr]r0covariance_prior_rr_r`r rrras rrNz8BayesianGaussianMixture._checkcovariance_prior_parameters :  ( bffQSSk2 bffQSSk2qqq1VVAAA6;;= & "" &$D " ! !%5 5%0%%bjj"**-EQV&D " &&Z(%(<(<<  $D$:$:D(>@T@T U&*%:%:D "rct|||j|j\}}}|j||j |||j |||y)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)rr=r0_estimate_weights_estimate_means_estimate_precisions)rHrOrespnkxksks r _initializez#BayesianGaussianMixture._initializesY3 tT^^T%9%9 B r" R$ !!"b"-rc |jdk(rNd|z|jtjtj|dddddddfzf|_y|j|z|_y)zEstimate the parameters of the Dirichlet distribution. Parameters ---------- nk : array-like of shape (n_components,) r,rRNr)r1rSrhstackcumsumweight_concentration_)rHrss rroz)BayesianGaussianMixture._estimate_weightssw  / /3F Fb44ii2dd8!4RVV!  & &)9)9 9Bq"**}I : :1 =>I))Q )k*A B3B GHIJ 4556t112: rc |j\}}t||j|j|jd|zt j |jzz }|t j dzt jtd|jt jd|ddt jfz zdz}|d|||jz z zzS)Nrrr) r[rrrr0rrrrrr r!r~)rHrOrbr$ log_gauss log_lambdas r_estimate_log_probz*BayesianGaussianMixture._estimate_log_probs :0 t{{D55t7K7K * rvvd&>&>? ?@  "&&+- ++bii:.Fq"**}.UUW   1  3*zD&>? ?#@   6 )++bjj!,,.Ez/K &&!,,.EzK  / /3F F!vvt11!4d6P6PQR6ST O2$2L2LMOVVBFF8$x/ 0 0  Jt/C/C(D!EE F rc|j|j|j|j|j|j fS)N)r|r~rrrrrTs r_get_parametersz'BayesianGaussianMixture._get_parametersHs@  & &  KK  $ $     % %   rc |\|_|_|_|_|_|_|j dk(r|jd|jdz}|jd|z }|jd|z tjdtj|ddfz|_ |xjtj|jzc_ n1|jtj|jz |_ |jdk(rQtj|j Dcgc]"}tj||j$c}|_y|jdk(r:tj|j |j j|_y|j dz|_ycc}w)Nr,rr rxr)r*r)r|r~rrrrr1rrzcumprodweights_rr0arrayrrk precisions_)rHparamsweight_dirichlet_sumtmp prec_chols r_set_parametersz'BayesianGaussianMixture._set_parametersRs   &  K  $    %  / /3F F**1-0J0J10MM !,,Q/2FFC**1-&'))Q 3s8 4567 M MMRVVDMM2 2M 66**:DM   6 )!xx&*%>%>!FF9ikk2 D  ! !V +!vv))4+D+D+F+F D  $88!;D s='G) __name__ __module__ __qualname____doc__r r7r r rdict__annotations__rGrPrKrLrMrNrvrorprqrrrrrrrrrr __classcell__)rIs@rr'r'JsQRh$  , ,$&'LMN +-EF G,   T3Y 7' "&xc4 'R S\*%)8D#tI+V$W   T3Y 7 $D. (;#'!!%'(1T 1OC,(';R."O* 0 6"QH 6DE<6>.($R$9 v )rsD&  22:,$>q