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_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_routing_passed_metadata_not_supported(method): """Test that the right error message is raised when metadata is passed while not supported when `enable_metadata_routing=False`.""" pipe = Pipeline([("estimator", SimpleEstimator())]) with pytest.raises( ValueError, match="is only support...
Test that the right error message is raised when metadata is passed while not supported when `enable_metadata_routing=False`.
test_routing_passed_metadata_not_supported
python
scikit-learn/scikit-learn
sklearn/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_error(): """Test that the right error is raised when metadata is not requested.""" X = np.array([[0, 1], [2, 2], [4, 6]]) y = [1, 2, 3] sample_weight, metadata = [1, 1, 1], "a" # test lacking set_fit_request feature_union = FeatureUnion([("sub_transformer...
Test that the right error is raised when metadata is not requested.
test_feature_union_metadata_routing_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_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
def test_sample_weight_non_uniform(make_data, Tree): """Check sample weight is correctly handled with missing values.""" rng = np.random.RandomState(0) n_samples, n_features = 1000, 10 X, y = make_data(n_samples=n_samples, n_features=n_features, random_state=rng) # Create dataset with missing value...
Check sample weight is correctly handled with missing values.
test_sample_weight_non_uniform
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_regression_tree_missing_values_toy(Tree, X, criterion): """Check that we properly handle missing values in regression trees using a toy dataset. The regression targeted by this test was that we were not reinitializing the criterion when it comes to the number of missing values. Therefore, the ...
Check that we properly handle missing values in regression trees using a toy dataset. The regression targeted by this test was that we were not reinitializing the criterion when it comes to the number of missing values. Therefore, the value of the critetion (i.e. MSE) was completely wrong. This te...
test_regression_tree_missing_values_toy
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_classification_tree_missing_values_toy(): """Check that we properly handle missing values in classification trees using a toy dataset. The test is more involved because we use a case where we detected a regression in a random forest. We therefore define the seed and bootstrap indices to detect...
Check that we properly handle missing values in classification trees using a toy dataset. The test is more involved because we use a case where we detected a regression in a random forest. We therefore define the seed and bootstrap indices to detect one of the non-frequent regression. Here, we che...
test_classification_tree_missing_values_toy
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_build_pruned_tree_py(): """Test pruning a tree with the Python caller of the Cythonized prune tree.""" tree = DecisionTreeClassifier(random_state=0, max_depth=1) tree.fit(iris.data, iris.target) n_classes = np.atleast_1d(tree.n_classes_) pruned_tree = CythonTree(tree.n_features_in_, n_clas...
Test pruning a tree with the Python caller of the Cythonized prune tree.
test_build_pruned_tree_py
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_build_pruned_tree_infinite_loop(): """Test pruning a tree does not result in an infinite loop.""" # Create a tree with root and two children tree = DecisionTreeClassifier(random_state=0, max_depth=1) tree.fit(iris.data, iris.target) n_classes = np.atleast_1d(tree.n_classes_) pruned_tre...
Test pruning a tree does not result in an infinite loop.
test_build_pruned_tree_infinite_loop
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_sort_log2_build(): """Non-regression test for gh-30554. Using log2 and log in sort correctly sorts feature_values, but the tie breaking is different which can results in placing samples in a different order. """ rng = np.random.default_rng(75) some = rng.normal(loc=0.0, scale=10.0, siz...
Non-regression test for gh-30554. Using log2 and log in sort correctly sorts feature_values, but the tie breaking is different which can results in placing samples in a different order.
test_sort_log2_build
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 compute_class_weight(class_weight, *, classes, y, sample_weight=None): """Estimate class weights for unbalanced datasets. Parameters ---------- class_weight : dict, "balanced" or None If "balanced", class weights will be given by `n_samples / (n_classes * np.bincount(y))` or their w...
Estimate class weights for unbalanced datasets. Parameters ---------- class_weight : dict, "balanced" or None If "balanced", class weights will be given by `n_samples / (n_classes * np.bincount(y))` or their weighted equivalent if `sample_weight` is provided. If a dictionary...
compute_class_weight
python
scikit-learn/scikit-learn
sklearn/utils/class_weight.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/class_weight.py
BSD-3-Clause
def compute_sample_weight(class_weight, y, *, indices=None): """Estimate sample weights by class for unbalanced datasets. Parameters ---------- class_weight : dict, list of dicts, "balanced", or None Weights associated with classes in the form `{class_label: weight}`. If not given, all ...
Estimate sample weights by class for unbalanced datasets. Parameters ---------- class_weight : dict, list of dicts, "balanced", or None Weights associated with classes in the form `{class_label: weight}`. If not given, all classes are supposed to have weight one. For multi-output pr...
compute_sample_weight
python
scikit-learn/scikit-learn
sklearn/utils/class_weight.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/class_weight.py
BSD-3-Clause
def _is_deprecated(func): """Helper to check if func is wrapped by our deprecated decorator""" closures = getattr(func, "__closure__", []) if closures is None: closures = [] is_deprecated = "deprecated" in "".join( [c.cell_contents for c in closures if isinstance(c.cell_contents, str)] ...
Helper to check if func is wrapped by our deprecated decorator
_is_deprecated
python
scikit-learn/scikit-learn
sklearn/utils/deprecation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/deprecation.py
BSD-3-Clause
def _deprecate_force_all_finite(force_all_finite, ensure_all_finite): """Helper to deprecate force_all_finite in favor of ensure_all_finite.""" if force_all_finite != "deprecated": warnings.warn( "'force_all_finite' was renamed to 'ensure_all_finite' in 1.6 and will be " "removed...
Helper to deprecate force_all_finite in favor of ensure_all_finite.
_deprecate_force_all_finite
python
scikit-learn/scikit-learn
sklearn/utils/deprecation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/deprecation.py
BSD-3-Clause
def all_estimators(type_filter=None): """Get a list of all estimators from `sklearn`. This function crawls the module and gets all classes that inherit from BaseEstimator. Classes that are defined in test-modules are not included. Parameters ---------- type_filter : {"classifier", "regress...
Get a list of all estimators from `sklearn`. This function crawls the module and gets all classes that inherit from BaseEstimator. Classes that are defined in test-modules are not included. Parameters ---------- type_filter : {"classifier", "regressor", "cluster", "transformer"} or...
all_estimators
python
scikit-learn/scikit-learn
sklearn/utils/discovery.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/discovery.py
BSD-3-Clause
def all_displays(): """Get a list of all displays from `sklearn`. Returns ------- displays : list of tuples List of (name, class), where ``name`` is the display class name as string and ``class`` is the actual type of the class. Examples -------- >>> from sklearn.utils.disc...
Get a list of all displays from `sklearn`. Returns ------- displays : list of tuples List of (name, class), where ``name`` is the display class name as string and ``class`` is the actual type of the class. Examples -------- >>> from sklearn.utils.discovery import all_displays ...
all_displays
python
scikit-learn/scikit-learn
sklearn/utils/discovery.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/discovery.py
BSD-3-Clause
def all_functions(): """Get a list of all functions from `sklearn`. Returns ------- functions : list of tuples List of (name, function), where ``name`` is the function name as string and ``function`` is the actual function. Examples -------- >>> from sklearn.utils.discovery...
Get a list of all functions from `sklearn`. Returns ------- functions : list of tuples List of (name, function), where ``name`` is the function name as string and ``function`` is the actual function. Examples -------- >>> from sklearn.utils.discovery import all_functions >>...
all_functions
python
scikit-learn/scikit-learn
sklearn/utils/discovery.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/discovery.py
BSD-3-Clause
def _maybe_mark( estimator, check, expected_failed_checks: dict[str, str] | None = None, mark: Literal["xfail", "skip", None] = None, pytest=None, ): """Mark the test as xfail or skip if needed. Parameters ---------- estimator : estimator object Estimator instance for which ...
Mark the test as xfail or skip if needed. Parameters ---------- estimator : estimator object Estimator instance for which to generate checks. check : partial or callable Check to be marked. expected_failed_checks : dict[str, str], default=None Dictionary of the form {check_n...
_maybe_mark
python
scikit-learn/scikit-learn
sklearn/utils/estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/estimator_checks.py
BSD-3-Clause
def _should_be_skipped_or_marked( estimator, check, expected_failed_checks: dict[str, str] | None = None ) -> tuple[bool, str]: """Check whether a check should be skipped or marked as xfail. Parameters ---------- estimator : estimator object Estimator instance for which to generate checks. ...
Check whether a check should be skipped or marked as xfail. Parameters ---------- estimator : estimator object Estimator instance for which to generate checks. check : partial or callable Check to be marked. expected_failed_checks : dict[str, str], default=None Dictionary of...
_should_be_skipped_or_marked
python
scikit-learn/scikit-learn
sklearn/utils/estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/estimator_checks.py
BSD-3-Clause
def estimator_checks_generator( estimator, *, legacy: bool = True, expected_failed_checks: dict[str, str] | None = None, mark: Literal["xfail", "skip", None] = None, ): """Iteratively yield all check callables for an estimator. .. versionadded:: 1.6 Parameters ---------- estima...
Iteratively yield all check callables for an estimator. .. versionadded:: 1.6 Parameters ---------- estimator : estimator object Estimator instance for which to generate checks. legacy : bool, default=True Whether to include legacy checks. Over time we remove checks from this categ...
estimator_checks_generator
python
scikit-learn/scikit-learn
sklearn/utils/estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/estimator_checks.py
BSD-3-Clause
def parametrize_with_checks( estimators, *, legacy: bool = True, expected_failed_checks: Callable | None = None, ): """Pytest specific decorator for parametrizing estimator checks. Checks are categorised into the following groups: - API checks: a set of checks to ensure API compatibility w...
Pytest specific decorator for parametrizing estimator checks. Checks are categorised into the following groups: - API checks: a set of checks to ensure API compatibility with scikit-learn. Refer to https://scikit-learn.org/dev/developers/develop.html a requirement of scikit-learn estimators. -...
parametrize_with_checks
python
scikit-learn/scikit-learn
sklearn/utils/estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/estimator_checks.py
BSD-3-Clause
def check_estimator( estimator=None, generate_only=False, *, legacy: bool = True, expected_failed_checks: dict[str, str] | None = None, on_skip: Literal["warn"] | None = "warn", on_fail: Literal["raise", "warn"] | None = "raise", callback: Callable | None = None, ): """Check if estim...
Check if estimator adheres to scikit-learn conventions. This function will run an extensive test-suite for input validation, shapes, etc, making sure that the estimator complies with `scikit-learn` conventions as detailed in :ref:`rolling_your_own_estimator`. Additional tests for classifiers, regressor...
check_estimator
python
scikit-learn/scikit-learn
sklearn/utils/estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/estimator_checks.py
BSD-3-Clause
def _is_pairwise_metric(estimator): """Returns True if estimator accepts pairwise metric. Parameters ---------- estimator : object Estimator object to test. Returns ------- out : bool True if _pairwise is set to True and False otherwise. """ metric = getattr(estimat...
Returns True if estimator accepts pairwise metric. Parameters ---------- estimator : object Estimator object to test. Returns ------- out : bool True if _pairwise is set to True and False otherwise.
_is_pairwise_metric
python
scikit-learn/scikit-learn
sklearn/utils/estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/estimator_checks.py
BSD-3-Clause
def _generate_sparse_data(X_csr): """Generate sparse matrices or arrays with {32,64}bit indices of diverse format. Parameters ---------- X_csr: scipy.sparse.csr_matrix or scipy.sparse.csr_array Input in CSR format. Returns ------- out: iter(Matrices) or iter(Arrays) In form...
Generate sparse matrices or arrays with {32,64}bit indices of diverse format. Parameters ---------- X_csr: scipy.sparse.csr_matrix or scipy.sparse.csr_array Input in CSR format. Returns ------- out: iter(Matrices) or iter(Arrays) In format['dok', 'lil', 'dia', 'bsr', 'csr', 'cs...
_generate_sparse_data
python
scikit-learn/scikit-learn
sklearn/utils/estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/estimator_checks.py
BSD-3-Clause
def check_array_api_input( name, estimator_orig, array_namespace, device=None, dtype_name="float64", check_values=False, ): """Check that the estimator can work consistently with the Array API By default, this just checks that the types and shapes of the arrays are consistent with c...
Check that the estimator can work consistently with the Array API By default, this just checks that the types and shapes of the arrays are consistent with calling the same estimator with numpy arrays. When check_values is True, it also checks that calling the estimator on the array_api Array gives the...
check_array_api_input
python
scikit-learn/scikit-learn
sklearn/utils/estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/estimator_checks.py
BSD-3-Clause
def check_estimator_sparse_tag(name, estimator_orig): """Check that estimator tag related with accepting sparse data is properly set.""" estimator = clone(estimator_orig) rng = np.random.RandomState(0) n_samples = 15 if name == "SpectralCoclustering" else 40 X = rng.uniform(size=(n_samples, 3)) ...
Check that estimator tag related with accepting sparse data is properly set.
check_estimator_sparse_tag
python
scikit-learn/scikit-learn
sklearn/utils/estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/estimator_checks.py
BSD-3-Clause
def check_transformers_unfitted_stateless(name, transformer): """Check that using transform without prior fitting doesn't raise a NotFittedError for stateless transformers. """ rng = np.random.RandomState(0) X = rng.uniform(size=(20, 5)) X = _enforce_estimator_tags_X(transformer, X) transfo...
Check that using transform without prior fitting doesn't raise a NotFittedError for stateless transformers.
check_transformers_unfitted_stateless
python
scikit-learn/scikit-learn
sklearn/utils/estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/estimator_checks.py
BSD-3-Clause
def check_mixin_order(name, estimator_orig): """Check that mixins are inherited in the correct order.""" # We define a list of edges, which in effect define a DAG of mixins and their # required order of inheritance. # This is of the form (mixin_a_should_be_before, mixin_b_should_be_after) dag = [ ...
Check that mixins are inherited in the correct order.
check_mixin_order
python
scikit-learn/scikit-learn
sklearn/utils/estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/estimator_checks.py
BSD-3-Clause
def check_nonsquare_error(name, estimator_orig): """Test that error is thrown when non-square data provided.""" X, y = make_blobs(n_samples=20, n_features=10) estimator = clone(estimator_orig) with raises( ValueError, err_msg=( f"The pairwise estimator {name} does not raise...
Test that error is thrown when non-square data provided.
check_nonsquare_error
python
scikit-learn/scikit-learn
sklearn/utils/estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/estimator_checks.py
BSD-3-Clause
def check_estimators_pickle(name, estimator_orig, readonly_memmap=False): """Test that we can pickle all estimators.""" check_methods = ["predict", "transform", "decision_function", "predict_proba"] X, y = make_blobs( n_samples=30, centers=[[0, 0, 0], [1, 1, 1]], random_state=0, ...
Test that we can pickle all estimators.
check_estimators_pickle
python
scikit-learn/scikit-learn
sklearn/utils/estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/estimator_checks.py
BSD-3-Clause