`L iP/dZddlZddlZddlmZmZddlmZddlmZm Z ddl Z ddl m Z ddlmZdd lmZmZmZmZmZmZmZdd lmZmZmZdd lmZmZmZm Z dd l!m"Z"dd l#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)ddl*m+Z+m,Z,m-Z-ddl+m.Z.ddl,m/Z/ddl-m0Z0m1Z1m2Z2m3Z3m4Z4ddl5m6Z6gdZ7e-jpZ8e-jrZ9e+jte+jve+jvdZ>+B+BNsK ++A. a 1= 1 [[h ' $&&)K ${{;' +A V" V Vxx $)9!)<&-- $ $s CCc t|j}|r ttdd}tdd}t |||||f\}}|j |}t |ri|j|jjtjk7s'|jjtjk7r td|jdk(rFtj|dkr td tj |dkr td |j"\} |_t'|} tj(|}d} |j*d k(rtj,|d }|j"d |_| rQt1|tj2|}g|_g|_|j8tj2|} tj:|j"t< } t?|j.D]m}tj@|dd|fd\}| dd|f<|j4jC||j6jC|j"do| }|j8tE|j8 } tjF|j6tjH |_tK|ddtLk7s|jNjPstjR|tL }|jT-tjVtjXjZn |jT}t]|j^t`jbr |j^}nte|j^| z}t]|jft`jbr |jf}n$te|jf| z}t[d|}t[|d|z}t]|jhtjr|jhdk(r3t[d t=tjl|j$}n|jhdk(rt[d t=tjn|j$}n|jh |j$}not]|jht`jbr |jh}n>|jhdkDr-t[d t=|jh|j$z}nd}|_8|jrdn |jr}tu|| k7rtdtu|| fz|tw||tL }| ||| z}n| }||jx| z}n"|jxtj |z}|j}t]|tzsT| r.t}|j|j.|j6}n9t|j|j.| }nt3j|}t |rtnt}|j}|jd}n-|j.d kDr tdtj|j}|j"d|j"d k7r5tdj|j"d|j"d tj|d}tj|s#tj@|}td|tj|tj }t'|r"|j6ddkDr td|dz}t]|jts$||j||jp||||}t'|r1t|j$|j6|j.|_LnWt|j$tjFd g|j.ztjH |j.|_L|dkrt||||||j}nt|||||||j}|j|j|||||j.d k(r3t'|r(|j6d|_|j4d|_|j|S)NcscF)dtype accept_sparseensure_all_finite) ensure_2dr{)validate_separately3No support for np.int64 index based sparse matricesr6rzLSome value(s) of y are negative which is not allowed for Poisson regression.zCSum of y is not positive which is necessary for Poisson regression.r )r r{T)return_inverser{r rDrEr?rz7Number of labels=%d does not match number of samples=%dzAMonotonicity constraints are not supported with multiple outputs.z@monotonic_cst has shape {} but the input data X has {} features.)rrr zCmonotonic_cst must be None or an array-like of -1, 0 or 1, but got zIMonotonicity constraints are not supported with multiclass classification)RrrFroDTYPErrxr sort_indicesindicesr{rpintcindptr ValueErrorrUanyrrshapen_features_in_r atleast_1dndimreshape n_outputs_rcopyclasses_ n_classes_rRzerosintrangeuniqueappendrarrayintpgetattrDOUBLEflags contiguousascontiguousarrayrHiinfoint32max isinstancerJnumbersrrrIrLstrrDrE max_features_rMlenrrKr$ CRITERIA_CLF CRITERIA_REGdeepcopySPARSE_SPLITTERSDENSE_SPLITTERSrGrPasarrayformatisinallint8r%r(r[r'rNr&build _prune_tree)rVrey sample_weightr<rwrFcheck_X_paramscheck_y_params n_samplesis_classificationexpanded_class_weight y_original y_encodedk classes_krHrJrIrLrMmin_weight_leafrU SPLITTERSrGrPvalid_constraintsunique_constaints_valuebuilders rW_fitzBaseDecisionTree._fits*$*;*;< "5EN"E>N a0PDAq <$< *+& 4&)$/ MM!  $ 66Q; 1g&A''!*  ( + ADM DO  ,WWQZ 4I4??+ ;-/YYqAwt-T* 9QT? $$Y/&&yq'9: ;A  ,(=%%z)%!hhtbggFDO 1gt $ .agg6H6H$$Qf5A.2nn.DBHHRXX&**$.. d++W-=-= >#44 #D$9$9I$EF  d,,g.>.> ? $ 6 6  $T%;%;i%G H  #A'8 9  117G3GH d'' -  F*"1c"''$2E2E*F&GH ""f,"1c"''$2E2E*F&GH    &..L ))7+;+; <,,L  3&"1c$*;*;d>Q>Q*Q&RS  )#22:@S@S q6Y Iq69%&   $0PM ,( -0E E 5   ";;iGO";;bff]>SSONN )Y/ (8OOT__ )8)T  i0I(0 $ ==    % M" WJJt'9'9:M""1%3 ))/ 0C0CA0FPQ )S!# z B 66+,*,))M*B' 346JJ}BGGDMT"??1%)$)# $--2/y/""  H  d114??DOOTDJ##!t.bgg> DJ A +! ** G+! **G  djj!Q 7UV ??a M$$7"ooa0DO MM!,DM  rYcH|r|j|rd}nd}t||tdd|}t|rY|jj t jk7s'|jj t jk7r td|St||d|S)z6Validate the training data on predict (probabilities).z allow-nanTcsrF)r{r|resetr}r)r) rfrrrrr{rprrrr)rVrer<r}s rW_validate_X_predictz$BaseDecisionTree._validate_X_predicts ++A.$/!$(!#"3 A{ 277*ahhnn.G !VWW dAU 3rYct||j||}|jj|}|jd}t |r|j dk(r2|jjtj|ddS|jdj}tj||j f|}t|j D]E}|j|jtj|dd|fdd|dd|f<G|S|j dk(r |dddfS|dddddfS)aGPredict class or regression value for X. For a classification model, the predicted class for each sample in X is returned. For a regression model, the predicted value based on X is returned. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided to a sparse ``csr_matrix``. check_input : bool, default=True Allow to bypass several input checking. Don't use this parameter unless you know what you're doing. Returns ------- y : array-like of shape (n_samples,) or (n_samples, n_outputs) The predicted classes, or the predict values. rr )axisrN)rrr[predictrrrrtakerpargmaxr{rr)rVrer<probar class_type predictionsrs rWrzBaseDecisionTree.predicts6.   $ $Q 4 ""1%GGAJ   !#}}))"))E*B)KK"]]1-33  hh 4??'C:V t/A(, a(8(=(= %1+A6Q)>)K1% #"!#QT{"Q1W~%rYcrt||j||}|jj|S)aWReturn the index of the leaf that each sample is predicted as. .. versionadded:: 0.17 Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided to a sparse ``csr_matrix``. check_input : bool, default=True Allow to bypass several input checking. Don't use this parameter unless you know what you're doing. Returns ------- X_leaves : array-like of shape (n_samples,) For each datapoint x in X, return the index of the leaf x ends up in. Leaves are numbered within ``[0; self.tree_.node_count)``, possibly with gaps in the numbering. )rrr[applyrVrer<s rWrzBaseDecisionTree.apply-s30   $ $Q 4zz""rYc\|j||}|jj|S)aReturn the decision path in the tree. .. versionadded:: 0.18 Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided to a sparse ``csr_matrix``. check_input : bool, default=True Allow to bypass several input checking. Don't use this parameter unless you know what you're doing. Returns ------- indicator : sparse matrix of shape (n_samples, n_nodes) Return a node indicator CSR matrix where non zero elements indicates that the samples goes through the nodes. )rr[ decision_pathrs rWrzBaseDecisionTree.decision_pathIs+,  $ $Q 4zz''**rYct||jdk(ryt|rAtj|j }t |j||j}nRt |jtjdg|jztj|j}t||j|j||_ y)z1Prune tree using Minimal Cost-Complexity Pruning.r?Nr r) rrOrrprrr(rrrrr)r[)rV n_classes pruned_trees rWrzBaseDecisionTree._prune_treebs >>S    doo6It22ItOK##!t.bgg> K {DJJG  rYct|jd}|j|||tdit |j S)aCompute the pruning path during Minimal Cost-Complexity Pruning. See :ref:`minimal_cost_complexity_pruning` for details on the pruning process. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The training input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided to a sparse ``csc_matrix``. y : array-like of shape (n_samples,) or (n_samples, n_outputs) The target values (class labels) as integers or strings. sample_weight : array-like of shape (n_samples,), default=None Sample weights. If None, then samples are equally weighted. Splits that would create child nodes with net zero or negative weight are ignored while searching for a split in each node. Splits are also ignored if they would result in any single class carrying a negative weight in either child node. Returns ------- ccp_path : :class:`~sklearn.utils.Bunch` Dictionary-like object, with the following attributes. ccp_alphas : ndarray Effective alphas of subtree during pruning. impurities : ndarray Sum of the impurities of the subtree leaves for the corresponding alpha value in ``ccp_alphas``. r?)rO)r)r set_paramsfitrr*r[)rVrerrests rWcost_complexity_pruning_pathz-BaseDecisionTree.cost_complexity_pruning_pathxsFFDk$$s$3 1M23' 233rYcLt||jjS)apReturn the feature importances. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance. Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See :func:`sklearn.inspection.permutation_importance` as an alternative. Returns ------- feature_importances_ : ndarray of shape (n_features,) Normalized total reduction of criteria by feature (Gini importance). )rr[compute_feature_importancesr\s rWfeature_importances_z%BaseDecisionTree.feature_importances_s$ zz5577rYcFt|}d|j_|SNT)superrbrcsparse)rVtagsrms rWrbz!BaseDecisionTree.__sklearn_tags__s!w')!% rYrT)NTNT) rn __module__ __qualname____doc__r UNUSED,_BaseDecisionTree__metadata_request__predictrrrrrrQro__annotations__rrXr]r`rfrxrrrrrrrpropertyrrb __classcell__rms@rWr;r;[s$12B2I2I"J  234xD@$G Xq$v 6 Zc' : Xq$v 6 Zc) < &.dCV%L$M Xq$v 6 Zc' : ' (   ((#HafEtL"*4d6"J!KtS$v>?&--$D2++> $ # &.X'+ yv01&f#8+2!,%4N88*rYr;) metaclassceZdZUdZdej iZdej iZieje hde e ge ee dhdgdZ e ed<dd dd d d dddd dd dd fd Zeddfd ZddZdZfdZxZS)r,a[)A decision tree classifier. Read more in the :ref:`User Guide `. Parameters ---------- criterion : {"gini", "entropy", "log_loss"}, default="gini" The function to measure the quality of a split. Supported criteria are "gini" for the Gini impurity and "log_loss" and "entropy" both for the Shannon information gain, see :ref:`tree_mathematical_formulation`. splitter : {"best", "random"}, default="best" The strategy used to choose the split at each node. Supported strategies are "best" to choose the best split and "random" to choose the best random split. max_depth : int, default=None The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples. min_samples_split : int or float, default=2 The minimum number of samples required to split an internal node: - If int, then consider `min_samples_split` as the minimum number. - If float, then `min_samples_split` is a fraction and `ceil(min_samples_split * n_samples)` are the minimum number of samples for each split. .. versionchanged:: 0.18 Added float values for fractions. min_samples_leaf : int or float, default=1 The minimum number of samples required to be at a leaf node. A split point at any depth will only be considered if it leaves at least ``min_samples_leaf`` training samples in each of the left and right branches. This may have the effect of smoothing the model, especially in regression. - If int, then consider `min_samples_leaf` as the minimum number. - If float, then `min_samples_leaf` is a fraction and `ceil(min_samples_leaf * n_samples)` are the minimum number of samples for each node. .. versionchanged:: 0.18 Added float values for fractions. min_weight_fraction_leaf : float, default=0.0 The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided. max_features : int, float or {"sqrt", "log2"}, default=None The number of features to consider when looking for the best split: - If int, then consider `max_features` features at each split. - If float, then `max_features` is a fraction and `max(1, int(max_features * n_features_in_))` features are considered at each split. - If "sqrt", then `max_features=sqrt(n_features)`. - If "log2", then `max_features=log2(n_features)`. - If None, then `max_features=n_features`. .. note:: The search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than ``max_features`` features. random_state : int, RandomState instance or None, default=None Controls the randomness of the estimator. The features are always randomly permuted at each split, even if ``splitter`` is set to ``"best"``. When ``max_features < n_features``, the algorithm will select ``max_features`` at random at each split before finding the best split among them. But the best found split may vary across different runs, even if ``max_features=n_features``. That is the case, if the improvement of the criterion is identical for several splits and one split has to be selected at random. To obtain a deterministic behaviour during fitting, ``random_state`` has to be fixed to an integer. See :term:`Glossary ` for details. max_leaf_nodes : int, default=None Grow a tree with ``max_leaf_nodes`` in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes. min_impurity_decrease : float, default=0.0 A node will be split if this split induces a decrease of the impurity greater than or equal to this value. The weighted impurity decrease equation is the following:: N_t / N * (impurity - N_t_R / N_t * right_impurity - N_t_L / N_t * left_impurity) where ``N`` is the total number of samples, ``N_t`` is the number of samples at the current node, ``N_t_L`` is the number of samples in the left child, and ``N_t_R`` is the number of samples in the right child. ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum, if ``sample_weight`` is passed. .. versionadded:: 0.19 class_weight : dict, list of dict or "balanced", default=None Weights associated with classes in the form ``{class_label: weight}``. If None, all classes are supposed to have weight one. For multi-output problems, a list of dicts can be provided in the same order as the columns of y. Note that for multioutput (including multilabel) weights should be defined for each class of every column in its own dict. For example, for four-class multilabel classification weights should be [{0: 1, 1: 1}, {0: 1, 1: 5}, {0: 1, 1: 1}, {0: 1, 1: 1}] instead of [{1:1}, {2:5}, {3:1}, {4:1}]. The "balanced" mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as ``n_samples / (n_classes * np.bincount(y))`` For multi-output, the weights of each column of y will be multiplied. Note that these weights will be multiplied with sample_weight (passed through the fit method) if sample_weight is specified. ccp_alpha : non-negative float, default=0.0 Complexity parameter used for Minimal Cost-Complexity Pruning. The subtree with the largest cost complexity that is smaller than ``ccp_alpha`` will be chosen. By default, no pruning is performed. See :ref:`minimal_cost_complexity_pruning` for details. See :ref:`sphx_glr_auto_examples_tree_plot_cost_complexity_pruning.py` for an example of such pruning. .. versionadded:: 0.22 monotonic_cst : array-like of int of shape (n_features), default=None Indicates the monotonicity constraint to enforce on each feature. - 1: monotonic increase - 0: no constraint - -1: monotonic decrease If monotonic_cst is None, no constraints are applied. Monotonicity constraints are not supported for: - multiclass classifications (i.e. when `n_classes > 2`), - multioutput classifications (i.e. when `n_outputs_ > 1`), - classifications trained on data with missing values. The constraints hold over the probability of the positive class. Read more in the :ref:`User Guide `. .. versionadded:: 1.4 Attributes ---------- classes_ : ndarray of shape (n_classes,) or list of ndarray The classes labels (single output problem), or a list of arrays of class labels (multi-output problem). feature_importances_ : ndarray of shape (n_features,) The impurity-based feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance [4]_. Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See :func:`sklearn.inspection.permutation_importance` as an alternative. max_features_ : int The inferred value of max_features. n_classes_ : int or list of int The number of classes (for single output problems), or a list containing the number of classes for each output (for multi-output problems). 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 n_outputs_ : int The number of outputs when ``fit`` is performed. tree_ : Tree instance The underlying Tree object. Please refer to ``help(sklearn.tree._tree.Tree)`` for attributes of Tree object and :ref:`sphx_glr_auto_examples_tree_plot_unveil_tree_structure.py` for basic usage of these attributes. See Also -------- DecisionTreeRegressor : A decision tree regressor. Notes ----- The default values for the parameters controlling the size of the trees (e.g. ``max_depth``, ``min_samples_leaf``, etc.) lead to fully grown and unpruned trees which can potentially be very large on some data sets. To reduce memory consumption, the complexity and size of the trees should be controlled by setting those parameter values. The :meth:`predict` method operates using the :func:`numpy.argmax` function on the outputs of :meth:`predict_proba`. This means that in case the highest predicted probabilities are tied, the classifier will predict the tied class with the lowest index in :term:`classes_`. References ---------- .. [1] https://en.wikipedia.org/wiki/Decision_tree_learning .. [2] L. Breiman, J. Friedman, R. Olshen, and C. Stone, "Classification and Regression Trees", Wadsworth, Belmont, CA, 1984. .. [3] T. Hastie, R. Tibshirani and J. Friedman. "Elements of Statistical Learning", Springer, 2009. .. [4] L. Breiman, and A. Cutler, "Random Forests", https://www.stat.berkeley.edu/~breiman/RandomForests/cc_home.htm Examples -------- >>> from sklearn.datasets import load_iris >>> from sklearn.model_selection import cross_val_score >>> from sklearn.tree import DecisionTreeClassifier >>> clf = DecisionTreeClassifier(random_state=0) >>> iris = load_iris() >>> cross_val_score(clf, iris.data, iris.target, cv=10) ... # doctest: +SKIP ... array([ 1. , 0.93, 0.86, 0.93, 0.93, 0.93, 0.93, 1. , 0.93, 1. ]) r<>r0r2r1balancedN)rUrRrQr0r8r r r? rUrGrHrIrJrKrLrFrMrNrRrOrPc >t||||||||| | || | |  y)N) rUrGrHrIrJrKrLrMrRrFrNrPrOrrXrVrUrGrHrIrJrKrLrFrMrNrRrOrPrms rWrXzDecisionTreeClassifier.__init__s>" /-%=%)%%"7'  rYTprefer_skip_nested_validationc.t||||||S)aBuild a decision tree classifier from the training set (X, y). Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The training input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided to a sparse ``csc_matrix``. y : array-like of shape (n_samples,) or (n_samples, n_outputs) The target values (class labels) as integers or strings. sample_weight : array-like of shape (n_samples,), default=None Sample weights. If None, then samples are equally weighted. Splits that would create child nodes with net zero or negative weight are ignored while searching for a split in each node. Splits are also ignored if they would result in any single class carrying a negative weight in either child node. check_input : bool, default=True Allow to bypass several input checking. Don't use this parameter unless you know what you're doing. Returns ------- self : DecisionTreeClassifier Fitted estimator. rr<rrrVrerrr<rms rWrzDecisionTreeClassifier.fits)>  '#   rYcJt||j||}|jj|}|jdk(r|ddd|j fSg}t |jD],}|dd|d|j |f}|j|.|S)aPredict class probabilities of the input samples X. The predicted class probability is the fraction of samples of the same class in a leaf. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided to a sparse ``csr_matrix``. check_input : bool, default=True Allow to bypass several input checking. Don't use this parameter unless you know what you're doing. Returns ------- proba : ndarray of shape (n_samples, n_classes) or list of n_outputs such arrays if n_outputs > 1 The class probabilities of the input samples. The order of the classes corresponds to that in the attribute :term:`classes_`. r N)rrr[rrrrr)rVrer<r all_probarproba_ks rW predict_probaz$DecisionTreeClassifier.predict_probas0   $ $Q 4 ""1% ??a -doo--. .I4??+ *1&:(:&: :;  ) * rYc|j|}|jdk(rtj|St |jD]}tj||||<|S)aPredict class log-probabilities of the input samples X. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided to a sparse ``csr_matrix``. Returns ------- proba : ndarray of shape (n_samples, n_classes) or list of n_outputs such arrays if n_outputs > 1 The class log-probabilities of the input samples. The order of the classes corresponds to that in the attribute :term:`classes_`. r )rrrplogr)rVrerrs rWpredict_log_probaz(DecisionTreeClassifier.predict_log_proba-se"""1% ??a 66%= 4??+ ,66%(+a ,LrYct|}|jdvxr|jdv}d|j_||j _|S)Nr7>r0r2r1TrrbrGrUclassifier_tags multi_labelrcrdrVrrdrms rWrbz'DecisionTreeClassifier.__sklearn_tags__IsXw')MM%77 DNNO = ,0($-! rYrr)rnrrrr r8_DecisionTreeClassifier__metadata_request__predict_proba._DecisionTreeClassifier__metadata_request__fitr;rQrrr$rolistrrXrrrrrbrrs@rWr,r,srl*78H8O8O(P%,.>.E.EF$  1 1$ !@A6)CTUtZ %=tD$D!$! B5$6$L#J8  rYr,c eZdZUdZdej iZiejde hde e giZe e d<dddd d d dddd d dd fd Zeddfd ZdZfdZxZS)r-a$A decision tree regressor. Read more in the :ref:`User Guide `. Parameters ---------- criterion : {"squared_error", "friedman_mse", "absolute_error", "poisson"}, default="squared_error" The function to measure the quality of a split. Supported criteria are "squared_error" for the mean squared error, which is equal to variance reduction as feature selection criterion and minimizes the L2 loss using the mean of each terminal node, "friedman_mse", which uses mean squared error with Friedman's improvement score for potential splits, "absolute_error" for the mean absolute error, which minimizes the L1 loss using the median of each terminal node, and "poisson" which uses reduction in the half mean Poisson deviance to find splits. .. versionadded:: 0.18 Mean Absolute Error (MAE) criterion. .. versionadded:: 0.24 Poisson deviance criterion. splitter : {"best", "random"}, default="best" The strategy used to choose the split at each node. Supported strategies are "best" to choose the best split and "random" to choose the best random split. max_depth : int, default=None The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples. For an example of how ``max_depth`` influences the model, see :ref:`sphx_glr_auto_examples_tree_plot_tree_regression.py`. min_samples_split : int or float, default=2 The minimum number of samples required to split an internal node: - If int, then consider `min_samples_split` as the minimum number. - If float, then `min_samples_split` is a fraction and `ceil(min_samples_split * n_samples)` are the minimum number of samples for each split. .. versionchanged:: 0.18 Added float values for fractions. min_samples_leaf : int or float, default=1 The minimum number of samples required to be at a leaf node. A split point at any depth will only be considered if it leaves at least ``min_samples_leaf`` training samples in each of the left and right branches. This may have the effect of smoothing the model, especially in regression. - If int, then consider `min_samples_leaf` as the minimum number. - If float, then `min_samples_leaf` is a fraction and `ceil(min_samples_leaf * n_samples)` are the minimum number of samples for each node. .. versionchanged:: 0.18 Added float values for fractions. min_weight_fraction_leaf : float, default=0.0 The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided. max_features : int, float or {"sqrt", "log2"}, default=None The number of features to consider when looking for the best split: - If int, then consider `max_features` features at each split. - If float, then `max_features` is a fraction and `max(1, int(max_features * n_features_in_))` features are considered at each split. - If "sqrt", then `max_features=sqrt(n_features)`. - If "log2", then `max_features=log2(n_features)`. - If None, then `max_features=n_features`. Note: the search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than ``max_features`` features. random_state : int, RandomState instance or None, default=None Controls the randomness of the estimator. The features are always randomly permuted at each split, even if ``splitter`` is set to ``"best"``. When ``max_features < n_features``, the algorithm will select ``max_features`` at random at each split before finding the best split among them. But the best found split may vary across different runs, even if ``max_features=n_features``. That is the case, if the improvement of the criterion is identical for several splits and one split has to be selected at random. To obtain a deterministic behaviour during fitting, ``random_state`` has to be fixed to an integer. See :term:`Glossary ` for details. max_leaf_nodes : int, default=None Grow a tree with ``max_leaf_nodes`` in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes. min_impurity_decrease : float, default=0.0 A node will be split if this split induces a decrease of the impurity greater than or equal to this value. The weighted impurity decrease equation is the following:: N_t / N * (impurity - N_t_R / N_t * right_impurity - N_t_L / N_t * left_impurity) where ``N`` is the total number of samples, ``N_t`` is the number of samples at the current node, ``N_t_L`` is the number of samples in the left child, and ``N_t_R`` is the number of samples in the right child. ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum, if ``sample_weight`` is passed. .. versionadded:: 0.19 ccp_alpha : non-negative float, default=0.0 Complexity parameter used for Minimal Cost-Complexity Pruning. The subtree with the largest cost complexity that is smaller than ``ccp_alpha`` will be chosen. By default, no pruning is performed. See :ref:`minimal_cost_complexity_pruning` for details. See :ref:`sphx_glr_auto_examples_tree_plot_cost_complexity_pruning.py` for an example of such pruning. .. versionadded:: 0.22 monotonic_cst : array-like of int of shape (n_features), default=None Indicates the monotonicity constraint to enforce on each feature. - 1: monotonic increase - 0: no constraint - -1: monotonic decrease If monotonic_cst is None, no constraints are applied. Monotonicity constraints are not supported for: - multioutput regressions (i.e. when `n_outputs_ > 1`), - regressions trained on data with missing values. Read more in the :ref:`User Guide `. .. versionadded:: 1.4 Attributes ---------- feature_importances_ : ndarray of shape (n_features,) The feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance [4]_. Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See :func:`sklearn.inspection.permutation_importance` as an alternative. max_features_ : int The inferred value of max_features. 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 n_outputs_ : int The number of outputs when ``fit`` is performed. tree_ : Tree instance The underlying Tree object. Please refer to ``help(sklearn.tree._tree.Tree)`` for attributes of Tree object and :ref:`sphx_glr_auto_examples_tree_plot_unveil_tree_structure.py` for basic usage of these attributes. See Also -------- DecisionTreeClassifier : A decision tree classifier. Notes ----- The default values for the parameters controlling the size of the trees (e.g. ``max_depth``, ``min_samples_leaf``, etc.) lead to fully grown and unpruned trees which can potentially be very large on some data sets. To reduce memory consumption, the complexity and size of the trees should be controlled by setting those parameter values. References ---------- .. [1] https://en.wikipedia.org/wiki/Decision_tree_learning .. [2] L. Breiman, J. Friedman, R. Olshen, and C. Stone, "Classification and Regression Trees", Wadsworth, Belmont, CA, 1984. .. [3] T. Hastie, R. Tibshirani and J. Friedman. "Elements of Statistical Learning", Springer, 2009. .. [4] L. Breiman, and A. Cutler, "Random Forests", https://www.stat.berkeley.edu/~breiman/RandomForests/cc_home.htm Examples -------- >>> from sklearn.datasets import load_diabetes >>> from sklearn.model_selection import cross_val_score >>> from sklearn.tree import DecisionTreeRegressor >>> X, y = load_diabetes(return_X_y=True) >>> regressor = DecisionTreeRegressor(random_state=0) >>> cross_val_score(regressor, X, y, cv=10) ... # doctest: +SKIP ... array([-0.39, -0.46, 0.02, 0.06, -0.50, 0.16, 0.11, -0.73, -0.30, -0.00]) r<rU>r6r4r3r5rQr3r8Nr r r?) rUrGrHrIrJrKrLrFrMrNrOrPc <t ||||||||| || | |  y)N) rUrGrHrIrJrKrLrMrFrNrOrPr)rVrUrGrHrIrJrKrLrFrMrNrOrPrms rWrXzDecisionTreeRegressor.__init__?s; /-%=%)%"7'  rYTrc.t||||||S)aaBuild a decision tree regressor from the training set (X, y). Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The training input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided to a sparse ``csc_matrix``. y : array-like of shape (n_samples,) or (n_samples, n_outputs) The target values (real numbers). Use ``dtype=np.float64`` and ``order='C'`` for maximum efficiency. sample_weight : array-like of shape (n_samples,), default=None Sample weights. If None, then samples are equally weighted. Splits that would create child nodes with net zero or negative weight are ignored while searching for a split in each node. check_input : bool, default=True Allow to bypass several input checking. Don't use this parameter unless you know what you're doing. Returns ------- self : DecisionTreeRegressor Fitted estimator. rrrs rWrzDecisionTreeRegressor.fit^s)<  '#   rYc*tj|td}tj|jdtj d}tj|tj d}|jj||||S)avFast partial dependence computation. Parameters ---------- grid : ndarray of shape (n_samples, n_target_features), dtype=np.float32 The grid points on which the partial dependence should be evaluated. target_features : ndarray of shape (n_target_features), dtype=np.intp The set of target features for which the partial dependence should be evaluated. Returns ------- averaged_predictions : ndarray of shape (n_samples,), dtype=np.float64 The value of the partial dependence function on each grid point. C)r{orderr)rr{r) rprrrrfloat64rr[compute_partial_dependence)rVgridtarget_featuresaveraged_predictionss rW%_compute_partial_dependence_recursionz;DecisionTreeRegressor._compute_partial_dependence_recursionsr"zz$e37!xx**Q-rzz **_BGG3O -- /#7 $#rYct|}|jdvxr|jdv}||j_|S)Nr7>r6r4r3rrbrGrUrcrdr s rWrbz&DecisionTreeRegressor.__sklearn_tags__sJw')MM%77 DNNO = %.! rYr)rnrrrr r-_DecisionTreeRegressor__metadata_request__fitr;rQrrr$rorrXrrrrbrrs@rWr-r-WsYz -.>.E.EF$  1 1$ U V 9  $D"!$! >5#6#J$8  rYr-cJeZdZdZdddddddddddddd fd Zfd ZxZS) r.a(An extremely randomized tree classifier. Extra-trees differ from classic decision trees in the way they are built. When looking for the best split to separate the samples of a node into two groups, random splits are drawn for each of the `max_features` randomly selected features and the best split among those is chosen. When `max_features` is set 1, this amounts to building a totally random decision tree. Warning: Extra-trees should only be used within ensemble methods. Read more in the :ref:`User Guide `. Parameters ---------- criterion : {"gini", "entropy", "log_loss"}, default="gini" The function to measure the quality of a split. Supported criteria are "gini" for the Gini impurity and "log_loss" and "entropy" both for the Shannon information gain, see :ref:`tree_mathematical_formulation`. splitter : {"random", "best"}, default="random" The strategy used to choose the split at each node. Supported strategies are "best" to choose the best split and "random" to choose the best random split. max_depth : int, default=None The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples. min_samples_split : int or float, default=2 The minimum number of samples required to split an internal node: - If int, then consider `min_samples_split` as the minimum number. - If float, then `min_samples_split` is a fraction and `ceil(min_samples_split * n_samples)` are the minimum number of samples for each split. .. versionchanged:: 0.18 Added float values for fractions. min_samples_leaf : int or float, default=1 The minimum number of samples required to be at a leaf node. A split point at any depth will only be considered if it leaves at least ``min_samples_leaf`` training samples in each of the left and right branches. This may have the effect of smoothing the model, especially in regression. - If int, then consider `min_samples_leaf` as the minimum number. - If float, then `min_samples_leaf` is a fraction and `ceil(min_samples_leaf * n_samples)` are the minimum number of samples for each node. .. versionchanged:: 0.18 Added float values for fractions. min_weight_fraction_leaf : float, default=0.0 The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided. max_features : int, float, {"sqrt", "log2"} or None, default="sqrt" The number of features to consider when looking for the best split: - If int, then consider `max_features` features at each split. - If float, then `max_features` is a fraction and `max(1, int(max_features * n_features_in_))` features are considered at each split. - If "sqrt", then `max_features=sqrt(n_features)`. - If "log2", then `max_features=log2(n_features)`. - If None, then `max_features=n_features`. .. versionchanged:: 1.1 The default of `max_features` changed from `"auto"` to `"sqrt"`. Note: the search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than ``max_features`` features. random_state : int, RandomState instance or None, default=None Used to pick randomly the `max_features` used at each split. See :term:`Glossary ` for details. max_leaf_nodes : int, default=None Grow a tree with ``max_leaf_nodes`` in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes. min_impurity_decrease : float, default=0.0 A node will be split if this split induces a decrease of the impurity greater than or equal to this value. The weighted impurity decrease equation is the following:: N_t / N * (impurity - N_t_R / N_t * right_impurity - N_t_L / N_t * left_impurity) where ``N`` is the total number of samples, ``N_t`` is the number of samples at the current node, ``N_t_L`` is the number of samples in the left child, and ``N_t_R`` is the number of samples in the right child. ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum, if ``sample_weight`` is passed. .. versionadded:: 0.19 class_weight : dict, list of dict or "balanced", default=None Weights associated with classes in the form ``{class_label: weight}``. If None, all classes are supposed to have weight one. For multi-output problems, a list of dicts can be provided in the same order as the columns of y. Note that for multioutput (including multilabel) weights should be defined for each class of every column in its own dict. For example, for four-class multilabel classification weights should be [{0: 1, 1: 1}, {0: 1, 1: 5}, {0: 1, 1: 1}, {0: 1, 1: 1}] instead of [{1:1}, {2:5}, {3:1}, {4:1}]. The "balanced" mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as ``n_samples / (n_classes * np.bincount(y))`` For multi-output, the weights of each column of y will be multiplied. Note that these weights will be multiplied with sample_weight (passed through the fit method) if sample_weight is specified. ccp_alpha : non-negative float, default=0.0 Complexity parameter used for Minimal Cost-Complexity Pruning. The subtree with the largest cost complexity that is smaller than ``ccp_alpha`` will be chosen. By default, no pruning is performed. See :ref:`minimal_cost_complexity_pruning` for details. See :ref:`sphx_glr_auto_examples_tree_plot_cost_complexity_pruning.py` for an example of such pruning. .. versionadded:: 0.22 monotonic_cst : array-like of int of shape (n_features), default=None Indicates the monotonicity constraint to enforce on each feature. - 1: monotonic increase - 0: no constraint - -1: monotonic decrease If monotonic_cst is None, no constraints are applied. Monotonicity constraints are not supported for: - multiclass classifications (i.e. when `n_classes > 2`), - multioutput classifications (i.e. when `n_outputs_ > 1`), - classifications trained on data with missing values. The constraints hold over the probability of the positive class. Read more in the :ref:`User Guide `. .. versionadded:: 1.4 Attributes ---------- classes_ : ndarray of shape (n_classes,) or list of ndarray The classes labels (single output problem), or a list of arrays of class labels (multi-output problem). max_features_ : int The inferred value of max_features. n_classes_ : int or list of int The number of classes (for single output problems), or a list containing the number of classes for each output (for multi-output problems). feature_importances_ : ndarray of shape (n_features,) The impurity-based feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance. Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See :func:`sklearn.inspection.permutation_importance` as an alternative. 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 n_outputs_ : int The number of outputs when ``fit`` is performed. tree_ : Tree instance The underlying Tree object. Please refer to ``help(sklearn.tree._tree.Tree)`` for attributes of Tree object and :ref:`sphx_glr_auto_examples_tree_plot_unveil_tree_structure.py` for basic usage of these attributes. See Also -------- ExtraTreeRegressor : An extremely randomized tree regressor. sklearn.ensemble.ExtraTreesClassifier : An extra-trees classifier. sklearn.ensemble.ExtraTreesRegressor : An extra-trees regressor. sklearn.ensemble.RandomForestClassifier : A random forest classifier. sklearn.ensemble.RandomForestRegressor : A random forest regressor. sklearn.ensemble.RandomTreesEmbedding : An ensemble of totally random trees. Notes ----- The default values for the parameters controlling the size of the trees (e.g. ``max_depth``, ``min_samples_leaf``, etc.) lead to fully grown and unpruned trees which can potentially be very large on some data sets. To reduce memory consumption, the complexity and size of the trees should be controlled by setting those parameter values. References ---------- .. [1] P. Geurts, D. Ernst., and L. Wehenkel, "Extremely randomized trees", Machine Learning, 63(1), 3-42, 2006. Examples -------- >>> from sklearn.datasets import load_iris >>> from sklearn.model_selection import train_test_split >>> from sklearn.ensemble import BaggingClassifier >>> from sklearn.tree import ExtraTreeClassifier >>> X, y = load_iris(return_X_y=True) >>> X_train, X_test, y_train, y_test = train_test_split( ... X, y, random_state=0) >>> extra_tree = ExtraTreeClassifier(random_state=0) >>> cls = BaggingClassifier(extra_tree, random_state=0).fit( ... X_train, y_train) >>> cls.score(X_test, y_test) 0.8947 r0r9Nr r r?rDrc >t||||||||| | | || |  y)N) rUrGrHrIrJrKrLrMrRrNrFrOrPrrs rWrXzExtraTreeClassifier.__init__s>" /-%=%)%"7%'  rYct|}|jdk(xr|jdv}d|j_||j _|S)Nr9>r0r2r1Trr s rWrbz$ExtraTreeClassifier.__sklearn_tags__sWw')MMX- $..E 3 ,0($-! rYrnrrrrXrbrrs@rWr.r.sCoh!$! B  rYr.c HeZdZdZddddddddddddd fd Zfd ZxZS) r/a"An extremely randomized tree regressor. Extra-trees differ from classic decision trees in the way they are built. When looking for the best split to separate the samples of a node into two groups, random splits are drawn for each of the `max_features` randomly selected features and the best split among those is chosen. When `max_features` is set 1, this amounts to building a totally random decision tree. Warning: Extra-trees should only be used within ensemble methods. Read more in the :ref:`User Guide `. Parameters ---------- criterion : {"squared_error", "friedman_mse", "absolute_error", "poisson"}, default="squared_error" The function to measure the quality of a split. Supported criteria are "squared_error" for the mean squared error, which is equal to variance reduction as feature selection criterion and minimizes the L2 loss using the mean of each terminal node, "friedman_mse", which uses mean squared error with Friedman's improvement score for potential splits, "absolute_error" for the mean absolute error, which minimizes the L1 loss using the median of each terminal node, and "poisson" which uses reduction in Poisson deviance to find splits. .. versionadded:: 0.18 Mean Absolute Error (MAE) criterion. .. versionadded:: 0.24 Poisson deviance criterion. splitter : {"random", "best"}, default="random" The strategy used to choose the split at each node. Supported strategies are "best" to choose the best split and "random" to choose the best random split. max_depth : int, default=None The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples. min_samples_split : int or float, default=2 The minimum number of samples required to split an internal node: - If int, then consider `min_samples_split` as the minimum number. - If float, then `min_samples_split` is a fraction and `ceil(min_samples_split * n_samples)` are the minimum number of samples for each split. .. versionchanged:: 0.18 Added float values for fractions. min_samples_leaf : int or float, default=1 The minimum number of samples required to be at a leaf node. A split point at any depth will only be considered if it leaves at least ``min_samples_leaf`` training samples in each of the left and right branches. This may have the effect of smoothing the model, especially in regression. - If int, then consider `min_samples_leaf` as the minimum number. - If float, then `min_samples_leaf` is a fraction and `ceil(min_samples_leaf * n_samples)` are the minimum number of samples for each node. .. versionchanged:: 0.18 Added float values for fractions. min_weight_fraction_leaf : float, default=0.0 The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided. max_features : int, float, {"sqrt", "log2"} or None, default=1.0 The number of features to consider when looking for the best split: - If int, then consider `max_features` features at each split. - If float, then `max_features` is a fraction and `max(1, int(max_features * n_features_in_))` features are considered at each split. - If "sqrt", then `max_features=sqrt(n_features)`. - If "log2", then `max_features=log2(n_features)`. - If None, then `max_features=n_features`. .. versionchanged:: 1.1 The default of `max_features` changed from `"auto"` to `1.0`. Note: the search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than ``max_features`` features. random_state : int, RandomState instance or None, default=None Used to pick randomly the `max_features` used at each split. See :term:`Glossary ` for details. min_impurity_decrease : float, default=0.0 A node will be split if this split induces a decrease of the impurity greater than or equal to this value. The weighted impurity decrease equation is the following:: N_t / N * (impurity - N_t_R / N_t * right_impurity - N_t_L / N_t * left_impurity) where ``N`` is the total number of samples, ``N_t`` is the number of samples at the current node, ``N_t_L`` is the number of samples in the left child, and ``N_t_R`` is the number of samples in the right child. ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum, if ``sample_weight`` is passed. .. versionadded:: 0.19 max_leaf_nodes : int, default=None Grow a tree with ``max_leaf_nodes`` in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes. ccp_alpha : non-negative float, default=0.0 Complexity parameter used for Minimal Cost-Complexity Pruning. The subtree with the largest cost complexity that is smaller than ``ccp_alpha`` will be chosen. By default, no pruning is performed. See :ref:`minimal_cost_complexity_pruning` for details. See :ref:`sphx_glr_auto_examples_tree_plot_cost_complexity_pruning.py` for an example of such pruning. .. versionadded:: 0.22 monotonic_cst : array-like of int of shape (n_features), default=None Indicates the monotonicity constraint to enforce on each feature. - 1: monotonic increase - 0: no constraint - -1: monotonic decrease If monotonic_cst is None, no constraints are applied. Monotonicity constraints are not supported for: - multioutput regressions (i.e. when `n_outputs_ > 1`), - regressions trained on data with missing values. Read more in the :ref:`User Guide `. .. versionadded:: 1.4 Attributes ---------- max_features_ : int The inferred value of max_features. 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 feature_importances_ : ndarray of shape (n_features,) Return impurity-based feature importances (the higher, the more important the feature). Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See :func:`sklearn.inspection.permutation_importance` as an alternative. n_outputs_ : int The number of outputs when ``fit`` is performed. tree_ : Tree instance The underlying Tree object. Please refer to ``help(sklearn.tree._tree.Tree)`` for attributes of Tree object and :ref:`sphx_glr_auto_examples_tree_plot_unveil_tree_structure.py` for basic usage of these attributes. See Also -------- ExtraTreeClassifier : An extremely randomized tree classifier. sklearn.ensemble.ExtraTreesClassifier : An extra-trees classifier. sklearn.ensemble.ExtraTreesRegressor : An extra-trees regressor. Notes ----- The default values for the parameters controlling the size of the trees (e.g. ``max_depth``, ``min_samples_leaf``, etc.) lead to fully grown and unpruned trees which can potentially be very large on some data sets. To reduce memory consumption, the complexity and size of the trees should be controlled by setting those parameter values. References ---------- .. [1] P. Geurts, D. Ernst., and L. Wehenkel, "Extremely randomized trees", Machine Learning, 63(1), 3-42, 2006. Examples -------- >>> from sklearn.datasets import load_diabetes >>> from sklearn.model_selection import train_test_split >>> from sklearn.ensemble import BaggingRegressor >>> from sklearn.tree import ExtraTreeRegressor >>> X, y = load_diabetes(return_X_y=True) >>> X_train, X_test, y_train, y_test = train_test_split( ... X, y, random_state=0) >>> extra_tree = ExtraTreeRegressor(random_state=0) >>> reg = BaggingRegressor(extra_tree, random_state=0).fit( ... X_train, y_train) >>> reg.score(X_test, y_test) 0.33 r3r9Nr r r?r@) rUrGrHrIrJrKrLrFrNrMrOrPc <t ||||||||| | || |  y)N) rUrGrHrIrJrKrLrMrNrFrOrPr)rVrUrGrHrIrJrKrLrFrNrMrOrPrms rWrXzExtraTreeRegressor.__init__s; /-%=%)"7%'  rYct|}|jdk(xr|jdv}||j_|S)Nr9>r6r4r3rr s rWrbz#ExtraTreeRegressor.__sklearn_tags__sIw')MMX- $..E 3 %.! rYrrs@rWr/r/s?Sp"!$! >  rYr/)Mrrrabcrrmathrrrnumpyrp scipy.sparser sklearn.utilsr baser r r rrrrutilsrrrutils._param_validationrrrrutils.multiclassrutils.validationrrrrrrr!r"r#r$r%r&r'r(r)r*_utilsr+__all__rrGiniEntropyrMSE FriedmanMSEMAEPoissonr BestSplitterRandomSplitterrBestSparseSplitterRandomSparseSplitterrr;r,r-r.r/rrYrWr:s] '"!*EDNN;+*!%     OO""!!  ^^** nn!!  %11Y=U=UV  ( (,,] ''] JT_.>Tn SN,<Sl ^0^B .rY