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_polynomial_count_sketch_dense_sparse(gamma, degree, coef0, csr_container):
"""Check that PolynomialCountSketch results are the same for dense and sparse
input.
"""
ps_dense = PolynomialCountSketch(
n_components=500, gamma=gamma, degree=degree, coef0=coef0, random_state=42
)
Xt_d... | Check that PolynomialCountSketch results are the same for dense and sparse
input.
| test_polynomial_count_sketch_dense_sparse | python | scikit-learn/scikit-learn | sklearn/tests/test_kernel_approximation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_kernel_approximation.py | BSD-3-Clause |
def test_additive_chi2_sampler_sample_steps(method, sample_steps):
"""Check that the input sample step doesn't raise an error
and that sample interval doesn't change after fit.
"""
transformer = AdditiveChi2Sampler(sample_steps=sample_steps)
getattr(transformer, method)(X)
sample_interval = 0.5... | Check that the input sample step doesn't raise an error
and that sample interval doesn't change after fit.
| test_additive_chi2_sampler_sample_steps | python | scikit-learn/scikit-learn | sklearn/tests/test_kernel_approximation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_kernel_approximation.py | BSD-3-Clause |
def test_additive_chi2_sampler_wrong_sample_steps(method):
"""Check that we raise a ValueError on invalid sample_steps"""
transformer = AdditiveChi2Sampler(sample_steps=4)
msg = re.escape(
"If sample_steps is not in [1, 2, 3], you need to provide sample_interval"
)
with pytest.raises(ValueEr... | Check that we raise a ValueError on invalid sample_steps | test_additive_chi2_sampler_wrong_sample_steps | python | scikit-learn/scikit-learn | sklearn/tests/test_kernel_approximation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_kernel_approximation.py | BSD-3-Clause |
def test_rbf_sampler_gamma_scale():
"""Check the inner value computed when `gamma='scale'`."""
X, y = [[0.0], [1.0]], [0, 1]
rbf = RBFSampler(gamma="scale")
rbf.fit(X, y)
assert rbf._gamma == pytest.approx(4) | Check the inner value computed when `gamma='scale'`. | test_rbf_sampler_gamma_scale | python | scikit-learn/scikit-learn | sklearn/tests/test_kernel_approximation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_kernel_approximation.py | BSD-3-Clause |
def logging_histogram_kernel(x, y, log):
"""Histogram kernel that writes to a log."""
log.append(1)
return np.minimum(x, y).sum() | Histogram kernel that writes to a log. | logging_histogram_kernel | python | scikit-learn/scikit-learn | sklearn/tests/test_kernel_approximation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_kernel_approximation.py | BSD-3-Clause |
def test_nystroem_component_indices():
"""Check that `component_indices_` corresponds to the subset of
training points used to construct the feature map.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/20474
"""
X, _ = make_classification(n_samples=100, n_features=20... | Check that `component_indices_` corresponds to the subset of
training points used to construct the feature map.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/20474
| test_nystroem_component_indices | python | scikit-learn/scikit-learn | sklearn/tests/test_kernel_approximation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_kernel_approximation.py | BSD-3-Clause |
def test_estimator_puts_self_in_registry(estimator):
"""Check that an estimator puts itself in the registry upon fit."""
estimator.fit(X, y)
assert estimator in estimator.registry | Check that an estimator puts itself in the registry upon fit. | test_estimator_puts_self_in_registry | python | scikit-learn/scikit-learn | sklearn/tests/test_metadata_routing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_metadata_routing.py | BSD-3-Clause |
def test_default_request_override():
"""Test that default requests are correctly overridden regardless of the ASCII order
of the class names, hence testing small and capital letter class name starts.
Non-regression test for https://github.com/scikit-learn/scikit-learn/issues/28430
"""
class Base(Ba... | Test that default requests are correctly overridden regardless of the ASCII order
of the class names, hence testing small and capital letter class name starts.
Non-regression test for https://github.com/scikit-learn/scikit-learn/issues/28430
| test_default_request_override | python | scikit-learn/scikit-learn | sklearn/tests/test_metadata_routing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_metadata_routing.py | BSD-3-Clause |
def test_removing_non_existing_param_raises():
"""Test that removing a metadata using UNUSED which doesn't exist raises."""
class InvalidRequestRemoval(BaseEstimator):
# `fit` (in this class or a parent) requests `prop`, but we don't want
# it requested at all.
__metadata_request__fit =... | Test that removing a metadata using UNUSED which doesn't exist raises. | test_removing_non_existing_param_raises | python | scikit-learn/scikit-learn | sklearn/tests/test_metadata_routing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_metadata_routing.py | BSD-3-Clause |
def test_metadata_request_consumes_method():
"""Test that MetadataRequest().consumes() method works as expected."""
request = MetadataRouter(owner="test")
assert request.consumes(method="fit", params={"foo"}) == set()
request = MetadataRequest(owner="test")
request.fit.add_request(param="foo", alia... | Test that MetadataRequest().consumes() method works as expected. | test_metadata_request_consumes_method | python | scikit-learn/scikit-learn | sklearn/tests/test_metadata_routing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_metadata_routing.py | BSD-3-Clause |
def test_metadata_router_consumes_method():
"""Test that MetadataRouter().consumes method works as expected."""
# having it here instead of parametrizing the test since `set_fit_request`
# is not available while collecting the tests.
cases = [
(
WeightedMetaRegressor(
... | Test that MetadataRouter().consumes method works as expected. | test_metadata_router_consumes_method | python | scikit-learn/scikit-learn | sklearn/tests/test_metadata_routing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_metadata_routing.py | BSD-3-Clause |
def test_no_feature_flag_raises_error():
"""Test that when feature flag disabled, set_{method}_requests raises."""
with config_context(enable_metadata_routing=False):
with pytest.raises(RuntimeError, match="This method is only available"):
ConsumingClassifier().set_fit_request(sample_weight=... | Test that when feature flag disabled, set_{method}_requests raises. | test_no_feature_flag_raises_error | python | scikit-learn/scikit-learn | sklearn/tests/test_metadata_routing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_metadata_routing.py | BSD-3-Clause |
def test_no_metadata_always_works():
"""Test that when no metadata is passed, having a meta-estimator which does
not yet support metadata routing works.
Non-regression test for https://github.com/scikit-learn/scikit-learn/issues/28246
"""
class Estimator(_RoutingNotSupportedMixin, BaseEstimator):
... | Test that when no metadata is passed, having a meta-estimator which does
not yet support metadata routing works.
Non-regression test for https://github.com/scikit-learn/scikit-learn/issues/28246
| test_no_metadata_always_works | python | scikit-learn/scikit-learn | sklearn/tests/test_metadata_routing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_metadata_routing.py | BSD-3-Clause |
def test_unsetmetadatapassederror_correct():
"""Test that UnsetMetadataPassedError raises the correct error message when
set_{method}_request is not set in nested cases."""
weighted_meta = WeightedMetaClassifier(estimator=ConsumingClassifier())
pipe = SimplePipeline([weighted_meta])
msg = re.escape(... | Test that UnsetMetadataPassedError raises the correct error message when
set_{method}_request is not set in nested cases. | test_unsetmetadatapassederror_correct | python | scikit-learn/scikit-learn | sklearn/tests/test_metadata_routing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_metadata_routing.py | BSD-3-Clause |
def test_unsetmetadatapassederror_correct_for_composite_methods():
"""Test that UnsetMetadataPassedError raises the correct error message when
composite metadata request methods are not set in nested cases."""
consuming_transformer = ConsumingTransformer()
pipe = Pipeline([("consuming_transformer", cons... | Test that UnsetMetadataPassedError raises the correct error message when
composite metadata request methods are not set in nested cases. | test_unsetmetadatapassederror_correct_for_composite_methods | python | scikit-learn/scikit-learn | sklearn/tests/test_metadata_routing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_metadata_routing.py | BSD-3-Clause |
def test_unbound_set_methods_work():
"""Tests that if the set_{method}_request is unbound, it still works.
Also test that passing positional arguments to the set_{method}_request fails
with the right TypeError message.
Non-regression test for https://github.com/scikit-learn/scikit-learn/issues/28632
... | Tests that if the set_{method}_request is unbound, it still works.
Also test that passing positional arguments to the set_{method}_request fails
with the right TypeError message.
Non-regression test for https://github.com/scikit-learn/scikit-learn/issues/28632
| test_unbound_set_methods_work | python | scikit-learn/scikit-learn | sklearn/tests/test_metadata_routing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_metadata_routing.py | BSD-3-Clause |
def _get_instance_with_pipeline(meta_estimator, init_params):
"""Given a single meta-estimator instance, generate an instance with a pipeline"""
if {"estimator", "base_estimator", "regressor"} & init_params:
if is_regressor(meta_estimator):
estimator = make_pipeline(TfidfVectorizer(), Ridge(... | Given a single meta-estimator instance, generate an instance with a pipeline | _get_instance_with_pipeline | python | scikit-learn/scikit-learn | sklearn/tests/test_metaestimators.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_metaestimators.py | BSD-3-Clause |
def _generate_meta_estimator_instances_with_pipeline():
"""Generate instances of meta-estimators fed with a pipeline
Are considered meta-estimators all estimators accepting one of "estimator",
"base_estimator" or "estimators".
"""
print("estimators: ", len(all_estimators()))
for _, Estimator in... | Generate instances of meta-estimators fed with a pipeline
Are considered meta-estimators all estimators accepting one of "estimator",
"base_estimator" or "estimators".
| _generate_meta_estimator_instances_with_pipeline | python | scikit-learn/scikit-learn | sklearn/tests/test_metaestimators.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_metaestimators.py | BSD-3-Clause |
def get_init_args(metaestimator_info, sub_estimator_consumes):
"""Get the init args for a metaestimator
This is a helper function to get the init args for a metaestimator from
the METAESTIMATORS list. It returns an empty dict if no init args are
required.
Parameters
----------
metaestimato... | Get the init args for a metaestimator
This is a helper function to get the init args for a metaestimator from
the METAESTIMATORS list. It returns an empty dict if no init args are
required.
Parameters
----------
metaestimator_info : dict
The metaestimator info from METAESTIMATORS
... | get_init_args | python | scikit-learn/scikit-learn | sklearn/tests/test_metaestimators_metadata_routing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_metaestimators_metadata_routing.py | BSD-3-Clause |
def set_requests(obj, *, method_mapping, methods, metadata_name, value=True):
"""Call `set_{method}_request` on a list of methods from the sub-estimator.
Parameters
----------
obj : BaseEstimator
The object for which `set_{method}_request` methods are called.
method_mapping : dict
... | Call `set_{method}_request` on a list of methods from the sub-estimator.
Parameters
----------
obj : BaseEstimator
The object for which `set_{method}_request` methods are called.
method_mapping : dict
The method mapping in the form of `{caller: [callee, ...]}`.
If a "caller" is... | set_requests | python | scikit-learn/scikit-learn | sklearn/tests/test_metaestimators_metadata_routing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_metaestimators_metadata_routing.py | BSD-3-Clause |
def test_unsupported_estimators_fit_with_metadata(estimator):
"""Test that fit raises NotImplementedError when metadata routing is
enabled and a metadata is passed on meta-estimators for which we haven't
implemented routing yet."""
with pytest.raises(NotImplementedError):
try:
estima... | Test that fit raises NotImplementedError when metadata routing is
enabled and a metadata is passed on meta-estimators for which we haven't
implemented routing yet. | test_unsupported_estimators_fit_with_metadata | python | scikit-learn/scikit-learn | sklearn/tests/test_metaestimators_metadata_routing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_metaestimators_metadata_routing.py | BSD-3-Clause |
def test_metadata_is_routed_correctly_to_scorer(metaestimator):
"""Test that any requested metadata is correctly routed to the underlying
scorers in CV estimators.
"""
if "scorer_name" not in metaestimator:
# This test only makes sense for CV estimators
return
metaestimator_class = ... | Test that any requested metadata is correctly routed to the underlying
scorers in CV estimators.
| test_metadata_is_routed_correctly_to_scorer | python | scikit-learn/scikit-learn | sklearn/tests/test_metaestimators_metadata_routing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_metaestimators_metadata_routing.py | BSD-3-Clause |
def test_metadata_is_routed_correctly_to_splitter(metaestimator):
"""Test that any requested metadata is correctly routed to the underlying
splitters in CV estimators.
"""
if "cv_routing_methods" not in metaestimator:
# This test is only for metaestimators accepting a CV splitter
return
... | Test that any requested metadata is correctly routed to the underlying
splitters in CV estimators.
| test_metadata_is_routed_correctly_to_splitter | python | scikit-learn/scikit-learn | sklearn/tests/test_metaestimators_metadata_routing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_metaestimators_metadata_routing.py | BSD-3-Clause |
def test_metadata_routed_to_group_splitter(metaestimator):
"""Test that groups are routed correctly if group splitter of CV estimator is used
within cross_validate. Regression test for issue described in PR #29634 to test that
`ValueError: The 'groups' parameter should not be None.` is not raised."""
i... | Test that groups are routed correctly if group splitter of CV estimator is used
within cross_validate. Regression test for issue described in PR #29634 to test that
`ValueError: The 'groups' parameter should not be None.` is not raised. | test_metadata_routed_to_group_splitter | python | scikit-learn/scikit-learn | sklearn/tests/test_metaestimators_metadata_routing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_metaestimators_metadata_routing.py | BSD-3-Clause |
def test_min_dependencies_pyproject_toml(pyproject_section, min_dependencies_tag):
"""Check versions in pyproject.toml is consistent with _min_dependencies."""
# NumPy is more complex because build-time (>=1.25) and run-time (>=1.19.5)
# requirement currently don't match
skip_version_check_for = ["numpy... | Check versions in pyproject.toml is consistent with _min_dependencies. | test_min_dependencies_pyproject_toml | python | scikit-learn/scikit-learn | sklearn/tests/test_min_dependencies_readme.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_min_dependencies_readme.py | BSD-3-Clause |
def test_ovr_single_label_predict_proba_zero():
"""Check that predic_proba returns all zeros when the base estimator
never predicts the positive class.
"""
class NaiveBinaryClassifier(BaseEstimator, ClassifierMixin):
def fit(self, X, y):
self.classes_ = np.unique(y)
retu... | Check that predic_proba returns all zeros when the base estimator
never predicts the positive class.
| test_ovr_single_label_predict_proba_zero | python | scikit-learn/scikit-learn | sklearn/tests/test_multiclass.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_multiclass.py | BSD-3-Clause |
def test_pairwise_n_features_in():
"""Check the n_features_in_ attributes of the meta and base estimators
When the training data is a regular design matrix, everything is intuitive.
However, when the training data is a precomputed kernel matrix, the
multiclass strategy can resample the kernel matrix of... | Check the n_features_in_ attributes of the meta and base estimators
When the training data is a regular design matrix, everything is intuitive.
However, when the training data is a precomputed kernel matrix, the
multiclass strategy can resample the kernel matrix of the underlying base
estimator both ro... | test_pairwise_n_features_in | python | scikit-learn/scikit-learn | sklearn/tests/test_multiclass.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_multiclass.py | BSD-3-Clause |
def test_constant_int_target(make_y):
"""Check that constant y target does not raise.
Non-regression test for #21869
"""
X = np.ones((10, 2))
y = make_y((10, 1), dtype=np.int32)
ovr = OneVsRestClassifier(LogisticRegression())
ovr.fit(X, y)
y_pred = ovr.predict_proba(X)
expected = n... | Check that constant y target does not raise.
Non-regression test for #21869
| test_constant_int_target | python | scikit-learn/scikit-learn | sklearn/tests/test_multiclass.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_multiclass.py | BSD-3-Clause |
def test_ovo_consistent_binary_classification():
"""Check that ovo is consistent with binary classifier.
Non-regression test for #13617.
"""
X, y = load_breast_cancer(return_X_y=True)
clf = KNeighborsClassifier(n_neighbors=8, weights="distance")
ovo = OneVsOneClassifier(clf)
clf.fit(X, y)... | Check that ovo is consistent with binary classifier.
Non-regression test for #13617.
| test_ovo_consistent_binary_classification | python | scikit-learn/scikit-learn | sklearn/tests/test_multiclass.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_multiclass.py | BSD-3-Clause |
def test_multiclass_estimator_attribute_error():
"""Check that we raise the proper AttributeError when the final estimator
does not implement the `partial_fit` method, which is decorated with
`available_if`.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/28108
"""
... | Check that we raise the proper AttributeError when the final estimator
does not implement the `partial_fit` method, which is decorated with
`available_if`.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/28108
| test_multiclass_estimator_attribute_error | python | scikit-learn/scikit-learn | sklearn/tests/test_multiclass.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_multiclass.py | BSD-3-Clause |
def test_multi_output_not_fitted_error(response_method):
"""Check that we raise the proper error when the estimator is not fitted"""
moc = MultiOutputClassifier(LogisticRegression())
with pytest.raises(NotFittedError):
getattr(moc, response_method)(X) | Check that we raise the proper error when the estimator is not fitted | test_multi_output_not_fitted_error | python | scikit-learn/scikit-learn | sklearn/tests/test_multioutput.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_multioutput.py | BSD-3-Clause |
def test_multi_output_delegate_predict_proba():
"""Check the behavior for the delegation of predict_proba to the underlying
estimator"""
# A base estimator with `predict_proba`should expose the method even before fit
moc = MultiOutputClassifier(LogisticRegression())
assert hasattr(moc, "predict_pro... | Check the behavior for the delegation of predict_proba to the underlying
estimator | test_multi_output_delegate_predict_proba | python | scikit-learn/scikit-learn | sklearn/tests/test_multioutput.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_multioutput.py | BSD-3-Clause |
def test_multioutputregressor_ducktypes_fitted_estimator():
"""Test that MultiOutputRegressor checks the fitted estimator for
predict. Non-regression test for #16549."""
X, y = load_linnerud(return_X_y=True)
stacker = StackingRegressor(
estimators=[("sgd", SGDRegressor(random_state=1))],
... | Test that MultiOutputRegressor checks the fitted estimator for
predict. Non-regression test for #16549. | test_multioutputregressor_ducktypes_fitted_estimator | python | scikit-learn/scikit-learn | sklearn/tests/test_multioutput.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_multioutput.py | BSD-3-Clause |
def test_fit_params_no_routing(Cls, method):
"""Check that we raise an error when passing metadata not requested by the
underlying classifier.
"""
X, y = make_classification(n_samples=50)
clf = Cls(PassiveAggressiveClassifier())
with pytest.raises(ValueError, match="is only supported if"):
... | Check that we raise an error when passing metadata not requested by the
underlying classifier.
| test_fit_params_no_routing | python | scikit-learn/scikit-learn | sklearn/tests/test_multioutput.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_multioutput.py | BSD-3-Clause |
def test_base_estimator_deprecation(Estimator):
"""Check that we warn about the deprecation of `base_estimator`."""
X = np.array([[1, 2], [3, 4]])
y = np.array([[1, 0], [0, 1]])
estimator = LogisticRegression()
with pytest.warns(FutureWarning):
Estimator(base_estimator=estimator).fit(X, y)... | Check that we warn about the deprecation of `base_estimator`. | test_base_estimator_deprecation | python | scikit-learn/scikit-learn | sklearn/tests/test_multioutput.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_multioutput.py | BSD-3-Clause |
def test_gnb_sample_weight(global_random_seed):
"""Test whether sample weights are properly used in GNB."""
# Sample weights all being 1 should not change results
sw = np.ones(6)
clf = GaussianNB().fit(X, y)
clf_sw = GaussianNB().fit(X, y, sw)
assert_array_almost_equal(clf.theta_, clf_sw.theta_... | Test whether sample weights are properly used in GNB. | test_gnb_sample_weight | python | scikit-learn/scikit-learn | sklearn/tests/test_naive_bayes.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_naive_bayes.py | BSD-3-Clause |
def test_gnb_neg_priors():
"""Test whether an error is raised in case of negative priors"""
clf = GaussianNB(priors=np.array([-1.0, 2.0]))
msg = "Priors must be non-negative"
with pytest.raises(ValueError, match=msg):
clf.fit(X, y) | Test whether an error is raised in case of negative priors | test_gnb_neg_priors | python | scikit-learn/scikit-learn | sklearn/tests/test_naive_bayes.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_naive_bayes.py | BSD-3-Clause |
def test_gnb_priors():
"""Test whether the class prior override is properly used"""
clf = GaussianNB(priors=np.array([0.3, 0.7])).fit(X, y)
assert_array_almost_equal(
clf.predict_proba([[-0.1, -0.1]]),
np.array([[0.825303662161683, 0.174696337838317]]),
8,
)
assert_array_almo... | Test whether the class prior override is properly used | test_gnb_priors | python | scikit-learn/scikit-learn | sklearn/tests/test_naive_bayes.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_naive_bayes.py | BSD-3-Clause |
def test_gnb_wrong_nb_priors():
"""Test whether an error is raised if the number of prior is different
from the number of class"""
clf = GaussianNB(priors=np.array([0.25, 0.25, 0.25, 0.25]))
msg = "Number of priors must match number of classes"
with pytest.raises(ValueError, match=msg):
clf... | Test whether an error is raised if the number of prior is different
from the number of class | test_gnb_wrong_nb_priors | python | scikit-learn/scikit-learn | sklearn/tests/test_naive_bayes.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_naive_bayes.py | BSD-3-Clause |
def test_gnb_prior_greater_one():
"""Test if an error is raised if the sum of prior greater than one"""
clf = GaussianNB(priors=np.array([2.0, 1.0]))
msg = "The sum of the priors should be 1"
with pytest.raises(ValueError, match=msg):
clf.fit(X, y) | Test if an error is raised if the sum of prior greater than one | test_gnb_prior_greater_one | python | scikit-learn/scikit-learn | sklearn/tests/test_naive_bayes.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_naive_bayes.py | BSD-3-Clause |
def test_gnb_prior_large_bias():
"""Test if good prediction when class prior favor largely one class"""
clf = GaussianNB(priors=np.array([0.01, 0.99]))
clf.fit(X, y)
assert clf.predict([[-0.1, -0.1]]) == np.array([2]) | Test if good prediction when class prior favor largely one class | test_gnb_prior_large_bias | python | scikit-learn/scikit-learn | sklearn/tests/test_naive_bayes.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_naive_bayes.py | BSD-3-Clause |
def test_gnb_check_update_with_no_data():
"""Test when the partial fit is called without any data"""
# Create an empty array
prev_points = 100
mean = 0.0
var = 1.0
x_empty = np.empty((0, X.shape[1]))
tmean, tvar = GaussianNB._update_mean_variance(prev_points, mean, var, x_empty)
assert t... | Test when the partial fit is called without any data | test_gnb_check_update_with_no_data | python | scikit-learn/scikit-learn | sklearn/tests/test_naive_bayes.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_naive_bayes.py | BSD-3-Clause |
def test_check_alpha():
"""The provided value for alpha must only be
used if alpha < _ALPHA_MIN and force_alpha is True.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/10772
"""
_ALPHA_MIN = 1e-10
b = BernoulliNB(alpha=0, force_alpha=True)
assert b._check_a... | The provided value for alpha must only be
used if alpha < _ALPHA_MIN and force_alpha is True.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/10772
| test_check_alpha | python | scikit-learn/scikit-learn | sklearn/tests/test_naive_bayes.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_naive_bayes.py | BSD-3-Clause |
def create_mock_transformer(base_name, n_features=3):
"""Helper to create a mock transformer with custom feature names."""
mock = Transf()
mock.get_feature_names_out = lambda input_features: [
f"{base_name}{i}" for i in range(n_features)
]
return mock | Helper to create a mock transformer with custom feature names. | create_mock_transformer | python | scikit-learn/scikit-learn | sklearn/tests/test_pipeline.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_pipeline.py | BSD-3-Clause |
def test_pipeline_estimator_type(pipeline, check_estimator_type):
"""Check that the estimator type returned by the pipeline is correct.
Non-regression test as part of:
https://github.com/scikit-learn/scikit-learn/issues/30197
"""
# Smoke test the repr
repr(pipeline)
assert check_estimator_t... | Check that the estimator type returned by the pipeline is correct.
Non-regression test as part of:
https://github.com/scikit-learn/scikit-learn/issues/30197
| test_pipeline_estimator_type | python | scikit-learn/scikit-learn | sklearn/tests/test_pipeline.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_pipeline.py | BSD-3-Clause |
def test_sklearn_tags_with_empty_pipeline():
"""Check that we propagate properly the tags in a Pipeline.
Non-regression test as part of:
https://github.com/scikit-learn/scikit-learn/issues/30197
"""
empty_pipeline = Pipeline(steps=[])
be = BaseEstimator()
expected_tags = be.__sklearn_tags_... | Check that we propagate properly the tags in a Pipeline.
Non-regression test as part of:
https://github.com/scikit-learn/scikit-learn/issues/30197
| test_sklearn_tags_with_empty_pipeline | python | scikit-learn/scikit-learn | sklearn/tests/test_pipeline.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_pipeline.py | BSD-3-Clause |
def test_set_feature_union_passthrough():
"""Check the behaviour of setting a transformer to `"passthrough"`."""
mult2 = Mult(2)
mult3 = Mult(3)
# We only test get_features_names_out, as get_feature_names is unsupported by
# FunctionTransformer, and hence unsupported by FeatureUnion passthrough.
... | Check the behaviour of setting a transformer to `"passthrough"`. | test_set_feature_union_passthrough | python | scikit-learn/scikit-learn | sklearn/tests/test_pipeline.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_pipeline.py | BSD-3-Clause |
def test_feature_union_passthrough_get_feature_names_out_false_errors():
"""Check get_feature_names_out and non-verbose names and colliding names."""
pd = pytest.importorskip("pandas")
X = pd.DataFrame([[1, 2], [2, 3]], columns=["a", "b"])
select_a = FunctionTransformer(
lambda X: X[["a"]], fea... | Check get_feature_names_out and non-verbose names and colliding names. | test_feature_union_passthrough_get_feature_names_out_false_errors | python | scikit-learn/scikit-learn | sklearn/tests/test_pipeline.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_pipeline.py | BSD-3-Clause |
def test_feature_union_passthrough_get_feature_names_out_false_errors_overlap_over_5():
"""Check get_feature_names_out with non-verbose names and >= 5 colliding names."""
pd = pytest.importorskip("pandas")
X = pd.DataFrame([list(range(10))], columns=[f"f{i}" for i in range(10)])
union = FeatureUnion(
... | Check get_feature_names_out with non-verbose names and >= 5 colliding names. | test_feature_union_passthrough_get_feature_names_out_false_errors_overlap_over_5 | python | scikit-learn/scikit-learn | sklearn/tests/test_pipeline.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_pipeline.py | BSD-3-Clause |
def test_pipeline_feature_names_out_error_without_definition():
"""Check that error is raised when a transformer does not define
`get_feature_names_out`."""
pipe = Pipeline(steps=[("notrans", NoTrans())])
iris = load_iris()
pipe.fit(iris.data, iris.target)
msg = "does not provide get_feature_na... | Check that error is raised when a transformer does not define
`get_feature_names_out`. | test_pipeline_feature_names_out_error_without_definition | python | scikit-learn/scikit-learn | sklearn/tests/test_pipeline.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_pipeline.py | BSD-3-Clause |
def test_pipeline_get_feature_names_out_passes_names_through():
"""Check that pipeline passes names through.
Non-regresion test for #21349.
"""
X, y = iris.data, iris.target
class AddPrefixStandardScalar(StandardScaler):
def get_feature_names_out(self, input_features=None):
nam... | Check that pipeline passes names through.
Non-regresion test for #21349.
| test_pipeline_get_feature_names_out_passes_names_through | python | scikit-learn/scikit-learn | sklearn/tests/test_pipeline.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_pipeline.py | BSD-3-Clause |
def test_feature_union_getitem_error(key):
"""Raise error when __getitem__ gets a non-string input."""
union = FeatureUnion([("scalar", StandardScaler()), ("pca", PCA())])
msg = "Only string keys are supported"
with pytest.raises(KeyError, match=msg):
union[key] | Raise error when __getitem__ gets a non-string input. | test_feature_union_getitem_error | python | scikit-learn/scikit-learn | sklearn/tests/test_pipeline.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_pipeline.py | BSD-3-Clause |
def test_feature_union_feature_names_in_():
"""Ensure feature union has `.feature_names_in_` attribute if `X` has a
`columns` attribute.
Test for #24754.
"""
pytest.importorskip("pandas")
X, _ = load_iris(as_frame=True, return_X_y=True)
# FeatureUnion should have the feature_names_in_ att... | Ensure feature union has `.feature_names_in_` attribute if `X` has a
`columns` attribute.
Test for #24754.
| test_feature_union_feature_names_in_ | python | scikit-learn/scikit-learn | sklearn/tests/test_pipeline.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_pipeline.py | BSD-3-Clause |
def test_transform_input_pipeline(method):
"""Test that with transform_input, data is correctly transformed for each step."""
def get_transformer(registry, sample_weight, metadata):
"""Get a transformer with requests set."""
return (
ConsumingTransformer(registry=registry)
... | Test that with transform_input, data is correctly transformed for each step. | test_transform_input_pipeline | python | scikit-learn/scikit-learn | sklearn/tests/test_pipeline.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_pipeline.py | BSD-3-Clause |
def get_pipeline():
"""Get a pipeline and corresponding registries.
The pipeline has 4 steps, with different request values set to test different
cases. One is aliased.
"""
registry_1, registry_2, registry_3, registry_4 = (
_Registry(),
_Registry(),
... | Get a pipeline and corresponding registries.
The pipeline has 4 steps, with different request values set to test different
cases. One is aliased.
| get_pipeline | python | scikit-learn/scikit-learn | sklearn/tests/test_pipeline.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_pipeline.py | BSD-3-Clause |
def check_metadata(registry, methods, **metadata):
"""Check that the right metadata was recorded for the given methods."""
assert registry
for estimator in registry:
for method in methods:
check_recorded_metadata(
estimator,
met... | Check that the right metadata was recorded for the given methods. | check_metadata | python | scikit-learn/scikit-learn | sklearn/tests/test_pipeline.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_pipeline.py | BSD-3-Clause |
def test_transform_input_explicit_value_check():
"""Test that the right transformed values are passed to `fit`."""
class Transformer(TransformerMixin, BaseEstimator):
def fit(self, X, y):
self.fitted_ = True
return self
def transform(self, X):
return X + 1
... | Test that the right transformed values are passed to `fit`. | test_transform_input_explicit_value_check | python | scikit-learn/scikit-learn | sklearn/tests/test_pipeline.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_pipeline.py | BSD-3-Clause |
def test_transform_input_no_slep6():
"""Make sure the right error is raised if slep6 is not enabled."""
X = np.array([[1, 2], [3, 4]])
y = np.array([0, 1])
msg = "The `transform_input` parameter can only be set if metadata"
with pytest.raises(ValueError, match=msg):
make_pipeline(DummyTransf... | Make sure the right error is raised if slep6 is not enabled. | test_transform_input_no_slep6 | python | scikit-learn/scikit-learn | sklearn/tests/test_pipeline.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_pipeline.py | BSD-3-Clause |
def test_transform_tuple_input():
"""Test that if metadata is a tuple of arrays, both arrays are transformed."""
class Estimator(ClassifierMixin, BaseEstimator):
def fit(self, X, y, X_val=None, y_val=None):
assert isinstance(X_val, tuple)
assert isinstance(y_val, tuple)
... | Test that if metadata is a tuple of arrays, both arrays are transformed. | test_transform_tuple_input | python | scikit-learn/scikit-learn | sklearn/tests/test_pipeline.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_pipeline.py | BSD-3-Clause |
def test_metadata_routing_for_pipeline(method):
"""Test that metadata is routed correctly for pipelines."""
def set_request(est, method, **kwarg):
"""Set requests for a given method.
If the given method is a composite method, set the same requests for
all the methods that compose it.
... | Test that metadata is routed correctly for pipelines. | test_metadata_routing_for_pipeline | python | scikit-learn/scikit-learn | sklearn/tests/test_pipeline.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_pipeline.py | BSD-3-Clause |
def set_request(est, method, **kwarg):
"""Set requests for a given method.
If the given method is a composite method, set the same requests for
all the methods that compose it.
"""
if method in COMPOSITE_METHODS:
methods = COMPOSITE_METHODS[method]
else:
... | Set requests for a given method.
If the given method is a composite method, set the same requests for
all the methods that compose it.
| set_request | python | scikit-learn/scikit-learn | sklearn/tests/test_pipeline.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_pipeline.py | BSD-3-Clause |
def test_metadata_routing_error_for_pipeline(method):
"""Test that metadata is not routed for pipelines when not requested."""
X, y = [[1]], [1]
sample_weight, prop = [1], "a"
est = SimpleEstimator()
# here not setting sample_weight request and leaving it as None
pipeline = Pipeline([("estimator... | Test that metadata is not routed for pipelines when not requested. | test_metadata_routing_error_for_pipeline | python | scikit-learn/scikit-learn | sklearn/tests/test_pipeline.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_pipeline.py | BSD-3-Clause |
def test_pipeline_with_estimator_with_len():
"""Test that pipeline works with estimators that have a `__len__` method."""
pipe = Pipeline(
[("trs", RandomTreesEmbedding()), ("estimator", RandomForestClassifier())]
)
pipe.fit([[1]], [1])
pipe.predict([[1]]) | Test that pipeline works with estimators that have a `__len__` method. | test_pipeline_with_estimator_with_len | python | scikit-learn/scikit-learn | sklearn/tests/test_pipeline.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_pipeline.py | BSD-3-Clause |
def test_pipeline_with_no_last_step(last_step):
"""Test that the pipeline works when there is not last step.
It should just ignore and pass through the data on transform.
"""
pipe = Pipeline([("trs", FunctionTransformer()), ("estimator", last_step)])
assert pipe.fit([[1]], [1]).transform([[1], [2],... | Test that the pipeline works when there is not last step.
It should just ignore and pass through the data on transform.
| test_pipeline_with_no_last_step | python | scikit-learn/scikit-learn | sklearn/tests/test_pipeline.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_pipeline.py | BSD-3-Clause |
def test_feature_union_metadata_routing(transformer):
"""Test that metadata is routed correctly for FeatureUnion."""
X = np.array([[0, 1], [2, 2], [4, 6]])
y = [1, 2, 3]
sample_weight, metadata = [1, 1, 1], "a"
feature_union = FeatureUnion(
[
(
"sub_trans1",
... | Test that metadata is routed correctly for FeatureUnion. | test_feature_union_metadata_routing | python | scikit-learn/scikit-learn | sklearn/tests/test_pipeline.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_pipeline.py | BSD-3-Clause |
def _check_function_param_validation(
func, func_name, func_params, required_params, parameter_constraints
):
"""Check that an informative error is raised when the value of a parameter does not
have an appropriate type or value.
"""
# generate valid values for the required parameters
valid_requi... | Check that an informative error is raised when the value of a parameter does not
have an appropriate type or value.
| _check_function_param_validation | python | scikit-learn/scikit-learn | sklearn/tests/test_public_functions.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_public_functions.py | BSD-3-Clause |
def test_function_param_validation(func_module):
"""Check param validation for public functions that are not wrappers around
estimators.
"""
func, func_name, func_params, required_params = _get_func_info(func_module)
parameter_constraints = getattr(func, "_skl_parameter_constraints")
_check_fu... | Check param validation for public functions that are not wrappers around
estimators.
| test_function_param_validation | python | scikit-learn/scikit-learn | sklearn/tests/test_public_functions.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_public_functions.py | BSD-3-Clause |
def test_class_wrapper_param_validation(func_module, class_module):
"""Check param validation for public functions that are wrappers around
estimators.
"""
func, func_name, func_params, required_params = _get_func_info(func_module)
module_name, class_name = class_module.rsplit(".", 1)
module = ... | Check param validation for public functions that are wrappers around
estimators.
| test_class_wrapper_param_validation | python | scikit-learn/scikit-learn | sklearn/tests/test_public_functions.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_public_functions.py | BSD-3-Clause |
def make_sparse_random_data(
coo_container,
n_samples,
n_features,
n_nonzeros,
random_state=None,
sparse_format="csr",
):
"""Make some random data with uniformly located non zero entries with
Gaussian distributed values; `sparse_format` can be `"csr"` (default) or
`None` (in which ca... | Make some random data with uniformly located non zero entries with
Gaussian distributed values; `sparse_format` can be `"csr"` (default) or
`None` (in which case a dense array is returned).
| make_sparse_random_data | python | scikit-learn/scikit-learn | sklearn/tests/test_random_projection.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_random_projection.py | BSD-3-Clause |
def _compute_missing_values_in_feature_mask(self, X, estimator_name=None):
"""Return boolean mask denoting if there are missing values for each feature.
This method also ensures that X is finite.
Parameter
---------
X : array-like of shape (n_samples, n_features), dtype=DOUBLE
... | Return boolean mask denoting if there are missing values for each feature.
This method also ensures that X is finite.
Parameter
---------
X : array-like of shape (n_samples, n_features), dtype=DOUBLE
Input data.
estimator_name : str or None, default=None
... | _compute_missing_values_in_feature_mask | python | scikit-learn/scikit-learn | sklearn/tree/_classes.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/_classes.py | BSD-3-Clause |
def _validate_X_predict(self, X, check_input):
"""Validate the training data on predict (probabilities)."""
if check_input:
if self._support_missing_values(X):
ensure_all_finite = "allow-nan"
else:
ensure_all_finite = True
X = validate_... | Validate the training data on predict (probabilities). | _validate_X_predict | python | scikit-learn/scikit-learn | sklearn/tree/_classes.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/_classes.py | BSD-3-Clause |
def predict(self, X, check_input=True):
"""Predict class or regression value for X.
For a classification model, the predicted class for each sample in X is
returned. For a regression model, the predicted value based on X is
returned.
Parameters
----------
X : {a... | Predict class or regression value for X.
For a classification model, the predicted class for each sample in X is
returned. For a regression model, the predicted value based on X is
returned.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_fe... | predict | python | scikit-learn/scikit-learn | sklearn/tree/_classes.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/_classes.py | BSD-3-Clause |
def apply(self, X, check_input=True):
"""Return the index of the leaf that each sample is predicted as.
.. versionadded:: 0.17
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted ... | Return the index of the leaf that each sample is predicted as.
.. versionadded:: 0.17
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to
``dtype=np.float32`` and if a spar... | apply | python | scikit-learn/scikit-learn | sklearn/tree/_classes.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/_classes.py | BSD-3-Clause |
def _prune_tree(self):
"""Prune tree using Minimal Cost-Complexity Pruning."""
check_is_fitted(self)
if self.ccp_alpha == 0.0:
return
# build pruned tree
if is_classifier(self):
n_classes = np.atleast_1d(self.n_classes_)
pruned_tree = Tree(se... | Prune tree using Minimal Cost-Complexity Pruning. | _prune_tree | python | scikit-learn/scikit-learn | sklearn/tree/_classes.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/_classes.py | BSD-3-Clause |
def cost_complexity_pruning_path(self, X, y, sample_weight=None):
"""Compute the pruning path during Minimal Cost-Complexity Pruning.
See :ref:`minimal_cost_complexity_pruning` for details on the pruning
process.
Parameters
----------
X : {array-like, sparse matrix} of ... | Compute the pruning path during Minimal Cost-Complexity Pruning.
See :ref:`minimal_cost_complexity_pruning` for details on the pruning
process.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Interna... | cost_complexity_pruning_path | python | scikit-learn/scikit-learn | sklearn/tree/_classes.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/_classes.py | BSD-3-Clause |
def fit(self, X, y, sample_weight=None, check_input=True):
"""Build a decision tree classifier from the training set (X, y).
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Internally, it will be converted to... | Build a decision tree classifier from the training set (X, y).
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Internally, it will be converted to
``dtype=np.float32`` and if a sparse matrix is provided
... | fit | python | scikit-learn/scikit-learn | sklearn/tree/_classes.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/_classes.py | BSD-3-Clause |
def predict_proba(self, X, check_input=True):
"""Predict class probabilities of the input samples X.
The predicted class probability is the fraction of samples of the same
class in a leaf.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_feat... | Predict class probabilities of the input samples X.
The predicted class probability is the fraction of samples of the same
class in a leaf.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will ... | predict_proba | python | scikit-learn/scikit-learn | sklearn/tree/_classes.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/_classes.py | BSD-3-Clause |
def predict_log_proba(self, X):
"""Predict class log-probabilities of the input samples X.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to
``dtype=np.float32`` and if a ... | Predict class log-probabilities of the input samples X.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to
``dtype=np.float32`` and if a sparse matrix is provided
to a ... | predict_log_proba | python | scikit-learn/scikit-learn | sklearn/tree/_classes.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/_classes.py | BSD-3-Clause |
def fit(self, X, y, sample_weight=None, check_input=True):
"""Build a decision tree regressor from the training set (X, y).
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Internally, it will be converted to
... | Build a decision tree regressor from the training set (X, y).
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Internally, it will be converted to
``dtype=np.float32`` and if a sparse matrix is provided
... | fit | python | scikit-learn/scikit-learn | sklearn/tree/_classes.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/_classes.py | BSD-3-Clause |
def _compute_partial_dependence_recursion(self, grid, target_features):
"""Fast partial dependence computation.
Parameters
----------
grid : ndarray of shape (n_samples, n_target_features), dtype=np.float32
The grid points on which the partial dependence should be
... | Fast partial dependence computation.
Parameters
----------
grid : ndarray of shape (n_samples, n_target_features), dtype=np.float32
The grid points on which the partial dependence should be
evaluated.
target_features : ndarray of shape (n_target_features), dtype=... | _compute_partial_dependence_recursion | python | scikit-learn/scikit-learn | sklearn/tree/_classes.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/_classes.py | BSD-3-Clause |
def _color_brew(n):
"""Generate n colors with equally spaced hues.
Parameters
----------
n : int
The number of colors required.
Returns
-------
color_list : list, length n
List of n tuples of form (R, G, B) being the components of each color.
"""
color_list = []
... | Generate n colors with equally spaced hues.
Parameters
----------
n : int
The number of colors required.
Returns
-------
color_list : list, length n
List of n tuples of form (R, G, B) being the components of each color.
| _color_brew | python | scikit-learn/scikit-learn | sklearn/tree/_export.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/_export.py | BSD-3-Clause |
def _compute_depth(tree, node):
"""
Returns the depth of the subtree rooted in node.
"""
def compute_depth_(
current_node, current_depth, children_left, children_right, depths
):
depths += [current_depth]
left = children_left[current_node]
right = children_right[curr... |
Returns the depth of the subtree rooted in node.
| _compute_depth | python | scikit-learn/scikit-learn | sklearn/tree/_export.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/_export.py | BSD-3-Clause |
def export_text(
decision_tree,
*,
feature_names=None,
class_names=None,
max_depth=10,
spacing=3,
decimals=2,
show_weights=False,
):
"""Build a text report showing the rules of a decision tree.
Note that backwards compatibility may not be supported.
Parameters
---------... | Build a text report showing the rules of a decision tree.
Note that backwards compatibility may not be supported.
Parameters
----------
decision_tree : object
The decision tree estimator to be exported.
It can be an instance of
DecisionTreeClassifier or DecisionTreeRegressor.
... | export_text | python | scikit-learn/scikit-learn | sklearn/tree/_export.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/_export.py | BSD-3-Clause |
def check_min_weight_fraction_leaf(name, datasets, sparse_container=None):
"""Test if leaves contain at least min_weight_fraction_leaf of the
training set"""
X = DATASETS[datasets]["X"].astype(np.float32)
if sparse_container is not None:
X = sparse_container(X)
y = DATASETS[datasets]["y"]
... | Test if leaves contain at least min_weight_fraction_leaf of the
training set | check_min_weight_fraction_leaf | python | scikit-learn/scikit-learn | sklearn/tree/tests/test_tree.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/tests/test_tree.py | BSD-3-Clause |
def check_min_weight_fraction_leaf_with_min_samples_leaf(
name, datasets, sparse_container=None
):
"""Test the interaction between min_weight_fraction_leaf and
min_samples_leaf when sample_weights is not provided in fit."""
X = DATASETS[datasets]["X"].astype(np.float32)
if sparse_container is not No... | Test the interaction between min_weight_fraction_leaf and
min_samples_leaf when sample_weights is not provided in fit. | check_min_weight_fraction_leaf_with_min_samples_leaf | python | scikit-learn/scikit-learn | sklearn/tree/tests/test_tree.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/tests/test_tree.py | BSD-3-Clause |
def test_pickle():
"""Test pickling preserves Tree properties and performance."""
for name, TreeEstimator in ALL_TREES.items():
if "Classifier" in name:
X, y = iris.data, iris.target
else:
X, y = diabetes.data, diabetes.target
est = TreeEstimator(random_state=0)
... | Test pickling preserves Tree properties and performance. | test_pickle | python | scikit-learn/scikit-learn | sklearn/tree/tests/test_tree.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/tests/test_tree.py | BSD-3-Clause |
def test_mae():
"""Check MAE criterion produces correct results on small toy dataset:
------------------
| X | y | weight |
------------------
| 3 | 3 | 0.1 |
| 5 | 3 | 0.3 |
| 8 | 4 | 1.0 |
| 3 | 6 | 0.6 |
| 5 | 7 | 0.3 |
------------------
|sum wt:| 2.3 |... | Check MAE criterion produces correct results on small toy dataset:
------------------
| X | y | weight |
------------------
| 3 | 3 | 0.1 |
| 5 | 3 | 0.3 |
| 8 | 4 | 1.0 |
| 3 | 6 | 0.6 |
| 5 | 7 | 0.3 |
------------------
|sum wt:| 2.3 |
------------------... | test_mae | python | scikit-learn/scikit-learn | sklearn/tree/tests/test_tree.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/tests/test_tree.py | BSD-3-Clause |
def test_criterion_entropy_same_as_log_loss(Tree, n_classes):
"""Test that criterion=entropy gives same as log_loss."""
n_samples, n_features = 50, 5
X, y = datasets.make_classification(
n_classes=n_classes,
n_samples=n_samples,
n_features=n_features,
n_informative=n_features... | Test that criterion=entropy gives same as log_loss. | test_criterion_entropy_same_as_log_loss | python | scikit-learn/scikit-learn | sklearn/tree/tests/test_tree.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/tests/test_tree.py | BSD-3-Clause |
def test_tree_deserialization_from_read_only_buffer(tmpdir):
"""Check that Trees can be deserialized with read only buffers.
Non-regression test for gh-25584.
"""
pickle_path = str(tmpdir.join("clf.joblib"))
clf = DecisionTreeClassifier(random_state=0)
clf.fit(X_small, y_small)
joblib.dump... | Check that Trees can be deserialized with read only buffers.
Non-regression test for gh-25584.
| test_tree_deserialization_from_read_only_buffer | python | scikit-learn/scikit-learn | sklearn/tree/tests/test_tree.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/tests/test_tree.py | BSD-3-Clause |
def test_min_sample_split_1_error(Tree):
"""Check that an error is raised when min_sample_split=1.
non-regression test for issue gh-25481.
"""
X = np.array([[0, 0], [1, 1]])
y = np.array([0, 1])
# min_samples_split=1.0 is valid
Tree(min_samples_split=1.0).fit(X, y)
# min_samples_split... | Check that an error is raised when min_sample_split=1.
non-regression test for issue gh-25481.
| test_min_sample_split_1_error | python | scikit-learn/scikit-learn | sklearn/tree/tests/test_tree.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/tests/test_tree.py | BSD-3-Clause |
def test_missing_values_best_splitter_on_equal_nodes_no_missing(criterion):
"""Check missing values goes to correct node during predictions."""
X = np.array([[0, 1, 2, 3, 8, 9, 11, 12, 15]]).T
y = np.array([0.1, 0.2, 0.3, 0.2, 1.4, 1.4, 1.5, 1.6, 2.6])
dtc = DecisionTreeRegressor(random_state=42, max_d... | Check missing values goes to correct node during predictions. | test_missing_values_best_splitter_on_equal_nodes_no_missing | python | scikit-learn/scikit-learn | sklearn/tree/tests/test_tree.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/tests/test_tree.py | BSD-3-Clause |
def test_missing_values_random_splitter_on_equal_nodes_no_missing(criterion, seed):
"""Check missing values go to the correct node during predictions for ExtraTree.
Since ETC use random splits, we use different seeds to verify that the
left/right node is chosen correctly when the splits occur.
"""
... | Check missing values go to the correct node during predictions for ExtraTree.
Since ETC use random splits, we use different seeds to verify that the
left/right node is chosen correctly when the splits occur.
| test_missing_values_random_splitter_on_equal_nodes_no_missing | python | scikit-learn/scikit-learn | sklearn/tree/tests/test_tree.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/tests/test_tree.py | BSD-3-Clause |
def test_missing_values_best_splitter_three_classes(criterion):
"""Test when missing values are uniquely present in a class among 3 classes."""
missing_values_class = 0
X = np.array([[np.nan] * 4 + [0, 1, 2, 3, 8, 9, 11, 12]]).T
y = np.array([missing_values_class] * 4 + [1] * 4 + [2] * 4)
dtc = Deci... | Test when missing values are uniquely present in a class among 3 classes. | test_missing_values_best_splitter_three_classes | python | scikit-learn/scikit-learn | sklearn/tree/tests/test_tree.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/tests/test_tree.py | BSD-3-Clause |
def test_missing_values_best_splitter_to_left(criterion):
"""Missing values spanning only one class at fit-time must make missing
values at predict-time be classified has belonging to this class."""
X = np.array([[np.nan] * 4 + [0, 1, 2, 3, 4, 5]]).T
y = np.array([0] * 4 + [1] * 6)
dtc = DecisionTr... | Missing values spanning only one class at fit-time must make missing
values at predict-time be classified has belonging to this class. | test_missing_values_best_splitter_to_left | python | scikit-learn/scikit-learn | sklearn/tree/tests/test_tree.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/tests/test_tree.py | BSD-3-Clause |
def test_missing_values_best_splitter_to_right(criterion):
"""Missing values and non-missing values sharing one class at fit-time
must make missing values at predict-time be classified has belonging
to this class."""
X = np.array([[np.nan] * 4 + [0, 1, 2, 3, 4, 5]]).T
y = np.array([1] * 4 + [0] * 4 ... | Missing values and non-missing values sharing one class at fit-time
must make missing values at predict-time be classified has belonging
to this class. | test_missing_values_best_splitter_to_right | python | scikit-learn/scikit-learn | sklearn/tree/tests/test_tree.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/tests/test_tree.py | BSD-3-Clause |
def test_missing_values_best_splitter_missing_both_classes_has_nan(criterion):
"""Check behavior of missing value when there is one missing value in each class."""
X = np.array([[1, 2, 3, 5, np.nan, 10, 20, 30, 60, np.nan]]).T
y = np.array([0] * 5 + [1] * 5)
dtc = DecisionTreeClassifier(random_state=42... | Check behavior of missing value when there is one missing value in each class. | test_missing_values_best_splitter_missing_both_classes_has_nan | python | scikit-learn/scikit-learn | sklearn/tree/tests/test_tree.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/tests/test_tree.py | BSD-3-Clause |
def test_missing_value_errors(sparse_container, tree):
"""Check unsupported configurations for missing values."""
X = np.array([[1, 2, 3, 5, np.nan, 10, 20, 30, 60, np.nan]]).T
y = np.array([0] * 5 + [1] * 5)
if sparse_container is not None:
X = sparse_container(X)
with pytest.raises(Valu... | Check unsupported configurations for missing values. | test_missing_value_errors | python | scikit-learn/scikit-learn | sklearn/tree/tests/test_tree.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/tests/test_tree.py | BSD-3-Clause |
def test_missing_values_poisson(Tree):
"""Smoke test for poisson regression and missing values."""
X, y = diabetes.data.copy(), diabetes.target
# Set some values missing
X[::5, 0] = np.nan
X[::6, -1] = np.nan
reg = Tree(criterion="poisson", random_state=42)
reg.fit(X, y)
y_pred = reg.... | Smoke test for poisson regression and missing values. | test_missing_values_poisson | python | scikit-learn/scikit-learn | sklearn/tree/tests/test_tree.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/tests/test_tree.py | BSD-3-Clause |
def test_missing_values_is_resilience(
make_data, Tree, sample_weight_train, global_random_seed, tolerance
):
"""Check that trees can deal with missing values have decent performance."""
n_samples, n_features = 5_000, 10
X, y = make_data(
n_samples=n_samples,
n_features=n_features,
... | Check that trees can deal with missing values have decent performance. | test_missing_values_is_resilience | python | scikit-learn/scikit-learn | sklearn/tree/tests/test_tree.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/tests/test_tree.py | BSD-3-Clause |
def test_missing_value_is_predictive(Tree, expected_score, global_random_seed):
"""Check the tree learns when only the missing value is predictive."""
rng = np.random.RandomState(0)
n_samples = 500
X = rng.standard_normal(size=(n_samples, 20))
y = np.concatenate([np.zeros(n_samples // 2), np.ones(n... | Check the tree learns when only the missing value is predictive. | test_missing_value_is_predictive | python | scikit-learn/scikit-learn | sklearn/tree/tests/test_tree.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/tests/test_tree.py | BSD-3-Clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.