197 KiB
197 KiB
<html>
<head>
</head>
</html>
Gradient Boosting and GridSearch¶
The Data¶
Mushroom Hunting: Edible or Poisonous?¶
Data Source: https://archive.ics.uci.edu/ml/datasets/Mushroom
This data set includes descriptions of hypothetical samples corresponding to 23 species of gilled mushrooms in the Agaricus and Lepiota Family (pp. 500-525). Each species is identified as definitely edible, definitely poisonous, or of unknown edibility and not recommended. This latter class was combined with the poisonous one. The Guide clearly states that there is no simple rule for determining the edibility of a mushroom; no rule like ``leaflets three, let it be'' for Poisonous Oak and Ivy.
Attribute Information:
- cap-shape: bell=b,conical=c,convex=x,flat=f, knobbed=k,sunken=s
- cap-surface: fibrous=f,grooves=g,scaly=y,smooth=s
- cap-color: brown=n,buff=b,cinnamon=c,gray=g,green=r, pink=p,purple=u,red=e,white=w,yellow=y
- bruises?: bruises=t,no=f
- odor: almond=a,anise=l,creosote=c,fishy=y,foul=f, musty=m,none=n,pungent=p,spicy=s
- gill-attachment: attached=a,descending=d,free=f,notched=n
- gill-spacing: close=c,crowded=w,distant=d
- gill-size: broad=b,narrow=n
- gill-color: black=k,brown=n,buff=b,chocolate=h,gray=g, green=r,orange=o,pink=p,purple=u,red=e, white=w,yellow=y
- stalk-shape: enlarging=e,tapering=t
- stalk-root: bulbous=b,club=c,cup=u,equal=e, rhizomorphs=z,rooted=r,missing=?
- stalk-surface-above-ring: fibrous=f,scaly=y,silky=k,smooth=s
- stalk-surface-below-ring: fibrous=f,scaly=y,silky=k,smooth=s
- stalk-color-above-ring: brown=n,buff=b,cinnamon=c,gray=g,orange=o, pink=p,red=e,white=w,yellow=y
- stalk-color-below-ring: brown=n,buff=b,cinnamon=c,gray=g,orange=o, pink=p,red=e,white=w,yellow=y
- veil-type: partial=p,universal=u
- veil-color: brown=n,orange=o,white=w,yellow=y
- ring-number: none=n,one=o,two=t
- ring-type: cobwebby=c,evanescent=e,flaring=f,large=l, none=n,pendant=p,sheathing=s,zone=z
- spore-print-color: black=k,brown=n,buff=b,chocolate=h,green=r, orange=o,purple=u,white=w,yellow=y
- population: abundant=a,clustered=c,numerous=n, scattered=s,several=v,solitary=y
- habitat: grasses=g,leaves=l,meadows=m,paths=p, urban=u,waste=w,woods=d
Imports¶
In [1]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
In [2]:
df = pd.read_csv("../DATA/mushrooms.csv")
In [3]:
df.head()
Out[3]:
class | cap-shape | cap-surface | cap-color | bruises | odor | gill-attachment | gill-spacing | gill-size | gill-color | ... | stalk-surface-below-ring | stalk-color-above-ring | stalk-color-below-ring | veil-type | veil-color | ring-number | ring-type | spore-print-color | population | habitat | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | p | x | s | n | t | p | f | c | n | k | ... | s | w | w | p | w | o | p | k | s | u |
1 | e | x | s | y | t | a | f | c | b | k | ... | s | w | w | p | w | o | p | n | n | g |
2 | e | b | s | w | t | l | f | c | b | n | ... | s | w | w | p | w | o | p | n | n | m |
3 | p | x | y | w | t | p | f | c | n | n | ... | s | w | w | p | w | o | p | k | s | u |
4 | e | x | s | g | f | n | f | w | b | k | ... | s | w | w | p | w | o | e | n | a | g |
5 rows × 23 columns
Data Prep¶
In [4]:
X = df.drop('class',axis=1)
In [5]:
y = df['class']
In [6]:
X = pd.get_dummies(X,drop_first=True)
In [7]:
X.head()
Out[7]:
cap-shape_c | cap-shape_f | cap-shape_k | cap-shape_s | cap-shape_x | cap-surface_g | cap-surface_s | cap-surface_y | cap-color_c | cap-color_e | ... | population_n | population_s | population_v | population_y | habitat_g | habitat_l | habitat_m | habitat_p | habitat_u | habitat_w | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | ... | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 |
1 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | ... | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 |
2 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | ... | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 |
3 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | ... | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 |
4 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | ... | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 |
5 rows × 95 columns
In [8]:
y.head()
Out[8]:
0 p 1 e 2 e 3 p 4 e Name: class, dtype: object
Train Test Split¶
In [9]:
from sklearn.model_selection import train_test_split
In [10]:
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.15, random_state=101)
Gradient Boosting and Grid Search with CV¶
In [11]:
from sklearn.ensemble import GradientBoostingClassifier
In [12]:
help(GradientBoostingClassifier)
Help on class GradientBoostingClassifier in module sklearn.ensemble._gb: class GradientBoostingClassifier(sklearn.base.ClassifierMixin, BaseGradientBoosting) | GradientBoostingClassifier(*, loss='deviance', learning_rate=0.1, n_estimators=100, subsample=1.0, criterion='friedman_mse', min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_depth=3, min_impurity_decrease=0.0, min_impurity_split=None, init=None, random_state=None, max_features=None, verbose=0, max_leaf_nodes=None, warm_start=False, presort='deprecated', validation_fraction=0.1, n_iter_no_change=None, tol=0.0001, ccp_alpha=0.0) | | Gradient Boosting for classification. | | GB builds an additive model in a | forward stage-wise fashion; it allows for the optimization of | arbitrary differentiable loss functions. In each stage ``n_classes_`` | regression trees are fit on the negative gradient of the | binomial or multinomial deviance loss function. Binary classification | is a special case where only a single regression tree is induced. | | Read more in the :ref:`User Guide <gradient_boosting>`. | | Parameters | ---------- | loss : {'deviance', 'exponential'}, default='deviance' | loss function to be optimized. 'deviance' refers to | deviance (= logistic regression) for classification | with probabilistic outputs. For loss 'exponential' gradient | boosting recovers the AdaBoost algorithm. | | learning_rate : float, default=0.1 | learning rate shrinks the contribution of each tree by `learning_rate`. | There is a trade-off between learning_rate and n_estimators. | | n_estimators : int, default=100 | The number of boosting stages to perform. Gradient boosting | is fairly robust to over-fitting so a large number usually | results in better performance. | | subsample : float, default=1.0 | The fraction of samples to be used for fitting the individual base | learners. If smaller than 1.0 this results in Stochastic Gradient | Boosting. `subsample` interacts with the parameter `n_estimators`. | Choosing `subsample < 1.0` leads to a reduction of variance | and an increase in bias. | | criterion : {'friedman_mse', 'mse', 'mae'}, default='friedman_mse' | The function to measure the quality of a split. Supported criteria | are 'friedman_mse' for the mean squared error with improvement | score by Friedman, 'mse' for mean squared error, and 'mae' for | the mean absolute error. The default value of 'friedman_mse' is | generally the best as it can provide a better approximation in | some cases. | | .. versionadded:: 0.18 | | 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_depth : int, default=3 | maximum depth of the individual regression estimators. The maximum | depth limits the number of nodes in the tree. Tune this parameter | for best performance; the best value depends on the interaction | of the input variables. | | 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 | | min_impurity_split : float, default=None | Threshold for early stopping in tree growth. A node will split | if its impurity is above the threshold, otherwise it is a leaf. | | .. deprecated:: 0.19 | ``min_impurity_split`` has been deprecated in favor of | ``min_impurity_decrease`` in 0.19. The default value of | ``min_impurity_split`` has changed from 1e-7 to 0 in 0.23 and it | will be removed in 0.25. Use ``min_impurity_decrease`` instead. | | init : estimator or 'zero', default=None | An estimator object that is used to compute the initial predictions. | ``init`` has to provide :meth:`fit` and :meth:`predict_proba`. If | 'zero', the initial raw predictions are set to zero. By default, a | ``DummyEstimator`` predicting the classes priors is used. | | random_state : int or RandomState, default=None | Controls the random seed given to each Tree estimator at each | boosting iteration. | In addition, it controls the random permutation of the features at | each split (see Notes for more details). | It also controls the random spliting of the training data to obtain a | validation set if `n_iter_no_change` is not None. | Pass an int for reproducible output across multiple function calls. | See :term:`Glossary <random_state>`. | | max_features : {'auto', 'sqrt', 'log2'}, int or float, 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 | `int(max_features * n_features)` features are considered at each | split. | - If 'auto', then `max_features=sqrt(n_features)`. | - If 'sqrt', then `max_features=sqrt(n_features)`. | - If 'log2', then `max_features=log2(n_features)`. | - If None, then `max_features=n_features`. | | Choosing `max_features < n_features` leads to a reduction of variance | and an increase in bias. | | 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. | | verbose : int, default=0 | Enable verbose output. If 1 then it prints progress and performance | once in a while (the more trees the lower the frequency). If greater | than 1 then it prints progress and performance for every tree. | | max_leaf_nodes : int, default=None | Grow trees 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. | | warm_start : bool, default=False | When set to ``True``, reuse the solution of the previous call to fit | and add more estimators to the ensemble, otherwise, just erase the | previous solution. See :term:`the Glossary <warm_start>`. | | presort : deprecated, default='deprecated' | This parameter is deprecated and will be removed in v0.24. | | .. deprecated :: 0.22 | | validation_fraction : float, default=0.1 | The proportion of training data to set aside as validation set for | early stopping. Must be between 0 and 1. | Only used if ``n_iter_no_change`` is set to an integer. | | .. versionadded:: 0.20 | | n_iter_no_change : int, default=None | ``n_iter_no_change`` is used to decide if early stopping will be used | to terminate training when validation score is not improving. By | default it is set to None to disable early stopping. If set to a | number, it will set aside ``validation_fraction`` size of the training | data as validation and terminate training when validation score is not | improving in all of the previous ``n_iter_no_change`` numbers of | iterations. The split is stratified. | | .. versionadded:: 0.20 | | tol : float, default=1e-4 | Tolerance for the early stopping. When the loss is not improving | by at least tol for ``n_iter_no_change`` iterations (if set to a | number), the training stops. | | .. versionadded:: 0.20 | | 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. | | .. versionadded:: 0.22 | | Attributes | ---------- | n_estimators_ : int | The number of estimators as selected by early stopping (if | ``n_iter_no_change`` is specified). Otherwise it is set to | ``n_estimators``. | | .. versionadded:: 0.20 | | 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. | | oob_improvement_ : ndarray of shape (n_estimators,) | The improvement in loss (= deviance) on the out-of-bag samples | relative to the previous iteration. | ``oob_improvement_[0]`` is the improvement in | loss of the first stage over the ``init`` estimator. | Only available if ``subsample < 1.0`` | | train_score_ : ndarray of shape (n_estimators,) | The i-th score ``train_score_[i]`` is the deviance (= loss) of the | model at iteration ``i`` on the in-bag sample. | If ``subsample == 1`` this is the deviance on the training data. | | loss_ : LossFunction | The concrete ``LossFunction`` object. | | init_ : estimator | The estimator that provides the initial predictions. | Set via the ``init`` argument or ``loss.init_estimator``. | | estimators_ : ndarray of DecisionTreeRegressor of shape (n_estimators, ``loss_.K``) | The collection of fitted sub-estimators. ``loss_.K`` is 1 for binary | classification, otherwise n_classes. | | classes_ : ndarray of shape (n_classes,) | The classes labels. | | n_features_ : int | The number of data features. | | n_classes_ : int | The number of classes. | | max_features_ : int | The inferred value of max_features. | | Notes | ----- | The features are always randomly permuted at each split. Therefore, | the best found split may vary, even with the same training data and | ``max_features=n_features``, if the improvement of the criterion is | identical for several splits enumerated during the search of the best | split. To obtain a deterministic behaviour during fitting, | ``random_state`` has to be fixed. | | Examples | -------- | >>> from sklearn.datasets import make_classification | >>> from sklearn.ensemble import GradientBoostingClassifier | >>> from sklearn.model_selection import train_test_split | >>> X, y = make_classification(random_state=0) | >>> X_train, X_test, y_train, y_test = train_test_split( | ... X, y, random_state=0) | >>> clf = GradientBoostingClassifier(random_state=0) | >>> clf.fit(X_train, y_train) | GradientBoostingClassifier(random_state=0) | >>> clf.predict(X_test[:2]) | array([1, 0]) | >>> clf.score(X_test, y_test) | 0.88 | | See also | -------- | sklearn.ensemble.HistGradientBoostingClassifier, | sklearn.tree.DecisionTreeClassifier, RandomForestClassifier | AdaBoostClassifier | | References | ---------- | J. Friedman, Greedy Function Approximation: A Gradient Boosting | Machine, The Annals of Statistics, Vol. 29, No. 5, 2001. | | J. Friedman, Stochastic Gradient Boosting, 1999 | | T. Hastie, R. Tibshirani and J. Friedman. | Elements of Statistical Learning Ed. 2, Springer, 2009. | | Method resolution order: | GradientBoostingClassifier | sklearn.base.ClassifierMixin | BaseGradientBoosting | sklearn.ensemble._base.BaseEnsemble | sklearn.base.MetaEstimatorMixin | sklearn.base.BaseEstimator | builtins.object | | Methods defined here: | | __init__(self, *, loss='deviance', learning_rate=0.1, n_estimators=100, subsample=1.0, criterion='friedman_mse', min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_depth=3, min_impurity_decrease=0.0, min_impurity_split=None, init=None, random_state=None, max_features=None, verbose=0, max_leaf_nodes=None, warm_start=False, presort='deprecated', validation_fraction=0.1, n_iter_no_change=None, tol=0.0001, ccp_alpha=0.0) | Initialize self. See help(type(self)) for accurate signature. | | decision_function(self, X) | Compute the decision function of ``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 | ------- | score : ndarray of shape (n_samples, n_classes) or (n_samples,) | The decision function of the input samples, which corresponds to | the raw values predicted from the trees of the ensemble . The | order of the classes corresponds to that in the attribute | :term:`classes_`. Regression and binary classification produce an | array of shape [n_samples]. | | predict(self, X) | Predict class for 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 | ------- | y : ndarray of shape (n_samples,) | The predicted values. | | predict_log_proba(self, X) | Predict class log-probabilities for 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``. | | Raises | ------ | AttributeError | If the ``loss`` does not support probabilities. | | Returns | ------- | p : ndarray of shape (n_samples, n_classes) | The class log-probabilities of the input samples. The order of the | classes corresponds to that in the attribute :term:`classes_`. | | predict_proba(self, X) | Predict class probabilities for 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``. | | Raises | ------ | AttributeError | If the ``loss`` does not support probabilities. | | Returns | ------- | p : ndarray of shape (n_samples, n_classes) | The class probabilities of the input samples. The order of the | classes corresponds to that in the attribute :term:`classes_`. | | staged_decision_function(self, X) | Compute decision function of ``X`` for each iteration. | | This method allows monitoring (i.e. determine error on testing set) | after each stage. | | 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 | ------- | score : generator of ndarray of shape (n_samples, k) | The decision function of the input samples, which corresponds to | the raw values predicted from the trees of the ensemble . The | classes corresponds to that in the attribute :term:`classes_`. | Regression and binary classification are special cases with | ``k == 1``, otherwise ``k==n_classes``. | | staged_predict(self, X) | Predict class at each stage for X. | | This method allows monitoring (i.e. determine error on testing set) | after each stage. | | 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 | ------- | y : generator of ndarray of shape (n_samples,) | The predicted value of the input samples. | | staged_predict_proba(self, X) | Predict class probabilities at each stage for X. | | This method allows monitoring (i.e. determine error on testing set) | after each stage. | | 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 | ------- | y : generator of ndarray of shape (n_samples,) | The predicted value of the input samples. | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __abstractmethods__ = frozenset() | | ---------------------------------------------------------------------- | Methods inherited from sklearn.base.ClassifierMixin: | | score(self, X, y, sample_weight=None) | Return the mean accuracy on the given test data and labels. | | In multi-label classification, this is the subset accuracy | which is a harsh metric since you require for each sample that | each label set be correctly predicted. | | Parameters | ---------- | X : array-like of shape (n_samples, n_features) | Test samples. | | y : array-like of shape (n_samples,) or (n_samples, n_outputs) | True labels for X. | | sample_weight : array-like of shape (n_samples,), default=None | Sample weights. | | Returns | ------- | score : float | Mean accuracy of self.predict(X) wrt. y. | | ---------------------------------------------------------------------- | Data descriptors inherited from sklearn.base.ClassifierMixin: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Methods inherited from BaseGradientBoosting: | | apply(self, X) | Apply trees in the ensemble to X, return leaf indices. | | .. versionadded:: 0.17 | | Parameters | ---------- | X : {array-like, sparse matrix} of shape (n_samples, n_features) | The input samples. Internally, its dtype will be converted to | ``dtype=np.float32``. If a sparse matrix is provided, it will | be converted to a sparse ``csr_matrix``. | | Returns | ------- | X_leaves : array-like of shape (n_samples, n_estimators, n_classes) | For each datapoint x in X and for each tree in the ensemble, | return the index of the leaf x ends up in each estimator. | In the case of binary classification n_classes is 1. | | fit(self, X, y, sample_weight=None, monitor=None) | Fit the gradient boosting model. | | 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``. | | y : array-like of shape (n_samples,) | Target values (strings or integers in classification, real numbers | in regression) | For classification, labels must correspond to classes. | | 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. In the case of | classification, splits are also ignored if they would result in any | single class carrying a negative weight in either child node. | | monitor : callable, default=None | The monitor is called after each iteration with the current | iteration, a reference to the estimator and the local variables of | ``_fit_stages`` as keyword arguments ``callable(i, self, | locals())``. If the callable returns ``True`` the fitting procedure | is stopped. The monitor can be used for various things such as | computing held-out estimates, early stopping, model introspect, and | snapshoting. | | Returns | ------- | self : object | | ---------------------------------------------------------------------- | Readonly properties inherited from BaseGradientBoosting: | | feature_importances_ | 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. | | Returns | ------- | feature_importances_ : array, shape (n_features,) | The values of this array sum to 1, unless all trees are single node | trees consisting of only the root node, in which case it will be an | array of zeros. | | ---------------------------------------------------------------------- | Methods inherited from sklearn.ensemble._base.BaseEnsemble: | | __getitem__(self, index) | Return the index'th estimator in the ensemble. | | __iter__(self) | Return iterator over estimators in the ensemble. | | __len__(self) | Return the number of estimators in the ensemble. | | ---------------------------------------------------------------------- | Data and other attributes inherited from sklearn.ensemble._base.BaseEnsemble: | | __annotations__ = {'_required_parameters': typing.List[str]} | | ---------------------------------------------------------------------- | Methods inherited from sklearn.base.BaseEstimator: | | __getstate__(self) | | __repr__(self, N_CHAR_MAX=700) | Return repr(self). | | __setstate__(self, state) | | get_params(self, deep=True) | Get parameters for this estimator. | | Parameters | ---------- | deep : bool, default=True | If True, will return the parameters for this estimator and | contained subobjects that are estimators. | | Returns | ------- | params : mapping of string to any | Parameter names mapped to their values. | | set_params(self, **params) | Set the parameters of this estimator. | | The method works on simple estimators as well as on nested objects | (such as pipelines). The latter have parameters of the form | ``<component>__<parameter>`` so that it's possible to update each | component of a nested object. | | Parameters | ---------- | **params : dict | Estimator parameters. | | Returns | ------- | self : object | Estimator instance.
In [13]:
from sklearn.model_selection import GridSearchCV
In [14]:
param_grid = {"n_estimators":[1,5,10,20,40,100],'max_depth':[3,4,5,6]}
In [15]:
gb_model = GradientBoostingClassifier()
In [16]:
grid = GridSearchCV(gb_model,param_grid)
Fit to Training Data with CV Search¶
In [17]:
grid.fit(X_train,y_train)
Out[17]:
GridSearchCV(estimator=GradientBoostingClassifier(), param_grid={'max_depth': [3, 4, 5, 6], 'n_estimators': [1, 5, 10, 20, 40, 100]})
In [18]:
grid.best_params_
Out[18]:
{'max_depth': 3, 'n_estimators': 100}
Performance¶
In [19]:
from sklearn.metrics import classification_report,plot_confusion_matrix,accuracy_score
In [20]:
predictions = grid.predict(X_test)
In [21]:
predictions
Out[21]:
array(['p', 'e', 'p', ..., 'p', 'p', 'e'], dtype=object)
In [22]:
print(classification_report(y_test,predictions))
precision recall f1-score support e 1.00 1.00 1.00 655 p 1.00 1.00 1.00 564 accuracy 1.00 1219 macro avg 1.00 1.00 1.00 1219 weighted avg 1.00 1.00 1.00 1219
In [23]:
grid.best_estimator_.feature_importances_
Out[23]:
array([2.91150176e-04, 1.55427847e-17, 2.67658844e-21, 0.00000000e+00, 1.11459235e-16, 1.05030313e-03, 3.26837862e-18, 9.23288948e-17, 3.33934930e-18, 0.00000000e+00, 1.27133255e-17, 0.00000000e+00, 3.56629935e-17, 2.46527883e-21, 0.00000000e+00, 5.60405971e-07, 2.31055039e-03, 5.13955090e-02, 1.84253604e-04, 1.40371481e-02, 1.82499853e-02, 3.13472494e-03, 6.14744334e-01, 9.20844491e-04, 0.00000000e+00, 0.00000000e+00, 5.26020065e-19, 1.25278108e-02, 1.16509070e-02, 0.00000000e+00, 4.86322971e-17, 0.00000000e+00, 1.08107877e-17, 1.10350576e-21, 0.00000000e+00, 3.66548515e-17, 2.07693543e-16, 0.00000000e+00, 1.80938787e-17, 0.00000000e+00, 4.39922283e-04, 0.00000000e+00, 1.35977416e-01, 7.71855052e-03, 3.23882633e-02, 4.64723214e-04, 1.49599812e-03, 4.95063766e-06, 1.83319493e-05, 1.70638552e-06, 3.38601933e-02, 2.07732168e-03, 0.00000000e+00, 0.00000000e+00, 6.80156959e-04, 0.00000000e+00, 0.00000000e+00, 5.74694069e-04, 0.00000000e+00, 1.84524355e-04, 0.00000000e+00, 0.00000000e+00, 5.33104127e-05, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 3.02342639e-03, 0.00000000e+00, 1.35380870e-07, 7.74443653e-05, 2.62871992e-03, 0.00000000e+00, 7.08716926e-05, 0.00000000e+00, 1.32788040e-03, 1.83494013e-03, 7.34476580e-03, 2.14240381e-04, 2.08941481e-04, 0.00000000e+00, 3.04953583e-02, 4.10000880e-03, 4.86768755e-04, 0.00000000e+00, 1.17434515e-03, 0.00000000e+00, 7.67619495e-08, 1.34881889e-05, 5.50395653e-04, 1.82220979e-16, 0.00000000e+00, 9.07373812e-17, 0.00000000e+00, 1.00485103e-05, 0.00000000e+00])
In [24]:
feat_import = grid.best_estimator_.feature_importances_
In [25]:
imp_feats = pd.DataFrame(index=X.columns,data=feat_import,columns=['Importance'])
In [26]:
imp_feats
Out[26]:
Importance | |
---|---|
cap-shape_c | 2.911502e-04 |
cap-shape_f | 1.554278e-17 |
cap-shape_k | 2.676588e-21 |
cap-shape_s | 0.000000e+00 |
cap-shape_x | 1.114592e-16 |
... | ... |
habitat_l | 0.000000e+00 |
habitat_m | 9.073738e-17 |
habitat_p | 0.000000e+00 |
habitat_u | 1.004851e-05 |
habitat_w | 0.000000e+00 |
95 rows × 1 columns
In [27]:
imp_feats.sort_values("Importance",ascending=False)
Out[27]:
Importance | |
---|---|
odor_n | 0.614744 |
stalk-root_c | 0.135977 |
bruises_t | 0.051396 |
stalk-surface-below-ring_y | 0.033860 |
stalk-root_r | 0.032388 |
... | ... |
veil-color_o | 0.000000 |
gill-color_y | 0.000000 |
odor_y | 0.000000 |
odor_s | 0.000000 |
habitat_w | 0.000000 |
95 rows × 1 columns
In [28]:
imp_feats.describe().transpose()
Out[28]:
count | mean | std | min | 25% | 50% | 75% | max | |
---|---|---|---|---|---|---|---|---|
Importance | 95.0 | 0.010526 | 0.06463 | 0.0 | 0.0 | 1.822210e-16 | 0.000801 | 0.614744 |
In [29]:
imp_feats = imp_feats[imp_feats['Importance'] > 0.000527]
In [30]:
imp_feats.sort_values('Importance')
Out[30]:
Importance | |
---|---|
population_y | 0.000550 |
stalk-color-above-ring_w | 0.000575 |
stalk-color-above-ring_n | 0.000680 |
odor_p | 0.000921 |
cap-surface_g | 0.001050 |
population_c | 0.001174 |
ring-type_n | 0.001328 |
stalk-surface-above-ring_s | 0.001496 |
ring-type_p | 0.001835 |
stalk-color-above-ring_c | 0.002077 |
cap-color_y | 0.002311 |
ring-number_o | 0.002629 |
stalk-color-below-ring_y | 0.003023 |
odor_m | 0.003135 |
spore-print-color_u | 0.004100 |
spore-print-color_h | 0.007345 |
stalk-root_e | 0.007719 |
gill-size_n | 0.011651 |
gill-spacing_w | 0.012528 |
odor_f | 0.014037 |
odor_l | 0.018250 |
spore-print-color_r | 0.030495 |
stalk-root_r | 0.032388 |
stalk-surface-below-ring_y | 0.033860 |
bruises_t | 0.051396 |
stalk-root_c | 0.135977 |
odor_n | 0.614744 |
In [33]:
plt.figure(figsize=(14,6),dpi=200)
sns.barplot(data=imp_feats.sort_values('Importance'),x=imp_feats.sort_values('Importance').index,y='Importance')
plt.xticks(rotation=90);
In [ ]: