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 test_tuned_threshold_classifier_error_constant_predictor():
"""Check that we raise a ValueError if the underlying classifier returns constant
probabilities such that we cannot find any threshold.
"""
X, y = make_classification(random_state=0)
estimator = DummyClassifier(strategy="constant", cons... | Check that we raise a ValueError if the underlying classifier returns constant
probabilities such that we cannot find any threshold.
| test_tuned_threshold_classifier_error_constant_predictor | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_classification_threshold.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py | BSD-3-Clause |
def test_fixed_threshold_classifier_equivalence_default(response_method):
"""Check that `FixedThresholdClassifier` has the same behaviour as the vanilla
classifier.
"""
X, y = make_classification(random_state=0)
classifier = LogisticRegression().fit(X, y)
classifier_default_threshold = FixedThre... | Check that `FixedThresholdClassifier` has the same behaviour as the vanilla
classifier.
| test_fixed_threshold_classifier_equivalence_default | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_classification_threshold.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py | BSD-3-Clause |
def test_fixed_threshold_classifier(response_method, threshold, pos_label):
"""Check that applying `predict` lead to the same prediction as applying the
threshold to the output of the response method.
"""
X, y = make_classification(n_samples=50, random_state=0)
logistic_regression = LogisticRegressi... | Check that applying `predict` lead to the same prediction as applying the
threshold to the output of the response method.
| test_fixed_threshold_classifier | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_classification_threshold.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py | BSD-3-Clause |
def test_fixed_threshold_classifier_metadata_routing():
"""Check that everything works with metadata routing."""
X, y = make_classification(random_state=0)
sample_weight = np.ones_like(y)
sample_weight[::2] = 2
classifier = LogisticRegression().set_fit_request(sample_weight=True)
classifier.fit(... | Check that everything works with metadata routing. | test_fixed_threshold_classifier_metadata_routing | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_classification_threshold.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py | BSD-3-Clause |
def test_fixed_threshold_classifier_fitted_estimator(method):
"""Check that if the underlying estimator is already fitted, no fit is required."""
X, y = make_classification(random_state=0)
classifier = LogisticRegression().fit(X, y)
fixed_threshold_classifier = FixedThresholdClassifier(estimator=classif... | Check that if the underlying estimator is already fitted, no fit is required. | test_fixed_threshold_classifier_fitted_estimator | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_classification_threshold.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py | BSD-3-Clause |
def test_fixed_threshold_classifier_classes_():
"""Check that the classes_ attribute is properly set."""
X, y = make_classification(random_state=0)
with pytest.raises(
AttributeError, match="The underlying estimator is not fitted yet."
):
FixedThresholdClassifier(estimator=LogisticRegres... | Check that the classes_ attribute is properly set. | test_fixed_threshold_classifier_classes_ | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_classification_threshold.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py | BSD-3-Clause |
def test_curve_display_parameters_validation(
pyplot, data, params, err_type, err_msg, CurveDisplay, specific_params
):
"""Check that we raise a proper error when passing invalid parameters."""
X, y = data
estimator = DecisionTreeClassifier(random_state=0)
with pytest.raises(err_type, match=err_msg... | Check that we raise a proper error when passing invalid parameters. | test_curve_display_parameters_validation | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_plot.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_plot.py | BSD-3-Clause |
def test_learning_curve_display_default_usage(pyplot, data):
"""Check the default usage of the LearningCurveDisplay class."""
X, y = data
estimator = DecisionTreeClassifier(random_state=0)
train_sizes = [0.3, 0.6, 0.9]
display = LearningCurveDisplay.from_estimator(
estimator, X, y, train_si... | Check the default usage of the LearningCurveDisplay class. | test_learning_curve_display_default_usage | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_plot.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_plot.py | BSD-3-Clause |
def test_validation_curve_display_default_usage(pyplot, data):
"""Check the default usage of the ValidationCurveDisplay class."""
X, y = data
estimator = DecisionTreeClassifier(random_state=0)
param_name, param_range = "max_depth", [1, 3, 5]
display = ValidationCurveDisplay.from_estimator(
... | Check the default usage of the ValidationCurveDisplay class. | test_validation_curve_display_default_usage | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_plot.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_plot.py | BSD-3-Clause |
def test_curve_display_negate_score(pyplot, data, CurveDisplay, specific_params):
"""Check the behaviour of the `negate_score` parameter calling `from_estimator` and
`plot`.
"""
X, y = data
estimator = DecisionTreeClassifier(max_depth=1, random_state=0)
negate_score = False
display = CurveD... | Check the behaviour of the `negate_score` parameter calling `from_estimator` and
`plot`.
| test_curve_display_negate_score | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_plot.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_plot.py | BSD-3-Clause |
def test_curve_display_score_name(
pyplot, data, score_name, ylabel, CurveDisplay, specific_params
):
"""Check that we can overwrite the default score name shown on the y-axis."""
X, y = data
estimator = DecisionTreeClassifier(random_state=0)
display = CurveDisplay.from_estimator(
estimator... | Check that we can overwrite the default score name shown on the y-axis. | test_curve_display_score_name | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_plot.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_plot.py | BSD-3-Clause |
def test_learning_curve_display_score_type(pyplot, data, std_display_style):
"""Check the behaviour of setting the `score_type` parameter."""
X, y = data
estimator = DecisionTreeClassifier(random_state=0)
train_sizes = [0.3, 0.6, 0.9]
train_sizes_abs, train_scores, test_scores = learning_curve(
... | Check the behaviour of setting the `score_type` parameter. | test_learning_curve_display_score_type | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_plot.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_plot.py | BSD-3-Clause |
def test_validation_curve_display_score_type(pyplot, data, std_display_style):
"""Check the behaviour of setting the `score_type` parameter."""
X, y = data
estimator = DecisionTreeClassifier(random_state=0)
param_name, param_range = "max_depth", [1, 3, 5]
train_scores, test_scores = validation_curv... | Check the behaviour of setting the `score_type` parameter. | test_validation_curve_display_score_type | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_plot.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_plot.py | BSD-3-Clause |
def test_curve_display_xscale_auto(
pyplot, data, CurveDisplay, specific_params, expected_xscale
):
"""Check the behaviour of the x-axis scaling depending on the data provided."""
X, y = data
estimator = DecisionTreeClassifier(random_state=0)
display = CurveDisplay.from_estimator(estimator, X, y, *... | Check the behaviour of the x-axis scaling depending on the data provided. | test_curve_display_xscale_auto | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_plot.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_plot.py | BSD-3-Clause |
def test_curve_display_std_display_style(pyplot, data, CurveDisplay, specific_params):
"""Check the behaviour of the parameter `std_display_style`."""
X, y = data
estimator = DecisionTreeClassifier(random_state=0)
import matplotlib as mpl
std_display_style = None
display = CurveDisplay.from_es... | Check the behaviour of the parameter `std_display_style`. | test_curve_display_std_display_style | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_plot.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_plot.py | BSD-3-Clause |
def test_curve_display_plot_kwargs(pyplot, data, CurveDisplay, specific_params):
"""Check the behaviour of the different plotting keyword arguments: `line_kw`,
`fill_between_kw`, and `errorbar_kw`."""
X, y = data
estimator = DecisionTreeClassifier(random_state=0)
std_display_style = "fill_between"
... | Check the behaviour of the different plotting keyword arguments: `line_kw`,
`fill_between_kw`, and `errorbar_kw`. | test_curve_display_plot_kwargs | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_plot.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_plot.py | BSD-3-Clause |
def test_validation_curve_xscale_from_param_range_provided_as_a_list(
pyplot, data, param_range, xscale
):
"""Check the induced xscale from the provided param_range values."""
X, y = data
estimator = DecisionTreeClassifier(random_state=0)
param_name = "max_depth"
display = ValidationCurveDispla... | Check the induced xscale from the provided param_range values. | test_validation_curve_xscale_from_param_range_provided_as_a_list | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_plot.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_plot.py | BSD-3-Clause |
def test_subclassing_displays(pyplot, data, Display, params):
"""Check that named constructors return the correct type when subclassed.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/pull/27675
"""
X, y = data
estimator = DecisionTreeClassifier(random_state=0)
class ... | Check that named constructors return the correct type when subclassed.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/pull/27675
| test_subclassing_displays | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_plot.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_plot.py | BSD-3-Clause |
def test_refit_callable():
"""
Test refit=callable, which adds flexibility in identifying the
"best" estimator.
"""
def refit_callable(cv_results):
"""
A dummy function tests `refit=callable` interface.
Return the index of a model that has the least
`mean_test_score`... |
Test refit=callable, which adds flexibility in identifying the
"best" estimator.
| test_refit_callable | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_search.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_search.py | BSD-3-Clause |
def refit_callable(cv_results):
"""
A dummy function tests `refit=callable` interface.
Return the index of a model that has the least
`mean_test_score`.
"""
# Fit a dummy clf with `refit=True` to get a list of keys in
# clf.cv_results_.
X, y = make_classif... |
A dummy function tests `refit=callable` interface.
Return the index of a model that has the least
`mean_test_score`.
| refit_callable | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_search.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_search.py | BSD-3-Clause |
def test_refit_callable_invalid_type():
"""
Test implementation catches the errors when 'best_index_' returns an
invalid result.
"""
def refit_callable_invalid_type(cv_results):
"""
A dummy function tests when returned 'best_index_' is not integer.
"""
return None
... |
Test implementation catches the errors when 'best_index_' returns an
invalid result.
| test_refit_callable_invalid_type | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_search.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_search.py | BSD-3-Clause |
def test_refit_callable_out_bound(out_bound_value, search_cv):
"""
Test implementation catches the errors when 'best_index_' returns an
out of bound result.
"""
def refit_callable_out_bound(cv_results):
"""
A dummy function tests when returned 'best_index_' is out of bounds.
... |
Test implementation catches the errors when 'best_index_' returns an
out of bound result.
| test_refit_callable_out_bound | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_search.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_search.py | BSD-3-Clause |
def test_refit_callable_multi_metric():
"""
Test refit=callable in multiple metric evaluation setting
"""
def refit_callable(cv_results):
"""
A dummy function tests `refit=callable` interface.
Return the index of a model that has the least
`mean_test_prec`.
"""
... |
Test refit=callable in multiple metric evaluation setting
| test_refit_callable_multi_metric | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_search.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_search.py | BSD-3-Clause |
def compare_cv_results_multimetric_with_single(search_multi, search_acc, search_rec):
"""Compare multi-metric cv_results with the ensemble of multiple
single metric cv_results from single metric grid/random search"""
assert search_multi.multimetric_
assert_array_equal(sorted(search_multi.scorer_), ("ac... | Compare multi-metric cv_results with the ensemble of multiple
single metric cv_results from single metric grid/random search | compare_cv_results_multimetric_with_single | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_search.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_search.py | BSD-3-Clause |
def compare_refit_methods_when_refit_with_acc(search_multi, search_acc, refit):
"""Compare refit multi-metric search methods with single metric methods"""
assert search_acc.refit == refit
if refit:
assert search_multi.refit == "accuracy"
else:
assert not search_multi.refit
return... | Compare refit multi-metric search methods with single metric methods | compare_refit_methods_when_refit_with_acc | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_search.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_search.py | BSD-3-Clause |
def test_unsupported_sample_weight_scorer():
"""Checks that fitting with sample_weight raises a warning if the scorer does not
support sample_weight"""
def fake_score_func(y_true, y_pred):
"Fake scoring function that does not support sample_weight"
return 0.5
fake_scorer = make_scorer(... | Checks that fitting with sample_weight raises a warning if the scorer does not
support sample_weight | test_unsupported_sample_weight_scorer | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_search.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_search.py | BSD-3-Clause |
def test_search_cv_pairwise_property_delegated_to_base_estimator(pairwise):
"""
Test implementation of BaseSearchCV has the pairwise tag
which matches the pairwise tag of its estimator.
This test make sure pairwise tag is delegated to the base estimator.
Non-regression test for issue #13920.
""... |
Test implementation of BaseSearchCV has the pairwise tag
which matches the pairwise tag of its estimator.
This test make sure pairwise tag is delegated to the base estimator.
Non-regression test for issue #13920.
| test_search_cv_pairwise_property_delegated_to_base_estimator | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_search.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_search.py | BSD-3-Clause |
def test_search_cv__pairwise_property_delegated_to_base_estimator():
"""
Test implementation of BaseSearchCV has the pairwise property
which matches the pairwise tag of its estimator.
This test make sure pairwise tag is delegated to the base estimator.
Non-regression test for issue #13920.
"""
... |
Test implementation of BaseSearchCV has the pairwise property
which matches the pairwise tag of its estimator.
This test make sure pairwise tag is delegated to the base estimator.
Non-regression test for issue #13920.
| test_search_cv__pairwise_property_delegated_to_base_estimator | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_search.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_search.py | BSD-3-Clause |
def test_search_cv_pairwise_property_equivalence_of_precomputed():
"""
Test implementation of BaseSearchCV has the pairwise tag
which matches the pairwise tag of its estimator.
This test ensures the equivalence of 'precomputed'.
Non-regression test for issue #13920.
"""
n_samples = 50
n... |
Test implementation of BaseSearchCV has the pairwise tag
which matches the pairwise tag of its estimator.
This test ensures the equivalence of 'precomputed'.
Non-regression test for issue #13920.
| test_search_cv_pairwise_property_equivalence_of_precomputed | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_search.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_search.py | BSD-3-Clause |
def test_search_cv_verbose_3(capsys, return_train_score):
"""Check that search cv with verbose>2 shows the score for single
metrics. non-regression test for #19658."""
X, y = make_classification(n_samples=100, n_classes=2, flip_y=0.2, random_state=0)
clf = LinearSVC(random_state=0)
grid = {"C": [0.1... | Check that search cv with verbose>2 shows the score for single
metrics. non-regression test for #19658. | test_search_cv_verbose_3 | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_search.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_search.py | BSD-3-Clause |
def test_search_html_repr():
"""Test different HTML representations for GridSearchCV."""
X, y = make_classification(random_state=42)
pipeline = Pipeline([("scale", StandardScaler()), ("clf", DummyClassifier())])
param_grid = {"clf": [DummyClassifier(), LogisticRegression()]}
# Unfitted shows the o... | Test different HTML representations for GridSearchCV. | test_search_html_repr | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_search.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_search.py | BSD-3-Clause |
def test_multi_metric_search_forwards_metadata(SearchCV, param_search):
"""Test that *SearchCV forwards metadata correctly when passed multiple metrics."""
X, y = make_classification(random_state=42)
n_samples = _num_samples(X)
rng = np.random.RandomState(0)
score_weights = rng.rand(n_samples)
s... | Test that *SearchCV forwards metadata correctly when passed multiple metrics. | test_multi_metric_search_forwards_metadata | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_search.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_search.py | BSD-3-Clause |
def test_score_rejects_params_with_no_routing_enabled(SearchCV, param_search):
"""*SearchCV should reject **params when metadata routing is not enabled
since this is added only when routing is enabled."""
X, y = make_classification(random_state=42)
est = LinearSVC()
param_grid_search = {param_search... | *SearchCV should reject **params when metadata routing is not enabled
since this is added only when routing is enabled. | test_score_rejects_params_with_no_routing_enabled | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_search.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_search.py | BSD-3-Clause |
def test_cv_results_dtype_issue_29074():
"""Non-regression test for https://github.com/scikit-learn/scikit-learn/issues/29074"""
class MetaEstimator(BaseEstimator, ClassifierMixin):
def __init__(
self,
base_clf,
parameter1=None,
parameter2=None,
... | Non-regression test for https://github.com/scikit-learn/scikit-learn/issues/29074 | test_cv_results_dtype_issue_29074 | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_search.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_search.py | BSD-3-Clause |
def test_search_with_estimators_issue_29157():
"""Check cv_results_ for estimators with a `dtype` parameter, e.g. OneHotEncoder."""
pd = pytest.importorskip("pandas")
df = pd.DataFrame(
{
"numeric_1": [1, 2, 3, 4, 5],
"object_1": ["a", "a", "a", "a", "a"],
"target... | Check cv_results_ for estimators with a `dtype` parameter, e.g. OneHotEncoder. | test_search_with_estimators_issue_29157 | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_search.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_search.py | BSD-3-Clause |
def test_cv_results_multi_size_array():
"""Check that GridSearchCV works with params that are arrays of different sizes.
Non-regression test for #29277.
"""
n_features = 10
X, y = make_classification(n_features=10)
spline_reg_pipe = make_pipeline(
SplineTransformer(extrapolation="perio... | Check that GridSearchCV works with params that are arrays of different sizes.
Non-regression test for #29277.
| test_cv_results_multi_size_array | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_search.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_search.py | BSD-3-Clause |
def test_train_test_split_32bit_overflow():
"""Check for integer overflow on 32-bit platforms.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/20774
"""
# A number 'n' big enough for expression 'n * n * train_size' to cause
# an overflow for signed 32-bit integer
... | Check for integer overflow on 32-bit platforms.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/20774
| test_train_test_split_32bit_overflow | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_split.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_split.py | BSD-3-Clause |
def test_splitter_set_split_request(cv):
"""Check set_split_request is defined for group splitters and not for others."""
if cv in GROUP_SPLITTERS:
assert hasattr(cv, "set_split_request")
elif cv in NO_GROUP_SPLITTERS:
assert not hasattr(cv, "set_split_request") | Check set_split_request is defined for group splitters and not for others. | test_splitter_set_split_request | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_split.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_split.py | BSD-3-Clause |
def test_nan_handling(HalvingSearch, fail_at):
"""Check the selection of the best scores in presence of failure represented by
NaN values."""
n_samples = 1_000
X, y = make_classification(n_samples=n_samples, random_state=0)
search = HalvingSearch(
SometimesFailClassifier(),
{f"fail_... | Check the selection of the best scores in presence of failure represented by
NaN values. | test_nan_handling | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_successive_halving.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_successive_halving.py | BSD-3-Clause |
def test_min_resources_null(SearchCV):
"""Check that we raise an error if the minimum resources is set to 0."""
base_estimator = FastClassifier()
param_grid = {"a": [1]}
X = np.empty(0).reshape(0, 3)
search = SearchCV(base_estimator, param_grid, min_resources="smallest")
err_msg = "min_resourc... | Check that we raise an error if the minimum resources is set to 0. | test_min_resources_null | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_successive_halving.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_successive_halving.py | BSD-3-Clause |
def test_select_best_index(SearchCV):
"""Check the selection strategy of the halving search."""
results = { # this isn't a 'real world' result dict
"iter": np.array([0, 0, 0, 0, 1, 1, 2, 2, 2]),
"mean_test_score": np.array([4, 3, 5, 1, 11, 10, 5, 6, 9]),
"params": np.array(["a", "b", "c... | Check the selection strategy of the halving search. | test_select_best_index | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_successive_halving.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_successive_halving.py | BSD-3-Clause |
def test_halving_random_search_list_of_dicts():
"""Check the behaviour of the `HalvingRandomSearchCV` with `param_distribution`
being a list of dictionary.
"""
X, y = make_classification(n_samples=150, n_features=4, random_state=42)
params = [
{"kernel": ["rbf"], "C": expon(scale=10), "gamm... | Check the behaviour of the `HalvingRandomSearchCV` with `param_distribution`
being a list of dictionary.
| test_halving_random_search_list_of_dicts | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_successive_halving.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_successive_halving.py | BSD-3-Clause |
def fit(
self,
X,
Y=None,
sample_weight=None,
class_prior=None,
sparse_sample_weight=None,
sparse_param=None,
dummy_int=None,
dummy_str=None,
dummy_obj=None,
callback=None,
):
"""The dummy arguments are to test that this... | The dummy arguments are to test that this fit function can
accept non-array arguments through cross-validation, such as:
- int
- str (this is actually array-like)
- object
- function
| fit | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_validation.py | BSD-3-Clause |
def check_cross_val_predict_binary(est, X, y, method):
"""Helper for tests of cross_val_predict with binary classification"""
cv = KFold(n_splits=3, shuffle=False)
# Generate expected outputs
if y.ndim == 1:
exp_shape = (len(X),) if method == "decision_function" else (len(X), 2)
else:
... | Helper for tests of cross_val_predict with binary classification | check_cross_val_predict_binary | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_validation.py | BSD-3-Clause |
def check_cross_val_predict_multiclass(est, X, y, method):
"""Helper for tests of cross_val_predict with multiclass classification"""
cv = KFold(n_splits=3, shuffle=False)
# Generate expected outputs
float_min = np.finfo(np.float64).min
default_values = {
"decision_function": float_min,
... | Helper for tests of cross_val_predict with multiclass classification | check_cross_val_predict_multiclass | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_validation.py | BSD-3-Clause |
def check_cross_val_predict_multilabel(est, X, y, method):
"""Check the output of cross_val_predict for 2D targets using
Estimators which provide a predictions as a list with one
element per class.
"""
cv = KFold(n_splits=3, shuffle=False)
# Create empty arrays of the correct size to hold outpu... | Check the output of cross_val_predict for 2D targets using
Estimators which provide a predictions as a list with one
element per class.
| check_cross_val_predict_multilabel | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_validation.py | BSD-3-Clause |
def test_learning_curve_partial_fit_regressors():
"""Check that regressors with partial_fit is supported.
Non-regression test for #22981.
"""
X, y = make_regression(random_state=42)
# Does not error
learning_curve(MLPRegressor(), X, y, exploit_incremental_learning=True, cv=2) | Check that regressors with partial_fit is supported.
Non-regression test for #22981.
| test_learning_curve_partial_fit_regressors | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_validation.py | BSD-3-Clause |
def test_learning_curve_some_failing_fits_warning(global_random_seed):
"""Checks for fit failures in `learning_curve` and raises the required warning"""
X, y = make_classification(
n_samples=30,
n_classes=3,
n_informative=6,
shuffle=False,
random_state=global_random_seed... | Checks for fit failures in `learning_curve` and raises the required warning | test_learning_curve_some_failing_fits_warning | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_validation.py | BSD-3-Clause |
def test_fit_param_deprecation(func, extra_args):
"""Check that we warn about deprecating `fit_params`."""
with pytest.warns(FutureWarning, match="`fit_params` is deprecated"):
func(
estimator=ConsumingClassifier(), X=X, y=y, cv=2, fit_params={}, **extra_args
)
with pytest.raise... | Check that we warn about deprecating `fit_params`. | test_fit_param_deprecation | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_validation.py | BSD-3-Clause |
def test_groups_with_routing_validation(func, extra_args):
"""Check that we raise an error if `groups` are passed to the cv method instead
of `params` when metadata routing is enabled.
"""
with pytest.raises(ValueError, match="`groups` can only be passed if"):
func(
estimator=Consumi... | Check that we raise an error if `groups` are passed to the cv method instead
of `params` when metadata routing is enabled.
| test_groups_with_routing_validation | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_validation.py | BSD-3-Clause |
def test_cross_validate_params_none(func, extra_args):
"""Test that no errors are raised when passing `params=None`, which is the
default value.
Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/30447
"""
X, y = make_classification(n_samples=100, n_classes=2, random_state=... | Test that no errors are raised when passing `params=None`, which is the
default value.
Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/30447
| test_cross_validate_params_none | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_validation.py | BSD-3-Clause |
def test_passed_unrequested_metadata(func, extra_args):
"""Check that we raise an error when passing metadata that is not
requested."""
err_msg = re.escape(
"[metadata] are passed but are not explicitly set as requested or not "
"requested for ConsumingClassifier.fit, which is used within"
... | Check that we raise an error when passing metadata that is not
requested. | test_passed_unrequested_metadata | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_validation.py | BSD-3-Clause |
def test_validation_functions_routing(func, extra_args):
"""Check that the respective cv method is properly dispatching the metadata
to the consumer."""
scorer_registry = _Registry()
scorer = ConsumingScorer(registry=scorer_registry).set_score_request(
sample_weight="score_weights", metadata="sc... | Check that the respective cv method is properly dispatching the metadata
to the consumer. | test_validation_functions_routing | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_validation.py | BSD-3-Clause |
def test_learning_curve_exploit_incremental_learning_routing():
"""Test that learning_curve routes metadata to the estimator correctly while
partial_fitting it with `exploit_incremental_learning=True`."""
n_samples = _num_samples(X)
rng = np.random.RandomState(0)
fit_sample_weight = rng.rand(n_samp... | Test that learning_curve routes metadata to the estimator correctly while
partial_fitting it with `exploit_incremental_learning=True`. | test_learning_curve_exploit_incremental_learning_routing | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_validation.py | BSD-3-Clause |
def _get_weights(dist, weights):
"""Get the weights from an array of distances and a parameter ``weights``.
Assume weights have already been validated.
Parameters
----------
dist : ndarray
The input distances.
weights : {'uniform', 'distance'}, callable or None
The kind of wei... | Get the weights from an array of distances and a parameter ``weights``.
Assume weights have already been validated.
Parameters
----------
dist : ndarray
The input distances.
weights : {'uniform', 'distance'}, callable or None
The kind of weighting used.
Returns
-------
... | _get_weights | python | scikit-learn/scikit-learn | sklearn/neighbors/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_base.py | BSD-3-Clause |
def _is_sorted_by_data(graph):
"""Return whether the graph's non-zero entries are sorted by data.
The non-zero entries are stored in graph.data and graph.indices.
For each row (or sample), the non-zero entries can be either:
- sorted by indices, as after graph.sort_indices();
- sorted by da... | Return whether the graph's non-zero entries are sorted by data.
The non-zero entries are stored in graph.data and graph.indices.
For each row (or sample), the non-zero entries can be either:
- sorted by indices, as after graph.sort_indices();
- sorted by data, as after _check_precomputed(graph)... | _is_sorted_by_data | python | scikit-learn/scikit-learn | sklearn/neighbors/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_base.py | BSD-3-Clause |
def _check_precomputed(X):
"""Check precomputed distance matrix.
If the precomputed distance matrix is sparse, it checks that the non-zero
entries are sorted by distances. If not, the matrix is copied and sorted.
Parameters
----------
X : {sparse matrix, array-like}, (n_samples, n_samples)
... | Check precomputed distance matrix.
If the precomputed distance matrix is sparse, it checks that the non-zero
entries are sorted by distances. If not, the matrix is copied and sorted.
Parameters
----------
X : {sparse matrix, array-like}, (n_samples, n_samples)
Distance matrix to other samp... | _check_precomputed | python | scikit-learn/scikit-learn | sklearn/neighbors/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_base.py | BSD-3-Clause |
def sort_graph_by_row_values(graph, copy=False, warn_when_not_sorted=True):
"""Sort a sparse graph such that each row is stored with increasing values.
.. versionadded:: 1.2
Parameters
----------
graph : sparse matrix of shape (n_samples, n_samples)
Distance matrix to other samples, where ... | Sort a sparse graph such that each row is stored with increasing values.
.. versionadded:: 1.2
Parameters
----------
graph : sparse matrix of shape (n_samples, n_samples)
Distance matrix to other samples, where only non-zero elements are
considered neighbors. Matrix is converted to CSR... | sort_graph_by_row_values | python | scikit-learn/scikit-learn | sklearn/neighbors/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_base.py | BSD-3-Clause |
def _kneighbors_from_graph(graph, n_neighbors, return_distance):
"""Decompose a nearest neighbors sparse graph into distances and indices.
Parameters
----------
graph : sparse matrix of shape (n_samples, n_samples)
Neighbors graph as given by `kneighbors_graph` or
`radius_neighbors_grap... | Decompose a nearest neighbors sparse graph into distances and indices.
Parameters
----------
graph : sparse matrix of shape (n_samples, n_samples)
Neighbors graph as given by `kneighbors_graph` or
`radius_neighbors_graph`. Matrix should be of format CSR format.
n_neighbors : int
... | _kneighbors_from_graph | python | scikit-learn/scikit-learn | sklearn/neighbors/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_base.py | BSD-3-Clause |
def _radius_neighbors_from_graph(graph, radius, return_distance):
"""Decompose a nearest neighbors sparse graph into distances and indices.
Parameters
----------
graph : sparse matrix of shape (n_samples, n_samples)
Neighbors graph as given by `kneighbors_graph` or
`radius_neighbors_gra... | Decompose a nearest neighbors sparse graph into distances and indices.
Parameters
----------
graph : sparse matrix of shape (n_samples, n_samples)
Neighbors graph as given by `kneighbors_graph` or
`radius_neighbors_graph`. Matrix should be of format CSR format.
radius : float
R... | _radius_neighbors_from_graph | python | scikit-learn/scikit-learn | sklearn/neighbors/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_base.py | BSD-3-Clause |
def _kneighbors_reduce_func(self, dist, start, n_neighbors, return_distance):
"""Reduce a chunk of distances to the nearest neighbors.
Callback to :func:`sklearn.metrics.pairwise.pairwise_distances_chunked`
Parameters
----------
dist : ndarray of shape (n_samples_chunk, n_sampl... | Reduce a chunk of distances to the nearest neighbors.
Callback to :func:`sklearn.metrics.pairwise.pairwise_distances_chunked`
Parameters
----------
dist : ndarray of shape (n_samples_chunk, n_samples)
The distance matrix.
start : int
The index in X whic... | _kneighbors_reduce_func | python | scikit-learn/scikit-learn | sklearn/neighbors/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_base.py | BSD-3-Clause |
def kneighbors(self, X=None, n_neighbors=None, return_distance=True):
"""Find the K-neighbors of a point.
Returns indices of and distances to the neighbors of each point.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_queries, n_features), \
or (n_q... | Find the K-neighbors of a point.
Returns indices of and distances to the neighbors of each point.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_queries, n_features), or (n_queries, n_indexed) if metric == 'precomputed', default=None
The query p... | kneighbors | python | scikit-learn/scikit-learn | sklearn/neighbors/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_base.py | BSD-3-Clause |
def kneighbors_graph(self, X=None, n_neighbors=None, mode="connectivity"):
"""Compute the (weighted) graph of k-Neighbors for points in X.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_queries, n_features), \
or (n_queries, n_indexed) if metric == 'precom... | Compute the (weighted) graph of k-Neighbors for points in X.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == 'precomputed', default=None
The query point or points.
If not provided,... | kneighbors_graph | python | scikit-learn/scikit-learn | sklearn/neighbors/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_base.py | BSD-3-Clause |
def _radius_neighbors_reduce_func(self, dist, start, radius, return_distance):
"""Reduce a chunk of distances to the nearest neighbors.
Callback to :func:`sklearn.metrics.pairwise.pairwise_distances_chunked`
Parameters
----------
dist : ndarray of shape (n_samples_chunk, n_samp... | Reduce a chunk of distances to the nearest neighbors.
Callback to :func:`sklearn.metrics.pairwise.pairwise_distances_chunked`
Parameters
----------
dist : ndarray of shape (n_samples_chunk, n_samples)
The distance matrix.
start : int
The index in X whic... | _radius_neighbors_reduce_func | python | scikit-learn/scikit-learn | sklearn/neighbors/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_base.py | BSD-3-Clause |
def radius_neighbors_graph(
self, X=None, radius=None, mode="connectivity", sort_results=False
):
"""Compute the (weighted) graph of Neighbors for points in X.
Neighborhoods are restricted the points at a distance lower than
radius.
Parameters
----------
X :... | Compute the (weighted) graph of Neighbors for points in X.
Neighborhoods are restricted the points at a distance lower than
radius.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features), default=None
The query point or points.
... | radius_neighbors_graph | python | scikit-learn/scikit-learn | sklearn/neighbors/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_base.py | BSD-3-Clause |
def predict(self, X):
"""Predict the class labels for the provided data.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_queries, n_features), \
or (n_queries, n_indexed) if metric == 'precomputed', or None
Test samples. If `None`, predictio... | Predict the class labels for the provided data.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == 'precomputed', or None
Test samples. If `None`, predictions for all indexed points are
... | predict | python | scikit-learn/scikit-learn | sklearn/neighbors/_classification.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_classification.py | BSD-3-Clause |
def predict_proba(self, X):
"""Return probability estimates for the test data X.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_queries, n_features), \
or (n_queries, n_indexed) if metric == 'precomputed', or None
Test samples. If `None`, p... | Return probability estimates for the test data X.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == 'precomputed', or None
Test samples. If `None`, predictions for all indexed points are
... | predict_proba | python | scikit-learn/scikit-learn | sklearn/neighbors/_classification.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_classification.py | BSD-3-Clause |
def fit(self, X, y):
"""Fit the radius neighbors classifier from the training dataset.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features) or \
(n_samples, n_samples) if metric='precomputed'
Training data.
y : {arra... | Fit the radius neighbors classifier from the training dataset.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples) if metric='precomputed'
Training data.
y : {array-like, sparse matrix} of shape (n... | fit | python | scikit-learn/scikit-learn | sklearn/neighbors/_classification.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_classification.py | BSD-3-Clause |
def predict(self, X):
"""Predict the class labels for the provided data.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_queries, n_features), \
or (n_queries, n_indexed) if metric == 'precomputed', or None
Test samples. If `None`, predictio... | Predict the class labels for the provided data.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == 'precomputed', or None
Test samples. If `None`, predictions for all indexed points are
... | predict | python | scikit-learn/scikit-learn | sklearn/neighbors/_classification.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_classification.py | BSD-3-Clause |
def predict_proba(self, X):
"""Return probability estimates for the test data X.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_queries, n_features), \
or (n_queries, n_indexed) if metric == 'precomputed', or None
Test samples. If `None`, p... | Return probability estimates for the test data X.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == 'precomputed', or None
Test samples. If `None`, predictions for all indexed points are
... | predict_proba | python | scikit-learn/scikit-learn | sklearn/neighbors/_classification.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_classification.py | BSD-3-Clause |
def _check_params(X, metric, p, metric_params):
"""Check the validity of the input parameters"""
params = zip(["metric", "p", "metric_params"], [metric, p, metric_params])
est_params = X.get_params()
for param_name, func_param in params:
if func_param != est_params[param_name]:
raise... | Check the validity of the input parameters | _check_params | python | scikit-learn/scikit-learn | sklearn/neighbors/_graph.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_graph.py | BSD-3-Clause |
def _query_include_self(X, include_self, mode):
"""Return the query based on include_self param"""
if include_self == "auto":
include_self = mode == "connectivity"
# it does not include each sample as its own neighbors
if not include_self:
X = None
return X | Return the query based on include_self param | _query_include_self | python | scikit-learn/scikit-learn | sklearn/neighbors/_graph.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_graph.py | BSD-3-Clause |
def kneighbors_graph(
X,
n_neighbors,
*,
mode="connectivity",
metric="minkowski",
p=2,
metric_params=None,
include_self=False,
n_jobs=None,
):
"""Compute the (weighted) graph of k-Neighbors for points in X.
Read more in the :ref:`User Guide <unsupervised_neighbors>`.
Pa... | Compute the (weighted) graph of k-Neighbors for points in X.
Read more in the :ref:`User Guide <unsupervised_neighbors>`.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Sample data.
n_neighbors : int
Number of neighbors for each sample.
... | kneighbors_graph | python | scikit-learn/scikit-learn | sklearn/neighbors/_graph.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_graph.py | BSD-3-Clause |
def radius_neighbors_graph(
X,
radius,
*,
mode="connectivity",
metric="minkowski",
p=2,
metric_params=None,
include_self=False,
n_jobs=None,
):
"""Compute the (weighted) graph of Neighbors for points in X.
Neighborhoods are restricted the points at a distance lower than
... | Compute the (weighted) graph of Neighbors for points in X.
Neighborhoods are restricted the points at a distance lower than
radius.
Read more in the :ref:`User Guide <unsupervised_neighbors>`.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Sampl... | radius_neighbors_graph | python | scikit-learn/scikit-learn | sklearn/neighbors/_graph.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_graph.py | BSD-3-Clause |
def fit(self, X, y=None):
"""Fit the k-nearest neighbors transformer from the training dataset.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features) or \
(n_samples, n_samples) if metric='precomputed'
Training data.
y... | Fit the k-nearest neighbors transformer from the training dataset.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples) if metric='precomputed'
Training data.
y : Ignored
Not used, presen... | fit | python | scikit-learn/scikit-learn | sklearn/neighbors/_graph.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_graph.py | BSD-3-Clause |
def transform(self, X):
"""Compute the (weighted) graph of Neighbors for points in X.
Parameters
----------
X : array-like of shape (n_samples_transform, n_features)
Sample data.
Returns
-------
Xt : sparse matrix of shape (n_samples_transform, n_sam... | Compute the (weighted) graph of Neighbors for points in X.
Parameters
----------
X : array-like of shape (n_samples_transform, n_features)
Sample data.
Returns
-------
Xt : sparse matrix of shape (n_samples_transform, n_samples_fit)
Xt[i, j] is a... | transform | python | scikit-learn/scikit-learn | sklearn/neighbors/_graph.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_graph.py | BSD-3-Clause |
def fit(self, X, y=None):
"""Fit the radius neighbors transformer from the training dataset.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features) or \
(n_samples, n_samples) if metric='precomputed'
Training data.
y :... | Fit the radius neighbors transformer from the training dataset.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples) if metric='precomputed'
Training data.
y : Ignored
Not used, present ... | fit | python | scikit-learn/scikit-learn | sklearn/neighbors/_graph.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_graph.py | BSD-3-Clause |
def transform(self, X):
"""Compute the (weighted) graph of Neighbors for points in X.
Parameters
----------
X : array-like of shape (n_samples_transform, n_features)
Sample data.
Returns
-------
Xt : sparse matrix of shape (n_samples_transform, n_sam... | Compute the (weighted) graph of Neighbors for points in X.
Parameters
----------
X : array-like of shape (n_samples_transform, n_features)
Sample data.
Returns
-------
Xt : sparse matrix of shape (n_samples_transform, n_samples_fit)
Xt[i, j] is a... | transform | python | scikit-learn/scikit-learn | sklearn/neighbors/_graph.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_graph.py | BSD-3-Clause |
def fit(self, X, y=None, sample_weight=None):
"""Fit the Kernel Density model on the data.
Parameters
----------
X : array-like of shape (n_samples, n_features)
List of n_features-dimensional data points. Each row
corresponds to a single data point.
y :... | Fit the Kernel Density model on the data.
Parameters
----------
X : array-like of shape (n_samples, n_features)
List of n_features-dimensional data points. Each row
corresponds to a single data point.
y : None
Ignored. This parameter exists only for... | fit | python | scikit-learn/scikit-learn | sklearn/neighbors/_kde.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_kde.py | BSD-3-Clause |
def score_samples(self, X):
"""Compute the log-likelihood of each sample under the model.
Parameters
----------
X : array-like of shape (n_samples, n_features)
An array of points to query. Last dimension should match dimension
of training data (n_features).
... | Compute the log-likelihood of each sample under the model.
Parameters
----------
X : array-like of shape (n_samples, n_features)
An array of points to query. Last dimension should match dimension
of training data (n_features).
Returns
-------
de... | score_samples | python | scikit-learn/scikit-learn | sklearn/neighbors/_kde.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_kde.py | BSD-3-Clause |
def sample(self, n_samples=1, random_state=None):
"""Generate random samples from the model.
Currently, this is implemented only for gaussian and tophat kernels.
Parameters
----------
n_samples : int, default=1
Number of samples to generate.
random_state : ... | Generate random samples from the model.
Currently, this is implemented only for gaussian and tophat kernels.
Parameters
----------
n_samples : int, default=1
Number of samples to generate.
random_state : int, RandomState instance or None, default=None
D... | sample | python | scikit-learn/scikit-learn | sklearn/neighbors/_kde.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_kde.py | BSD-3-Clause |
def fit_predict(self, X, y=None):
"""Fit the model to the training set X and return the labels.
**Not available for novelty detection (when novelty is set to True).**
Label is 1 for an inlier and -1 for an outlier according to the LOF
score and the contamination parameter.
Para... | Fit the model to the training set X and return the labels.
**Not available for novelty detection (when novelty is set to True).**
Label is 1 for an inlier and -1 for an outlier according to the LOF
score and the contamination parameter.
Parameters
----------
X : {array-... | fit_predict | python | scikit-learn/scikit-learn | sklearn/neighbors/_lof.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_lof.py | BSD-3-Clause |
def fit(self, X, y=None):
"""Fit the local outlier factor detector from the training dataset.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features) or \
(n_samples, n_samples) if metric='precomputed'
Training data.
y ... | Fit the local outlier factor detector from the training dataset.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples) if metric='precomputed'
Training data.
y : Ignored
Not used, present... | fit | python | scikit-learn/scikit-learn | sklearn/neighbors/_lof.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_lof.py | BSD-3-Clause |
def _predict(self, X=None):
"""Predict the labels (1 inlier, -1 outlier) of X according to LOF.
If X is None, returns the same as fit_predict(X_train).
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features), default=None
The query sam... | Predict the labels (1 inlier, -1 outlier) of X according to LOF.
If X is None, returns the same as fit_predict(X_train).
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features), default=None
The query sample or samples to compute the Local Out... | _predict | python | scikit-learn/scikit-learn | sklearn/neighbors/_lof.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_lof.py | BSD-3-Clause |
def score_samples(self, X):
"""Opposite of the Local Outlier Factor of X.
It is the opposite as bigger is better, i.e. large values correspond
to inliers.
**Only available for novelty detection (when novelty is set to True).**
The argument X is supposed to contain *new data*: i... | Opposite of the Local Outlier Factor of X.
It is the opposite as bigger is better, i.e. large values correspond
to inliers.
**Only available for novelty detection (when novelty is set to True).**
The argument X is supposed to contain *new data*: if X contains a
point from train... | score_samples | python | scikit-learn/scikit-learn | sklearn/neighbors/_lof.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_lof.py | BSD-3-Clause |
def _local_reachability_density(self, distances_X, neighbors_indices):
"""The local reachability density (LRD)
The LRD of a sample is the inverse of the average reachability
distance of its k-nearest neighbors.
Parameters
----------
distances_X : ndarray of shape (n_que... | The local reachability density (LRD)
The LRD of a sample is the inverse of the average reachability
distance of its k-nearest neighbors.
Parameters
----------
distances_X : ndarray of shape (n_queries, self.n_neighbors)
Distances to the neighbors (in the training sa... | _local_reachability_density | python | scikit-learn/scikit-learn | sklearn/neighbors/_lof.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_lof.py | BSD-3-Clause |
def fit(self, X, y):
"""Fit the model according to the given training data.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The training samples.
y : array-like of shape (n_samples,)
The corresponding training labels.
Retur... | Fit the model according to the given training data.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The training samples.
y : array-like of shape (n_samples,)
The corresponding training labels.
Returns
-------
self ... | fit | python | scikit-learn/scikit-learn | sklearn/neighbors/_nca.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_nca.py | BSD-3-Clause |
def transform(self, X):
"""Apply the learned transformation to the given data.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Data samples.
Returns
-------
X_embedded: ndarray of shape (n_samples, n_components)
The ... | Apply the learned transformation to the given data.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Data samples.
Returns
-------
X_embedded: ndarray of shape (n_samples, n_components)
The data samples transformed.
... | transform | python | scikit-learn/scikit-learn | sklearn/neighbors/_nca.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_nca.py | BSD-3-Clause |
def _initialize(self, X, y, init):
"""Initialize the transformation.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The training samples.
y : array-like of shape (n_samples,)
The training labels.
init : str or ndarray of s... | Initialize the transformation.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The training samples.
y : array-like of shape (n_samples,)
The training labels.
init : str or ndarray of shape (n_features_a, n_features_b)
... | _initialize | python | scikit-learn/scikit-learn | sklearn/neighbors/_nca.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_nca.py | BSD-3-Clause |
def _callback(self, transformation):
"""Called after each iteration of the optimizer.
Parameters
----------
transformation : ndarray of shape (n_components * n_features,)
The solution computed by the optimizer in this iteration.
"""
if self.callback is not No... | Called after each iteration of the optimizer.
Parameters
----------
transformation : ndarray of shape (n_components * n_features,)
The solution computed by the optimizer in this iteration.
| _callback | python | scikit-learn/scikit-learn | sklearn/neighbors/_nca.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_nca.py | BSD-3-Clause |
def _loss_grad_lbfgs(self, transformation, X, same_class_mask, sign=1.0):
"""Compute the loss and the loss gradient w.r.t. `transformation`.
Parameters
----------
transformation : ndarray of shape (n_components * n_features,)
The raveled linear transformation on which to com... | Compute the loss and the loss gradient w.r.t. `transformation`.
Parameters
----------
transformation : ndarray of shape (n_components * n_features,)
The raveled linear transformation on which to compute loss and
evaluate gradient.
X : ndarray of shape (n_samples... | _loss_grad_lbfgs | python | scikit-learn/scikit-learn | sklearn/neighbors/_nca.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_nca.py | BSD-3-Clause |
def fit(self, X, y):
"""
Fit the NearestCentroid model according to the given training data.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Training vector, where `n_samples` is the number of samples and
`n_features... |
Fit the NearestCentroid model according to the given training data.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Training vector, where `n_samples` is the number of samples and
`n_features` is the number of features.
... | fit | python | scikit-learn/scikit-learn | sklearn/neighbors/_nearest_centroid.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_nearest_centroid.py | BSD-3-Clause |
def predict(self, X):
"""Perform classification on an array of test vectors `X`.
The predicted class `C` for each sample in `X` is returned.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Input data.
Returns
-... | Perform classification on an array of test vectors `X`.
The predicted class `C` for each sample in `X` is returned.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Input data.
Returns
-------
y_pred : ndarray o... | predict | python | scikit-learn/scikit-learn | sklearn/neighbors/_nearest_centroid.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_nearest_centroid.py | BSD-3-Clause |
def predict(self, X):
"""Predict the target for the provided data.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_queries, n_features), \
or (n_queries, n_indexed) if metric == 'precomputed', or None
Test samples. If `None`, predictions for... | Predict the target for the provided data.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == 'precomputed', or None
Test samples. If `None`, predictions for all indexed points are
... | predict | python | scikit-learn/scikit-learn | sklearn/neighbors/_regression.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_regression.py | BSD-3-Clause |
def predict(self, X):
"""Predict the target for the provided data.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_queries, n_features), \
or (n_queries, n_indexed) if metric == 'precomputed', or None
Test samples. If `None`, predictions for... | Predict the target for the provided data.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == 'precomputed', or None
Test samples. If `None`, predictions for all indexed points are
... | predict | python | scikit-learn/scikit-learn | sklearn/neighbors/_regression.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_regression.py | BSD-3-Clause |
def test_array_object_type(BallTreeImplementation):
"""Check that we do not accept object dtype array."""
X = np.array([(1, 2, 3), (2, 5), (5, 5, 1, 2)], dtype=object)
with pytest.raises(ValueError, match="setting an array element with a sequence"):
BallTreeImplementation(X) | Check that we do not accept object dtype array. | test_array_object_type | python | scikit-learn/scikit-learn | sklearn/neighbors/tests/test_ball_tree.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/tests/test_ball_tree.py | BSD-3-Clause |
def _has_explicit_diagonal(X):
"""Return True if the diagonal is explicitly stored"""
X = X.tocoo()
explicit = X.row[X.row == X.col]
return len(explicit) == X.shape[0] | Return True if the diagonal is explicitly stored | _has_explicit_diagonal | python | scikit-learn/scikit-learn | sklearn/neighbors/tests/test_graph.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/tests/test_graph.py | BSD-3-Clause |
def test_graph_feature_names_out(Klass):
"""Check `get_feature_names_out` for transformers defined in `_graph.py`."""
n_samples_fit = 20
n_features = 10
rng = np.random.RandomState(42)
X = rng.randn(n_samples_fit, n_features)
est = Klass().fit(X)
names_out = est.get_feature_names_out()
... | Check `get_feature_names_out` for transformers defined in `_graph.py`. | test_graph_feature_names_out | python | scikit-learn/scikit-learn | sklearn/neighbors/tests/test_graph.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/tests/test_graph.py | BSD-3-Clause |
def test_array_object_type(BinarySearchTree):
"""Check that we do not accept object dtype array."""
X = np.array([(1, 2, 3), (2, 5), (5, 5, 1, 2)], dtype=object)
with pytest.raises(ValueError, match="setting an array element with a sequence"):
BinarySearchTree(X) | Check that we do not accept object dtype array. | test_array_object_type | python | scikit-learn/scikit-learn | sklearn/neighbors/tests/test_kd_tree.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/tests/test_kd_tree.py | BSD-3-Clause |
def test_kdtree_picklable_with_joblib(BinarySearchTree):
"""Make sure that KDTree queries work when joblib memmaps.
Non-regression test for #21685 and #21228."""
rng = np.random.RandomState(0)
X = rng.random_sample((10, 3))
tree = BinarySearchTree(X, leaf_size=2)
# Call Parallel with max_nbyte... | Make sure that KDTree queries work when joblib memmaps.
Non-regression test for #21685 and #21228. | test_kdtree_picklable_with_joblib | python | scikit-learn/scikit-learn | sklearn/neighbors/tests/test_kd_tree.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/tests/test_kd_tree.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.