`L ia0dZddlmZddlmZddlZddlmZm Z m Z m Z m Z ddl mZddlmZdd lmZdd lmZdd lmZdd lmZmZmZmZmZdd lmZddlm Z ddl!m"Z"m#Z#ddl$m%Z%m&Z&m'Z'ddl(m)Z)m*Z*Gdde e)Z+Gddee+Z,Gdde e+Z-y)z Soft Voting/Majority Rule classifier and Voting regressor. This module contains: - A Soft Voting/Majority Rule classifier for classification estimators. - A Voting regressor for regression estimators. )abstractmethod)IntegralN)ClassifierMixinRegressorMixinTransformerMixin _fit_contextclone)NotFittedError) LabelEncoder)Bunch) StrOptions) _VisualBlock)MetadataRouter MethodMapping_raise_for_params_routing_enabledprocess_routing) available_if)type_of_target)Paralleldelayed)_check_feature_names_incheck_is_fitted column_or_1d)_BaseHeterogeneousEnsemble_fit_single_estimatorceZdZUdZegddgdegdgdZeed<dZ e dZ d Z e d Zdfd Ze d Zd ZdZxZS) _BaseVotingzrBase class for voting. Warning: This class should not be used directly. Use derived classes instead. z array-likeNverbose) estimatorsweightsn_jobsr!_parameter_constraintsc2|jsyd|d|d|S)N(z of z ) Processing )r!)selfnameidxtotals ^/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sklearn/ensemble/_voting.py _log_messagez_BaseVoting._log_message=s%||3%tE7-v66c|jyt|j|jDcgc]\}}|ddk7s|c}}Scc}}w)z)Get the weights of not `None` estimators.Nrdrop)r#zipr")r(estws r,_weights_not_nonez_BaseVoting._weights_not_noneBsD <<  #DOOT\\ BWfc1c!fPVFVWWWs A A ctj|jDcgc]}|j|c}jScc}wz'Collect results from clf.predict calls.)npasarray estimators_predictT)r(Xr2s r,_predictz_BaseVoting._predictIs3zzT5E5EFc3;;q>FGIIIFsAc ( j\} jctjtjk7r8t dtjdtjdt rt dfi| n:t |D]+}ti |<d|vs|d |jd<-tj fdtt| D_ t_tj}jD]D\}}|d k(r|n t!|}|j|<t#|d s4|j$_FS) zGet common fit operations.z6Number of `estimators` and weights must be equal; got z weights, z estimatorsfit)r? sample_weight)r$c3K|]V\}\}}|dk7rIttt||ddj||dzt Xyw)r0r?Votingr) fit_paramsmessage_clsnamemessageN)rrr r-len) .0r*r)clfr<clfs routed_paramsr(ys r, z"_BaseVoting.fit..css 8 ![dCf} +G) *c (.u5 ())$aTC    8 sAAr0feature_names_in_)_validate_estimatorsr#rFr" ValueErrorrrr r?rr$ enumerater1r9named_estimators_iternexthasattrrM) r(r<rKrCnamesr)est_iterr2 current_estrIrJs ``` @@r,r?z_BaseVoting.fitMs//1 t << #DLL(9S=Q(Q %&jT__1E0FkS   +D%F:FM!GM &+m d#"j0?I'@M$'++O< 884;;7 8 %.c%.>$? 8  "'(() GID#!$#DNK+6D " "4 ({$78)4)F)F&  G r.c &t|||fi|S)a`Return class labels or probabilities for each estimator. Return predictions for X for each estimator. Parameters ---------- X : {array-like, sparse matrix, dataframe} of shape (n_samples, n_features) Input samples. y : ndarray of shape (n_samples,), default=None Target values (None for unsupervised transformations). **fit_params : dict Additional fit parameters. Returns ------- X_new : ndarray array of shape (n_samples, n_features_new) Transformed array. )super fit_transformr(r<rKrC __class__s r,rZz_BaseVoting.fit_transform}s,w$Q8Z88r.c t||j djS#t$r4}tdj|jj |d}~wwxYw)z+Number of features seen during :term:`fit`.z*{} object has no n_features_in_ attribute.Nr)rr AttributeErrorformatr\__name__r9n_features_in_)r(nfes r,raz_BaseVoting.n_features_in_sg   D !"111  <CCNN++   s & A#/AA#cHt|j\}}td||S)Nparallel)rU)r1r"r)r(rUr"s r,_sk_visual_block_z_BaseVoting._sk_visual_block_s$1zJ %@@r.c t|jj}|jD]6\}}|jdi||idt j ddi8|S)ajGet metadata routing of this object. Please check :ref:`User Guide ` on how the routing mechanism works. .. versionadded:: 1.5 Returns ------- routing : MetadataRouter A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating routing information. )ownermethod_mappingr?)calleecaller)rr\r`r"addr)r(routerr) estimators r,get_metadata_routingz _BaseVoting.get_metadata_routingsm dnn&=&=> $ OD) FJJ # ,22%2N    r.N)r` __module__ __qualname____doc__listrr%dict__annotations__r-propertyr4r=rr?rZrarero __classcell__r\s@r,r r /sf $'"; $D7 XX J--^90 2 2Ar.r ceZdZUdZiej eddhgdgdZeed<ddddd d fd Z e d fd Z dZ dZ dZeedZdZddZfdZxZS)VotingClassifieraSoft Voting/Majority Rule classifier for unfitted estimators. Read more in the :ref:`User Guide `. .. versionadded:: 0.17 Parameters ---------- estimators : list of (str, estimator) tuples Invoking the ``fit`` method on the ``VotingClassifier`` will fit clones of those original estimators that will be stored in the class attribute ``self.estimators_``. An estimator can be set to ``'drop'`` using :meth:`set_params`. .. versionchanged:: 0.21 ``'drop'`` is accepted. Using None was deprecated in 0.22 and support was removed in 0.24. voting : {'hard', 'soft'}, default='hard' If 'hard', uses predicted class labels for majority rule voting. Else if 'soft', predicts the class label based on the argmax of the sums of the predicted probabilities, which is recommended for an ensemble of well-calibrated classifiers. weights : array-like of shape (n_classifiers,), default=None Sequence of weights (`float` or `int`) to weight the occurrences of predicted class labels (`hard` voting) or class probabilities before averaging (`soft` voting). Uses uniform weights if `None`. n_jobs : int, default=None The number of jobs to run in parallel for ``fit``. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary ` for more details. .. versionadded:: 0.18 flatten_transform : bool, default=True Affects shape of transform output only when voting='soft' If voting='soft' and flatten_transform=True, transform method returns matrix with shape (n_samples, n_classifiers * n_classes). If flatten_transform=False, it returns (n_classifiers, n_samples, n_classes). verbose : bool, default=False If True, the time elapsed while fitting will be printed as it is completed. .. versionadded:: 0.23 Attributes ---------- estimators_ : list of classifiers The collection of fitted sub-estimators as defined in ``estimators`` that are not 'drop'. named_estimators_ : :class:`~sklearn.utils.Bunch` Attribute to access any fitted sub-estimators by name. .. versionadded:: 0.20 le_ : :class:`~sklearn.preprocessing.LabelEncoder` Transformer used to encode the labels during fit and decode during prediction. classes_ : ndarray of shape (n_classes,) The classes labels. n_features_in_ : int Number of features seen during :term:`fit`. Only defined if the underlying classifier exposes such an attribute when fit. .. versionadded:: 0.24 feature_names_in_ : ndarray of shape (`n_features_in_`,) Names of features seen during :term:`fit`. Only defined if the underlying estimators expose such an attribute when fit. .. versionadded:: 1.0 See Also -------- VotingRegressor : Prediction voting regressor. Examples -------- >>> import numpy as np >>> from sklearn.linear_model import LogisticRegression >>> from sklearn.naive_bayes import GaussianNB >>> from sklearn.ensemble import RandomForestClassifier, VotingClassifier >>> clf1 = LogisticRegression(random_state=1) >>> clf2 = RandomForestClassifier(n_estimators=50, random_state=1) >>> clf3 = GaussianNB() >>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]]) >>> y = np.array([1, 1, 1, 2, 2, 2]) >>> eclf1 = VotingClassifier(estimators=[ ... ('lr', clf1), ('rf', clf2), ('gnb', clf3)], voting='hard') >>> eclf1 = eclf1.fit(X, y) >>> print(eclf1.predict(X)) [1 1 1 2 2 2] >>> np.array_equal(eclf1.named_estimators_.lr.predict(X), ... eclf1.named_estimators_['lr'].predict(X)) True >>> eclf2 = VotingClassifier(estimators=[ ... ('lr', clf1), ('rf', clf2), ('gnb', clf3)], ... voting='soft') >>> eclf2 = eclf2.fit(X, y) >>> print(eclf2.predict(X)) [1 1 1 2 2 2] To drop an estimator, :meth:`set_params` can be used to remove it. Here we dropped one of the estimators, resulting in 2 fitted estimators: >>> eclf2 = eclf2.set_params(lr='drop') >>> eclf2 = eclf2.fit(X, y) >>> len(eclf2.estimators_) 2 Setting `flatten_transform=True` with `voting='soft'` flattens output shape of `transform`: >>> eclf3 = VotingClassifier(estimators=[ ... ('lr', clf1), ('rf', clf2), ('gnb', clf3)], ... voting='soft', weights=[2,1,1], ... flatten_transform=True) >>> eclf3 = eclf3.fit(X, y) >>> print(eclf3.predict(X)) [1 1 1 2 2 2] >>> print(eclf3.transform(X).shape) (6, 6) hardsoftboolean)votingflatten_transformr%NTF)rr#r$rr!clt||||_||_||_||_||_yN)r")rY__init__rr#r$rr!)r(r"rr#r$rr!r\s r,rzVotingClassifier.__init__Ms9 J/   !2 r.prefer_skip_nested_validationc zt||ddgt|d}|dvrtd|d|d vr"t|jj d t j||_|jj|_ |jj|}t|||fi|S) aRFit the estimators. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training vectors, where `n_samples` is the number of samples and `n_features` is the number of features. y : array-like of shape (n_samples,) Target values. **fit_params : dict Parameters to pass to the underlying estimators. .. versionadded:: 1.5 Only available if `enable_metadata_routing=True`, which can be set by using ``sklearn.set_config(enable_metadata_routing=True)``. See :ref:`Metadata Routing User Guide ` for more details. Returns ------- self : object Returns the instance itself. r?r@allowrK) input_name)unknown continuouszUnknown label type: zy. Maybe you are trying to fit a classifier, which expects discrete classes on a regression target with continuous values.)binary multiclasszq only supports binary or multiclass classification. Multilabel and multi-output classification are not supported.) rrrONotImplementedErrorr\r`r r?le_classes_ transformrY)r(r<rKrCy_type transformed_yr\s r,r?zVotingClassifier.fit^s@ *dE/9JKc2 . .&vh/<<  3 3&>>**+,   >%%a()) **1- w{1m:z::r.ctjdk(r'tjj |d}n,j |}tj fdd|}jj|}|S)a'Predict class labels for X. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Returns ------- maj : array-like of shape (n_samples,) Predicted class labels. r}r)axiscltjtj|jS)N)r#)r7argmaxbincountr4)xr(s r,z*VotingClassifier.predict..s!"))BKK4;Q;Q$RSr.)rarr) rrr7r predict_probar=apply_along_axisrinverse_transform)r(r<maj predictionss` r,r:zVotingClassifier.predictsx  ;;& ))D..q1:C--*K%%SC hh((- r.ctj|jDcgc]}|j|c}Scc}wr6)r7r8r9r)r(r<rHs r,_collect_probasz VotingClassifier._collect_probass0zz4;K;KLC3,,Q/LMMLs=cR|jdk(rtd|jy)Nr|z+predict_proba is not available when voting=T)rr^)r(s r, _check_votingzVotingClassifier._check_votings. ;;&  =dkk_M r.c~t|tj|j|d|j}|S)arCompute probabilities of possible outcomes for samples in X. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Returns ------- avg : array-like of shape (n_samples, n_classes) Weighted average probability for each class per sample. rrr#)rr7averagerr4)r(r<avgs r,rzVotingClassifier.predict_probas9 jj   #!T5K5K  r.ct||jdk(r4|j|}|js|St j |S|j |S)arReturn class labels or probabilities for X for each estimator. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training vectors, where `n_samples` is the number of samples and `n_features` is the number of features. Returns ------- probabilities_or_labels If `voting='soft'` and `flatten_transform=True`: returns ndarray of shape (n_samples, n_classifiers * n_classes), being class probabilities calculated by each classifier. If `voting='soft' and `flatten_transform=False`: ndarray of shape (n_classifiers, n_samples, n_classes) If `voting='hard'`: ndarray of shape (n_samples, n_classifiers), being class labels predicted by each classifier. r})rrrrr7hstackr=)r(r<probass r,rzVotingClassifier.transformsV*  ;;& ))!,F)) 99V$ $==# #r.c ^t|d|jdk(r|js tdt ||d|j j j}|jDcgc] \}}|dk7s |}}}|jdk(r.tj|Dcgc] }|d| c}t St|j}|Dcgc]}t|D] }|d|| }}}tj|t Scc}}wcc}wcc}}w) ^Get output feature names for transformation. Parameters ---------- input_features : array-like of str or None, default=None Not used, present here for API consistency by convention. Returns ------- feature_names_out : ndarray of str objects Transformed feature names. rar}zYget_feature_names_out is not supported when `voting='soft'` and `flatten_transform=False`Fgenerate_namesr0r|_dtype)rrrrOrr\r`lowerr"r7r8objectrFrrange) r(input_features class_namer)r2 active_names n_classesi names_outs r,get_feature_names_outz&VotingClassifier.get_feature_names_outs( ./ ;;& )?)?,  nUK^^,,224 .2ooOsO O ;;& ::4@ADJ *.iHX CDzl!D6! % %  zz)622PB  s4 DD+D$ D)cFt|}g|j_|Srp)rY__sklearn_tags__transformer_tagspreserves_dtype)r(tagsr\s r,rz!VotingClassifier.__sklearn_tags__s#w')02- r.rp)r`rqrrrsr r%rrurvrr r?r:rrrrrrrrxrys@r,r{r{sBH$  , ,$vv./0'[$D"&+3; 3;j:N- !&$@#3Jr.r{cbeZdZdZddddfd ZedfdZdZd Zd d Z xZ S) VotingRegressora Prediction voting regressor for unfitted estimators. A voting regressor is an ensemble meta-estimator that fits several base regressors, each on the whole dataset. Then it averages the individual predictions to form a final prediction. For a detailed example, refer to :ref:`sphx_glr_auto_examples_ensemble_plot_voting_regressor.py`. Read more in the :ref:`User Guide `. .. versionadded:: 0.21 Parameters ---------- estimators : list of (str, estimator) tuples Invoking the ``fit`` method on the ``VotingRegressor`` will fit clones of those original estimators that will be stored in the class attribute ``self.estimators_``. An estimator can be set to ``'drop'`` using :meth:`set_params`. .. versionchanged:: 0.21 ``'drop'`` is accepted. Using None was deprecated in 0.22 and support was removed in 0.24. weights : array-like of shape (n_regressors,), default=None Sequence of weights (`float` or `int`) to weight the occurrences of predicted values before averaging. Uses uniform weights if `None`. n_jobs : int, default=None The number of jobs to run in parallel for ``fit``. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary ` for more details. verbose : bool, default=False If True, the time elapsed while fitting will be printed as it is completed. .. versionadded:: 0.23 Attributes ---------- estimators_ : list of regressors The collection of fitted sub-estimators as defined in ``estimators`` that are not 'drop'. named_estimators_ : :class:`~sklearn.utils.Bunch` Attribute to access any fitted sub-estimators by name. .. versionadded:: 0.20 n_features_in_ : int Number of features seen during :term:`fit`. Only defined if the underlying regressor exposes such an attribute when fit. .. versionadded:: 0.24 feature_names_in_ : ndarray of shape (`n_features_in_`,) Names of features seen during :term:`fit`. Only defined if the underlying estimators expose such an attribute when fit. .. versionadded:: 1.0 See Also -------- VotingClassifier : Soft Voting/Majority Rule classifier. Examples -------- >>> import numpy as np >>> from sklearn.linear_model import LinearRegression >>> from sklearn.ensemble import RandomForestRegressor >>> from sklearn.ensemble import VotingRegressor >>> from sklearn.neighbors import KNeighborsRegressor >>> r1 = LinearRegression() >>> r2 = RandomForestRegressor(n_estimators=10, random_state=1) >>> r3 = KNeighborsRegressor() >>> X = np.array([[1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36]]) >>> y = np.array([2, 6, 12, 20, 30, 42]) >>> er = VotingRegressor([('lr', r1), ('rf', r2), ('r3', r3)]) >>> print(er.fit(X, y).predict(X)) [ 6.8 8.4 12.5 17.8 26 34] In the following example, we drop the `'lr'` estimator with :meth:`~VotingRegressor.set_params` and fit the remaining two estimators: >>> er = er.set_params(lr='drop') >>> er = er.fit(X, y) >>> len(er.estimators_) 2 NF)r#r$r!cPt||||_||_||_yr)rYrr#r$r!)r(r"r#r$r!r\s r,rzVotingRegressor.__init__|s( J/   r.rc `t||ddgt|d}t| ||fi|S)aGFit the estimators. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training vectors, where `n_samples` is the number of samples and `n_features` is the number of features. y : array-like of shape (n_samples,) Target values. **fit_params : dict Parameters to pass to the underlying estimators. .. versionadded:: 1.5 Only available if `enable_metadata_routing=True`, which can be set by using ``sklearn.set_config(enable_metadata_routing=True)``. See :ref:`Metadata Routing User Guide ` for more details. Returns ------- self : object Fitted estimator. r?r@rT)warn)rrrYr?r[s r,r?zVotingRegressor.fits9@ *dE/9JK  &w{1a.:..r.czt|tj|j|d|jS)aPredict regression target for X. The predicted regression target of an input sample is computed as the mean predicted regression targets of the estimators in the ensemble. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Returns ------- y : ndarray of shape (n_samples,) The predicted values. rr)rr7rr=r4r(r<s r,r:zVotingRegressor.predicts. zz$--*Drs((050-. EP"$>PfY Yx @ nk@ r.