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 fit(
self,
X,
y,
sample_weight=None,
*,
X_val=None,
y_val=None,
sample_weight_val=None,
):
"""Fit the gradient boosting model.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The in... | Fit the gradient boosting model.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The input samples.
y : array-like of shape (n_samples,)
Target values.
sample_weight : array-like of shape (n_samples,) default=None
Weigh... | fit | 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 _clear_state(self):
"""Clear the state of the gradient boosting model."""
for var in ("train_score_", "validation_score_"):
if hasattr(self, var):
delattr(self, var) | Clear the state of the gradient boosting model. | _clear_state | 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 _get_small_trainset(self, X_binned_train, y_train, sample_weight_train, seed):
"""Compute the indices of the subsample set and return this set.
For efficiency, we need to subsample the training set to compute scores
with scorers.
"""
# TODO: incorporate sample_weights here i... | Compute the indices of the subsample set and return this set.
For efficiency, we need to subsample the training set to compute scores
with scorers.
| _get_small_trainset | 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_early_stopping_scorer(
self,
X_binned_small_train,
y_small_train,
sample_weight_small_train,
X_binned_val,
y_val,
sample_weight_val,
raw_predictions_small_train=None,
raw_predictions_val=None,
):
"""Check if fitting should be... | Check if fitting should be early-stopped based on scorer.
Scores are computed on validation data or on training data.
| _check_early_stopping_scorer | 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_early_stopping_loss(
self,
raw_predictions,
y_train,
sample_weight_train,
raw_predictions_val,
y_val,
sample_weight_val,
n_threads=1,
):
"""Check if fitting should be early-stopped based on loss.
Scores are computed on valid... | Check if fitting should be early-stopped based on loss.
Scores are computed on validation data or on training data.
| _check_early_stopping_loss | 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 _should_stop(self, scores):
"""
Return True (do early stopping) if the last n scores aren't better
than the (n-1)th-to-last score, up to some tolerance.
"""
reference_position = self.n_iter_no_change + 1
if len(scores) < reference_position:
return False
... |
Return True (do early stopping) if the last n scores aren't better
than the (n-1)th-to-last score, up to some tolerance.
| _should_stop | 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 _bin_data(self, X, is_training_data):
"""Bin data X.
If is_training_data, then fit the _bin_mapper attribute.
Else, the binned data is converted to a C-contiguous array.
"""
description = "training" if is_training_data else "validation"
if self.verbose:
... | Bin data X.
If is_training_data, then fit the _bin_mapper attribute.
Else, the binned data is converted to a C-contiguous array.
| _bin_data | 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 _print_iteration_stats(self, iteration_start_time):
"""Print info about the current fitting iteration."""
log_msg = ""
predictors_of_ith_iteration = [
predictors_list
for predictors_list in self._predictors[-1]
if predictors_list
]
n_trees... | Print info about the current fitting iteration. | _print_iteration_stats | 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 _raw_predict(self, X, n_threads=None):
"""Return the sum of the leaves values over all predictors.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The input samples.
n_threads : int, default=None
Number of OpenMP threads to use. ... | Return the sum of the leaves values over all predictors.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The input samples.
n_threads : int, default=None
Number of OpenMP threads to use. `_openmp_effective_n_threads` is called
to... | _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 _predict_iterations(self, X, predictors, raw_predictions, is_binned, n_threads):
"""Add the predictions of the predictors to raw_predictions."""
if not is_binned:
(
known_cat_bitsets,
f_idx_map,
) = self._bin_mapper.make_known_categories_bitset... | Add the predictions of the predictors to raw_predictions. | _predict_iterations | 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 _staged_raw_predict(self, X):
"""Compute raw predictions of ``X`` for each iteration.
This method allows monitoring (i.e. determine error on testing set)
after each stage.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The input sa... | Compute raw predictions of ``X`` for each iteration.
This method allows monitoring (i.e. determine error on testing set)
after each stage.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The input samples.
Yields
------
... | _staged_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 _compute_partial_dependence_recursion(self, grid, target_features):
"""Fast partial dependence computation.
Parameters
----------
grid : ndarray, shape (n_samples, n_target_features), dtype=np.float32
The grid points on which the partial dependence should be
... | Fast partial dependence computation.
Parameters
----------
grid : ndarray, shape (n_samples, n_target_features), dtype=np.float32
The grid points on which the partial dependence should be
evaluated.
target_features : ndarray, shape (n_target_features), dtype=np.i... | _compute_partial_dependence_recursion | 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 predict(self, X):
"""Predict values for X.
Parameters
----------
X : array-like, shape (n_samples, n_features)
The input samples.
Returns
-------
y : ndarray, shape (n_samples,)
The predicted values.
"""
check_is_fitte... | Predict values for X.
Parameters
----------
X : array-like, shape (n_samples, n_features)
The input samples.
Returns
-------
y : ndarray, shape (n_samples,)
The predicted values.
| 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 predict(self, X):
"""Predict classes for X.
Parameters
----------
X : array-like, shape (n_samples, n_features)
The input samples.
Returns
-------
y : ndarray, shape (n_samples,)
The predicted classes.
"""
# TODO: This... | Predict classes for X.
Parameters
----------
X : array-like, shape (n_samples, n_features)
The input samples.
Returns
-------
y : ndarray, shape (n_samples,)
The predicted classes.
| 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 staged_predict(self, X):
"""Predict classes at each iteration.
This method allows monitoring (i.e. determine error on testing set)
after each stage.
.. versionadded:: 0.24
Parameters
----------
X : array-like of shape (n_samples, n_features)
The... | Predict classes at each iteration.
This method allows monitoring (i.e. determine error on testing set)
after each stage.
.. versionadded:: 0.24
Parameters
----------
X : array-like of shape (n_samples, n_features)
The input samples.
Yields
... | staged_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 decision_function(self, X):
"""Compute the decision function of ``X``.
Parameters
----------
X : array-like, shape (n_samples, n_features)
The input samples.
Returns
-------
decision : ndarray, shape (n_samples,) or \
(n_samples, ... | Compute the decision function of ``X``.
Parameters
----------
X : array-like, shape (n_samples, n_features)
The input samples.
Returns
-------
decision : ndarray, shape (n_samples,) or (n_samples, n_trees_per_iteration)
The raw pr... | decision_function | 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 staged_decision_function(self, X):
"""Compute decision function of ``X`` for each iteration.
This method allows monitoring (i.e. determine error on testing set)
after each stage.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The i... | Compute decision function of ``X`` for each iteration.
This method allows monitoring (i.e. determine error on testing set)
after each stage.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The input samples.
Yields
------
... | staged_decision_function | 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 set_children_bounds(self, lower, upper):
"""Set children values bounds to respect monotonic constraints."""
# These are bounds for the node's *children* values, not the node's
# value. The bounds are used in the splitter when considering potential
# left and right child.
sel... | Set children values bounds to respect monotonic constraints. | set_children_bounds | python | scikit-learn/scikit-learn | sklearn/ensemble/_hist_gradient_boosting/grower.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/grower.py | BSD-3-Clause |
def _validate_parameters(
self,
X_binned,
min_gain_to_split,
min_hessian_to_split,
):
"""Validate parameters passed to __init__.
Also validate parameters passed to splitter.
"""
if X_binned.dtype != np.uint8:
raise NotImplementedError("X_b... | Validate parameters passed to __init__.
Also validate parameters passed to splitter.
| _validate_parameters | python | scikit-learn/scikit-learn | sklearn/ensemble/_hist_gradient_boosting/grower.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/grower.py | BSD-3-Clause |
def _apply_shrinkage(self):
"""Multiply leaves values by shrinkage parameter.
This must be done at the very end of the growing process. If this were
done during the growing process e.g. in finalize_leaf(), then a leaf
would be shrunk but its sibling would potentially not be (if it's a
... | Multiply leaves values by shrinkage parameter.
This must be done at the very end of the growing process. If this were
done during the growing process e.g. in finalize_leaf(), then a leaf
would be shrunk but its sibling would potentially not be (if it's a
non-leaf), which would lead to a... | _apply_shrinkage | python | scikit-learn/scikit-learn | sklearn/ensemble/_hist_gradient_boosting/grower.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/grower.py | BSD-3-Clause |
def _initialize_root(self):
"""Initialize root node and finalize it if needed."""
tic = time()
if self.interaction_cst is not None:
allowed_features = set().union(*self.interaction_cst)
allowed_features = np.fromiter(
allowed_features, dtype=np.uint32, cou... | Initialize root node and finalize it if needed. | _initialize_root | python | scikit-learn/scikit-learn | sklearn/ensemble/_hist_gradient_boosting/grower.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/grower.py | BSD-3-Clause |
def _compute_best_split_and_push(self, node):
"""Compute the best possible split (SplitInfo) of a given node.
Also push it in the heap of splittable nodes if gain isn't zero.
The gain of a node is 0 if either all the leaves are pure
(best gain = 0), or if no split would satisfy the cons... | Compute the best possible split (SplitInfo) of a given node.
Also push it in the heap of splittable nodes if gain isn't zero.
The gain of a node is 0 if either all the leaves are pure
(best gain = 0), or if no split would satisfy the constraints,
(min_hessians_to_split, min_gain_to_spli... | _compute_best_split_and_push | python | scikit-learn/scikit-learn | sklearn/ensemble/_hist_gradient_boosting/grower.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/grower.py | BSD-3-Clause |
def split_next(self):
"""Split the node with highest potential gain.
Returns
-------
left : TreeNode
The resulting left child.
right : TreeNode
The resulting right child.
"""
# Consider the node with the highest loss reduction (a.k.a. gain... | Split the node with highest potential gain.
Returns
-------
left : TreeNode
The resulting left child.
right : TreeNode
The resulting right child.
| split_next | python | scikit-learn/scikit-learn | sklearn/ensemble/_hist_gradient_boosting/grower.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/grower.py | BSD-3-Clause |
def _compute_interactions(self, node):
r"""Compute features allowed by interactions to be inherited by child nodes.
Example: Assume constraints [{0, 1}, {1, 2}].
1 <- Both constraint groups could be applied from now on
/ \
1 2 <- Left split still fulfills both co... | Compute features allowed by interactions to be inherited by child nodes.
Example: Assume constraints [{0, 1}, {1, 2}].
1 <- Both constraint groups could be applied from now on
/ \
1 2 <- Left split still fulfills both constraint groups.
/ \ / \ Right split a... | _compute_interactions | python | scikit-learn/scikit-learn | sklearn/ensemble/_hist_gradient_boosting/grower.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/grower.py | BSD-3-Clause |
def _finalize_splittable_nodes(self):
"""Transform all splittable nodes into leaves.
Used when some constraint is met e.g. maximum number of leaves or
maximum depth."""
while len(self.splittable_nodes) > 0:
node = self.splittable_nodes.pop()
self._finalize_leaf(n... | Transform all splittable nodes into leaves.
Used when some constraint is met e.g. maximum number of leaves or
maximum depth. | _finalize_splittable_nodes | python | scikit-learn/scikit-learn | sklearn/ensemble/_hist_gradient_boosting/grower.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/grower.py | BSD-3-Clause |
def make_predictor(self, binning_thresholds):
"""Make a TreePredictor object out of the current tree.
Parameters
----------
binning_thresholds : array-like of floats
Corresponds to the bin_thresholds_ attribute of the BinMapper.
For each feature, this stores:
... | Make a TreePredictor object out of the current tree.
Parameters
----------
binning_thresholds : array-like of floats
Corresponds to the bin_thresholds_ attribute of the BinMapper.
For each feature, this stores:
- the bin frontiers for continuous features
... | make_predictor | python | scikit-learn/scikit-learn | sklearn/ensemble/_hist_gradient_boosting/grower.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/grower.py | BSD-3-Clause |
def _fill_predictor_arrays(
predictor_nodes,
binned_left_cat_bitsets,
raw_left_cat_bitsets,
grower_node,
binning_thresholds,
n_bins_non_missing,
next_free_node_idx=0,
next_free_bitset_idx=0,
):
"""Helper used in make_predictor to set the TreePredictor fields."""
node = predictor_... | Helper used in make_predictor to set the TreePredictor fields. | _fill_predictor_arrays | python | scikit-learn/scikit-learn | sklearn/ensemble/_hist_gradient_boosting/grower.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/grower.py | BSD-3-Clause |
def predict(self, X, known_cat_bitsets, f_idx_map, n_threads):
"""Predict raw values for non-binned data.
Parameters
----------
X : ndarray, shape (n_samples, n_features)
The input samples.
known_cat_bitsets : ndarray of shape (n_categorical_features, 8)
... | Predict raw values for non-binned data.
Parameters
----------
X : ndarray, shape (n_samples, n_features)
The input samples.
known_cat_bitsets : ndarray of shape (n_categorical_features, 8)
Array of bitsets of known categories, for each categorical feature.
... | predict | python | scikit-learn/scikit-learn | sklearn/ensemble/_hist_gradient_boosting/predictor.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/predictor.py | BSD-3-Clause |
def predict_binned(self, X, missing_values_bin_idx, n_threads):
"""Predict raw values for binned data.
Parameters
----------
X : ndarray, shape (n_samples, n_features)
The input samples.
missing_values_bin_idx : uint8
Index of the bin that is used for mis... | Predict raw values for binned data.
Parameters
----------
X : ndarray, shape (n_samples, n_features)
The input samples.
missing_values_bin_idx : uint8
Index of the bin that is used for missing values. This is the
index of the last bin and is always eq... | predict_binned | python | scikit-learn/scikit-learn | sklearn/ensemble/_hist_gradient_boosting/predictor.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/predictor.py | BSD-3-Clause |
def get_equivalent_estimator(estimator, lib="lightgbm", n_classes=None):
"""Return an unfitted estimator from another lib with matching hyperparams.
This utility function takes care of renaming the sklearn parameters into
their LightGBM, XGBoost or CatBoost equivalent parameters.
# unmapped XGB parame... | Return an unfitted estimator from another lib with matching hyperparams.
This utility function takes care of renaming the sklearn parameters into
their LightGBM, XGBoost or CatBoost equivalent parameters.
# unmapped XGB parameters:
# - min_samples_leaf
# - min_data_in_bin
# - min_split_gain (t... | get_equivalent_estimator | python | scikit-learn/scikit-learn | sklearn/ensemble/_hist_gradient_boosting/utils.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/utils.py | BSD-3-Clause |
def test_categorical_feature_negative_missing():
"""Make sure bin mapper treats negative categories as missing values."""
X = np.array(
[[4] * 500 + [1] * 3 + [5] * 10 + [-1] * 3 + [np.nan] * 4], dtype=X_DTYPE
).T
bin_mapper = _BinMapper(
n_bins=4,
is_categorical=np.array([True])... | Make sure bin mapper treats negative categories as missing values. | test_categorical_feature_negative_missing | python | scikit-learn/scikit-learn | sklearn/ensemble/_hist_gradient_boosting/tests/test_binning.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/tests/test_binning.py | BSD-3-Clause |
def _make_dumb_dataset(n_samples):
"""Make a dumb dataset to test early stopping."""
rng = np.random.RandomState(42)
X_dumb = rng.randn(n_samples, 1)
y_dumb = (X_dumb[:, 0] > 0).astype("int64")
return X_dumb, y_dumb | Make a dumb dataset to test early stopping. | _make_dumb_dataset | python | scikit-learn/scikit-learn | sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py | BSD-3-Clause |
def test_quantile_asymmetric_error(quantile):
"""Test quantile regression for asymmetric distributed targets."""
n_samples = 10_000
rng = np.random.RandomState(42)
# take care that X @ coef + intercept > 0
X = np.concatenate(
(
np.abs(rng.randn(n_samples)[:, None]),
-... | Test quantile regression for asymmetric distributed targets. | test_quantile_asymmetric_error | python | scikit-learn/scikit-learn | sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py | BSD-3-Clause |
def test_early_stopping_with_sample_weights(monkeypatch):
"""Check that sample weights is passed in to the scorer and _raw_predict is not
called."""
mock_scorer = Mock(side_effect=get_scorer("neg_median_absolute_error"))
def mock_check_scoring(estimator, scoring):
assert scoring == "neg_median... | Check that sample weights is passed in to the scorer and _raw_predict is not
called. | test_early_stopping_with_sample_weights | python | scikit-learn/scikit-learn | sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py | BSD-3-Clause |
def test_check_interaction_cst(interaction_cst, n_features, result):
"""Check that _check_interaction_cst returns the expected list of sets"""
est = HistGradientBoostingRegressor()
est.set_params(interaction_cst=interaction_cst)
assert est._check_interaction_cst(n_features) == result | Check that _check_interaction_cst returns the expected list of sets | test_check_interaction_cst | python | scikit-learn/scikit-learn | sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py | BSD-3-Clause |
def test_interaction_cst_numerically():
"""Check that interaction constraints have no forbidden interactions."""
rng = np.random.RandomState(42)
n_samples = 1000
X = rng.uniform(size=(n_samples, 2))
# Construct y with a strong interaction term
# y = x0 + x1 + 5 * x0 * x1
y = np.hstack((X, 5 ... | Check that interaction constraints have no forbidden interactions. | test_interaction_cst_numerically | python | scikit-learn/scikit-learn | sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py | BSD-3-Clause |
def test_no_user_warning_with_scoring():
"""Check that no UserWarning is raised when scoring is set.
Non-regression test for #22907.
"""
pd = pytest.importorskip("pandas")
X, y = make_regression(n_samples=50, random_state=0)
X_df = pd.DataFrame(X, columns=[f"col{i}" for i in range(X.shape[1])])... | Check that no UserWarning is raised when scoring is set.
Non-regression test for #22907.
| test_no_user_warning_with_scoring | python | scikit-learn/scikit-learn | sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py | BSD-3-Clause |
def test_unknown_category_that_are_negative():
"""Check that unknown categories that are negative does not error.
Non-regression test for #24274.
"""
rng = np.random.RandomState(42)
n_samples = 1000
X = np.c_[rng.rand(n_samples), rng.randint(4, size=n_samples)]
y = np.zeros(shape=n_samples)... | Check that unknown categories that are negative does not error.
Non-regression test for #24274.
| test_unknown_category_that_are_negative | python | scikit-learn/scikit-learn | sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py | BSD-3-Clause |
def test_X_val_in_fit(GradientBoosting, make_X_y, sample_weight, global_random_seed):
"""Test that passing X_val, y_val in fit is same as validation fraction."""
rng = np.random.RandomState(42)
n_samples = 100
X, y = make_X_y(n_samples=n_samples, random_state=rng)
if sample_weight:
sample_we... | Test that passing X_val, y_val in fit is same as validation fraction. | test_X_val_in_fit | python | scikit-learn/scikit-learn | sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py | BSD-3-Clause |
def test_X_val_raises_missing_y_val():
"""Test that an error is raised if X_val given but y_val None."""
X, y = make_classification(n_samples=4)
X, X_val = X[:2], X[2:]
y, y_val = y[:2], y[2:]
with pytest.raises(
ValueError,
match="X_val is provided, but y_val was not provided",
... | Test that an error is raised if X_val given but y_val None. | test_X_val_raises_missing_y_val | python | scikit-learn/scikit-learn | sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py | BSD-3-Clause |
def test_X_val_raises_with_early_stopping_false():
"""Test that an error is raised if X_val given but early_stopping is False."""
X, y = make_regression(n_samples=4)
X, X_val = X[:2], X[2:]
y, y_val = y[:2], y[2:]
with pytest.raises(
ValueError,
match="X_val and y_val are passed to f... | Test that an error is raised if X_val given but early_stopping is False. | test_X_val_raises_with_early_stopping_false | python | scikit-learn/scikit-learn | sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py | BSD-3-Clause |
def test_dataframe_categorical_results_same_as_ndarray(
dataframe_lib, HistGradientBoosting
):
"""Check that pandas categorical give the same results as ndarray."""
pytest.importorskip(dataframe_lib)
rng = np.random.RandomState(42)
n_samples = 5_000
n_cardinality = 50
max_bins = 100
f_n... | Check that pandas categorical give the same results as ndarray. | test_dataframe_categorical_results_same_as_ndarray | python | scikit-learn/scikit-learn | sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py | BSD-3-Clause |
def test_dataframe_categorical_errors(dataframe_lib, HistGradientBoosting):
"""Check error cases for pandas categorical feature."""
pytest.importorskip(dataframe_lib)
msg = "Categorical feature 'f_cat' is expected to have a cardinality <= 16"
hist = HistGradientBoosting(categorical_features="from_dtype"... | Check error cases for pandas categorical feature. | test_dataframe_categorical_errors | python | scikit-learn/scikit-learn | sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py | BSD-3-Clause |
def test_categorical_different_order_same_model(dataframe_lib):
"""Check that the order of the categorical gives same model."""
pytest.importorskip(dataframe_lib)
rng = np.random.RandomState(42)
n_samples = 1_000
f_ints = rng.randint(low=0, high=2, size=n_samples)
# Construct a target with some... | Check that the order of the categorical gives same model. | test_categorical_different_order_same_model | python | scikit-learn/scikit-learn | sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py | BSD-3-Clause |
def true_decision_function(input_features):
"""Ground truth decision function
This is a very simple yet asymmetric decision tree. Therefore the
grower code should have no trouble recovering the decision function
from 10000 training samples.
"""
if input_features[0] <= n_... | Ground truth decision function
This is a very simple yet asymmetric decision tree. Therefore the
grower code should have no trouble recovering the decision function
from 10000 training samples.
| true_decision_function | python | scikit-learn/scikit-learn | sklearn/ensemble/_hist_gradient_boosting/tests/test_grower.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/tests/test_grower.py | BSD-3-Clause |
def test_grower_interaction_constraints():
"""Check that grower respects interaction constraints."""
n_features = 6
interaction_cst = [{0, 1}, {1, 2}, {3, 4, 5}]
n_samples = 10
n_bins = 6
root_feature_splits = []
def get_all_children(node):
res = []
if node.is_leaf:
... | Check that grower respects interaction constraints. | test_grower_interaction_constraints | python | scikit-learn/scikit-learn | sklearn/ensemble/_hist_gradient_boosting/tests/test_grower.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/tests/test_grower.py | BSD-3-Clause |
def get_leaves_values():
"""get leaves values from left to right"""
values = []
def depth_first_collect_leaf_values(node_idx):
node = nodes[node_idx]
if node["is_leaf"]:
values.append(node["value"])
return
depth_first_collect_l... | get leaves values from left to right | get_leaves_values | python | scikit-learn/scikit-learn | sklearn/ensemble/_hist_gradient_boosting/tests/test_monotonic_constraints.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/tests/test_monotonic_constraints.py | BSD-3-Clause |
def test_split_feature_fraction_per_split(forbidden_features):
"""Check that feature_fraction_per_split is respected.
Because we set `n_features = 4` and `feature_fraction_per_split = 0.25`, it means
that calling `splitter.find_node_split` will be allowed to select a split for a
single completely rando... | Check that feature_fraction_per_split is respected.
Because we set `n_features = 4` and `feature_fraction_per_split = 0.25`, it means
that calling `splitter.find_node_split` will be allowed to select a split for a
single completely random feature at each call. So if we iterate enough, we should
cover a... | test_split_feature_fraction_per_split | python | scikit-learn/scikit-learn | sklearn/ensemble/_hist_gradient_boosting/tests/test_splitting.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/tests/test_splitting.py | BSD-3-Clause |
def _assert_predictor_equal(gb_1, gb_2, X):
"""Assert that two HistGBM instances are identical."""
# Check identical nodes for each tree
for pred_ith_1, pred_ith_2 in zip(gb_1._predictors, gb_2._predictors):
for predictor_1, predictor_2 in zip(pred_ith_1, pred_ith_2):
assert_array_equal(... | Assert that two HistGBM instances are identical. | _assert_predictor_equal | python | scikit-learn/scikit-learn | sklearn/ensemble/_hist_gradient_boosting/tests/test_warm_start.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/_hist_gradient_boosting/tests/test_warm_start.py | BSD-3-Clause |
def _parse_values(s):
'''(INTERNAL) Split a line into a list of values'''
if not _RE_NONTRIVIAL_DATA.search(s):
# Fast path for trivial cases (unfortunately we have to handle missing
# values because of the empty string case :(.)
return [None if s in ('?', '') else s
for ... | (INTERNAL) Split a line into a list of values | _parse_values | python | scikit-learn/scikit-learn | sklearn/externals/_arff.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/_arff.py | BSD-3-Clause |
def _decode_relation(self, s):
'''(INTERNAL) Decodes a relation line.
The relation declaration is a line with the format ``@RELATION
<relation-name>``, where ``relation-name`` is a string. The string must
start with alphabetic character and must be quoted if the name includes
sp... | (INTERNAL) Decodes a relation line.
The relation declaration is a line with the format ``@RELATION
<relation-name>``, where ``relation-name`` is a string. The string must
start with alphabetic character and must be quoted if the name includes
spaces, otherwise this method will raise a `... | _decode_relation | python | scikit-learn/scikit-learn | sklearn/externals/_arff.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/_arff.py | BSD-3-Clause |
def _decode_attribute(self, s):
'''(INTERNAL) Decodes an attribute line.
The attribute is the most complex declaration in an arff file. All
attributes must follow the template::
@attribute <attribute-name> <datatype>
where ``attribute-name`` is a string, quoted if the nam... | (INTERNAL) Decodes an attribute line.
The attribute is the most complex declaration in an arff file. All
attributes must follow the template::
@attribute <attribute-name> <datatype>
where ``attribute-name`` is a string, quoted if the name contains any
whitespace, and ``da... | _decode_attribute | python | scikit-learn/scikit-learn | sklearn/externals/_arff.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/_arff.py | BSD-3-Clause |
def decode(self, s, encode_nominal=False, return_type=DENSE):
'''Returns the Python representation of a given ARFF file.
When a file object is passed as an argument, this method reads lines
iteratively, avoiding to load unnecessary information to the memory.
:param s: a string or file ... | Returns the Python representation of a given ARFF file.
When a file object is passed as an argument, this method reads lines
iteratively, avoiding to load unnecessary information to the memory.
:param s: a string or file object with the ARFF file.
:param encode_nominal: boolean, if Tru... | decode | python | scikit-learn/scikit-learn | sklearn/externals/_arff.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/_arff.py | BSD-3-Clause |
def _encode_comment(self, s=''):
'''(INTERNAL) Encodes a comment line.
Comments are single line strings starting, obligatorily, with the ``%``
character, and can have any symbol, including whitespaces or special
characters.
If ``s`` is None, this method will simply return an em... | (INTERNAL) Encodes a comment line.
Comments are single line strings starting, obligatorily, with the ``%``
character, and can have any symbol, including whitespaces or special
characters.
If ``s`` is None, this method will simply return an empty comment.
:param s: (OPTIONAL) s... | _encode_comment | python | scikit-learn/scikit-learn | sklearn/externals/_arff.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/_arff.py | BSD-3-Clause |
def _encode_relation(self, name):
'''(INTERNAL) Decodes a relation line.
The relation declaration is a line with the format ``@RELATION
<relation-name>``, where ``relation-name`` is a string.
:param name: a string.
:return: a string with the encoded relation declaration.
... | (INTERNAL) Decodes a relation line.
The relation declaration is a line with the format ``@RELATION
<relation-name>``, where ``relation-name`` is a string.
:param name: a string.
:return: a string with the encoded relation declaration.
| _encode_relation | python | scikit-learn/scikit-learn | sklearn/externals/_arff.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/_arff.py | BSD-3-Clause |
def _encode_attribute(self, name, type_):
'''(INTERNAL) Encodes an attribute line.
The attribute follow the template::
@attribute <attribute-name> <datatype>
where ``attribute-name`` is a string, and ``datatype`` can be:
- Numerical attributes as ``NUMERIC``, ``INTEGER``... | (INTERNAL) Encodes an attribute line.
The attribute follow the template::
@attribute <attribute-name> <datatype>
where ``attribute-name`` is a string, and ``datatype`` can be:
- Numerical attributes as ``NUMERIC``, ``INTEGER`` or ``REAL``.
- Strings as ``STRING``.
... | _encode_attribute | python | scikit-learn/scikit-learn | sklearn/externals/_arff.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/_arff.py | BSD-3-Clause |
def iter_encode(self, obj):
'''The iterative version of `arff.ArffEncoder.encode`.
This encodes iteratively a given object and return, one-by-one, the
lines of the ARFF file.
:param obj: the object containing the ARFF information.
:return: (yields) the ARFF file as strings.
... | The iterative version of `arff.ArffEncoder.encode`.
This encodes iteratively a given object and return, one-by-one, the
lines of the ARFF file.
:param obj: the object containing the ARFF information.
:return: (yields) the ARFF file as strings.
| iter_encode | python | scikit-learn/scikit-learn | sklearn/externals/_arff.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/_arff.py | BSD-3-Clause |
def load(fp, encode_nominal=False, return_type=DENSE):
'''Load a file-like object containing the ARFF document and convert it into
a Python object.
:param fp: a file-like object.
:param encode_nominal: boolean, if True perform a label encoding
while reading the .arff file.
:param return_typ... | Load a file-like object containing the ARFF document and convert it into
a Python object.
:param fp: a file-like object.
:param encode_nominal: boolean, if True perform a label encoding
while reading the .arff file.
:param return_type: determines the data structure used to store the
dat... | load | python | scikit-learn/scikit-learn | sklearn/externals/_arff.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/_arff.py | BSD-3-Clause |
def loads(s, encode_nominal=False, return_type=DENSE):
'''Convert a string instance containing the ARFF document into a Python
object.
:param s: a string object.
:param encode_nominal: boolean, if True perform a label encoding
while reading the .arff file.
:param return_type: determines the... | Convert a string instance containing the ARFF document into a Python
object.
:param s: a string object.
:param encode_nominal: boolean, if True perform a label encoding
while reading the .arff file.
:param return_type: determines the data structure used to store the
dataset. Can be one ... | loads | python | scikit-learn/scikit-learn | sklearn/externals/_arff.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/_arff.py | BSD-3-Clause |
def dump(obj, fp):
'''Serialize an object representing the ARFF document to a given file-like
object.
:param obj: a dictionary.
:param fp: a file-like object.
'''
encoder = ArffEncoder()
generator = encoder.iter_encode(obj)
last_row = next(generator)
for row in generator:
f... | Serialize an object representing the ARFF document to a given file-like
object.
:param obj: a dictionary.
:param fp: a file-like object.
| dump | python | scikit-learn/scikit-learn | sklearn/externals/_arff.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/_arff.py | BSD-3-Clause |
def get_xp(xp: ModuleType) -> Callable[[Callable[..., _T]], Callable[..., _T]]:
"""
Decorator to automatically replace xp with the corresponding array module.
Use like
import numpy as np
@get_xp(np)
def func(x, /, xp, kwarg=None):
return xp.func(x, kwarg=kwarg)
Note that xp must ... |
Decorator to automatically replace xp with the corresponding array module.
Use like
import numpy as np
@get_xp(np)
def func(x, /, xp, kwarg=None):
return xp.func(x, kwarg=kwarg)
Note that xp must be a keyword argument and come after all non-keyword
arguments.
| get_xp | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/_internal.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/_internal.py | BSD-3-Clause |
def isdtype(
dtype: DType,
kind: DType | str | tuple[DType | str, ...],
xp: Namespace,
*,
_tuple: bool = True, # Disallow nested tuples
) -> bool:
"""
Returns a boolean indicating whether a provided dtype is of a specified data type ``kind``.
Note that outside of this function, this co... |
Returns a boolean indicating whether a provided dtype is of a specified data type ``kind``.
Note that outside of this function, this compat library does not yet fully
support complex numbers.
See
https://data-apis.org/array-api/latest/API_specification/generated/array_api.isdtype.html
for mor... | isdtype | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/common/_aliases.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/common/_aliases.py | BSD-3-Clause |
def _is_jax_zero_gradient_array(x: object) -> TypeGuard[_ZeroGradientArray]:
"""Return True if `x` is a zero-gradient array.
These arrays are a design quirk of Jax that may one day be removed.
See https://github.com/google/jax/issues/20620.
"""
# Fast exit
try:
dtype = x.dtype # type: ... | Return True if `x` is a zero-gradient array.
These arrays are a design quirk of Jax that may one day be removed.
See https://github.com/google/jax/issues/20620.
| _is_jax_zero_gradient_array | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/common/_helpers.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/common/_helpers.py | BSD-3-Clause |
def is_numpy_array(x: object) -> TypeGuard[npt.NDArray[Any]]:
"""
Return True if `x` is a NumPy array.
This function does not import NumPy if it has not already been imported
and is therefore cheap to use.
This also returns True for `ndarray` subclasses and NumPy scalar objects.
See Also
... |
Return True if `x` is a NumPy array.
This function does not import NumPy if it has not already been imported
and is therefore cheap to use.
This also returns True for `ndarray` subclasses and NumPy scalar objects.
See Also
--------
array_namespace
is_array_api_obj
is_cupy_array
... | is_numpy_array | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/common/_helpers.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/common/_helpers.py | BSD-3-Clause |
def is_cupy_array(x: object) -> bool:
"""
Return True if `x` is a CuPy array.
This function does not import CuPy if it has not already been imported
and is therefore cheap to use.
This also returns True for `cupy.ndarray` subclasses and CuPy scalar objects.
See Also
--------
array_na... |
Return True if `x` is a CuPy array.
This function does not import CuPy if it has not already been imported
and is therefore cheap to use.
This also returns True for `cupy.ndarray` subclasses and CuPy scalar objects.
See Also
--------
array_namespace
is_array_api_obj
is_numpy_arr... | is_cupy_array | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/common/_helpers.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/common/_helpers.py | BSD-3-Clause |
def is_torch_array(x: object) -> TypeIs[torch.Tensor]:
"""
Return True if `x` is a PyTorch tensor.
This function does not import PyTorch if it has not already been imported
and is therefore cheap to use.
See Also
--------
array_namespace
is_array_api_obj
is_numpy_array
is_cupy... |
Return True if `x` is a PyTorch tensor.
This function does not import PyTorch if it has not already been imported
and is therefore cheap to use.
See Also
--------
array_namespace
is_array_api_obj
is_numpy_array
is_cupy_array
is_dask_array
is_jax_array
is_pydata_sparse... | is_torch_array | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/common/_helpers.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/common/_helpers.py | BSD-3-Clause |
def is_ndonnx_array(x: object) -> TypeIs[ndx.Array]:
"""
Return True if `x` is a ndonnx Array.
This function does not import ndonnx if it has not already been imported
and is therefore cheap to use.
See Also
--------
array_namespace
is_array_api_obj
is_numpy_array
is_cupy_arra... |
Return True if `x` is a ndonnx Array.
This function does not import ndonnx if it has not already been imported
and is therefore cheap to use.
See Also
--------
array_namespace
is_array_api_obj
is_numpy_array
is_cupy_array
is_ndonnx_array
is_dask_array
is_jax_array
... | is_ndonnx_array | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/common/_helpers.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/common/_helpers.py | BSD-3-Clause |
def is_dask_array(x: object) -> TypeIs[da.Array]:
"""
Return True if `x` is a dask.array Array.
This function does not import dask if it has not already been imported
and is therefore cheap to use.
See Also
--------
array_namespace
is_array_api_obj
is_numpy_array
is_cupy_array... |
Return True if `x` is a dask.array Array.
This function does not import dask if it has not already been imported
and is therefore cheap to use.
See Also
--------
array_namespace
is_array_api_obj
is_numpy_array
is_cupy_array
is_torch_array
is_ndonnx_array
is_jax_array
... | is_dask_array | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/common/_helpers.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/common/_helpers.py | BSD-3-Clause |
def is_jax_array(x: object) -> TypeIs[jax.Array]:
"""
Return True if `x` is a JAX array.
This function does not import JAX if it has not already been imported
and is therefore cheap to use.
See Also
--------
array_namespace
is_array_api_obj
is_numpy_array
is_cupy_array
is... |
Return True if `x` is a JAX array.
This function does not import JAX if it has not already been imported
and is therefore cheap to use.
See Also
--------
array_namespace
is_array_api_obj
is_numpy_array
is_cupy_array
is_torch_array
is_ndonnx_array
is_dask_array
is... | is_jax_array | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/common/_helpers.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/common/_helpers.py | BSD-3-Clause |
def is_pydata_sparse_array(x: object) -> TypeIs[sparse.SparseArray]:
"""
Return True if `x` is an array from the `sparse` package.
This function does not import `sparse` if it has not already been imported
and is therefore cheap to use.
See Also
--------
array_namespace
is_array_api_... |
Return True if `x` is an array from the `sparse` package.
This function does not import `sparse` if it has not already been imported
and is therefore cheap to use.
See Also
--------
array_namespace
is_array_api_obj
is_numpy_array
is_cupy_array
is_torch_array
is_ndonnx_ar... | is_pydata_sparse_array | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/common/_helpers.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/common/_helpers.py | BSD-3-Clause |
def is_array_api_obj(x: object) -> TypeIs[_ArrayApiObj]: # pyright: ignore[reportUnknownParameterType]
"""
Return True if `x` is an array API compatible array object.
See Also
--------
array_namespace
is_numpy_array
is_cupy_array
is_torch_array
is_ndonnx_array
is_dask_array
... |
Return True if `x` is an array API compatible array object.
See Also
--------
array_namespace
is_numpy_array
is_cupy_array
is_torch_array
is_ndonnx_array
is_dask_array
is_jax_array
| is_array_api_obj | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/common/_helpers.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/common/_helpers.py | BSD-3-Clause |
def array_namespace(
*xs: Array | complex | None,
api_version: str | None = None,
use_compat: bool | None = None,
) -> Namespace:
"""
Get the array API compatible namespace for the arrays `xs`.
Parameters
----------
xs: arrays
one or more arrays. xs can also be Python scalars (b... |
Get the array API compatible namespace for the arrays `xs`.
Parameters
----------
xs: arrays
one or more arrays. xs can also be Python scalars (bool, int, float,
complex, or None), which are ignored.
api_version: str
The newest version of the spec that you need support for... | array_namespace | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/common/_helpers.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/common/_helpers.py | BSD-3-Clause |
def _check_device(bare_xp: Namespace, device: Device) -> None: # pyright: ignore[reportUnusedFunction]
"""
Validate dummy device on device-less array backends.
Notes
-----
This function is also invoked by CuPy, which does have multiple devices
if there are multiple GPUs available.
However,... |
Validate dummy device on device-less array backends.
Notes
-----
This function is also invoked by CuPy, which does have multiple devices
if there are multiple GPUs available.
However, CuPy multi-device support is currently impossible
without using the global device or a context manager:
... | _check_device | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/common/_helpers.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/common/_helpers.py | BSD-3-Clause |
def device(x: _ArrayApiObj, /) -> Device:
"""
Hardware device the array data resides on.
This is equivalent to `x.device` according to the `standard
<https://data-apis.org/array-api/latest/API_specification/generated/array_api.array.device.html>`__.
This helper is included because some array librar... |
Hardware device the array data resides on.
This is equivalent to `x.device` according to the `standard
<https://data-apis.org/array-api/latest/API_specification/generated/array_api.array.device.html>`__.
This helper is included because some array libraries either do not have
the `device` attribute... | device | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/common/_helpers.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/common/_helpers.py | BSD-3-Clause |
def to_device(x: Array, device: Device, /, *, stream: int | Any | None = None) -> Array:
"""
Copy the array from the device on which it currently resides to the specified ``device``.
This is equivalent to `x.to_device(device, stream=stream)` according to
the `standard
<https://data-apis.org/array-a... |
Copy the array from the device on which it currently resides to the specified ``device``.
This is equivalent to `x.to_device(device, stream=stream)` according to
the `standard
<https://data-apis.org/array-api/latest/API_specification/generated/array_api.array.to_device.html>`__.
This helper is inc... | to_device | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/common/_helpers.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/common/_helpers.py | BSD-3-Clause |
def size(x: HasShape[Collection[SupportsIndex | None]]) -> int | None:
"""
Return the total number of elements of x.
This is equivalent to `x.size` according to the `standard
<https://data-apis.org/array-api/latest/API_specification/generated/array_api.array.size.html>`__.
This helper is included ... |
Return the total number of elements of x.
This is equivalent to `x.size` according to the `standard
<https://data-apis.org/array-api/latest/API_specification/generated/array_api.array.size.html>`__.
This helper is included because PyTorch defines `size` in an
:external+torch:meth:`incompatible wa... | size | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/common/_helpers.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/common/_helpers.py | BSD-3-Clause |
def is_writeable_array(x: object) -> bool:
"""
Return False if ``x.__setitem__`` is expected to raise; True otherwise.
Return False if `x` is not an array API compatible object.
Warning
-------
As there is no standard way to check if an array is writeable without actually
writing to it, thi... |
Return False if ``x.__setitem__`` is expected to raise; True otherwise.
Return False if `x` is not an array API compatible object.
Warning
-------
As there is no standard way to check if an array is writeable without actually
writing to it, this function blindly returns True for all unknown ar... | is_writeable_array | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/common/_helpers.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/common/_helpers.py | BSD-3-Clause |
def is_lazy_array(x: object) -> bool:
"""Return True if x is potentially a future or it may be otherwise impossible or
expensive to eagerly read its contents, regardless of their size, e.g. by
calling ``bool(x)`` or ``float(x)``.
Return False otherwise; e.g. ``bool(x)`` etc. is guaranteed to succeed an... | Return True if x is potentially a future or it may be otherwise impossible or
expensive to eagerly read its contents, regardless of their size, e.g. by
calling ``bool(x)`` or ``float(x)``.
Return False otherwise; e.g. ``bool(x)`` etc. is guaranteed to succeed and to be
cheap as long as the array has th... | is_lazy_array | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/common/_helpers.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/common/_helpers.py | BSD-3-Clause |
def asarray(
obj: (
Array
| bool | int | float | complex
| NestedSequence[bool | int | float | complex]
| SupportsBufferProtocol
),
/,
*,
dtype: Optional[DType] = None,
device: Optional[Device] = None,
copy: Optional[bool] = None,
**kwargs,
) -> Array:
... |
Array API compatibility wrapper for asarray().
See the corresponding documentation in the array library and/or the array API
specification for more details.
| asarray | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/cupy/_aliases.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/cupy/_aliases.py | BSD-3-Clause |
def capabilities(self):
"""
Return a dictionary of array API library capabilities.
The resulting dictionary has the following keys:
- **"boolean indexing"**: boolean indicating whether an array library
supports boolean indexing. Always ``True`` for CuPy.
- **"data-de... |
Return a dictionary of array API library capabilities.
The resulting dictionary has the following keys:
- **"boolean indexing"**: boolean indicating whether an array library
supports boolean indexing. Always ``True`` for CuPy.
- **"data-dependent shapes"**: boolean indicati... | capabilities | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/cupy/_info.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/cupy/_info.py | BSD-3-Clause |
def default_dtypes(self, *, device=None):
"""
The default data types used for new CuPy arrays.
For CuPy, this always returns the following dictionary:
- **"real floating"**: ``cupy.float64``
- **"complex floating"**: ``cupy.complex128``
- **"integral"**: ``cupy.intp``
... |
The default data types used for new CuPy arrays.
For CuPy, this always returns the following dictionary:
- **"real floating"**: ``cupy.float64``
- **"complex floating"**: ``cupy.complex128``
- **"integral"**: ``cupy.intp``
- **"indexing"**: ``cupy.intp``
Param... | default_dtypes | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/cupy/_info.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/cupy/_info.py | BSD-3-Clause |
def dtypes(self, *, device=None, kind=None):
"""
The array API data types supported by CuPy.
Note that this function only returns data types that are defined by
the array API.
Parameters
----------
device : str, optional
The device to get the data ty... |
The array API data types supported by CuPy.
Note that this function only returns data types that are defined by
the array API.
Parameters
----------
device : str, optional
The device to get the data types for.
kind : str or tuple of str, optional
... | dtypes | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/cupy/_info.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/cupy/_info.py | BSD-3-Clause |
def astype(
x: Array,
dtype: DType,
/,
*,
copy: py_bool = True,
device: Device | None = None,
) -> Array:
"""
Array API compatibility wrapper for astype().
See the corresponding documentation in the array library and/or the array API
specification for more details.
"""
#... |
Array API compatibility wrapper for astype().
See the corresponding documentation in the array library and/or the array API
specification for more details.
| astype | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/dask/array/_aliases.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/dask/array/_aliases.py | BSD-3-Clause |
def arange(
start: float,
/,
stop: float | None = None,
step: float = 1,
*,
dtype: DType | None = None,
device: Device | None = None,
**kwargs: object,
) -> Array:
"""
Array API compatibility wrapper for arange().
See the corresponding documentation in the array library and/... |
Array API compatibility wrapper for arange().
See the corresponding documentation in the array library and/or the array API
specification for more details.
| arange | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/dask/array/_aliases.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/dask/array/_aliases.py | BSD-3-Clause |
def asarray(
obj: complex | NestedSequence[complex] | Array | SupportsBufferProtocol,
/,
*,
dtype: DType | None = None,
device: Device | None = None,
copy: py_bool | None = None,
**kwargs: object,
) -> Array:
"""
Array API compatibility wrapper for asarray().
See the correspondi... |
Array API compatibility wrapper for asarray().
See the corresponding documentation in the array library and/or the array API
specification for more details.
| asarray | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/dask/array/_aliases.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/dask/array/_aliases.py | BSD-3-Clause |
def clip(
x: Array,
/,
min: float | Array | None = None,
max: float | Array | None = None,
) -> Array:
"""
Array API compatibility wrapper for clip().
See the corresponding documentation in the array library and/or the array API
specification for more details.
"""
def _isscalar... |
Array API compatibility wrapper for clip().
See the corresponding documentation in the array library and/or the array API
specification for more details.
| clip | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/dask/array/_aliases.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/dask/array/_aliases.py | BSD-3-Clause |
def _ensure_single_chunk(x: Array, axis: int) -> tuple[Array, Callable[[Array], Array]]:
"""
Make sure that Array is not broken into multiple chunks along axis.
Returns
-------
x : Array
The input Array with a single chunk along axis.
restore : Callable[Array, Array]
function to... |
Make sure that Array is not broken into multiple chunks along axis.
Returns
-------
x : Array
The input Array with a single chunk along axis.
restore : Callable[Array, Array]
function to apply to the output to rechunk it back into reasonable chunks
| _ensure_single_chunk | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/dask/array/_aliases.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/dask/array/_aliases.py | BSD-3-Clause |
def sort(
x: Array,
/,
*,
axis: int = -1,
descending: py_bool = False,
stable: py_bool = True,
) -> Array:
"""
Array API compatibility layer around the lack of sort() in Dask.
Warnings
--------
This function temporarily rechunks the array along `axis` to a single chunk.
... |
Array API compatibility layer around the lack of sort() in Dask.
Warnings
--------
This function temporarily rechunks the array along `axis` to a single chunk.
This can be extremely inefficient and can lead to out-of-memory errors.
See the corresponding documentation in the array library and/... | sort | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/dask/array/_aliases.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/dask/array/_aliases.py | BSD-3-Clause |
def argsort(
x: Array,
/,
*,
axis: int = -1,
descending: py_bool = False,
stable: py_bool = True,
) -> Array:
"""
Array API compatibility layer around the lack of argsort() in Dask.
See the corresponding documentation in the array library and/or the array API
specification for m... |
Array API compatibility layer around the lack of argsort() in Dask.
See the corresponding documentation in the array library and/or the array API
specification for more details.
Warnings
--------
This function temporarily rechunks the array along `axis` into a single chunk.
This can be ex... | argsort | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/dask/array/_aliases.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/dask/array/_aliases.py | BSD-3-Clause |
def capabilities(self) -> Capabilities:
"""
Return a dictionary of array API library capabilities.
The resulting dictionary has the following keys:
- **"boolean indexing"**: boolean indicating whether an array library
supports boolean indexing.
Dask support boolean... |
Return a dictionary of array API library capabilities.
The resulting dictionary has the following keys:
- **"boolean indexing"**: boolean indicating whether an array library
supports boolean indexing.
Dask support boolean indexing as long as both the index
and t... | capabilities | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/dask/array/_info.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/dask/array/_info.py | BSD-3-Clause |
def default_dtypes(self, /, *, device: _Device | None = None) -> DefaultDTypes:
"""
The default data types used for new Dask arrays.
For Dask, this always returns the following dictionary:
- **"real floating"**: ``numpy.float64``
- **"complex floating"**: ``numpy.complex128``
... |
The default data types used for new Dask arrays.
For Dask, this always returns the following dictionary:
- **"real floating"**: ``numpy.float64``
- **"complex floating"**: ``numpy.complex128``
- **"integral"**: ``numpy.intp``
- **"indexing"**: ``numpy.intp``
P... | default_dtypes | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/dask/array/_info.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/dask/array/_info.py | BSD-3-Clause |
def dtypes(
self, /, *, device: _Device | None = None, kind: DTypeKind | None = None
) -> DTypesAny:
"""
The array API data types supported by Dask.
Note that this function only returns data types that are defined by
the array API.
Parameters
----------
... |
The array API data types supported by Dask.
Note that this function only returns data types that are defined by
the array API.
Parameters
----------
device : str, optional
The device to get the data types for.
kind : str or tuple of str, optional
... | dtypes | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/dask/array/_info.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/dask/array/_info.py | BSD-3-Clause |
def asarray(
obj: Array | complex | NestedSequence[complex] | SupportsBufferProtocol,
/,
*,
dtype: DType | None = None,
device: Device | None = None,
copy: _Copy | None = None,
**kwargs: Any,
) -> Array:
"""
Array API compatibility wrapper for asarray().
See the corresponding do... |
Array API compatibility wrapper for asarray().
See the corresponding documentation in the array library and/or the array API
specification for more details.
| asarray | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/numpy/_aliases.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/numpy/_aliases.py | BSD-3-Clause |
def capabilities(self):
"""
Return a dictionary of array API library capabilities.
The resulting dictionary has the following keys:
- **"boolean indexing"**: boolean indicating whether an array library
supports boolean indexing. Always ``True`` for NumPy.
- **"data-d... |
Return a dictionary of array API library capabilities.
The resulting dictionary has the following keys:
- **"boolean indexing"**: boolean indicating whether an array library
supports boolean indexing. Always ``True`` for NumPy.
- **"data-dependent shapes"**: boolean indicat... | capabilities | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/numpy/_info.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/numpy/_info.py | BSD-3-Clause |
def default_dtypes(
self,
*,
device: Device | None = None,
) -> dict[str, dtype[intp | float64 | complex128]]:
"""
The default data types used for new NumPy arrays.
For NumPy, this always returns the following dictionary:
- **"real floating"**: ``numpy.float... |
The default data types used for new NumPy arrays.
For NumPy, this always returns the following dictionary:
- **"real floating"**: ``numpy.float64``
- **"complex floating"**: ``numpy.complex128``
- **"integral"**: ``numpy.intp``
- **"indexing"**: ``numpy.intp``
... | default_dtypes | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/numpy/_info.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/numpy/_info.py | BSD-3-Clause |
def dtypes(
self,
*,
device: Device | None = None,
kind: str | tuple[str, ...] | None = None,
) -> dict[str, DType]:
"""
The array API data types supported by NumPy.
Note that this function only returns data types that are defined by
the array API.
... |
The array API data types supported by NumPy.
Note that this function only returns data types that are defined by
the array API.
Parameters
----------
device : str, optional
The device to get the data types for. For NumPy, only ``'cpu'`` is
allow... | dtypes | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/numpy/_info.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/numpy/_info.py | BSD-3-Clause |
def _sum_prod_no_axis(x: Array, dtype: DType | None) -> Array:
"""
Implements `sum(..., axis=())` and `prod(..., axis=())`.
Works around https://github.com/pytorch/pytorch/issues/29137
"""
if dtype is not None:
return x.clone() if dtype == x.dtype else x.to(dtype)
# We can't upcast... |
Implements `sum(..., axis=())` and `prod(..., axis=())`.
Works around https://github.com/pytorch/pytorch/issues/29137
| _sum_prod_no_axis | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/torch/_aliases.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/torch/_aliases.py | BSD-3-Clause |
def isdtype(
dtype: DType, kind: Union[DType, str, Tuple[Union[DType, str], ...]],
*, _tuple=True, # Disallow nested tuples
) -> bool:
"""
Returns a boolean indicating whether a provided dtype is of a specified data type ``kind``.
Note that outside of this function, this compat library does not yet... |
Returns a boolean indicating whether a provided dtype is of a specified data type ``kind``.
Note that outside of this function, this compat library does not yet fully
support complex numbers.
See
https://data-apis.org/array-api/latest/API_specification/generated/array_api.isdtype.html
for mor... | isdtype | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/torch/_aliases.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/torch/_aliases.py | BSD-3-Clause |
def capabilities(self):
"""
Return a dictionary of array API library capabilities.
The resulting dictionary has the following keys:
- **"boolean indexing"**: boolean indicating whether an array library
supports boolean indexing. Always ``True`` for PyTorch.
- **"data... |
Return a dictionary of array API library capabilities.
The resulting dictionary has the following keys:
- **"boolean indexing"**: boolean indicating whether an array library
supports boolean indexing. Always ``True`` for PyTorch.
- **"data-dependent shapes"**: boolean indic... | capabilities | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/torch/_info.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/torch/_info.py | BSD-3-Clause |
def default_dtypes(self, *, device=None):
"""
The default data types used for new PyTorch arrays.
Parameters
----------
device : Device, optional
The device to get the default data types for.
Unused for PyTorch, as all devices use the same default dtypes.... |
The default data types used for new PyTorch arrays.
Parameters
----------
device : Device, optional
The device to get the default data types for.
Unused for PyTorch, as all devices use the same default dtypes.
Returns
-------
dtypes : di... | default_dtypes | python | scikit-learn/scikit-learn | sklearn/externals/array_api_compat/torch/_info.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_compat/torch/_info.py | BSD-3-Clause |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves Python code examples from Django repository that contain 'django' in the code, which helps identify Django-specific code snippets but provides limited analytical insights beyond basic filtering.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.