code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def predict_proba(self, X): """Compute 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. """ check_is_fitted(self) avg = np.average( self._collect_probas(X), axis=0, weights=self._weights_not_none ) return avg
Compute 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.
predict_proba
python
scikit-learn/scikit-learn
sklearn/ensemble/_voting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_voting.py
BSD-3-Clause
def transform(self, X): """Return 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. """ check_is_fitted(self) if self.voting == "soft": probas = self._collect_probas(X) if not self.flatten_transform: return probas return np.hstack(probas) else: return self._predict(X)
Return 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.
transform
python
scikit-learn/scikit-learn
sklearn/ensemble/_voting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_voting.py
BSD-3-Clause
def get_feature_names_out(self, input_features=None): """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. """ check_is_fitted(self, "n_features_in_") if self.voting == "soft" and not self.flatten_transform: raise ValueError( "get_feature_names_out is not supported when `voting='soft'` and " "`flatten_transform=False`" ) _check_feature_names_in(self, input_features, generate_names=False) class_name = self.__class__.__name__.lower() active_names = [name for name, est in self.estimators if est != "drop"] if self.voting == "hard": return np.asarray( [f"{class_name}_{name}" for name in active_names], dtype=object ) # voting == "soft" n_classes = len(self.classes_) names_out = [ f"{class_name}_{name}{i}" for name in active_names for i in range(n_classes) ] return np.asarray(names_out, dtype=object)
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.
get_feature_names_out
python
scikit-learn/scikit-learn
sklearn/ensemble/_voting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_voting.py
BSD-3-Clause
def fit(self, X, y, **fit_params): """Fit 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 <metadata_routing>` for more details. Returns ------- self : object Fitted estimator. """ _raise_for_params(fit_params, self, "fit", allow=["sample_weight"]) y = column_or_1d(y, warn=True) return super().fit(X, y, **fit_params)
Fit 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 <metadata_routing>` for more details. Returns ------- self : object Fitted estimator.
fit
python
scikit-learn/scikit-learn
sklearn/ensemble/_voting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_voting.py
BSD-3-Clause
def predict(self, X): """Predict 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. """ check_is_fitted(self) return np.average(self._predict(X), axis=1, weights=self._weights_not_none)
Predict 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.
predict
python
scikit-learn/scikit-learn
sklearn/ensemble/_voting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_voting.py
BSD-3-Clause
def get_feature_names_out(self, input_features=None): """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. """ check_is_fitted(self, "n_features_in_") _check_feature_names_in(self, input_features, generate_names=False) class_name = self.__class__.__name__.lower() return np.asarray( [f"{class_name}_{name}" for name, est in self.estimators if est != "drop"], dtype=object, )
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.
get_feature_names_out
python
scikit-learn/scikit-learn
sklearn/ensemble/_voting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_voting.py
BSD-3-Clause
def fit(self, X, y, sample_weight=None): """Build a boosted classifier/regressor from the training set (X, y). Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. y : array-like of shape (n_samples,) The target values. sample_weight : array-like of shape (n_samples,), default=None Sample weights. If None, the sample weights are initialized to 1 / n_samples. Returns ------- self : object Fitted estimator. """ _raise_for_unsupported_routing(self, "fit", sample_weight=sample_weight) X, y = validate_data( self, X, y, accept_sparse=["csr", "csc"], ensure_2d=True, allow_nd=True, dtype=None, y_numeric=is_regressor(self), ) sample_weight = _check_sample_weight( sample_weight, X, dtype=np.float64, copy=True, ensure_non_negative=True ) sample_weight /= sample_weight.sum() # Check parameters self._validate_estimator() # Clear any previous fit results self.estimators_ = [] self.estimator_weights_ = np.zeros(self.n_estimators, dtype=np.float64) self.estimator_errors_ = np.ones(self.n_estimators, dtype=np.float64) # Initialization of the random number instance that will be used to # generate a seed at each iteration random_state = check_random_state(self.random_state) epsilon = np.finfo(sample_weight.dtype).eps zero_weight_mask = sample_weight == 0.0 for iboost in range(self.n_estimators): # avoid extremely small sample weight, for details see issue #20320 sample_weight = np.clip(sample_weight, a_min=epsilon, a_max=None) # do not clip sample weights that were exactly zero originally sample_weight[zero_weight_mask] = 0.0 # Boosting step sample_weight, estimator_weight, estimator_error = self._boost( iboost, X, y, sample_weight, random_state ) # Early termination if sample_weight is None: break self.estimator_weights_[iboost] = estimator_weight self.estimator_errors_[iboost] = estimator_error # Stop if error is zero if estimator_error == 0: break sample_weight_sum = np.sum(sample_weight) if not np.isfinite(sample_weight_sum): warnings.warn( ( "Sample weights have reached infinite values," f" at iteration {iboost}, causing overflow. " "Iterations stopped. Try lowering the learning rate." ), stacklevel=2, ) break # Stop if the sum of sample weights has become non-positive if sample_weight_sum <= 0: break if iboost < self.n_estimators - 1: # Normalize sample_weight /= sample_weight_sum return self
Build a boosted classifier/regressor from the training set (X, y). Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. y : array-like of shape (n_samples,) The target values. sample_weight : array-like of shape (n_samples,), default=None Sample weights. If None, the sample weights are initialized to 1 / n_samples. Returns ------- self : object Fitted estimator.
fit
python
scikit-learn/scikit-learn
sklearn/ensemble/_weight_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_weight_boosting.py
BSD-3-Clause
def staged_score(self, X, y, sample_weight=None): """Return staged scores for X, y. This generator method yields the ensemble score after each iteration of boosting and therefore allows monitoring, such as to determine the score on a test set after each boost. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. y : array-like of shape (n_samples,) Labels for X. sample_weight : array-like of shape (n_samples,), default=None Sample weights. Yields ------ z : float """ X = self._check_X(X) for y_pred in self.staged_predict(X): if is_classifier(self): yield accuracy_score(y, y_pred, sample_weight=sample_weight) else: yield r2_score(y, y_pred, sample_weight=sample_weight)
Return staged scores for X, y. This generator method yields the ensemble score after each iteration of boosting and therefore allows monitoring, such as to determine the score on a test set after each boost. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. y : array-like of shape (n_samples,) Labels for X. sample_weight : array-like of shape (n_samples,), default=None Sample weights. Yields ------ z : float
staged_score
python
scikit-learn/scikit-learn
sklearn/ensemble/_weight_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_weight_boosting.py
BSD-3-Clause
def feature_importances_(self): """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_ : ndarray of shape (n_features,) The feature importances. """ if self.estimators_ is None or len(self.estimators_) == 0: raise ValueError( "Estimator not fitted, call `fit` before `feature_importances_`." ) try: norm = self.estimator_weights_.sum() return ( sum( weight * clf.feature_importances_ for weight, clf in zip(self.estimator_weights_, self.estimators_) ) / norm ) except AttributeError as e: raise AttributeError( "Unable to compute feature importances " "since estimator does not have a " "feature_importances_ attribute" ) from e
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_ : ndarray of shape (n_features,) The feature importances.
feature_importances_
python
scikit-learn/scikit-learn
sklearn/ensemble/_weight_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_weight_boosting.py
BSD-3-Clause
def _samme_proba(estimator, n_classes, X): """Calculate algorithm 4, step 2, equation c) of Zhu et al [1]. References ---------- .. [1] J. Zhu, H. Zou, S. Rosset, T. Hastie, "Multi-class AdaBoost", 2009. """ proba = estimator.predict_proba(X) # Displace zero probabilities so the log is defined. # Also fix negative elements which may occur with # negative sample weights. np.clip(proba, np.finfo(proba.dtype).eps, None, out=proba) log_proba = np.log(proba) return (n_classes - 1) * ( log_proba - (1.0 / n_classes) * log_proba.sum(axis=1)[:, np.newaxis] )
Calculate algorithm 4, step 2, equation c) of Zhu et al [1]. References ---------- .. [1] J. Zhu, H. Zou, S. Rosset, T. Hastie, "Multi-class AdaBoost", 2009.
_samme_proba
python
scikit-learn/scikit-learn
sklearn/ensemble/_weight_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_weight_boosting.py
BSD-3-Clause
def _validate_estimator(self): """Check the estimator and set the estimator_ attribute.""" super()._validate_estimator(default=DecisionTreeClassifier(max_depth=1)) if self.algorithm != "deprecated": warnings.warn( "The parameter 'algorithm' is deprecated in 1.6 and has no effect. " "It will be removed in version 1.8.", FutureWarning, ) if not has_fit_parameter(self.estimator_, "sample_weight"): raise ValueError( f"{self.estimator.__class__.__name__} doesn't support sample_weight." )
Check the estimator and set the estimator_ attribute.
_validate_estimator
python
scikit-learn/scikit-learn
sklearn/ensemble/_weight_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_weight_boosting.py
BSD-3-Clause
def _boost(self, iboost, X, y, sample_weight, random_state): """Implement a single boost. Perform a single boost according to the discrete SAMME algorithm and return the updated sample weights. Parameters ---------- iboost : int The index of the current boost iteration. X : {array-like, sparse matrix} of shape (n_samples, n_features) The training input samples. y : array-like of shape (n_samples,) The target values (class labels). sample_weight : array-like of shape (n_samples,) The current sample weights. random_state : RandomState instance The RandomState instance used if the base estimator accepts a `random_state` attribute. Returns ------- sample_weight : array-like of shape (n_samples,) or None The reweighted sample weights. If None then boosting has terminated early. estimator_weight : float The weight for the current boost. If None then boosting has terminated early. estimator_error : float The classification error for the current boost. If None then boosting has terminated early. """ estimator = self._make_estimator(random_state=random_state) estimator.fit(X, y, sample_weight=sample_weight) y_predict = estimator.predict(X) if iboost == 0: self.classes_ = getattr(estimator, "classes_", None) self.n_classes_ = len(self.classes_) # Instances incorrectly classified incorrect = y_predict != y # Error fraction estimator_error = np.mean(np.average(incorrect, weights=sample_weight, axis=0)) # Stop if classification is perfect if estimator_error <= 0: return sample_weight, 1.0, 0.0 n_classes = self.n_classes_ # Stop if the error is at least as bad as random guessing if estimator_error >= 1.0 - (1.0 / n_classes): self.estimators_.pop(-1) if len(self.estimators_) == 0: raise ValueError( "BaseClassifier in AdaBoostClassifier " "ensemble is worse than random, ensemble " "can not be fit." ) return None, None, None # Boost weight using multi-class AdaBoost SAMME alg estimator_weight = self.learning_rate * ( np.log((1.0 - estimator_error) / estimator_error) + np.log(n_classes - 1.0) ) # Only boost the weights if it will fit again if not iboost == self.n_estimators - 1: # Only boost positive weights sample_weight = np.exp( np.log(sample_weight) + estimator_weight * incorrect * (sample_weight > 0) ) return sample_weight, estimator_weight, estimator_error
Implement a single boost. Perform a single boost according to the discrete SAMME algorithm and return the updated sample weights. Parameters ---------- iboost : int The index of the current boost iteration. X : {array-like, sparse matrix} of shape (n_samples, n_features) The training input samples. y : array-like of shape (n_samples,) The target values (class labels). sample_weight : array-like of shape (n_samples,) The current sample weights. random_state : RandomState instance The RandomState instance used if the base estimator accepts a `random_state` attribute. Returns ------- sample_weight : array-like of shape (n_samples,) or None The reweighted sample weights. If None then boosting has terminated early. estimator_weight : float The weight for the current boost. If None then boosting has terminated early. estimator_error : float The classification error for the current boost. If None then boosting has terminated early.
_boost
python
scikit-learn/scikit-learn
sklearn/ensemble/_weight_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_weight_boosting.py
BSD-3-Clause
def predict(self, X): """Predict classes for X. The predicted class of an input sample is computed as the weighted mean prediction of the classifiers in the ensemble. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Returns ------- y : ndarray of shape (n_samples,) The predicted classes. """ pred = self.decision_function(X) if self.n_classes_ == 2: return self.classes_.take(pred > 0, axis=0) return self.classes_.take(np.argmax(pred, axis=1), axis=0)
Predict classes for X. The predicted class of an input sample is computed as the weighted mean prediction of the classifiers in the ensemble. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Returns ------- y : ndarray of shape (n_samples,) The predicted classes.
predict
python
scikit-learn/scikit-learn
sklearn/ensemble/_weight_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_weight_boosting.py
BSD-3-Clause
def staged_predict(self, X): """Return staged predictions for X. The predicted class of an input sample is computed as the weighted mean prediction of the classifiers in the ensemble. This generator method yields the ensemble prediction after each iteration of boosting and therefore allows monitoring, such as to determine the prediction on a test set after each boost. Parameters ---------- X : array-like of shape (n_samples, n_features) The input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Yields ------ y : generator of ndarray of shape (n_samples,) The predicted classes. """ X = self._check_X(X) n_classes = self.n_classes_ classes = self.classes_ if n_classes == 2: for pred in self.staged_decision_function(X): yield np.array(classes.take(pred > 0, axis=0)) else: for pred in self.staged_decision_function(X): yield np.array(classes.take(np.argmax(pred, axis=1), axis=0))
Return staged predictions for X. The predicted class of an input sample is computed as the weighted mean prediction of the classifiers in the ensemble. This generator method yields the ensemble prediction after each iteration of boosting and therefore allows monitoring, such as to determine the prediction on a test set after each boost. Parameters ---------- X : array-like of shape (n_samples, n_features) The input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Yields ------ y : generator of ndarray of shape (n_samples,) The predicted classes.
staged_predict
python
scikit-learn/scikit-learn
sklearn/ensemble/_weight_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_weight_boosting.py
BSD-3-Clause
def decision_function(self, X): """Compute the decision function of ``X``. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Returns ------- score : ndarray of shape of (n_samples, k) The decision function of the input samples. The order of outputs is the same as that of the :term:`classes_` attribute. Binary classification is a special cases with ``k == 1``, otherwise ``k==n_classes``. For binary classification, values closer to -1 or 1 mean more like the first or second class in ``classes_``, respectively. """ check_is_fitted(self) X = self._check_X(X) n_classes = self.n_classes_ classes = self.classes_[:, np.newaxis] if n_classes == 1: return np.zeros_like(X, shape=(X.shape[0], 1)) pred = sum( np.where( (estimator.predict(X) == classes).T, w, -1 / (n_classes - 1) * w, ) for estimator, w in zip(self.estimators_, self.estimator_weights_) ) pred /= self.estimator_weights_.sum() if n_classes == 2: pred[:, 0] *= -1 return pred.sum(axis=1) return pred
Compute the decision function of ``X``. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Returns ------- score : ndarray of shape of (n_samples, k) The decision function of the input samples. The order of outputs is the same as that of the :term:`classes_` attribute. Binary classification is a special cases with ``k == 1``, otherwise ``k==n_classes``. For binary classification, values closer to -1 or 1 mean more like the first or second class in ``classes_``, respectively.
decision_function
python
scikit-learn/scikit-learn
sklearn/ensemble/_weight_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_weight_boosting.py
BSD-3-Clause
def staged_decision_function(self, X): """Compute decision function of ``X`` for each boosting iteration. This method allows monitoring (i.e. determine error on testing set) after each boosting iteration. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Yields ------ score : generator of ndarray of shape (n_samples, k) The decision function of the input samples. The order of outputs is the same of that of the :term:`classes_` attribute. Binary classification is a special cases with ``k == 1``, otherwise ``k==n_classes``. For binary classification, values closer to -1 or 1 mean more like the first or second class in ``classes_``, respectively. """ check_is_fitted(self) X = self._check_X(X) n_classes = self.n_classes_ classes = self.classes_[:, np.newaxis] pred = None norm = 0.0 for weight, estimator in zip(self.estimator_weights_, self.estimators_): norm += weight current_pred = np.where( (estimator.predict(X) == classes).T, weight, -1 / (n_classes - 1) * weight, ) if pred is None: pred = current_pred else: pred += current_pred if n_classes == 2: tmp_pred = np.copy(pred) tmp_pred[:, 0] *= -1 yield (tmp_pred / norm).sum(axis=1) else: yield pred / norm
Compute decision function of ``X`` for each boosting iteration. This method allows monitoring (i.e. determine error on testing set) after each boosting iteration. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Yields ------ score : generator of ndarray of shape (n_samples, k) The decision function of the input samples. The order of outputs is the same of that of the :term:`classes_` attribute. Binary classification is a special cases with ``k == 1``, otherwise ``k==n_classes``. For binary classification, values closer to -1 or 1 mean more like the first or second class in ``classes_``, respectively.
staged_decision_function
python
scikit-learn/scikit-learn
sklearn/ensemble/_weight_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_weight_boosting.py
BSD-3-Clause
def _compute_proba_from_decision(decision, n_classes): """Compute probabilities from the decision function. This is based eq. (15) of [1] where: p(y=c|X) = exp((1 / K-1) f_c(X)) / sum_k(exp((1 / K-1) f_k(X))) = softmax((1 / K-1) * f(X)) References ---------- .. [1] J. Zhu, H. Zou, S. Rosset, T. Hastie, "Multi-class AdaBoost", 2009. """ if n_classes == 2: decision = np.vstack([-decision, decision]).T / 2 else: decision /= n_classes - 1 return softmax(decision, copy=False)
Compute probabilities from the decision function. This is based eq. (15) of [1] where: p(y=c|X) = exp((1 / K-1) f_c(X)) / sum_k(exp((1 / K-1) f_k(X))) = softmax((1 / K-1) * f(X)) References ---------- .. [1] J. Zhu, H. Zou, S. Rosset, T. Hastie, "Multi-class AdaBoost", 2009.
_compute_proba_from_decision
python
scikit-learn/scikit-learn
sklearn/ensemble/_weight_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_weight_boosting.py
BSD-3-Clause
def predict_proba(self, X): """Predict class probabilities for X. The predicted class probabilities of an input sample is computed as the weighted mean predicted class probabilities of the classifiers in the ensemble. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Returns ------- p : ndarray of shape (n_samples, n_classes) The class probabilities of the input samples. The order of outputs is the same of that of the :term:`classes_` attribute. """ check_is_fitted(self) n_classes = self.n_classes_ if n_classes == 1: return np.ones((_num_samples(X), 1)) decision = self.decision_function(X) return self._compute_proba_from_decision(decision, n_classes)
Predict class probabilities for X. The predicted class probabilities of an input sample is computed as the weighted mean predicted class probabilities of the classifiers in the ensemble. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Returns ------- p : ndarray of shape (n_samples, n_classes) The class probabilities of the input samples. The order of outputs is the same of that of the :term:`classes_` attribute.
predict_proba
python
scikit-learn/scikit-learn
sklearn/ensemble/_weight_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_weight_boosting.py
BSD-3-Clause
def staged_predict_proba(self, X): """Predict class probabilities for X. The predicted class probabilities of an input sample is computed as the weighted mean predicted class probabilities of the classifiers in the ensemble. This generator method yields the ensemble predicted class probabilities after each iteration of boosting and therefore allows monitoring, such as to determine the predicted class probabilities on a test set after each boost. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Yields ------ p : generator of ndarray of shape (n_samples,) The class probabilities of the input samples. The order of outputs is the same of that of the :term:`classes_` attribute. """ n_classes = self.n_classes_ for decision in self.staged_decision_function(X): yield self._compute_proba_from_decision(decision, n_classes)
Predict class probabilities for X. The predicted class probabilities of an input sample is computed as the weighted mean predicted class probabilities of the classifiers in the ensemble. This generator method yields the ensemble predicted class probabilities after each iteration of boosting and therefore allows monitoring, such as to determine the predicted class probabilities on a test set after each boost. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Yields ------ p : generator of ndarray of shape (n_samples,) The class probabilities of the input samples. The order of outputs is the same of that of the :term:`classes_` attribute.
staged_predict_proba
python
scikit-learn/scikit-learn
sklearn/ensemble/_weight_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_weight_boosting.py
BSD-3-Clause
def _boost(self, iboost, X, y, sample_weight, random_state): """Implement a single boost for regression Perform a single boost according to the AdaBoost.R2 algorithm and return the updated sample weights. Parameters ---------- iboost : int The index of the current boost iteration. X : {array-like, sparse matrix} of shape (n_samples, n_features) The training input samples. y : array-like of shape (n_samples,) The target values (class labels in classification, real numbers in regression). sample_weight : array-like of shape (n_samples,) The current sample weights. random_state : RandomState The RandomState instance used if the base estimator accepts a `random_state` attribute. Controls also the bootstrap of the weights used to train the weak learner. Returns ------- sample_weight : array-like of shape (n_samples,) or None The reweighted sample weights. If None then boosting has terminated early. estimator_weight : float The weight for the current boost. If None then boosting has terminated early. estimator_error : float The regression error for the current boost. If None then boosting has terminated early. """ estimator = self._make_estimator(random_state=random_state) # Weighted sampling of the training set with replacement bootstrap_idx = random_state.choice( np.arange(_num_samples(X)), size=_num_samples(X), replace=True, p=sample_weight, ) # Fit on the bootstrapped sample and obtain a prediction # for all samples in the training set X_ = _safe_indexing(X, bootstrap_idx) y_ = _safe_indexing(y, bootstrap_idx) estimator.fit(X_, y_) y_predict = estimator.predict(X) error_vect = np.abs(y_predict - y) sample_mask = sample_weight > 0 masked_sample_weight = sample_weight[sample_mask] masked_error_vector = error_vect[sample_mask] error_max = masked_error_vector.max() if error_max != 0: masked_error_vector /= error_max if self.loss == "square": masked_error_vector **= 2 elif self.loss == "exponential": masked_error_vector = 1.0 - np.exp(-masked_error_vector) # Calculate the average loss estimator_error = (masked_sample_weight * masked_error_vector).sum() if estimator_error <= 0: # Stop if fit is perfect return sample_weight, 1.0, 0.0 elif estimator_error >= 0.5: # Discard current estimator only if it isn't the only one if len(self.estimators_) > 1: self.estimators_.pop(-1) return None, None, None beta = estimator_error / (1.0 - estimator_error) # Boost weight using AdaBoost.R2 alg estimator_weight = self.learning_rate * np.log(1.0 / beta) if not iboost == self.n_estimators - 1: sample_weight[sample_mask] *= np.power( beta, (1.0 - masked_error_vector) * self.learning_rate ) return sample_weight, estimator_weight, estimator_error
Implement a single boost for regression Perform a single boost according to the AdaBoost.R2 algorithm and return the updated sample weights. Parameters ---------- iboost : int The index of the current boost iteration. X : {array-like, sparse matrix} of shape (n_samples, n_features) The training input samples. y : array-like of shape (n_samples,) The target values (class labels in classification, real numbers in regression). sample_weight : array-like of shape (n_samples,) The current sample weights. random_state : RandomState The RandomState instance used if the base estimator accepts a `random_state` attribute. Controls also the bootstrap of the weights used to train the weak learner. Returns ------- sample_weight : array-like of shape (n_samples,) or None The reweighted sample weights. If None then boosting has terminated early. estimator_weight : float The weight for the current boost. If None then boosting has terminated early. estimator_error : float The regression error for the current boost. If None then boosting has terminated early.
_boost
python
scikit-learn/scikit-learn
sklearn/ensemble/_weight_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_weight_boosting.py
BSD-3-Clause
def predict(self, X): """Predict regression value for X. The predicted regression value of an input sample is computed as the weighted median prediction of the regressors in the ensemble. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Returns ------- y : ndarray of shape (n_samples,) The predicted regression values. """ check_is_fitted(self) X = self._check_X(X) return self._get_median_predict(X, len(self.estimators_))
Predict regression value for X. The predicted regression value of an input sample is computed as the weighted median prediction of the regressors in the ensemble. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Returns ------- y : ndarray of shape (n_samples,) The predicted regression values.
predict
python
scikit-learn/scikit-learn
sklearn/ensemble/_weight_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_weight_boosting.py
BSD-3-Clause
def staged_predict(self, X): """Return staged predictions for X. The predicted regression value of an input sample is computed as the weighted median prediction of the regressors in the ensemble. This generator method yields the ensemble prediction after each iteration of boosting and therefore allows monitoring, such as to determine the prediction on a test set after each boost. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The training input samples. Yields ------ y : generator of ndarray of shape (n_samples,) The predicted regression values. """ check_is_fitted(self) X = self._check_X(X) for i, _ in enumerate(self.estimators_, 1): yield self._get_median_predict(X, limit=i)
Return staged predictions for X. The predicted regression value of an input sample is computed as the weighted median prediction of the regressors in the ensemble. This generator method yields the ensemble prediction after each iteration of boosting and therefore allows monitoring, such as to determine the prediction on a test set after each boost. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The training input samples. Yields ------ y : generator of ndarray of shape (n_samples,) The predicted regression values.
staged_predict
python
scikit-learn/scikit-learn
sklearn/ensemble/_weight_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_weight_boosting.py
BSD-3-Clause
def test_metadata_routing_with_dynamic_method_selection(sub_estimator, caller, callee): """Test that metadata routing works in `BaggingClassifier` with dynamic selection of the sub-estimator's methods. Here we test only specific test cases, where sub-estimator methods are not present and are not tested with `ConsumingClassifier` (which possesses all the methods) in sklearn/tests/test_metaestimators_metadata_routing.py: `BaggingClassifier.predict()` dynamically routes to `predict` if the sub-estimator doesn't have `predict_proba` and `BaggingClassifier.predict_log_proba()` dynamically routes to `predict_proba` if the sub-estimator doesn't have `predict_log_proba`, or to `predict`, if it doesn't have it. """ X = np.array([[0, 2], [1, 4], [2, 6]]) y = [1, 2, 3] sample_weight, metadata = [1], "a" registry = _Registry() estimator = sub_estimator(registry=registry) set_callee_request = "set_" + callee + "_request" getattr(estimator, set_callee_request)(sample_weight=True, metadata=True) bagging = BaggingClassifier(estimator=estimator) bagging.fit(X, y) getattr(bagging, caller)( X=np.array([[1, 1], [1, 3], [0, 2]]), sample_weight=sample_weight, metadata=metadata, ) assert len(registry) for estimator in registry: check_recorded_metadata( obj=estimator, method=callee, parent=caller, sample_weight=sample_weight, metadata=metadata, )
Test that metadata routing works in `BaggingClassifier` with dynamic selection of the sub-estimator's methods. Here we test only specific test cases, where sub-estimator methods are not present and are not tested with `ConsumingClassifier` (which possesses all the methods) in sklearn/tests/test_metaestimators_metadata_routing.py: `BaggingClassifier.predict()` dynamically routes to `predict` if the sub-estimator doesn't have `predict_proba` and `BaggingClassifier.predict_log_proba()` dynamically routes to `predict_proba` if the sub-estimator doesn't have `predict_log_proba`, or to `predict`, if it doesn't have it.
test_metadata_routing_with_dynamic_method_selection
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_bagging.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_bagging.py
BSD-3-Clause
def test_poisson_vs_mse(): """Test that random forest with poisson criterion performs better than mse for a poisson target. There is a similar test for DecisionTreeRegressor. """ rng = np.random.RandomState(42) n_train, n_test, n_features = 500, 500, 10 X = datasets.make_low_rank_matrix( n_samples=n_train + n_test, n_features=n_features, random_state=rng ) # We create a log-linear Poisson model and downscale coef as it will get # exponentiated. coef = rng.uniform(low=-2, high=2, size=n_features) / np.max(X, axis=0) y = rng.poisson(lam=np.exp(X @ coef)) X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=n_test, random_state=rng ) # We prevent some overfitting by setting min_samples_split=10. forest_poi = RandomForestRegressor( criterion="poisson", min_samples_leaf=10, max_features="sqrt", random_state=rng ) forest_mse = RandomForestRegressor( criterion="squared_error", min_samples_leaf=10, max_features="sqrt", random_state=rng, ) forest_poi.fit(X_train, y_train) forest_mse.fit(X_train, y_train) dummy = DummyRegressor(strategy="mean").fit(X_train, y_train) for X, y, data_name in [(X_train, y_train, "train"), (X_test, y_test, "test")]: metric_poi = mean_poisson_deviance(y, forest_poi.predict(X)) # squared_error forest might produce non-positive predictions => clip # If y = 0 for those, the poisson deviance gets too good. # If we drew more samples, we would eventually get y > 0 and the # poisson deviance would explode, i.e. be undefined. Therefore, we do # not clip to a tiny value like 1e-15, but to 1e-6. This acts like a # small penalty to the non-positive predictions. metric_mse = mean_poisson_deviance( y, np.clip(forest_mse.predict(X), 1e-6, None) ) metric_dummy = mean_poisson_deviance(y, dummy.predict(X)) # As squared_error might correctly predict 0 in train set, its train # score can be better than Poisson. This is no longer the case for the # test set. But keep the above comment for clipping in mind. if data_name == "test": assert metric_poi < metric_mse assert metric_poi < 0.8 * metric_dummy
Test that random forest with poisson criterion performs better than mse for a poisson target. There is a similar test for DecisionTreeRegressor.
test_poisson_vs_mse
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_forest.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_forest.py
BSD-3-Clause
def test_balance_property_random_forest(criterion): """ "Test that sum(y_pred)==sum(y_true) on the training set.""" rng = np.random.RandomState(42) n_train, n_test, n_features = 500, 500, 10 X = datasets.make_low_rank_matrix( n_samples=n_train + n_test, n_features=n_features, random_state=rng ) coef = rng.uniform(low=-2, high=2, size=n_features) / np.max(X, axis=0) y = rng.poisson(lam=np.exp(X @ coef)) reg = RandomForestRegressor( criterion=criterion, n_estimators=10, bootstrap=False, random_state=rng ) reg.fit(X, y) assert np.sum(reg.predict(X)) == pytest.approx(np.sum(y))
"Test that sum(y_pred)==sum(y_true) on the training set.
test_balance_property_random_forest
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_forest.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_forest.py
BSD-3-Clause
def test_forest_classifier_oob( ForestClassifier, X, y, X_type, lower_bound_accuracy, oob_score ): """Check that OOB score is close to score on a test set.""" X = _convert_container(X, constructor_name=X_type) X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.5, random_state=0, ) classifier = ForestClassifier( n_estimators=40, bootstrap=True, oob_score=oob_score, random_state=0, ) assert not hasattr(classifier, "oob_score_") assert not hasattr(classifier, "oob_decision_function_") classifier.fit(X_train, y_train) if callable(oob_score): test_score = oob_score(y_test, classifier.predict(X_test)) else: test_score = classifier.score(X_test, y_test) assert classifier.oob_score_ >= lower_bound_accuracy abs_diff = abs(test_score - classifier.oob_score_) assert abs_diff <= 0.11, f"{abs_diff=} is greater than 0.11" assert hasattr(classifier, "oob_score_") assert not hasattr(classifier, "oob_prediction_") assert hasattr(classifier, "oob_decision_function_") if y.ndim == 1: expected_shape = (X_train.shape[0], len(set(y))) else: expected_shape = (X_train.shape[0], len(set(y[:, 0])), y.shape[1]) assert classifier.oob_decision_function_.shape == expected_shape
Check that OOB score is close to score on a test set.
test_forest_classifier_oob
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_forest.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_forest.py
BSD-3-Clause
def test_forest_regressor_oob(ForestRegressor, X, y, X_type, lower_bound_r2, oob_score): """Check that forest-based regressor provide an OOB score close to the score on a test set.""" X = _convert_container(X, constructor_name=X_type) X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.5, random_state=0, ) regressor = ForestRegressor( n_estimators=50, bootstrap=True, oob_score=oob_score, random_state=0, ) assert not hasattr(regressor, "oob_score_") assert not hasattr(regressor, "oob_prediction_") regressor.fit(X_train, y_train) if callable(oob_score): test_score = oob_score(y_test, regressor.predict(X_test)) else: test_score = regressor.score(X_test, y_test) assert regressor.oob_score_ >= lower_bound_r2 assert abs(test_score - regressor.oob_score_) <= 0.1 assert hasattr(regressor, "oob_score_") assert hasattr(regressor, "oob_prediction_") assert not hasattr(regressor, "oob_decision_function_") if y.ndim == 1: expected_shape = (X_train.shape[0],) else: expected_shape = (X_train.shape[0], y.ndim) assert regressor.oob_prediction_.shape == expected_shape
Check that forest-based regressor provide an OOB score close to the score on a test set.
test_forest_regressor_oob
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_forest.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_forest.py
BSD-3-Clause
def test_forest_oob_warning(ForestEstimator): """Check that a warning is raised when not enough estimator and the OOB estimates will be inaccurate.""" estimator = ForestEstimator( n_estimators=1, oob_score=True, bootstrap=True, random_state=0, ) with pytest.warns(UserWarning, match="Some inputs do not have OOB scores"): estimator.fit(iris.data, iris.target)
Check that a warning is raised when not enough estimator and the OOB estimates will be inaccurate.
test_forest_oob_warning
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_forest.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_forest.py
BSD-3-Clause
def test_forest_oob_score_requires_bootstrap(ForestEstimator): """Check that we raise an error if OOB score is requested without activating bootstrapping. """ X = iris.data y = iris.target err_msg = "Out of bag estimation only available if bootstrap=True" estimator = ForestEstimator(oob_score=True, bootstrap=False) with pytest.raises(ValueError, match=err_msg): estimator.fit(X, y)
Check that we raise an error if OOB score is requested without activating bootstrapping.
test_forest_oob_score_requires_bootstrap
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_forest.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_forest.py
BSD-3-Clause
def test_classifier_error_oob_score_multiclass_multioutput(ForestClassifier): """Check that we raise an error with when requesting OOB score with multiclass-multioutput classification target. """ rng = np.random.RandomState(42) X = iris.data y = rng.randint(low=0, high=5, size=(iris.data.shape[0], 2)) y_type = type_of_target(y) assert y_type == "multiclass-multioutput" estimator = ForestClassifier(oob_score=True, bootstrap=True) err_msg = "The type of target cannot be used to compute OOB estimates" with pytest.raises(ValueError, match=err_msg): estimator.fit(X, y)
Check that we raise an error with when requesting OOB score with multiclass-multioutput classification target.
test_classifier_error_oob_score_multiclass_multioutput
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_forest.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_forest.py
BSD-3-Clause
def test_forest_multioutput_integral_regression_target(ForestRegressor): """Check that multioutput regression with integral values is not interpreted as a multiclass-multioutput target and OOB score can be computed. """ rng = np.random.RandomState(42) X = iris.data y = rng.randint(low=0, high=10, size=(iris.data.shape[0], 2)) estimator = ForestRegressor( n_estimators=30, oob_score=True, bootstrap=True, random_state=0 ) estimator.fit(X, y) n_samples_bootstrap = _get_n_samples_bootstrap(len(X), estimator.max_samples) n_samples_test = X.shape[0] // 4 oob_pred = np.zeros([n_samples_test, 2]) for sample_idx, sample in enumerate(X[:n_samples_test]): n_samples_oob = 0 oob_pred_sample = np.zeros(2) for tree in estimator.estimators_: oob_unsampled_indices = _generate_unsampled_indices( tree.random_state, len(X), n_samples_bootstrap ) if sample_idx in oob_unsampled_indices: n_samples_oob += 1 oob_pred_sample += tree.predict(sample.reshape(1, -1)).squeeze() oob_pred[sample_idx] = oob_pred_sample / n_samples_oob assert_allclose(oob_pred, estimator.oob_prediction_[:n_samples_test])
Check that multioutput regression with integral values is not interpreted as a multiclass-multioutput target and OOB score can be computed.
test_forest_multioutput_integral_regression_target
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_forest.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_forest.py
BSD-3-Clause
def test_random_trees_embedding_feature_names_out(): """Check feature names out for Random Trees Embedding.""" random_state = np.random.RandomState(0) X = np.abs(random_state.randn(100, 4)) hasher = RandomTreesEmbedding( n_estimators=2, max_depth=2, sparse_output=False, random_state=0 ).fit(X) names = hasher.get_feature_names_out() expected_names = [ f"randomtreesembedding_{tree}_{leaf}" # Note: nodes with indices 0, 1 and 4 are internal split nodes and # therefore do not appear in the expected output feature names. for tree, leaf in [ (0, 2), (0, 3), (0, 5), (0, 6), (1, 2), (1, 3), (1, 5), (1, 6), ] ] assert_array_equal(expected_names, names)
Check feature names out for Random Trees Embedding.
test_random_trees_embedding_feature_names_out
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_forest.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_forest.py
BSD-3-Clause
def test_read_only_buffer(csr_container, monkeypatch): """RandomForestClassifier must work on readonly sparse data. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/25333 """ monkeypatch.setattr( sklearn.ensemble._forest, "Parallel", partial(Parallel, max_nbytes=100), ) rng = np.random.RandomState(seed=0) X, y = make_classification(n_samples=100, n_features=200, random_state=rng) X = csr_container(X, copy=True) clf = RandomForestClassifier(n_jobs=2, random_state=rng) cross_val_score(clf, X, y, cv=2)
RandomForestClassifier must work on readonly sparse data. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/25333
test_read_only_buffer
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_forest.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_forest.py
BSD-3-Clause
def test_round_samples_to_one_when_samples_too_low(class_weight): """Check low max_samples works and is rounded to one. Non-regression test for gh-24037. """ X, y = datasets.load_wine(return_X_y=True) forest = RandomForestClassifier( n_estimators=10, max_samples=1e-4, class_weight=class_weight, random_state=0 ) forest.fit(X, y)
Check low max_samples works and is rounded to one. Non-regression test for gh-24037.
test_round_samples_to_one_when_samples_too_low
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_forest.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_forest.py
BSD-3-Clause
def test_estimators_samples(ForestClass, bootstrap, seed): """Estimators_samples_ property should be consistent. Tests consistency across fits and whether or not the seed for the random generator is set. """ X, y = make_hastie_10_2(n_samples=200, random_state=1) if bootstrap: max_samples = 0.5 else: max_samples = None est = ForestClass( n_estimators=10, max_samples=max_samples, max_features=0.5, random_state=seed, bootstrap=bootstrap, ) est.fit(X, y) estimators_samples = est.estimators_samples_.copy() # Test repeated calls result in same set of indices assert_array_equal(estimators_samples, est.estimators_samples_) estimators = est.estimators_ assert isinstance(estimators_samples, list) assert len(estimators_samples) == len(estimators) assert estimators_samples[0].dtype == np.int32 for i in range(len(estimators)): if bootstrap: assert len(estimators_samples[i]) == len(X) // 2 # the bootstrap should be a resampling with replacement assert len(np.unique(estimators_samples[i])) < len(estimators_samples[i]) else: assert len(set(estimators_samples[i])) == len(X) estimator_index = 0 estimator_samples = estimators_samples[estimator_index] estimator = estimators[estimator_index] X_train = X[estimator_samples] y_train = y[estimator_samples] orig_tree_values = estimator.tree_.value estimator = clone(estimator) estimator.fit(X_train, y_train) new_tree_values = estimator.tree_.value assert_allclose(orig_tree_values, new_tree_values)
Estimators_samples_ property should be consistent. Tests consistency across fits and whether or not the seed for the random generator is set.
test_estimators_samples
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_forest.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_forest.py
BSD-3-Clause
def test_missing_values_is_resilient(make_data, Forest): """Check that forest can deal with missing values and has decent performance.""" rng = np.random.RandomState(0) n_samples, n_features = 1000, 10 X, y = make_data(n_samples=n_samples, n_features=n_features, random_state=rng) # Create dataset with missing values X_missing = X.copy() X_missing[rng.choice([False, True], size=X.shape, p=[0.95, 0.05])] = np.nan assert np.isnan(X_missing).any() X_missing_train, X_missing_test, y_train, y_test = train_test_split( X_missing, y, random_state=0 ) # Train forest with missing values forest_with_missing = Forest(random_state=rng, n_estimators=50) forest_with_missing.fit(X_missing_train, y_train) score_with_missing = forest_with_missing.score(X_missing_test, y_test) # Train forest without missing values X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) forest = Forest(random_state=rng, n_estimators=50) forest.fit(X_train, y_train) score_without_missing = forest.score(X_test, y_test) # Score is still 80 percent of the forest's score that had no missing values assert score_with_missing >= 0.80 * score_without_missing
Check that forest can deal with missing values and has decent performance.
test_missing_values_is_resilient
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_forest.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_forest.py
BSD-3-Clause
def test_missing_value_is_predictive(Forest): """Check that the forest learns when missing values are only present for a predictive feature.""" rng = np.random.RandomState(0) n_samples = 300 expected_score = 0.75 X_non_predictive = rng.standard_normal(size=(n_samples, 10)) y = rng.randint(0, high=2, size=n_samples) # Create a predictive feature using `y` and with some noise X_random_mask = rng.choice([False, True], size=n_samples, p=[0.95, 0.05]) y_mask = y.astype(bool) y_mask[X_random_mask] = ~y_mask[X_random_mask] predictive_feature = rng.standard_normal(size=n_samples) predictive_feature[y_mask] = np.nan assert np.isnan(predictive_feature).any() X_predictive = X_non_predictive.copy() X_predictive[:, 5] = predictive_feature ( X_predictive_train, X_predictive_test, X_non_predictive_train, X_non_predictive_test, y_train, y_test, ) = train_test_split(X_predictive, X_non_predictive, y, random_state=0) forest_predictive = Forest(random_state=0).fit(X_predictive_train, y_train) forest_non_predictive = Forest(random_state=0).fit(X_non_predictive_train, y_train) predictive_test_score = forest_predictive.score(X_predictive_test, y_test) assert predictive_test_score >= expected_score assert predictive_test_score >= forest_non_predictive.score( X_non_predictive_test, y_test )
Check that the forest learns when missing values are only present for a predictive feature.
test_missing_value_is_predictive
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_forest.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_forest.py
BSD-3-Clause
def test_non_supported_criterion_raises_error_with_missing_values(Forest): """Raise error for unsupported criterion when there are missing values.""" X = np.array([[0, 1, 2], [np.nan, 0, 2.0]]) y = [0.5, 1.0] forest = Forest(criterion="absolute_error") msg = ".*does not accept missing values" with pytest.raises(ValueError, match=msg): forest.fit(X, y)
Raise error for unsupported criterion when there are missing values.
test_non_supported_criterion_raises_error_with_missing_values
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_forest.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_forest.py
BSD-3-Clause
def test_raise_if_init_has_no_predict_proba(): """Test raise if init_ has no predict_proba method.""" clf = GradientBoostingClassifier(init=GradientBoostingRegressor) msg = ( "The 'init' parameter of GradientBoostingClassifier must be a str among " "{'zero'}, None or an object implementing 'fit' and 'predict_proba'." ) with pytest.raises(ValueError, match=msg): clf.fit(X, y)
Test raise if init_ has no predict_proba method.
test_raise_if_init_has_no_predict_proba
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_gradient_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_gradient_boosting.py
BSD-3-Clause
def test_feature_importance_regression( fetch_california_housing_fxt, global_random_seed ): """Test that Gini importance is calculated correctly. This test follows the example from [1]_ (pg. 373). .. [1] Friedman, J., Hastie, T., & Tibshirani, R. (2001). The elements of statistical learning. New York: Springer series in statistics. """ california = fetch_california_housing_fxt() X, y = california.data, california.target X_train, X_test, y_train, y_test = train_test_split( X, y, random_state=global_random_seed ) reg = GradientBoostingRegressor( loss="huber", learning_rate=0.1, max_leaf_nodes=6, n_estimators=100, random_state=global_random_seed, ) reg.fit(X_train, y_train) sorted_idx = np.argsort(reg.feature_importances_)[::-1] sorted_features = [california.feature_names[s] for s in sorted_idx] # The most important feature is the median income by far. assert sorted_features[0] == "MedInc" # The three subsequent features are the following. Their relative ordering # might change a bit depending on the randomness of the trees and the # train / test split. assert set(sorted_features[1:4]) == {"Longitude", "AveOccup", "Latitude"}
Test that Gini importance is calculated correctly. This test follows the example from [1]_ (pg. 373). .. [1] Friedman, J., Hastie, T., & Tibshirani, R. (2001). The elements of statistical learning. New York: Springer series in statistics.
test_feature_importance_regression
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_gradient_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_gradient_boosting.py
BSD-3-Clause
def test_oob_attributes_error(GradientBoostingEstimator, oob_attribute): """ Check that we raise an AttributeError when the OOB statistics were not computed. """ X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1) estimator = GradientBoostingEstimator( n_estimators=100, random_state=1, subsample=1.0, ) estimator.fit(X, y) with pytest.raises(AttributeError): estimator.oob_attribute
Check that we raise an AttributeError when the OOB statistics were not computed.
test_oob_attributes_error
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_gradient_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_gradient_boosting.py
BSD-3-Clause
def test_warm_start_state_oob_scores(GradientBoosting): """ Check that the states of the OOB scores are cleared when used with `warm_start`. """ X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1) n_estimators = 100 estimator = GradientBoosting( n_estimators=n_estimators, max_depth=1, subsample=0.5, warm_start=True, random_state=1, ) estimator.fit(X, y) oob_scores, oob_score = estimator.oob_scores_, estimator.oob_score_ assert len(oob_scores) == n_estimators assert oob_scores[-1] == pytest.approx(oob_score) n_more_estimators = 200 estimator.set_params(n_estimators=n_more_estimators).fit(X, y) assert len(estimator.oob_scores_) == n_more_estimators assert_allclose(estimator.oob_scores_[:n_estimators], oob_scores) estimator.set_params(n_estimators=n_estimators, warm_start=False).fit(X, y) assert estimator.oob_scores_ is not oob_scores assert estimator.oob_score_ is not oob_score assert_allclose(estimator.oob_scores_, oob_scores) assert estimator.oob_score_ == pytest.approx(oob_score) assert oob_scores[-1] == pytest.approx(oob_score)
Check that the states of the OOB scores are cleared when used with `warm_start`.
test_warm_start_state_oob_scores
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_gradient_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_gradient_boosting.py
BSD-3-Clause
def test_huber_vs_mean_and_median(): """Check that huber lies between absolute and squared error.""" n_rep = 100 n_samples = 10 y = np.tile(np.arange(n_samples), n_rep) x1 = np.minimum(y, n_samples / 2) x2 = np.minimum(-y, -n_samples / 2) X = np.c_[x1, x2] rng = np.random.RandomState(42) # We want an asymmetric distribution. y = y + rng.exponential(scale=1, size=y.shape) gbt_absolute_error = GradientBoostingRegressor(loss="absolute_error").fit(X, y) gbt_huber = GradientBoostingRegressor(loss="huber").fit(X, y) gbt_squared_error = GradientBoostingRegressor().fit(X, y) gbt_huber_predictions = gbt_huber.predict(X) assert np.all(gbt_absolute_error.predict(X) <= gbt_huber_predictions) assert np.all(gbt_huber_predictions <= gbt_squared_error.predict(X))
Check that huber lies between absolute and squared error.
test_huber_vs_mean_and_median
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_gradient_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_gradient_boosting.py
BSD-3-Clause
def test_safe_divide(): """Test that _safe_divide handles division by zero.""" with warnings.catch_warnings(): warnings.simplefilter("error") assert _safe_divide(np.float64(1e300), 0) == 0 assert _safe_divide(np.float64(0.0), np.float64(0.0)) == 0 with pytest.warns(RuntimeWarning, match="overflow"): # np.finfo(float).max = 1.7976931348623157e+308 _safe_divide(np.float64(1e300), 1e-10)
Test that _safe_divide handles division by zero.
test_safe_divide
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_gradient_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_gradient_boosting.py
BSD-3-Clause
def test_squared_error_exact_backward_compat(): """Test squared error GBT backward compat on a simple dataset. The results to compare against are taken from scikit-learn v1.2.0. """ n_samples = 10 y = np.arange(n_samples) x1 = np.minimum(y, n_samples / 2) x2 = np.minimum(-y, -n_samples / 2) X = np.c_[x1, x2] gbt = GradientBoostingRegressor(loss="squared_error", n_estimators=100).fit(X, y) pred_result = np.array( [ 1.39245726e-04, 1.00010468e00, 2.00007043e00, 3.00004051e00, 4.00000802e00, 4.99998972e00, 5.99996312e00, 6.99993395e00, 7.99989372e00, 8.99985660e00, ] ) assert_allclose(gbt.predict(X), pred_result, rtol=1e-8) train_score = np.array( [ 4.87246390e-08, 3.95590036e-08, 3.21267865e-08, 2.60970300e-08, 2.11820178e-08, 1.71995782e-08, 1.39695549e-08, 1.13391770e-08, 9.19931587e-09, 7.47000575e-09, ] ) assert_allclose(gbt.train_score_[-10:], train_score, rtol=1e-8) # Same but with sample_weights sample_weights = np.tile([1, 10], n_samples // 2) gbt = GradientBoostingRegressor(loss="squared_error", n_estimators=100).fit( X, y, sample_weight=sample_weights ) pred_result = np.array( [ 1.52391462e-04, 1.00011168e00, 2.00007724e00, 3.00004638e00, 4.00001302e00, 4.99999873e00, 5.99997093e00, 6.99994329e00, 7.99991290e00, 8.99988727e00, ] ) assert_allclose(gbt.predict(X), pred_result, rtol=1e-6, atol=1e-5) train_score = np.array( [ 4.12445296e-08, 3.34418322e-08, 2.71151383e-08, 2.19782469e-08, 1.78173649e-08, 1.44461976e-08, 1.17120123e-08, 9.49485678e-09, 7.69772505e-09, 6.24155316e-09, ] ) assert_allclose(gbt.train_score_[-10:], train_score, rtol=1e-3, atol=1e-11)
Test squared error GBT backward compat on a simple dataset. The results to compare against are taken from scikit-learn v1.2.0.
test_squared_error_exact_backward_compat
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_gradient_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_gradient_boosting.py
BSD-3-Clause
def test_huber_exact_backward_compat(): """Test huber GBT backward compat on a simple dataset. The results to compare against are taken from scikit-learn v1.2.0. """ n_samples = 10 y = np.arange(n_samples) x1 = np.minimum(y, n_samples / 2) x2 = np.minimum(-y, -n_samples / 2) X = np.c_[x1, x2] gbt = GradientBoostingRegressor(loss="huber", n_estimators=100, alpha=0.8).fit(X, y) assert_allclose(gbt._loss.closs.delta, 0.0001655688041282133) pred_result = np.array( [ 1.48120765e-04, 9.99949174e-01, 2.00116957e00, 2.99986716e00, 4.00012064e00, 5.00002462e00, 5.99998898e00, 6.99692549e00, 8.00006356e00, 8.99985099e00, ] ) assert_allclose(gbt.predict(X), pred_result, rtol=1e-8) train_score = np.array( [ 2.59484709e-07, 2.19165900e-07, 1.89644782e-07, 1.64556454e-07, 1.38705110e-07, 1.20373736e-07, 1.04746082e-07, 9.13835687e-08, 8.20245756e-08, 7.17122188e-08, ] ) assert_allclose(gbt.train_score_[-10:], train_score, rtol=1e-8)
Test huber GBT backward compat on a simple dataset. The results to compare against are taken from scikit-learn v1.2.0.
test_huber_exact_backward_compat
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_gradient_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_gradient_boosting.py
BSD-3-Clause
def test_binomial_error_exact_backward_compat(): """Test binary log_loss GBT backward compat on a simple dataset. The results to compare against are taken from scikit-learn v1.2.0. """ n_samples = 10 y = np.arange(n_samples) % 2 x1 = np.minimum(y, n_samples / 2) x2 = np.minimum(-y, -n_samples / 2) X = np.c_[x1, x2] gbt = GradientBoostingClassifier(loss="log_loss", n_estimators=100).fit(X, y) pred_result = np.array( [ [9.99978098e-01, 2.19017313e-05], [2.19017313e-05, 9.99978098e-01], [9.99978098e-01, 2.19017313e-05], [2.19017313e-05, 9.99978098e-01], [9.99978098e-01, 2.19017313e-05], [2.19017313e-05, 9.99978098e-01], [9.99978098e-01, 2.19017313e-05], [2.19017313e-05, 9.99978098e-01], [9.99978098e-01, 2.19017313e-05], [2.19017313e-05, 9.99978098e-01], ] ) assert_allclose(gbt.predict_proba(X), pred_result, rtol=1e-8) train_score = np.array( [ 1.07742210e-04, 9.74889078e-05, 8.82113863e-05, 7.98167784e-05, 7.22210566e-05, 6.53481907e-05, 5.91293869e-05, 5.35023988e-05, 4.84109045e-05, 4.38039423e-05, ] ) assert_allclose(gbt.train_score_[-10:], train_score, rtol=1e-8)
Test binary log_loss GBT backward compat on a simple dataset. The results to compare against are taken from scikit-learn v1.2.0.
test_binomial_error_exact_backward_compat
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_gradient_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_gradient_boosting.py
BSD-3-Clause
def test_multinomial_error_exact_backward_compat(): """Test multiclass log_loss GBT backward compat on a simple dataset. The results to compare against are taken from scikit-learn v1.2.0. """ n_samples = 10 y = np.arange(n_samples) % 4 x1 = np.minimum(y, n_samples / 2) x2 = np.minimum(-y, -n_samples / 2) X = np.c_[x1, x2] gbt = GradientBoostingClassifier(loss="log_loss", n_estimators=100).fit(X, y) pred_result = np.array( [ [9.99999727e-01, 1.11956255e-07, 8.04921671e-08, 8.04921668e-08], [1.11956254e-07, 9.99999727e-01, 8.04921671e-08, 8.04921668e-08], [1.19417637e-07, 1.19417637e-07, 9.99999675e-01, 8.60526098e-08], [1.19417637e-07, 1.19417637e-07, 8.60526088e-08, 9.99999675e-01], [9.99999727e-01, 1.11956255e-07, 8.04921671e-08, 8.04921668e-08], [1.11956254e-07, 9.99999727e-01, 8.04921671e-08, 8.04921668e-08], [1.19417637e-07, 1.19417637e-07, 9.99999675e-01, 8.60526098e-08], [1.19417637e-07, 1.19417637e-07, 8.60526088e-08, 9.99999675e-01], [9.99999727e-01, 1.11956255e-07, 8.04921671e-08, 8.04921668e-08], [1.11956254e-07, 9.99999727e-01, 8.04921671e-08, 8.04921668e-08], ] ) assert_allclose(gbt.predict_proba(X), pred_result, rtol=1e-8) train_score = np.array( [ 1.13300150e-06, 9.75183397e-07, 8.39348103e-07, 7.22433588e-07, 6.21804338e-07, 5.35191943e-07, 4.60643966e-07, 3.96479930e-07, 3.41253434e-07, 2.93719550e-07, ] ) assert_allclose(gbt.train_score_[-10:], train_score, rtol=1e-8)
Test multiclass log_loss GBT backward compat on a simple dataset. The results to compare against are taken from scikit-learn v1.2.0.
test_multinomial_error_exact_backward_compat
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_gradient_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_gradient_boosting.py
BSD-3-Clause
def test_gb_denominator_zero(global_random_seed): """Test _update_terminal_regions denominator is not zero. For instance for log loss based binary classification, the line search step might become nan/inf as denominator = hessian = prob * (1 - prob) and prob = 0 or 1 can happen. Here, we create a situation were this happens (at least with roughly 80%) based on the random seed. """ X, y = datasets.make_hastie_10_2(n_samples=100, random_state=20) params = { "learning_rate": 1.0, "subsample": 0.5, "n_estimators": 100, "max_leaf_nodes": 4, "max_depth": None, "random_state": global_random_seed, "min_samples_leaf": 2, } clf = GradientBoostingClassifier(**params) # _safe_devide would raise a RuntimeWarning with warnings.catch_warnings(): warnings.simplefilter("error") clf.fit(X, y)
Test _update_terminal_regions denominator is not zero. For instance for log loss based binary classification, the line search step might become nan/inf as denominator = hessian = prob * (1 - prob) and prob = 0 or 1 can happen. Here, we create a situation were this happens (at least with roughly 80%) based on the random seed.
test_gb_denominator_zero
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_gradient_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_gradient_boosting.py
BSD-3-Clause
def test_iforest(global_random_seed): """Check Isolation Forest for various parameter settings.""" X_train = np.array([[0, 1], [1, 2]]) X_test = np.array([[2, 1], [1, 1]]) grid = ParameterGrid( {"n_estimators": [3], "max_samples": [0.5, 1.0, 3], "bootstrap": [True, False]} ) with ignore_warnings(): for params in grid: IsolationForest(random_state=global_random_seed, **params).fit( X_train ).predict(X_test)
Check Isolation Forest for various parameter settings.
test_iforest
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_iforest.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_iforest.py
BSD-3-Clause
def test_iforest_sparse(global_random_seed, sparse_container): """Check IForest for various parameter settings on sparse input.""" rng = check_random_state(global_random_seed) X_train, X_test = train_test_split(diabetes.data[:50], random_state=rng) grid = ParameterGrid({"max_samples": [0.5, 1.0], "bootstrap": [True, False]}) X_train_sparse = sparse_container(X_train) X_test_sparse = sparse_container(X_test) for params in grid: # Trained on sparse format sparse_classifier = IsolationForest( n_estimators=10, random_state=global_random_seed, **params ).fit(X_train_sparse) sparse_results = sparse_classifier.predict(X_test_sparse) # Trained on dense format dense_classifier = IsolationForest( n_estimators=10, random_state=global_random_seed, **params ).fit(X_train) dense_results = dense_classifier.predict(X_test) assert_array_equal(sparse_results, dense_results)
Check IForest for various parameter settings on sparse input.
test_iforest_sparse
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_iforest.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_iforest.py
BSD-3-Clause
def test_iforest_error(): """Test that it gives proper exception on deficient input.""" X = iris.data # The dataset has less than 256 samples, explicitly setting # max_samples > n_samples should result in a warning. If not set # explicitly there should be no warning warn_msg = "max_samples will be set to n_samples for estimation" with pytest.warns(UserWarning, match=warn_msg): IsolationForest(max_samples=1000).fit(X) with warnings.catch_warnings(): warnings.simplefilter("error", UserWarning) IsolationForest(max_samples="auto").fit(X) with warnings.catch_warnings(): warnings.simplefilter("error", UserWarning) IsolationForest(max_samples=np.int64(2)).fit(X) # test X_test n_features match X_train one: with pytest.raises(ValueError): IsolationForest().fit(X).predict(X[:, 1:])
Test that it gives proper exception on deficient input.
test_iforest_error
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_iforest.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_iforest.py
BSD-3-Clause
def test_recalculate_max_depth(): """Check max_depth recalculation when max_samples is reset to n_samples""" X = iris.data clf = IsolationForest().fit(X) for est in clf.estimators_: assert est.max_depth == int(np.ceil(np.log2(X.shape[0])))
Check max_depth recalculation when max_samples is reset to n_samples
test_recalculate_max_depth
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_iforest.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_iforest.py
BSD-3-Clause
def test_iforest_warm_start(): """Test iterative addition of iTrees to an iForest""" rng = check_random_state(0) X = rng.randn(20, 2) # fit first 10 trees clf = IsolationForest( n_estimators=10, max_samples=20, random_state=rng, warm_start=True ) clf.fit(X) # remember the 1st tree tree_1 = clf.estimators_[0] # fit another 10 trees clf.set_params(n_estimators=20) clf.fit(X) # expecting 20 fitted trees and no overwritten trees assert len(clf.estimators_) == 20 assert clf.estimators_[0] is tree_1
Test iterative addition of iTrees to an iForest
test_iforest_warm_start
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_iforest.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_iforest.py
BSD-3-Clause
def test_iforest_with_uniform_data(): """Test whether iforest predicts inliers when using uniform data""" # 2-d array of all 1s X = np.ones((100, 10)) iforest = IsolationForest() iforest.fit(X) rng = np.random.RandomState(0) assert all(iforest.predict(X) == 1) assert all(iforest.predict(rng.randn(100, 10)) == 1) assert all(iforest.predict(X + 1) == 1) assert all(iforest.predict(X - 1) == 1) # 2-d array where columns contain the same value across rows X = np.repeat(rng.randn(1, 10), 100, 0) iforest = IsolationForest() iforest.fit(X) assert all(iforest.predict(X) == 1) assert all(iforest.predict(rng.randn(100, 10)) == 1) assert all(iforest.predict(np.ones((100, 10))) == 1) # Single row X = rng.randn(1, 10) iforest = IsolationForest() iforest.fit(X) assert all(iforest.predict(X) == 1) assert all(iforest.predict(rng.randn(100, 10)) == 1) assert all(iforest.predict(np.ones((100, 10))) == 1)
Test whether iforest predicts inliers when using uniform data
test_iforest_with_uniform_data
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_iforest.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_iforest.py
BSD-3-Clause
def test_iforest_with_n_jobs_does_not_segfault(csc_container): """Check that Isolation Forest does not segfault with n_jobs=2 Non-regression test for #23252 """ X, _ = make_classification(n_samples=85_000, n_features=100, random_state=0) X = csc_container(X) IsolationForest(n_estimators=10, max_samples=256, n_jobs=2).fit(X)
Check that Isolation Forest does not segfault with n_jobs=2 Non-regression test for #23252
test_iforest_with_n_jobs_does_not_segfault
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_iforest.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_iforest.py
BSD-3-Clause
def test_iforest_preserve_feature_names(): """Check that feature names are preserved when contamination is not "auto". Feature names are required for consistency checks during scoring. Non-regression test for Issue #25844 """ pd = pytest.importorskip("pandas") rng = np.random.RandomState(0) X = pd.DataFrame(data=rng.randn(4), columns=["a"]) model = IsolationForest(random_state=0, contamination=0.05) with warnings.catch_warnings(): warnings.simplefilter("error", UserWarning) model.fit(X)
Check that feature names are preserved when contamination is not "auto". Feature names are required for consistency checks during scoring. Non-regression test for Issue #25844
test_iforest_preserve_feature_names
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_iforest.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_iforest.py
BSD-3-Clause
def test_iforest_sparse_input_float_contamination(sparse_container): """Check that `IsolationForest` accepts sparse matrix input and float value for contamination. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/27626 """ X, _ = make_classification(n_samples=50, n_features=4, random_state=0) X = sparse_container(X) X.sort_indices() contamination = 0.1 iforest = IsolationForest( n_estimators=5, contamination=contamination, random_state=0 ).fit(X) X_decision = iforest.decision_function(X) assert (X_decision < 0).sum() / X.shape[0] == pytest.approx(contamination)
Check that `IsolationForest` accepts sparse matrix input and float value for contamination. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/27626
test_iforest_sparse_input_float_contamination
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_iforest.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_iforest.py
BSD-3-Clause
def test_iforest_predict_parallel(global_random_seed, contamination, n_jobs): """Check that `IsolationForest.predict` is parallelized.""" # toy sample (the last two samples are outliers) X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1], [7, 4], [-5, 9]] # Test IsolationForest clf = IsolationForest( random_state=global_random_seed, contamination=contamination, n_jobs=None ) clf.fit(X) decision_func = -clf.decision_function(X) pred = clf.predict(X) # assert detect outliers: assert np.min(decision_func[-2:]) > np.max(decision_func[:-2]) assert_array_equal(pred, 6 * [1] + 2 * [-1]) clf_parallel = IsolationForest( random_state=global_random_seed, contamination=contamination, n_jobs=-1 ) clf_parallel.fit(X) with parallel_backend("threading", n_jobs=n_jobs): pred_paralell = clf_parallel.predict(X) # assert the same results as non-parallel assert_array_equal(pred, pred_paralell)
Check that `IsolationForest.predict` is parallelized.
test_iforest_predict_parallel
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_iforest.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_iforest.py
BSD-3-Clause
def test_stacking_prefit(Stacker, Estimator, stack_method, final_estimator, X, y): """Check the behaviour of stacking when `cv='prefit'`""" X_train1, X_train2, y_train1, y_train2 = train_test_split( X, y, random_state=42, test_size=0.5 ) estimators = [ ("d0", Estimator().fit(X_train1, y_train1)), ("d1", Estimator().fit(X_train1, y_train1)), ] # mock out fit and stack_method to be asserted later for _, estimator in estimators: estimator.fit = Mock(name="fit") stack_func = getattr(estimator, stack_method) predict_method_mocked = Mock(side_effect=stack_func) # Mocking a method will not provide a `__name__` while Python methods # do and we are using it in `_get_response_method`. predict_method_mocked.__name__ = stack_method setattr(estimator, stack_method, predict_method_mocked) stacker = Stacker( estimators=estimators, cv="prefit", final_estimator=final_estimator ) stacker.fit(X_train2, y_train2) assert stacker.estimators_ == [estimator for _, estimator in estimators] # fit was not called again assert all(estimator.fit.call_count == 0 for estimator in stacker.estimators_) # stack method is called with the proper inputs for estimator in stacker.estimators_: stack_func_mock = getattr(estimator, stack_method) stack_func_mock.assert_called_with(X_train2)
Check the behaviour of stacking when `cv='prefit'`
test_stacking_prefit
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_stacking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_stacking.py
BSD-3-Clause
def test_stacking_classifier_multilabel_predict_proba(estimator): """Check the behaviour for the multilabel classification case and the `predict_proba` stacking method. Estimators are not consistent with the output arrays and we need to ensure that we handle all cases. """ X_train, X_test, y_train, y_test = train_test_split( X_multilabel, y_multilabel, stratify=y_multilabel, random_state=42 ) n_outputs = 3 estimators = [("est", estimator)] stacker = StackingClassifier( estimators=estimators, final_estimator=KNeighborsClassifier(), stack_method="predict_proba", ).fit(X_train, y_train) X_trans = stacker.transform(X_test) assert X_trans.shape == (X_test.shape[0], n_outputs) # we should not have any collinear classes and thus nothing should sum to 1 assert not any(np.isclose(X_trans.sum(axis=1), 1.0)) y_pred = stacker.predict(X_test) assert y_pred.shape == y_test.shape
Check the behaviour for the multilabel classification case and the `predict_proba` stacking method. Estimators are not consistent with the output arrays and we need to ensure that we handle all cases.
test_stacking_classifier_multilabel_predict_proba
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_stacking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_stacking.py
BSD-3-Clause
def test_stacking_classifier_multilabel_decision_function(): """Check the behaviour for the multilabel classification case and the `decision_function` stacking method. Only `RidgeClassifier` supports this case. """ X_train, X_test, y_train, y_test = train_test_split( X_multilabel, y_multilabel, stratify=y_multilabel, random_state=42 ) n_outputs = 3 estimators = [("est", RidgeClassifier())] stacker = StackingClassifier( estimators=estimators, final_estimator=KNeighborsClassifier(), stack_method="decision_function", ).fit(X_train, y_train) X_trans = stacker.transform(X_test) assert X_trans.shape == (X_test.shape[0], n_outputs) y_pred = stacker.predict(X_test) assert y_pred.shape == y_test.shape
Check the behaviour for the multilabel classification case and the `decision_function` stacking method. Only `RidgeClassifier` supports this case.
test_stacking_classifier_multilabel_decision_function
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_stacking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_stacking.py
BSD-3-Clause
def test_stacking_classifier_multilabel_auto_predict(stack_method, passthrough): """Check the behaviour for the multilabel classification case for stack methods supported for all estimators or automatically picked up. """ X_train, X_test, y_train, y_test = train_test_split( X_multilabel, y_multilabel, stratify=y_multilabel, random_state=42 ) y_train_before_fit = y_train.copy() n_outputs = 3 estimators = [ ("mlp", MLPClassifier(random_state=42)), ("rf", RandomForestClassifier(random_state=42)), ("ridge", RidgeClassifier()), ] final_estimator = KNeighborsClassifier() clf = StackingClassifier( estimators=estimators, final_estimator=final_estimator, passthrough=passthrough, stack_method=stack_method, ).fit(X_train, y_train) # make sure we don't change `y_train` inplace assert_array_equal(y_train_before_fit, y_train) y_pred = clf.predict(X_test) assert y_pred.shape == y_test.shape if stack_method == "auto": expected_stack_methods = ["predict_proba", "predict_proba", "decision_function"] else: expected_stack_methods = ["predict"] * len(estimators) assert clf.stack_method_ == expected_stack_methods n_features_X_trans = n_outputs * len(estimators) if passthrough: n_features_X_trans += X_train.shape[1] X_trans = clf.transform(X_test) assert X_trans.shape == (X_test.shape[0], n_features_X_trans) assert_array_equal(clf.classes_, [np.array([0, 1])] * n_outputs)
Check the behaviour for the multilabel classification case for stack methods supported for all estimators or automatically picked up.
test_stacking_classifier_multilabel_auto_predict
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_stacking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_stacking.py
BSD-3-Clause
def test_stacking_classifier_base_regressor(): """Check that a regressor can be used as the first layer in `StackingClassifier`.""" X_train, X_test, y_train, y_test = train_test_split( scale(X_iris), y_iris, stratify=y_iris, random_state=42 ) clf = StackingClassifier(estimators=[("ridge", Ridge())]) clf.fit(X_train, y_train) clf.predict(X_test) clf.predict_proba(X_test) assert clf.score(X_test, y_test) > 0.8
Check that a regressor can be used as the first layer in `StackingClassifier`.
test_stacking_classifier_base_regressor
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_stacking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_stacking.py
BSD-3-Clause
def test_stacking_final_estimator_attribute_error(): """Check that we raise the proper AttributeError when the final estimator does not implement the `decision_function` method, which is decorated with `available_if`. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/28108 """ X, y = make_classification(random_state=42) estimators = [ ("lr", LogisticRegression()), ("rf", RandomForestClassifier(n_estimators=2, random_state=42)), ] # RandomForestClassifier does not implement 'decision_function' and should raise # an AttributeError final_estimator = RandomForestClassifier(n_estimators=2, random_state=42) clf = StackingClassifier( estimators=estimators, final_estimator=final_estimator, cv=3 ) outer_msg = "This 'StackingClassifier' has no attribute 'decision_function'" inner_msg = "'RandomForestClassifier' object has no attribute 'decision_function'" with pytest.raises(AttributeError, match=outer_msg) as exec_info: clf.fit(X, y).decision_function(X) assert isinstance(exec_info.value.__cause__, AttributeError) assert inner_msg in str(exec_info.value.__cause__)
Check that we raise the proper AttributeError when the final estimator does not implement the `decision_function` method, which is decorated with `available_if`. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/28108
test_stacking_final_estimator_attribute_error
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_stacking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_stacking.py
BSD-3-Clause
def test_routing_passed_metadata_not_supported(Estimator, Child): """Test that the right error message is raised when metadata is passed while not supported when `enable_metadata_routing=False`.""" with pytest.raises( ValueError, match="is only supported if enable_metadata_routing=True" ): Estimator(["clf", Child()]).fit( X_iris, y_iris, sample_weight=[1, 1, 1, 1, 1], metadata="a" )
Test that the right error message is raised when metadata is passed while not supported when `enable_metadata_routing=False`.
test_routing_passed_metadata_not_supported
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_stacking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_stacking.py
BSD-3-Clause
def test_metadata_routing_for_stacking_estimators(Estimator, Child, prop, prop_value): """Test that metadata is routed correctly for Stacking*.""" est = Estimator( [ ( "sub_est1", Child(registry=_Registry()).set_fit_request(**{prop: True}), ), ( "sub_est2", Child(registry=_Registry()).set_fit_request(**{prop: True}), ), ], final_estimator=Child(registry=_Registry()).set_predict_request(**{prop: True}), ) est.fit(X_iris, y_iris, **{prop: prop_value}) est.fit_transform(X_iris, y_iris, **{prop: prop_value}) est.predict(X_iris, **{prop: prop_value}) for estimator in est.estimators: # access sub-estimator in (name, est) with estimator[1]: registry = estimator[1].registry assert len(registry) for sub_est in registry: check_recorded_metadata( obj=sub_est, method="fit", parent="fit", split_params=(prop), **{prop: prop_value}, ) # access final_estimator: registry = est.final_estimator_.registry assert len(registry) check_recorded_metadata( obj=registry[-1], method="predict", parent="predict", split_params=(prop), **{prop: prop_value}, )
Test that metadata is routed correctly for Stacking*.
test_metadata_routing_for_stacking_estimators
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_stacking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_stacking.py
BSD-3-Clause
def test_metadata_routing_error_for_stacking_estimators(Estimator, Child): """Test that the right error is raised when metadata is not requested.""" sample_weight, metadata = np.ones(X_iris.shape[0]), "a" est = Estimator([("sub_est", Child())]) error_message = ( "[sample_weight, metadata] are passed but are not explicitly set as requested" f" or not requested for {Child.__name__}.fit" ) with pytest.raises(ValueError, match=re.escape(error_message)): est.fit(X_iris, y_iris, sample_weight=sample_weight, metadata=metadata)
Test that the right error is raised when metadata is not requested.
test_metadata_routing_error_for_stacking_estimators
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_stacking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_stacking.py
BSD-3-Clause
def test_majority_label_iris(global_random_seed): """Check classification by majority label on dataset iris.""" clf1 = LogisticRegression(random_state=global_random_seed) clf2 = RandomForestClassifier(n_estimators=10, random_state=global_random_seed) clf3 = GaussianNB() eclf = VotingClassifier( estimators=[("lr", clf1), ("rf", clf2), ("gnb", clf3)], voting="hard" ) scores = cross_val_score(eclf, X, y, scoring="accuracy") assert scores.mean() >= 0.9
Check classification by majority label on dataset iris.
test_majority_label_iris
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_voting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_voting.py
BSD-3-Clause
def test_tie_situation(): """Check voting classifier selects smaller class label in tie situation.""" clf1 = LogisticRegression(random_state=123) clf2 = RandomForestClassifier(random_state=123) eclf = VotingClassifier(estimators=[("lr", clf1), ("rf", clf2)], voting="hard") assert clf1.fit(X, y).predict(X)[52] == 2 assert clf2.fit(X, y).predict(X)[52] == 1 assert eclf.fit(X, y).predict(X)[52] == 1
Check voting classifier selects smaller class label in tie situation.
test_tie_situation
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_voting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_voting.py
BSD-3-Clause
def test_weights_iris(global_random_seed): """Check classification by average probabilities on dataset iris.""" clf1 = LogisticRegression(random_state=global_random_seed) clf2 = RandomForestClassifier(n_estimators=10, random_state=global_random_seed) clf3 = GaussianNB() eclf = VotingClassifier( estimators=[("lr", clf1), ("rf", clf2), ("gnb", clf3)], voting="soft", weights=[1, 2, 10], ) scores = cross_val_score(eclf, X_scaled, y, scoring="accuracy") assert scores.mean() >= 0.9
Check classification by average probabilities on dataset iris.
test_weights_iris
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_voting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_voting.py
BSD-3-Clause
def test_weights_regressor(): """Check weighted average regression prediction on diabetes dataset.""" reg1 = DummyRegressor(strategy="mean") reg2 = DummyRegressor(strategy="median") reg3 = DummyRegressor(strategy="quantile", quantile=0.2) ereg = VotingRegressor( [("mean", reg1), ("median", reg2), ("quantile", reg3)], weights=[1, 2, 10] ) X_r_train, X_r_test, y_r_train, y_r_test = train_test_split( X_r, y_r, test_size=0.25 ) reg1_pred = reg1.fit(X_r_train, y_r_train).predict(X_r_test) reg2_pred = reg2.fit(X_r_train, y_r_train).predict(X_r_test) reg3_pred = reg3.fit(X_r_train, y_r_train).predict(X_r_test) ereg_pred = ereg.fit(X_r_train, y_r_train).predict(X_r_test) avg = np.average( np.asarray([reg1_pred, reg2_pred, reg3_pred]), axis=0, weights=[1, 2, 10] ) assert_almost_equal(ereg_pred, avg, decimal=2) ereg_weights_none = VotingRegressor( [("mean", reg1), ("median", reg2), ("quantile", reg3)], weights=None ) ereg_weights_equal = VotingRegressor( [("mean", reg1), ("median", reg2), ("quantile", reg3)], weights=[1, 1, 1] ) ereg_weights_none.fit(X_r_train, y_r_train) ereg_weights_equal.fit(X_r_train, y_r_train) ereg_none_pred = ereg_weights_none.predict(X_r_test) ereg_equal_pred = ereg_weights_equal.predict(X_r_test) assert_almost_equal(ereg_none_pred, ereg_equal_pred, decimal=2)
Check weighted average regression prediction on diabetes dataset.
test_weights_regressor
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_voting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_voting.py
BSD-3-Clause
def test_predict_on_toy_problem(global_random_seed): """Manually check predicted class labels for toy dataset.""" clf1 = LogisticRegression(random_state=global_random_seed) clf2 = RandomForestClassifier(n_estimators=10, random_state=global_random_seed) clf3 = GaussianNB() X = np.array( [[-1.1, -1.5], [-1.2, -1.4], [-3.4, -2.2], [1.1, 1.2], [2.1, 1.4], [3.1, 2.3]] ) y = np.array([1, 1, 1, 2, 2, 2]) assert_array_equal(clf1.fit(X, y).predict(X), [1, 1, 1, 2, 2, 2]) assert_array_equal(clf2.fit(X, y).predict(X), [1, 1, 1, 2, 2, 2]) assert_array_equal(clf3.fit(X, y).predict(X), [1, 1, 1, 2, 2, 2]) eclf = VotingClassifier( estimators=[("lr", clf1), ("rf", clf2), ("gnb", clf3)], voting="hard", weights=[1, 1, 1], ) assert_array_equal(eclf.fit(X, y).predict(X), [1, 1, 1, 2, 2, 2]) eclf = VotingClassifier( estimators=[("lr", clf1), ("rf", clf2), ("gnb", clf3)], voting="soft", weights=[1, 1, 1], ) assert_array_equal(eclf.fit(X, y).predict(X), [1, 1, 1, 2, 2, 2])
Manually check predicted class labels for toy dataset.
test_predict_on_toy_problem
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_voting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_voting.py
BSD-3-Clause
def test_predict_proba_on_toy_problem(): """Calculate predicted probabilities on toy dataset.""" clf1 = LogisticRegression(random_state=123) clf2 = RandomForestClassifier(random_state=123) clf3 = GaussianNB() X = np.array([[-1.1, -1.5], [-1.2, -1.4], [-3.4, -2.2], [1.1, 1.2]]) y = np.array([1, 1, 2, 2]) clf1_res = np.array( [ [0.59790391, 0.40209609], [0.57622162, 0.42377838], [0.50728456, 0.49271544], [0.40241774, 0.59758226], ] ) clf2_res = np.array([[0.8, 0.2], [0.8, 0.2], [0.2, 0.8], [0.3, 0.7]]) clf3_res = np.array( [[0.9985082, 0.0014918], [0.99845843, 0.00154157], [0.0, 1.0], [0.0, 1.0]] ) t00 = (2 * clf1_res[0][0] + clf2_res[0][0] + clf3_res[0][0]) / 4 t11 = (2 * clf1_res[1][1] + clf2_res[1][1] + clf3_res[1][1]) / 4 t21 = (2 * clf1_res[2][1] + clf2_res[2][1] + clf3_res[2][1]) / 4 t31 = (2 * clf1_res[3][1] + clf2_res[3][1] + clf3_res[3][1]) / 4 eclf = VotingClassifier( estimators=[("lr", clf1), ("rf", clf2), ("gnb", clf3)], voting="soft", weights=[2, 1, 1], ) eclf_res = eclf.fit(X, y).predict_proba(X) assert_almost_equal(t00, eclf_res[0][0], decimal=1) assert_almost_equal(t11, eclf_res[1][1], decimal=1) assert_almost_equal(t21, eclf_res[2][1], decimal=1) assert_almost_equal(t31, eclf_res[3][1], decimal=1) inner_msg = "predict_proba is not available when voting='hard'" outer_msg = "'VotingClassifier' has no attribute 'predict_proba'" with pytest.raises(AttributeError, match=outer_msg) as exec_info: eclf = VotingClassifier( estimators=[("lr", clf1), ("rf", clf2), ("gnb", clf3)], voting="hard" ) eclf.fit(X, y).predict_proba(X) assert isinstance(exec_info.value.__cause__, AttributeError) assert inner_msg in str(exec_info.value.__cause__)
Calculate predicted probabilities on toy dataset.
test_predict_proba_on_toy_problem
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_voting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_voting.py
BSD-3-Clause
def test_multilabel(): """Check if error is raised for multilabel classification.""" X, y = make_multilabel_classification( n_classes=2, n_labels=1, allow_unlabeled=False, random_state=123 ) clf = OneVsRestClassifier(SVC(kernel="linear")) eclf = VotingClassifier(estimators=[("ovr", clf)], voting="hard") try: eclf.fit(X, y) except NotImplementedError: return
Check if error is raised for multilabel classification.
test_multilabel
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_voting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_voting.py
BSD-3-Clause
def test_parallel_fit(global_random_seed): """Check parallel backend of VotingClassifier on toy dataset.""" clf1 = LogisticRegression(random_state=global_random_seed) clf2 = RandomForestClassifier(n_estimators=10, random_state=global_random_seed) clf3 = GaussianNB() X = np.array([[-1.1, -1.5], [-1.2, -1.4], [-3.4, -2.2], [1.1, 1.2]]) y = np.array([1, 1, 2, 2]) eclf1 = VotingClassifier( estimators=[("lr", clf1), ("rf", clf2), ("gnb", clf3)], voting="soft", n_jobs=1 ).fit(X, y) eclf2 = VotingClassifier( estimators=[("lr", clf1), ("rf", clf2), ("gnb", clf3)], voting="soft", n_jobs=2 ).fit(X, y) assert_array_equal(eclf1.predict(X), eclf2.predict(X)) assert_array_almost_equal(eclf1.predict_proba(X), eclf2.predict_proba(X))
Check parallel backend of VotingClassifier on toy dataset.
test_parallel_fit
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_voting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_voting.py
BSD-3-Clause
def test_sample_weight_kwargs(): """Check that VotingClassifier passes sample_weight as kwargs""" class MockClassifier(ClassifierMixin, BaseEstimator): """Mock Classifier to check that sample_weight is received as kwargs""" def fit(self, X, y, *args, **sample_weight): assert "sample_weight" in sample_weight clf = MockClassifier() eclf = VotingClassifier(estimators=[("mock", clf)], voting="soft") # Should not raise an error. eclf.fit(X, y, sample_weight=np.ones((len(y),)))
Check that VotingClassifier passes sample_weight as kwargs
test_sample_weight_kwargs
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_voting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_voting.py
BSD-3-Clause
def test_transform(global_random_seed): """Check transform method of VotingClassifier on toy dataset.""" clf1 = LogisticRegression(random_state=global_random_seed) clf2 = RandomForestClassifier(n_estimators=10, random_state=global_random_seed) clf3 = GaussianNB() X = np.array([[-1.1, -1.5], [-1.2, -1.4], [-3.4, -2.2], [1.1, 1.2]]) y = np.array([1, 1, 2, 2]) eclf1 = VotingClassifier( estimators=[("lr", clf1), ("rf", clf2), ("gnb", clf3)], voting="soft" ).fit(X, y) eclf2 = VotingClassifier( estimators=[("lr", clf1), ("rf", clf2), ("gnb", clf3)], voting="soft", flatten_transform=True, ).fit(X, y) eclf3 = VotingClassifier( estimators=[("lr", clf1), ("rf", clf2), ("gnb", clf3)], voting="soft", flatten_transform=False, ).fit(X, y) assert_array_equal(eclf1.transform(X).shape, (4, 6)) assert_array_equal(eclf2.transform(X).shape, (4, 6)) assert_array_equal(eclf3.transform(X).shape, (3, 4, 2)) assert_array_almost_equal(eclf1.transform(X), eclf2.transform(X)) assert_array_almost_equal( eclf3.transform(X).swapaxes(0, 1).reshape((4, 6)), eclf2.transform(X) )
Check transform method of VotingClassifier on toy dataset.
test_transform
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_voting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_voting.py
BSD-3-Clause
def test_get_features_names_out_classifier(kwargs, expected_names): """Check get_feature_names_out for classifier for different settings.""" X = [[1, 2], [3, 4], [5, 6], [1, 1.2]] y = [0, 1, 2, 0] voting = VotingClassifier( estimators=[ ("lr", LogisticRegression(random_state=0)), ("tree", DecisionTreeClassifier(random_state=0)), ], **kwargs, ) voting.fit(X, y) X_trans = voting.transform(X) names_out = voting.get_feature_names_out() assert X_trans.shape[1] == len(expected_names) assert_array_equal(names_out, expected_names)
Check get_feature_names_out for classifier for different settings.
test_get_features_names_out_classifier
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_voting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_voting.py
BSD-3-Clause
def test_get_features_names_out_classifier_error(): """Check that error is raised when voting="soft" and flatten_transform=False.""" X = [[1, 2], [3, 4], [5, 6]] y = [0, 1, 2] voting = VotingClassifier( estimators=[ ("lr", LogisticRegression(random_state=0)), ("tree", DecisionTreeClassifier(random_state=0)), ], voting="soft", flatten_transform=False, ) voting.fit(X, y) msg = ( "get_feature_names_out is not supported when `voting='soft'` and " "`flatten_transform=False`" ) with pytest.raises(ValueError, match=msg): voting.get_feature_names_out()
Check that error is raised when voting="soft" and flatten_transform=False.
test_get_features_names_out_classifier_error
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_voting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_voting.py
BSD-3-Clause
def test_routing_passed_metadata_not_supported(Estimator, Child): """Test that the right error message is raised when metadata is passed while not supported when `enable_metadata_routing=False`.""" X = np.array([[0, 1], [2, 2], [4, 6]]) y = [1, 2, 3] with pytest.raises( ValueError, match="is only supported if enable_metadata_routing=True" ): Estimator(["clf", Child()]).fit(X, y, sample_weight=[1, 1, 1], metadata="a")
Test that the right error message is raised when metadata is passed while not supported when `enable_metadata_routing=False`.
test_routing_passed_metadata_not_supported
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_voting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_voting.py
BSD-3-Clause
def test_metadata_routing_for_voting_estimators(Estimator, Child, prop): """Test that metadata is routed correctly for Voting*.""" X = np.array([[0, 1], [2, 2], [4, 6]]) y = [1, 2, 3] sample_weight, metadata = [1, 1, 1], "a" est = Estimator( [ ( "sub_est1", Child(registry=_Registry()).set_fit_request(**{prop: True}), ), ( "sub_est2", Child(registry=_Registry()).set_fit_request(**{prop: True}), ), ] ) est.fit(X, y, **{prop: sample_weight if prop == "sample_weight" else metadata}) for estimator in est.estimators: if prop == "sample_weight": kwargs = {prop: sample_weight} else: kwargs = {prop: metadata} # access sub-estimator in (name, est) with estimator[1] registry = estimator[1].registry assert len(registry) for sub_est in registry: check_recorded_metadata(obj=sub_est, method="fit", parent="fit", **kwargs)
Test that metadata is routed correctly for Voting*.
test_metadata_routing_for_voting_estimators
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_voting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_voting.py
BSD-3-Clause
def test_metadata_routing_error_for_voting_estimators(Estimator, Child): """Test that the right error is raised when metadata is not requested.""" X = np.array([[0, 1], [2, 2], [4, 6]]) y = [1, 2, 3] sample_weight, metadata = [1, 1, 1], "a" est = Estimator([("sub_est", Child())]) error_message = ( "[sample_weight, metadata] are passed but are not explicitly set as requested" f" or not requested for {Child.__name__}.fit" ) with pytest.raises(ValueError, match=re.escape(error_message)): est.fit(X, y, sample_weight=sample_weight, metadata=metadata)
Test that the right error is raised when metadata is not requested.
test_metadata_routing_error_for_voting_estimators
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_voting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_voting.py
BSD-3-Clause
def fit(self, X, y, sample_weight=None): """Modification on fit caries data type for later verification.""" super().fit(X, y, sample_weight=sample_weight) self.data_type_ = type(X) return self
Modification on fit caries data type for later verification.
fit
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_weight_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_weight_boosting.py
BSD-3-Clause
def fit(self, X, y, sample_weight=None): """Modification on fit caries data type for later verification.""" super().fit(X, y, sample_weight=sample_weight) self.data_type_ = type(X) return self
Modification on fit caries data type for later verification.
fit
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_weight_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_weight_boosting.py
BSD-3-Clause
def test_sample_weight_adaboost_regressor(): """ AdaBoostRegressor should work without sample_weights in the base estimator The random weighted sampling is done internally in the _boost method in AdaBoostRegressor. """ class DummyEstimator(BaseEstimator): def fit(self, X, y): pass def predict(self, X): return np.zeros(X.shape[0]) boost = AdaBoostRegressor(DummyEstimator(), n_estimators=3) boost.fit(X, y_regr) assert len(boost.estimator_weights_) == len(boost.estimator_errors_)
AdaBoostRegressor should work without sample_weights in the base estimator The random weighted sampling is done internally in the _boost method in AdaBoostRegressor.
test_sample_weight_adaboost_regressor
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_weight_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_weight_boosting.py
BSD-3-Clause
def test_multidimensional_X(): """ Check that the AdaBoost estimators can work with n-dimensional data matrix """ rng = np.random.RandomState(0) X = rng.randn(51, 3, 3) yc = rng.choice([0, 1], 51) yr = rng.randn(51) boost = AdaBoostClassifier(DummyClassifier(strategy="most_frequent")) boost.fit(X, yc) boost.predict(X) boost.predict_proba(X) boost = AdaBoostRegressor(DummyRegressor()) boost.fit(X, yr) boost.predict(X)
Check that the AdaBoost estimators can work with n-dimensional data matrix
test_multidimensional_X
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_weight_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_weight_boosting.py
BSD-3-Clause
def test_adaboost_numerically_stable_feature_importance_with_small_weights(): """Check that we don't create NaN feature importance with numerically instable inputs. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/20320 """ rng = np.random.RandomState(42) X = rng.normal(size=(1000, 10)) y = rng.choice([0, 1], size=1000) sample_weight = np.ones_like(y) * 1e-263 tree = DecisionTreeClassifier(max_depth=10, random_state=12) ada_model = AdaBoostClassifier(estimator=tree, n_estimators=20, random_state=12) ada_model.fit(X, y, sample_weight=sample_weight) assert np.isnan(ada_model.feature_importances_).sum() == 0
Check that we don't create NaN feature importance with numerically instable inputs. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/20320
test_adaboost_numerically_stable_feature_importance_with_small_weights
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_weight_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_weight_boosting.py
BSD-3-Clause
def test_adaboost_decision_function(global_random_seed): """Check that the decision function respects the symmetric constraint for weak learners. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/26520 """ n_classes = 3 X, y = datasets.make_classification( n_classes=n_classes, n_clusters_per_class=1, random_state=global_random_seed ) clf = AdaBoostClassifier(n_estimators=1, random_state=global_random_seed).fit(X, y) y_score = clf.decision_function(X) assert_allclose(y_score.sum(axis=1), 0, atol=1e-8) # With a single learner, we expect to have a decision function in # {1, - 1 / (n_classes - 1)}. assert set(np.unique(y_score)) == {1, -1 / (n_classes - 1)} # We can assert the same for staged_decision_function since we have a single learner for y_score in clf.staged_decision_function(X): assert_allclose(y_score.sum(axis=1), 0, atol=1e-8) # With a single learner, we expect to have a decision function in # {1, - 1 / (n_classes - 1)}. assert set(np.unique(y_score)) == {1, -1 / (n_classes - 1)} clf.set_params(n_estimators=5).fit(X, y) y_score = clf.decision_function(X) assert_allclose(y_score.sum(axis=1), 0, atol=1e-8) for y_score in clf.staged_decision_function(X): assert_allclose(y_score.sum(axis=1), 0, atol=1e-8)
Check that the decision function respects the symmetric constraint for weak learners. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/26520
test_adaboost_decision_function
python
scikit-learn/scikit-learn
sklearn/ensemble/tests/test_weight_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/tests/test_weight_boosting.py
BSD-3-Clause
def _find_binning_thresholds(col_data, max_bins): """Extract quantiles from a continuous feature. Missing values are ignored for finding the thresholds. Parameters ---------- col_data : array-like, shape (n_samples,) The continuous feature to bin. max_bins: int The maximum number of bins to use for non-missing values. If for a given feature the number of unique values is less than ``max_bins``, then those unique values will be used to compute the bin thresholds, instead of the quantiles Return ------ binning_thresholds : ndarray of shape(min(max_bins, n_unique_values) - 1,) The increasing numeric values that can be used to separate the bins. A given value x will be mapped into bin value i iff bining_thresholds[i - 1] < x <= binning_thresholds[i] """ # ignore missing values when computing bin thresholds missing_mask = np.isnan(col_data) if missing_mask.any(): col_data = col_data[~missing_mask] # The data will be sorted anyway in np.unique and again in percentile, so we do it # here. Sorting also returns a contiguous array. col_data = np.sort(col_data) distinct_values = np.unique(col_data).astype(X_DTYPE) if len(distinct_values) <= max_bins: midpoints = distinct_values[:-1] + distinct_values[1:] midpoints *= 0.5 else: # We could compute approximate midpoint percentiles using the output of # np.unique(col_data, return_counts) instead but this is more # work and the performance benefit will be limited because we # work on a fixed-size subsample of the full data. percentiles = np.linspace(0, 100, num=max_bins + 1) percentiles = percentiles[1:-1] midpoints = np.percentile(col_data, percentiles, method="midpoint").astype( X_DTYPE ) assert midpoints.shape[0] == max_bins - 1 # We avoid having +inf thresholds: +inf thresholds are only allowed in # a "split on nan" situation. np.clip(midpoints, a_min=None, a_max=ALMOST_INF, out=midpoints) return midpoints
Extract quantiles from a continuous feature. Missing values are ignored for finding the thresholds. Parameters ---------- col_data : array-like, shape (n_samples,) The continuous feature to bin. max_bins: int The maximum number of bins to use for non-missing values. If for a given feature the number of unique values is less than ``max_bins``, then those unique values will be used to compute the bin thresholds, instead of the quantiles Return ------ binning_thresholds : ndarray of shape(min(max_bins, n_unique_values) - 1,) The increasing numeric values that can be used to separate the bins. A given value x will be mapped into bin value i iff bining_thresholds[i - 1] < x <= binning_thresholds[i]
_find_binning_thresholds
python
scikit-learn/scikit-learn
sklearn/ensemble/_hist_gradient_boosting/binning.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/binning.py
BSD-3-Clause
def fit(self, X, y=None): """Fit data X by computing the binning thresholds. The last bin is reserved for missing values, whether missing values are present in the data or not. Parameters ---------- X : array-like of shape (n_samples, n_features) The data to bin. y: None Ignored. Returns ------- self : object """ if not (3 <= self.n_bins <= 256): # min is 3: at least 2 distinct bins and a missing values bin raise ValueError( "n_bins={} should be no smaller than 3 and no larger than 256.".format( self.n_bins ) ) X = check_array(X, dtype=[X_DTYPE], ensure_all_finite=False) max_bins = self.n_bins - 1 rng = check_random_state(self.random_state) if self.subsample is not None and X.shape[0] > self.subsample: subset = rng.choice(X.shape[0], self.subsample, replace=False) X = X.take(subset, axis=0) if self.is_categorical is None: self.is_categorical_ = np.zeros(X.shape[1], dtype=np.uint8) else: self.is_categorical_ = np.asarray(self.is_categorical, dtype=np.uint8) n_features = X.shape[1] known_categories = self.known_categories if known_categories is None: known_categories = [None] * n_features # validate is_categorical and known_categories parameters for f_idx in range(n_features): is_categorical = self.is_categorical_[f_idx] known_cats = known_categories[f_idx] if is_categorical and known_cats is None: raise ValueError( f"Known categories for feature {f_idx} must be provided." ) if not is_categorical and known_cats is not None: raise ValueError( f"Feature {f_idx} isn't marked as a categorical feature, " "but categories were passed." ) self.missing_values_bin_idx_ = self.n_bins - 1 self.bin_thresholds_ = [None] * n_features n_bins_non_missing = [None] * n_features non_cat_thresholds = Parallel(n_jobs=self.n_threads, backend="threading")( delayed(_find_binning_thresholds)(X[:, f_idx], max_bins) for f_idx in range(n_features) if not self.is_categorical_[f_idx] ) non_cat_idx = 0 for f_idx in range(n_features): if self.is_categorical_[f_idx]: # Since categories are assumed to be encoded in # [0, n_cats] and since n_cats <= max_bins, # the thresholds *are* the unique categorical values. This will # lead to the correct mapping in transform() thresholds = known_categories[f_idx] n_bins_non_missing[f_idx] = thresholds.shape[0] self.bin_thresholds_[f_idx] = thresholds else: self.bin_thresholds_[f_idx] = non_cat_thresholds[non_cat_idx] n_bins_non_missing[f_idx] = self.bin_thresholds_[f_idx].shape[0] + 1 non_cat_idx += 1 self.n_bins_non_missing_ = np.array(n_bins_non_missing, dtype=np.uint32) return self
Fit data X by computing the binning thresholds. The last bin is reserved for missing values, whether missing values are present in the data or not. Parameters ---------- X : array-like of shape (n_samples, n_features) The data to bin. y: None Ignored. Returns ------- self : object
fit
python
scikit-learn/scikit-learn
sklearn/ensemble/_hist_gradient_boosting/binning.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/binning.py
BSD-3-Clause
def transform(self, X): """Bin data X. Missing values will be mapped to the last bin. For categorical features, the mapping will be incorrect for unknown categories. Since the BinMapper is given known_categories of the entire training data (i.e. before the call to train_test_split() in case of early-stopping), this never happens. Parameters ---------- X : array-like of shape (n_samples, n_features) The data to bin. Returns ------- X_binned : array-like of shape (n_samples, n_features) The binned data (fortran-aligned). """ X = check_array(X, dtype=[X_DTYPE], ensure_all_finite=False) check_is_fitted(self) if X.shape[1] != self.n_bins_non_missing_.shape[0]: raise ValueError( "This estimator was fitted with {} features but {} got passed " "to transform()".format(self.n_bins_non_missing_.shape[0], X.shape[1]) ) n_threads = _openmp_effective_n_threads(self.n_threads) binned = np.zeros_like(X, dtype=X_BINNED_DTYPE, order="F") _map_to_bins( X, self.bin_thresholds_, self.is_categorical_, self.missing_values_bin_idx_, n_threads, binned, ) return binned
Bin data X. Missing values will be mapped to the last bin. For categorical features, the mapping will be incorrect for unknown categories. Since the BinMapper is given known_categories of the entire training data (i.e. before the call to train_test_split() in case of early-stopping), this never happens. Parameters ---------- X : array-like of shape (n_samples, n_features) The data to bin. Returns ------- X_binned : array-like of shape (n_samples, n_features) The binned data (fortran-aligned).
transform
python
scikit-learn/scikit-learn
sklearn/ensemble/_hist_gradient_boosting/binning.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/binning.py
BSD-3-Clause
def make_known_categories_bitsets(self): """Create bitsets of known categories. Returns ------- - known_cat_bitsets : ndarray of shape (n_categorical_features, 8) Array of bitsets of known categories, for each categorical feature. - f_idx_map : ndarray of shape (n_features,) Map from original feature index to the corresponding index in the known_cat_bitsets array. """ categorical_features_indices = np.flatnonzero(self.is_categorical_) n_features = self.is_categorical_.size n_categorical_features = categorical_features_indices.size f_idx_map = np.zeros(n_features, dtype=np.uint32) f_idx_map[categorical_features_indices] = np.arange( n_categorical_features, dtype=np.uint32 ) known_categories = self.bin_thresholds_ known_cat_bitsets = np.zeros( (n_categorical_features, 8), dtype=X_BITSET_INNER_DTYPE ) # TODO: complexity is O(n_categorical_features * 255). Maybe this is # worth cythonizing for mapped_f_idx, f_idx in enumerate(categorical_features_indices): for raw_cat_val in known_categories[f_idx]: set_bitset_memoryview(known_cat_bitsets[mapped_f_idx], raw_cat_val) return known_cat_bitsets, f_idx_map
Create bitsets of known categories. Returns ------- - known_cat_bitsets : ndarray of shape (n_categorical_features, 8) Array of bitsets of known categories, for each categorical feature. - f_idx_map : ndarray of shape (n_features,) Map from original feature index to the corresponding index in the known_cat_bitsets array.
make_known_categories_bitsets
python
scikit-learn/scikit-learn
sklearn/ensemble/_hist_gradient_boosting/binning.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/binning.py
BSD-3-Clause
def _update_leaves_values(loss, grower, y_true, raw_prediction, sample_weight): """Update the leaf values to be predicted by the tree. Update equals: loss.fit_intercept_only(y_true - raw_prediction) This is only applied if loss.differentiable is False. Note: It only works, if the loss is a function of the residual, as is the case for AbsoluteError and PinballLoss. Otherwise, one would need to get the minimum of loss(y_true, raw_prediction + x) in x. A few examples: - AbsoluteError: median(y_true - raw_prediction). - PinballLoss: quantile(y_true - raw_prediction). More background: For the standard gradient descent method according to "Greedy Function Approximation: A Gradient Boosting Machine" by Friedman, all loss functions but the squared loss need a line search step. BaseHistGradientBoosting, however, implements a so called Newton boosting where the trees are fitted to a 2nd order approximations of the loss in terms of gradients and hessians. In this case, the line search step is only necessary if the loss is not smooth, i.e. not differentiable, which renders the 2nd order approximation invalid. In fact, non-smooth losses arbitrarily set hessians to 1 and effectively use the standard gradient descent method with line search. """ # TODO: Ideally this should be computed in parallel over the leaves using something # similar to _update_raw_predictions(), but this requires a cython version of # median(). for leaf in grower.finalized_leaves: indices = leaf.sample_indices if sample_weight is None: sw = None else: sw = sample_weight[indices] update = loss.fit_intercept_only( y_true=y_true[indices] - raw_prediction[indices], sample_weight=sw, ) leaf.value = grower.shrinkage * update # Note that the regularization is ignored here
Update the leaf values to be predicted by the tree. Update equals: loss.fit_intercept_only(y_true - raw_prediction) This is only applied if loss.differentiable is False. Note: It only works, if the loss is a function of the residual, as is the case for AbsoluteError and PinballLoss. Otherwise, one would need to get the minimum of loss(y_true, raw_prediction + x) in x. A few examples: - AbsoluteError: median(y_true - raw_prediction). - PinballLoss: quantile(y_true - raw_prediction). More background: For the standard gradient descent method according to "Greedy Function Approximation: A Gradient Boosting Machine" by Friedman, all loss functions but the squared loss need a line search step. BaseHistGradientBoosting, however, implements a so called Newton boosting where the trees are fitted to a 2nd order approximations of the loss in terms of gradients and hessians. In this case, the line search step is only necessary if the loss is not smooth, i.e. not differentiable, which renders the 2nd order approximation invalid. In fact, non-smooth losses arbitrarily set hessians to 1 and effectively use the standard gradient descent method with line search.
_update_leaves_values
python
scikit-learn/scikit-learn
sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py
BSD-3-Clause
def _patch_raw_predict(estimator, raw_predictions): """Context manager that patches _raw_predict to return raw_predictions. `raw_predictions` is typically a precomputed array to avoid redundant state-wise computations fitting with early stopping enabled: in this case `raw_predictions` is incrementally updated whenever we add a tree to the boosted ensemble. Note: this makes fitting HistGradientBoosting* models inherently non thread safe at fit time. However thread-safety at fit time was never guaranteed nor enforced for scikit-learn estimators in general. Thread-safety at prediction/transform time is another matter as those operations are typically side-effect free and therefore often thread-safe by default for most scikit-learn models and would like to keep it that way. Therefore this context manager should only be used at fit time. TODO: in the future, we could explore the possibility to extend the scorer public API to expose a way to compute vales from raw predictions. That would probably require also making the scorer aware of the inverse link function used by the estimator which is typically private API for now, hence the need for this patching mechanism. """ orig_raw_predict = estimator._raw_predict def _patched_raw_predicts(*args, **kwargs): return raw_predictions estimator._raw_predict = _patched_raw_predicts yield estimator estimator._raw_predict = orig_raw_predict
Context manager that patches _raw_predict to return raw_predictions. `raw_predictions` is typically a precomputed array to avoid redundant state-wise computations fitting with early stopping enabled: in this case `raw_predictions` is incrementally updated whenever we add a tree to the boosted ensemble. Note: this makes fitting HistGradientBoosting* models inherently non thread safe at fit time. However thread-safety at fit time was never guaranteed nor enforced for scikit-learn estimators in general. Thread-safety at prediction/transform time is another matter as those operations are typically side-effect free and therefore often thread-safe by default for most scikit-learn models and would like to keep it that way. Therefore this context manager should only be used at fit time. TODO: in the future, we could explore the possibility to extend the scorer public API to expose a way to compute vales from raw predictions. That would probably require also making the scorer aware of the inverse link function used by the estimator which is typically private API for now, hence the need for this patching mechanism.
_patch_raw_predict
python
scikit-learn/scikit-learn
sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py
BSD-3-Clause
def _validate_parameters(self): """Validate parameters passed to __init__. The parameters that are directly passed to the grower are checked in TreeGrower.""" if self.monotonic_cst is not None and self.n_trees_per_iteration_ != 1: raise ValueError( "monotonic constraints are not supported for multiclass classification." )
Validate parameters passed to __init__. The parameters that are directly passed to the grower are checked in TreeGrower.
_validate_parameters
python
scikit-learn/scikit-learn
sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py
BSD-3-Clause
def _preprocess_X(self, X, *, reset): """Preprocess and validate X. Parameters ---------- X : {array-like, pandas DataFrame} of shape (n_samples, n_features) Input data. reset : bool Whether to reset the `n_features_in_` and `feature_names_in_ attributes. Returns ------- X : ndarray of shape (n_samples, n_features) Validated input data. known_categories : list of ndarray of shape (n_categories,) List of known categories for each categorical feature. """ # If there is a preprocessor, we let the preprocessor handle the validation. # Otherwise, we validate the data ourselves. check_X_kwargs = dict(dtype=[X_DTYPE], ensure_all_finite=False) if not reset: if self._preprocessor is None: return validate_data(self, X, reset=False, **check_X_kwargs) return self._preprocessor.transform(X) # At this point, reset is False, which runs during `fit`. self.is_categorical_ = self._check_categorical_features(X) if self.is_categorical_ is None: self._preprocessor = None self._is_categorical_remapped = None X = validate_data(self, X, **check_X_kwargs) return X, None n_features = X.shape[1] ordinal_encoder = OrdinalEncoder( categories="auto", handle_unknown="use_encoded_value", unknown_value=np.nan, encoded_missing_value=np.nan, dtype=X_DTYPE, ) check_X = partial(check_array, **check_X_kwargs) numerical_preprocessor = FunctionTransformer(check_X) self._preprocessor = ColumnTransformer( [ ("encoder", ordinal_encoder, self.is_categorical_), ("numerical", numerical_preprocessor, ~self.is_categorical_), ] ) self._preprocessor.set_output(transform="default") X = self._preprocessor.fit_transform(X) # check categories found by the OrdinalEncoder and get their encoded values known_categories = self._check_categories() self.n_features_in_ = self._preprocessor.n_features_in_ with suppress(AttributeError): self.feature_names_in_ = self._preprocessor.feature_names_in_ # The ColumnTransformer's output places the categorical features at the # beginning categorical_remapped = np.zeros(n_features, dtype=bool) categorical_remapped[self._preprocessor.output_indices_["encoder"]] = True self._is_categorical_remapped = categorical_remapped return X, known_categories
Preprocess and validate X. Parameters ---------- X : {array-like, pandas DataFrame} of shape (n_samples, n_features) Input data. reset : bool Whether to reset the `n_features_in_` and `feature_names_in_ attributes. Returns ------- X : ndarray of shape (n_samples, n_features) Validated input data. known_categories : list of ndarray of shape (n_categories,) List of known categories for each categorical feature.
_preprocess_X
python
scikit-learn/scikit-learn
sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py
BSD-3-Clause
def _check_categories(self): """Check categories found by the preprocessor and return their encoded values. Returns a list of length ``self.n_features_in_``, with one entry per input feature. For non-categorical features, the corresponding entry is ``None``. For categorical features, the corresponding entry is an array containing the categories as encoded by the preprocessor (an ``OrdinalEncoder``), excluding missing values. The entry is therefore ``np.arange(n_categories)`` where ``n_categories`` is the number of unique values in the considered feature column, after removing missing values. If ``n_categories > self.max_bins`` for any feature, a ``ValueError`` is raised. """ encoder = self._preprocessor.named_transformers_["encoder"] known_categories = [None] * self._preprocessor.n_features_in_ categorical_column_indices = np.arange(self._preprocessor.n_features_in_)[ self._preprocessor.output_indices_["encoder"] ] for feature_idx, categories in zip( categorical_column_indices, encoder.categories_ ): # OrdinalEncoder always puts np.nan as the last category if the # training data has missing values. Here we remove it because it is # already added by the _BinMapper. if len(categories) and is_scalar_nan(categories[-1]): categories = categories[:-1] if categories.size > self.max_bins: try: feature_name = repr(encoder.feature_names_in_[feature_idx]) except AttributeError: feature_name = f"at index {feature_idx}" raise ValueError( f"Categorical feature {feature_name} is expected to " f"have a cardinality <= {self.max_bins} but actually " f"has a cardinality of {categories.size}." ) known_categories[feature_idx] = np.arange(len(categories), dtype=X_DTYPE) return known_categories
Check categories found by the preprocessor and return their encoded values. Returns a list of length ``self.n_features_in_``, with one entry per input feature. For non-categorical features, the corresponding entry is ``None``. For categorical features, the corresponding entry is an array containing the categories as encoded by the preprocessor (an ``OrdinalEncoder``), excluding missing values. The entry is therefore ``np.arange(n_categories)`` where ``n_categories`` is the number of unique values in the considered feature column, after removing missing values. If ``n_categories > self.max_bins`` for any feature, a ``ValueError`` is raised.
_check_categories
python
scikit-learn/scikit-learn
sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py
BSD-3-Clause
def _check_categorical_features(self, X): """Check and validate categorical features in X Parameters ---------- X : {array-like, pandas DataFrame} of shape (n_samples, n_features) Input data. Return ------ is_categorical : ndarray of shape (n_features,) or None, dtype=bool Indicates whether a feature is categorical. If no feature is categorical, this is None. """ # Special code for pandas because of a bug in recent pandas, which is # fixed in main and maybe included in 2.2.1, see # https://github.com/pandas-dev/pandas/pull/57173. # Also pandas versions < 1.5.1 do not support the dataframe interchange if _is_pandas_df(X): X_is_dataframe = True categorical_columns_mask = np.asarray(X.dtypes == "category") elif hasattr(X, "__dataframe__"): X_is_dataframe = True categorical_columns_mask = np.asarray( [ c.dtype[0].name == "CATEGORICAL" for c in X.__dataframe__().get_columns() ] ) else: X_is_dataframe = False categorical_columns_mask = None categorical_features = self.categorical_features categorical_by_dtype = ( isinstance(categorical_features, str) and categorical_features == "from_dtype" ) no_categorical_dtype = categorical_features is None or ( categorical_by_dtype and not X_is_dataframe ) if no_categorical_dtype: return None use_pandas_categorical = categorical_by_dtype and X_is_dataframe if use_pandas_categorical: categorical_features = categorical_columns_mask else: categorical_features = np.asarray(categorical_features) if categorical_features.size == 0: return None if categorical_features.dtype.kind not in ("i", "b", "U", "O"): raise ValueError( "categorical_features must be an array-like of bool, int or " f"str, got: {categorical_features.dtype.name}." ) if categorical_features.dtype.kind == "O": types = set(type(f) for f in categorical_features) if types != {str}: raise ValueError( "categorical_features must be an array-like of bool, int or " f"str, got: {', '.join(sorted(t.__name__ for t in types))}." ) n_features = X.shape[1] # At this point `validate_data` was not called yet because we use the original # dtypes to discover the categorical features. Thus `feature_names_in_` # is not defined yet. feature_names_in_ = getattr(X, "columns", None) if categorical_features.dtype.kind in ("U", "O"): # check for feature names if feature_names_in_ is None: raise ValueError( "categorical_features should be passed as an array of " "integers or as a boolean mask when the model is fitted " "on data without feature names." ) is_categorical = np.zeros(n_features, dtype=bool) feature_names = list(feature_names_in_) for feature_name in categorical_features: try: is_categorical[feature_names.index(feature_name)] = True except ValueError as e: raise ValueError( f"categorical_features has a item value '{feature_name}' " "which is not a valid feature name of the training " f"data. Observed feature names: {feature_names}" ) from e elif categorical_features.dtype.kind == "i": # check for categorical features as indices if ( np.max(categorical_features) >= n_features or np.min(categorical_features) < 0 ): raise ValueError( "categorical_features set as integer " "indices must be in [0, n_features - 1]" ) is_categorical = np.zeros(n_features, dtype=bool) is_categorical[categorical_features] = True else: if categorical_features.shape[0] != n_features: raise ValueError( "categorical_features set as a boolean mask " "must have shape (n_features,), got: " f"{categorical_features.shape}" ) is_categorical = categorical_features if not np.any(is_categorical): return None return is_categorical
Check and validate categorical features in X Parameters ---------- X : {array-like, pandas DataFrame} of shape (n_samples, n_features) Input data. Return ------ is_categorical : ndarray of shape (n_features,) or None, dtype=bool Indicates whether a feature is categorical. If no feature is categorical, this is None.
_check_categorical_features
python
scikit-learn/scikit-learn
sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py
BSD-3-Clause
def _check_interaction_cst(self, n_features): """Check and validation for interaction constraints.""" if self.interaction_cst is None: return None if self.interaction_cst == "no_interactions": interaction_cst = [[i] for i in range(n_features)] elif self.interaction_cst == "pairwise": interaction_cst = itertools.combinations(range(n_features), 2) else: interaction_cst = self.interaction_cst try: constraints = [set(group) for group in interaction_cst] except TypeError: raise ValueError( "Interaction constraints must be a sequence of tuples or lists, got:" f" {self.interaction_cst!r}." ) for group in constraints: for x in group: if not (isinstance(x, Integral) and 0 <= x < n_features): raise ValueError( "Interaction constraints must consist of integer indices in" f" [0, n_features - 1] = [0, {n_features - 1}], specifying the" " position of features, got invalid indices:" f" {group!r}" ) # Add all not listed features as own group by default. rest = set(range(n_features)) - set().union(*constraints) if len(rest) > 0: constraints.append(rest) return constraints
Check and validation for interaction constraints.
_check_interaction_cst
python
scikit-learn/scikit-learn
sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py
BSD-3-Clause