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_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 |
def check_clusterer_compute_labels_predict(name, clusterer_orig):
"""Check that predict is invariant of compute_labels."""
X, y = make_blobs(n_samples=20, random_state=0)
clusterer = clone(clusterer_orig)
set_random_state(clusterer)
if hasattr(clusterer, "compute_labels"):
# MiniBatchKMeans... | Check that predict is invariant of compute_labels. | check_clusterer_compute_labels_predict | 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_classifiers_one_label_sample_weights(name, classifier_orig):
"""Check that classifiers accepting sample_weight fit or throws a ValueError with
an explicit message if the problem is reduced to one class.
"""
error_fit = (
f"{name} failed when fitted on one label after sample_weight trim... | Check that classifiers accepting sample_weight fit or throws a ValueError with
an explicit message if the problem is reduced to one class.
| check_classifiers_one_label_sample_weights | 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_classifiers_multilabel_output_format_predict(name, classifier_orig):
"""Check the output of the `predict` method for classifiers supporting
multilabel-indicator targets."""
classifier = clone(classifier_orig)
set_random_state(classifier)
n_samples, test_size, n_outputs = 100, 25, 5
X,... | Check the output of the `predict` method for classifiers supporting
multilabel-indicator targets. | check_classifiers_multilabel_output_format_predict | 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_classifiers_multilabel_output_format_predict_proba(name, classifier_orig):
"""Check the output of the `predict_proba` method for classifiers supporting
multilabel-indicator targets."""
classifier = clone(classifier_orig)
set_random_state(classifier)
n_samples, test_size, n_outputs = 100, ... | Check the output of the `predict_proba` method for classifiers supporting
multilabel-indicator targets. | check_classifiers_multilabel_output_format_predict_proba | 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_classifiers_multilabel_output_format_decision_function(name, classifier_orig):
"""Check the output of the `decision_function` method for classifiers supporting
multilabel-indicator targets."""
classifier = clone(classifier_orig)
set_random_state(classifier)
n_samples, test_size, n_outputs... | Check the output of the `decision_function` method for classifiers supporting
multilabel-indicator targets. | check_classifiers_multilabel_output_format_decision_function | 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_get_feature_names_out_error(name, estimator_orig):
"""Check the error raised by get_feature_names_out when called before fit.
Unfitted estimators with get_feature_names_out should raise a NotFittedError.
"""
estimator = clone(estimator_orig)
err_msg = (
f"Estimator {name} should ... | Check the error raised by get_feature_names_out when called before fit.
Unfitted estimators with get_feature_names_out should raise a NotFittedError.
| check_get_feature_names_out_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_fit_returns_self(name, estimator_orig):
"""Check if self is returned when calling fit."""
X, y = make_blobs(random_state=0, n_samples=21)
X = _enforce_estimator_tags_X(estimator_orig, X)
estimator = clone(estimator_orig)
y = _enforce_estimator_tags_y(estimator, y)
set_rand... | Check if self is returned when calling fit. | check_estimators_fit_returns_self | 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_readonly_memmap_input(name, estimator_orig):
"""Check that the estimator can handle readonly memmap backed data.
This is particularly needed to support joblib parallelisation.
"""
X, y = make_blobs(random_state=0, n_samples=21)
X = _enforce_estimator_tags_X(estimator_orig, X)
estimat... | Check that the estimator can handle readonly memmap backed data.
This is particularly needed to support joblib parallelisation.
| check_readonly_memmap_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_estimators_unfitted(name, estimator_orig):
"""Check that predict raises an exception in an unfitted estimator.
Unfitted estimators should raise a NotFittedError.
"""
err_msg = (
"Estimator should raise a NotFittedError when calling `{method}` before fit. "
"Either call `check_... | Check that predict raises an exception in an unfitted estimator.
Unfitted estimators should raise a NotFittedError.
| check_estimators_unfitted | 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_class_weight_balanced_linear_classifier(name, estimator_orig):
"""Test class weights with non-contiguous class labels."""
# this is run on classes, not instances, though this should be changed
X = np.array([[-1.0, -1.0], [-1.0, 0], [-0.8, -1.0], [1.0, 1.0], [1.0, 0.0]])
y = np.array([1, 1, 1, ... | Test class weights with non-contiguous class labels. | check_class_weight_balanced_linear_classifier | 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_cloneable(name, estimator_orig):
"""Checks whether the estimator can be cloned."""
try:
clone(estimator_orig)
except Exception as e:
raise AssertionError(f"Cloning of {name} failed with error: {e}.") from e | Checks whether the estimator can be cloned. | check_estimator_cloneable | 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_repr(name, estimator_orig):
"""Check that the estimator has a functioning repr."""
estimator = clone(estimator_orig)
try:
repr(estimator)
except Exception as e:
raise AssertionError(f"Repr of {name} failed with error: {e}.") from e | Check that the estimator has a functioning repr. | check_estimator_repr | 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 param_default_value(p):
"""Identify hyper parameters of an estimator."""
return (
p.name != "self"
and p.kind != p.VAR_KEYWORD
and p.kind != p.VAR_POSITIONAL
# and it should have a default value for this ... | Identify hyper parameters of an estimator. | param_default_value | 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_positive_only_tag_during_fit(name, estimator_orig):
"""Test that the estimator correctly sets the tags.input_tags.positive_only
If the tag is False, the estimator should accept negative input regardless of the
tags.input_tags.pairwise flag.
"""
estimator = clone(estimator_orig)
tags =... | Test that the estimator correctly sets the tags.input_tags.positive_only
If the tag is False, the estimator should accept negative input regardless of the
tags.input_tags.pairwise flag.
| check_positive_only_tag_during_fit | 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_valid_tag_types(name, estimator):
"""Check that estimator tags are valid."""
assert hasattr(estimator, "__sklearn_tags__"), (
f"Estimator {name} does not have `__sklearn_tags__` method. This method is"
" implemented in BaseEstimator and returns a sklearn.utils.Tags instance."
)
... | Check that estimator tags are valid. | check_valid_tag_types | 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 _output_from_fit_transform(transformer, name, X, df, y):
"""Generate output to test `set_output` for different configuration:
- calling either `fit.transform` or `fit_transform`;
- passing either a dataframe or a numpy array to fit;
- passing either a dataframe or a numpy array to transform.
""... | Generate output to test `set_output` for different configuration:
- calling either `fit.transform` or `fit_transform`;
- passing either a dataframe or a numpy array to fit;
- passing either a dataframe or a numpy array to transform.
| _output_from_fit_transform | 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_generated_dataframe(
name,
case,
index,
outputs_default,
outputs_dataframe_lib,
is_supported_dataframe,
create_dataframe,
assert_frame_equal,
):
"""Check if the generated DataFrame by the transformer is valid.
The DataFrame implementation is specified through the para... | Check if the generated DataFrame by the transformer is valid.
The DataFrame implementation is specified through the parameters of this function.
Parameters
----------
name : str
The name of the transformer.
case : str
A single case from the cases generated by `_output_from_fit_tran... | _check_generated_dataframe | 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_set_output_transform_dataframe(
name,
transformer_orig,
*,
dataframe_lib,
is_supported_dataframe,
create_dataframe,
assert_frame_equal,
context,
):
"""Check that a transformer can output a DataFrame when requested.
The DataFrame implementation is specified through the... | Check that a transformer can output a DataFrame when requested.
The DataFrame implementation is specified through the parameters of this function.
Parameters
----------
name : str
The name of the transformer.
transformer_orig : estimator
The original transformer instance.
dataf... | _check_set_output_transform_dataframe | 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_inplace_ensure_writeable(name, estimator_orig):
"""Check that estimators able to do inplace operations can work on read-only
input data even if a copy is not explicitly requested by the user.
Make sure that a copy is made and consequently that the input array and its
writeability are not modi... | Check that estimators able to do inplace operations can work on read-only
input data even if a copy is not explicitly requested by the user.
Make sure that a copy is made and consequently that the input array and its
writeability are not modified by the estimator.
| check_inplace_ensure_writeable | 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_do_not_raise_errors_in_init_or_set_params(name, estimator_orig):
"""Check that init or set_param does not raise errors."""
Estimator = type(estimator_orig)
params = signature(Estimator).parameters
smoke_test_values = [-1, 3.0, "helloworld", np.array([1.0, 4.0]), [1], {}, []]
for value in ... | Check that init or set_param does not raise errors. | check_do_not_raise_errors_in_init_or_set_params | 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_classifier_not_supporting_multiclass(name, estimator_orig):
"""Check that if the classifier has tags.classifier_tags.multi_class=False,
then it should raise a ValueError when calling fit with a multiclass dataset.
This test is not yielded if the tag is not False.
"""
estimator = clone(est... | Check that if the classifier has tags.classifier_tags.multi_class=False,
then it should raise a ValueError when calling fit with a multiclass dataset.
This test is not yielded if the tag is not False.
| check_classifier_not_supporting_multiclass | 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 squared_norm(x):
"""Squared Euclidean or Frobenius norm of x.
Faster than norm(x) ** 2.
Parameters
----------
x : array-like
The input array which could be either be a vector or a 2 dimensional array.
Returns
-------
float
The Euclidean norm when x is a vector, the... | Squared Euclidean or Frobenius norm of x.
Faster than norm(x) ** 2.
Parameters
----------
x : array-like
The input array which could be either be a vector or a 2 dimensional array.
Returns
-------
float
The Euclidean norm when x is a vector, the Frobenius norm when x
... | squared_norm | python | scikit-learn/scikit-learn | sklearn/utils/extmath.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py | BSD-3-Clause |
def row_norms(X, squared=False):
"""Row-wise (squared) Euclidean norm of X.
Equivalent to np.sqrt((X * X).sum(axis=1)), but also supports sparse
matrices and does not create an X.shape-sized temporary.
Performs no input validation.
Parameters
----------
X : array-like
The input ar... | Row-wise (squared) Euclidean norm of X.
Equivalent to np.sqrt((X * X).sum(axis=1)), but also supports sparse
matrices and does not create an X.shape-sized temporary.
Performs no input validation.
Parameters
----------
X : array-like
The input array.
squared : bool, default=False
... | row_norms | python | scikit-learn/scikit-learn | sklearn/utils/extmath.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py | BSD-3-Clause |
def fast_logdet(A):
"""Compute logarithm of determinant of a square matrix.
The (natural) logarithm of the determinant of a square matrix
is returned if det(A) is non-negative and well defined.
If the determinant is zero or negative returns -Inf.
Equivalent to : np.log(np.det(A)) but more robust.
... | Compute logarithm of determinant of a square matrix.
The (natural) logarithm of the determinant of a square matrix
is returned if det(A) is non-negative and well defined.
If the determinant is zero or negative returns -Inf.
Equivalent to : np.log(np.det(A)) but more robust.
Parameters
-------... | fast_logdet | python | scikit-learn/scikit-learn | sklearn/utils/extmath.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py | BSD-3-Clause |
def density(w):
"""Compute density of a sparse vector.
Parameters
----------
w : {ndarray, sparse matrix}
The input data can be numpy ndarray or a sparse matrix.
Returns
-------
float
The density of w, between 0 and 1.
Examples
--------
>>> from scipy import sp... | Compute density of a sparse vector.
Parameters
----------
w : {ndarray, sparse matrix}
The input data can be numpy ndarray or a sparse matrix.
Returns
-------
float
The density of w, between 0 and 1.
Examples
--------
>>> from scipy import sparse
>>> from sklea... | density | python | scikit-learn/scikit-learn | sklearn/utils/extmath.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py | BSD-3-Clause |
def safe_sparse_dot(a, b, *, dense_output=False):
"""Dot product that handle the sparse matrix case correctly.
Parameters
----------
a : {ndarray, sparse matrix}
b : {ndarray, sparse matrix}
dense_output : bool, default=False
When False, ``a`` and ``b`` both being sparse will yield spar... | Dot product that handle the sparse matrix case correctly.
Parameters
----------
a : {ndarray, sparse matrix}
b : {ndarray, sparse matrix}
dense_output : bool, default=False
When False, ``a`` and ``b`` both being sparse will yield sparse output.
When True, output will always be a den... | safe_sparse_dot | python | scikit-learn/scikit-learn | sklearn/utils/extmath.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py | BSD-3-Clause |
def randomized_range_finder(
A, *, size, n_iter, power_iteration_normalizer="auto", random_state=None
):
"""Compute an orthonormal matrix whose range approximates the range of A.
Parameters
----------
A : {array-like, sparse matrix} of shape (n_samples, n_features)
The input data matrix.
... | Compute an orthonormal matrix whose range approximates the range of A.
Parameters
----------
A : {array-like, sparse matrix} of shape (n_samples, n_features)
The input data matrix.
size : int
Size of the return array.
n_iter : int
Number of power iterations used to stabili... | randomized_range_finder | python | scikit-learn/scikit-learn | sklearn/utils/extmath.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py | BSD-3-Clause |
def randomized_svd(
M,
n_components,
*,
n_oversamples=10,
n_iter="auto",
power_iteration_normalizer="auto",
transpose="auto",
flip_sign=True,
random_state=None,
svd_lapack_driver="gesdd",
):
"""Compute a truncated randomized SVD.
This method solves the fixed-rank approxi... | Compute a truncated randomized SVD.
This method solves the fixed-rank approximation problem described in [1]_
(problem (1.5), p5).
Refer to
:ref:`sphx_glr_auto_examples_applications_wikipedia_principal_eigenvector.py`
for a typical example where the power iteration algorithm is used to rank web pa... | randomized_svd | python | scikit-learn/scikit-learn | sklearn/utils/extmath.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py | BSD-3-Clause |
def weighted_mode(a, w, *, axis=0):
"""Return an array of the weighted modal (most common) value in the passed array.
If there is more than one such value, only the first is returned.
The bin-count for the modal bins is also returned.
This is an extension of the algorithm in scipy.stats.mode.
Par... | Return an array of the weighted modal (most common) value in the passed array.
If there is more than one such value, only the first is returned.
The bin-count for the modal bins is also returned.
This is an extension of the algorithm in scipy.stats.mode.
Parameters
----------
a : array-like o... | weighted_mode | python | scikit-learn/scikit-learn | sklearn/utils/extmath.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py | BSD-3-Clause |
def cartesian(arrays, out=None):
"""Generate a cartesian product of input arrays.
Parameters
----------
arrays : list of array-like
1-D arrays to form the cartesian product of.
out : ndarray of shape (M, len(arrays)), default=None
Array to place the cartesian product in.
Return... | Generate a cartesian product of input arrays.
Parameters
----------
arrays : list of array-like
1-D arrays to form the cartesian product of.
out : ndarray of shape (M, len(arrays)), default=None
Array to place the cartesian product in.
Returns
-------
out : ndarray of shape... | cartesian | python | scikit-learn/scikit-learn | sklearn/utils/extmath.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py | BSD-3-Clause |
def svd_flip(u, v, u_based_decision=True):
"""Sign correction to ensure deterministic output from SVD.
Adjusts the columns of u and the rows of v such that the loadings in the
columns in u that are largest in absolute value are always positive.
If u_based_decision is False, then the same sign correcti... | Sign correction to ensure deterministic output from SVD.
Adjusts the columns of u and the rows of v such that the loadings in the
columns in u that are largest in absolute value are always positive.
If u_based_decision is False, then the same sign correction is applied to
so that the rows in v that ar... | svd_flip | python | scikit-learn/scikit-learn | sklearn/utils/extmath.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py | BSD-3-Clause |
def softmax(X, copy=True):
"""
Calculate the softmax function.
The softmax function is calculated by
np.exp(X) / np.sum(np.exp(X), axis=1)
This will cause overflow when large values are exponentiated.
Hence the largest value in each row is subtracted from each data
point to prevent this.
... |
Calculate the softmax function.
The softmax function is calculated by
np.exp(X) / np.sum(np.exp(X), axis=1)
This will cause overflow when large values are exponentiated.
Hence the largest value in each row is subtracted from each data
point to prevent this.
Parameters
----------
... | softmax | python | scikit-learn/scikit-learn | sklearn/utils/extmath.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py | BSD-3-Clause |
def make_nonnegative(X, min_value=0):
"""Ensure `X.min()` >= `min_value`.
Parameters
----------
X : array-like
The matrix to make non-negative.
min_value : float, default=0
The threshold value.
Returns
-------
array-like
The thresholded array.
Raises
--... | Ensure `X.min()` >= `min_value`.
Parameters
----------
X : array-like
The matrix to make non-negative.
min_value : float, default=0
The threshold value.
Returns
-------
array-like
The thresholded array.
Raises
------
ValueError
When X is sparse.... | make_nonnegative | python | scikit-learn/scikit-learn | sklearn/utils/extmath.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py | BSD-3-Clause |
def _safe_accumulator_op(op, x, *args, **kwargs):
"""
This function provides numpy accumulator functions with a float64 dtype
when used on a floating point input. This prevents accumulator overflow on
smaller floating point dtypes.
Parameters
----------
op : function
A numpy accumul... |
This function provides numpy accumulator functions with a float64 dtype
when used on a floating point input. This prevents accumulator overflow on
smaller floating point dtypes.
Parameters
----------
op : function
A numpy accumulator function such as np.mean or np.sum.
x : ndarray
... | _safe_accumulator_op | python | scikit-learn/scikit-learn | sklearn/utils/extmath.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py | BSD-3-Clause |
def _incremental_mean_and_var(
X, last_mean, last_variance, last_sample_count, sample_weight=None
):
"""Calculate mean update and a Youngs and Cramer variance update.
If sample_weight is given, the weighted mean and variance is computed.
Update a given mean and (possibly) variance according to new dat... | Calculate mean update and a Youngs and Cramer variance update.
If sample_weight is given, the weighted mean and variance is computed.
Update a given mean and (possibly) variance according to new data given
in X. last_mean is always required to compute the new mean.
If last_variance is None, no varianc... | _incremental_mean_and_var | python | scikit-learn/scikit-learn | sklearn/utils/extmath.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py | BSD-3-Clause |
def _deterministic_vector_sign_flip(u):
"""Modify the sign of vectors for reproducibility.
Flips the sign of elements of all the vectors (rows of u) such that
the absolute maximum element of each vector is positive.
Parameters
----------
u : ndarray
Array with vectors as its rows.
... | Modify the sign of vectors for reproducibility.
Flips the sign of elements of all the vectors (rows of u) such that
the absolute maximum element of each vector is positive.
Parameters
----------
u : ndarray
Array with vectors as its rows.
Returns
-------
u_flipped : ndarray wi... | _deterministic_vector_sign_flip | python | scikit-learn/scikit-learn | sklearn/utils/extmath.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py | BSD-3-Clause |
def stable_cumsum(arr, axis=None, rtol=1e-05, atol=1e-08):
"""Use high precision for cumsum and check that final value matches sum.
Warns if the final cumulative sum does not match the sum (up to the chosen
tolerance).
Parameters
----------
arr : array-like
To be cumulatively summed as... | Use high precision for cumsum and check that final value matches sum.
Warns if the final cumulative sum does not match the sum (up to the chosen
tolerance).
Parameters
----------
arr : array-like
To be cumulatively summed as flat.
axis : int, default=None
Axis along which the c... | stable_cumsum | python | scikit-learn/scikit-learn | sklearn/utils/extmath.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py | BSD-3-Clause |
def _nanaverage(a, weights=None):
"""Compute the weighted average, ignoring NaNs.
Parameters
----------
a : ndarray
Array containing data to be averaged.
weights : array-like, default=None
An array of weights associated with the values in a. Each value in a
contributes to th... | Compute the weighted average, ignoring NaNs.
Parameters
----------
a : ndarray
Array containing data to be averaged.
weights : array-like, default=None
An array of weights associated with the values in a. Each value in a
contributes to the average according to its associated wei... | _nanaverage | python | scikit-learn/scikit-learn | sklearn/utils/extmath.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py | BSD-3-Clause |
def safe_sqr(X, *, copy=True):
"""Element wise squaring of array-likes and sparse matrices.
Parameters
----------
X : {array-like, ndarray, sparse matrix}
copy : bool, default=True
Whether to create a copy of X and operate on it or to perform
inplace computation (default behaviour)... | Element wise squaring of array-likes and sparse matrices.
Parameters
----------
X : {array-like, ndarray, sparse matrix}
copy : bool, default=True
Whether to create a copy of X and operate on it or to perform
inplace computation (default behaviour).
Returns
-------
X ** 2 ... | safe_sqr | python | scikit-learn/scikit-learn | sklearn/utils/extmath.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py | BSD-3-Clause |
def _approximate_mode(class_counts, n_draws, rng):
"""Computes approximate mode of multivariate hypergeometric.
This is an approximation to the mode of the multivariate
hypergeometric given by class_counts and n_draws.
It shouldn't be off by more than one.
It is the mostly likely outcome of drawin... | Computes approximate mode of multivariate hypergeometric.
This is an approximation to the mode of the multivariate
hypergeometric given by class_counts and n_draws.
It shouldn't be off by more than one.
It is the mostly likely outcome of drawing n_draws many
samples from the population given by cl... | _approximate_mode | python | scikit-learn/scikit-learn | sklearn/utils/extmath.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py | BSD-3-Clause |
def _yeojohnson_lambda(_neg_log_likelihood, x):
"""Estimate the optimal Yeo-Johnson transformation parameter (lambda).
This function provides a compatibility workaround for versions of SciPy
older than 1.9.0, where `scipy.stats.yeojohnson` did not return
the estimated lambda directly.
Parameters
... | Estimate the optimal Yeo-Johnson transformation parameter (lambda).
This function provides a compatibility workaround for versions of SciPy
older than 1.9.0, where `scipy.stats.yeojohnson` did not return
the estimated lambda directly.
Parameters
----------
_neg_log_likelihood : callable
... | _yeojohnson_lambda | python | scikit-learn/scikit-learn | sklearn/utils/fixes.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/fixes.py | BSD-3-Clause |
def _preserve_dia_indices_dtype(
sparse_container, original_container_format, requested_sparse_format
):
"""Preserve indices dtype for SciPy < 1.12 when converting from DIA to CSR/CSC.
For SciPy < 1.12, DIA arrays indices are upcasted to `np.int64` that is
inconsistent with DIA matrices. We downcast th... | Preserve indices dtype for SciPy < 1.12 when converting from DIA to CSR/CSC.
For SciPy < 1.12, DIA arrays indices are upcasted to `np.int64` that is
inconsistent with DIA matrices. We downcast the indices dtype to `np.int32` to
be consistent with DIA matrices.
The converted indices arrays are affected... | _preserve_dia_indices_dtype | python | scikit-learn/scikit-learn | sklearn/utils/fixes.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/fixes.py | BSD-3-Clause |
def _smallest_admissible_index_dtype(arrays=(), maxval=None, check_contents=False):
"""Based on input (integer) arrays `a`, determine a suitable index data
type that can hold the data in the arrays.
This function returns `np.int64` if it either required by `maxval` or based on the
largest precision of ... | Based on input (integer) arrays `a`, determine a suitable index data
type that can hold the data in the arrays.
This function returns `np.int64` if it either required by `maxval` or based on the
largest precision of the dtype of the arrays passed as argument, or by their
contents (when `check_contents ... | _smallest_admissible_index_dtype | python | scikit-learn/scikit-learn | sklearn/utils/fixes.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/fixes.py | BSD-3-Clause |
def _in_unstable_openblas_configuration():
"""Return True if in an unstable configuration for OpenBLAS"""
# Import libraries which might load OpenBLAS.
import numpy # noqa: F401
import scipy # noqa: F401
modules_info = _get_threadpool_controller().info()
open_blas_used = any(info["internal_... | Return True if in an unstable configuration for OpenBLAS | _in_unstable_openblas_configuration | python | scikit-learn/scikit-learn | sklearn/utils/fixes.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/fixes.py | BSD-3-Clause |
def single_source_shortest_path_length(graph, source, *, cutoff=None):
"""Return the length of the shortest path from source to all reachable nodes.
Parameters
----------
graph : {array-like, sparse matrix} of shape (n_nodes, n_nodes)
Adjacency matrix of the graph. Sparse matrix of format LIL i... | Return the length of the shortest path from source to all reachable nodes.
Parameters
----------
graph : {array-like, sparse matrix} of shape (n_nodes, n_nodes)
Adjacency matrix of the graph. Sparse matrix of format LIL is
preferred.
source : int
Start node for path.
cutoff... | single_source_shortest_path_length | python | scikit-learn/scikit-learn | sklearn/utils/graph.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/graph.py | BSD-3-Clause |
def _fix_connected_components(
X,
graph,
n_connected_components,
component_labels,
mode="distance",
metric="euclidean",
**kwargs,
):
"""Add connections to sparse graph to connect unconnected components.
For each pair of unconnected components, compute all pairwise distances
from... | Add connections to sparse graph to connect unconnected components.
For each pair of unconnected components, compute all pairwise distances
from one component to the other, and add a connection on the closest pair
of samples. This is a hacky way to get a graph with a single connected
component, which is... | _fix_connected_components | python | scikit-learn/scikit-learn | sklearn/utils/graph.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/graph.py | BSD-3-Clause |
def _safe_split(estimator, X, y, indices, train_indices=None):
"""Create subset of dataset and properly handle kernels.
Slice X, y according to indices for cross-validation, but take care of
precomputed kernel-matrices or pairwise affinities / distances.
If ``estimator._pairwise is True``, X needs to ... | Create subset of dataset and properly handle kernels.
Slice X, y according to indices for cross-validation, but take care of
precomputed kernel-matrices or pairwise affinities / distances.
If ``estimator._pairwise is True``, X needs to be square and
we slice rows and columns. If ``train_indices`` is n... | _safe_split | python | scikit-learn/scikit-learn | sklearn/utils/metaestimators.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/metaestimators.py | BSD-3-Clause |
def unique_labels(*ys):
"""Extract an ordered array of unique labels.
We don't allow:
- mix of multilabel and multiclass (single label) targets
- mix of label indicator matrix and anything else,
because there are no explicit labels)
- mix of label indicator matrices of differe... | Extract an ordered array of unique labels.
We don't allow:
- mix of multilabel and multiclass (single label) targets
- mix of label indicator matrix and anything else,
because there are no explicit labels)
- mix of label indicator matrices of different sizes
- mix of strin... | unique_labels | python | scikit-learn/scikit-learn | sklearn/utils/multiclass.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/multiclass.py | BSD-3-Clause |
def is_multilabel(y):
"""Check if ``y`` is in a multilabel format.
Parameters
----------
y : ndarray of shape (n_samples,)
Target values.
Returns
-------
out : bool
Return ``True``, if ``y`` is in a multilabel format, else ``False``.
Examples
--------
>>> impor... | Check if ``y`` is in a multilabel format.
Parameters
----------
y : ndarray of shape (n_samples,)
Target values.
Returns
-------
out : bool
Return ``True``, if ``y`` is in a multilabel format, else ``False``.
Examples
--------
>>> import numpy as np
>>> from sk... | is_multilabel | python | scikit-learn/scikit-learn | sklearn/utils/multiclass.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/multiclass.py | BSD-3-Clause |
def check_classification_targets(y):
"""Ensure that target y is of a non-regression type.
Only the following target types (as defined in type_of_target) are allowed:
'binary', 'multiclass', 'multiclass-multioutput',
'multilabel-indicator', 'multilabel-sequences'
Parameters
----------
... | Ensure that target y is of a non-regression type.
Only the following target types (as defined in type_of_target) are allowed:
'binary', 'multiclass', 'multiclass-multioutput',
'multilabel-indicator', 'multilabel-sequences'
Parameters
----------
y : array-like
Target values.
... | check_classification_targets | python | scikit-learn/scikit-learn | sklearn/utils/multiclass.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/multiclass.py | BSD-3-Clause |
def type_of_target(y, input_name="", raise_unknown=False):
"""Determine the type of data indicated by the target.
Note that this type is the most specific type that can be inferred.
For example:
* ``binary`` is more specific but compatible with ``multiclass``.
* ``multiclass`` of integers is more ... | Determine the type of data indicated by the target.
Note that this type is the most specific type that can be inferred.
For example:
* ``binary`` is more specific but compatible with ``multiclass``.
* ``multiclass`` of integers is more specific but compatible with ``continuous``.
* ``multilabel-in... | type_of_target | python | scikit-learn/scikit-learn | sklearn/utils/multiclass.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/multiclass.py | BSD-3-Clause |
def _raise_or_return():
"""Depending on the value of raise_unknown, either raise an error or return
'unknown'.
"""
if raise_unknown:
input = input_name if input_name else "data"
raise ValueError(f"Unknown label type for {input}: {y!r}")
else:
r... | Depending on the value of raise_unknown, either raise an error or return
'unknown'.
| _raise_or_return | python | scikit-learn/scikit-learn | sklearn/utils/multiclass.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/multiclass.py | BSD-3-Clause |
def _check_partial_fit_first_call(clf, classes=None):
"""Private helper function for factorizing common classes param logic.
Estimators that implement the ``partial_fit`` API need to be provided with
the list of possible classes at the first call to partial_fit.
Subsequent calls to partial_fit should ... | Private helper function for factorizing common classes param logic.
Estimators that implement the ``partial_fit`` API need to be provided with
the list of possible classes at the first call to partial_fit.
Subsequent calls to partial_fit should check that ``classes`` is still
consistent with a previou... | _check_partial_fit_first_call | python | scikit-learn/scikit-learn | sklearn/utils/multiclass.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/multiclass.py | BSD-3-Clause |
def class_distribution(y, sample_weight=None):
"""Compute class priors from multioutput-multiclass target data.
Parameters
----------
y : {array-like, sparse matrix} of size (n_samples, n_outputs)
The labels for each example.
sample_weight : array-like of shape (n_samples,), default=None
... | Compute class priors from multioutput-multiclass target data.
Parameters
----------
y : {array-like, sparse matrix} of size (n_samples, n_outputs)
The labels for each example.
sample_weight : array-like of shape (n_samples,), default=None
Sample weights.
Returns
-------
cl... | class_distribution | python | scikit-learn/scikit-learn | sklearn/utils/multiclass.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/multiclass.py | BSD-3-Clause |
def _ovr_decision_function(predictions, confidences, n_classes):
"""Compute a continuous, tie-breaking OvR decision function from OvO.
It is important to include a continuous value, not only votes,
to make computing AUC or calibration meaningful.
Parameters
----------
predictions : array-like ... | Compute a continuous, tie-breaking OvR decision function from OvO.
It is important to include a continuous value, not only votes,
to make computing AUC or calibration meaningful.
Parameters
----------
predictions : array-like of shape (n_samples, n_classifiers)
Predicted classes for each b... | _ovr_decision_function | python | scikit-learn/scikit-learn | sklearn/utils/multiclass.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/multiclass.py | BSD-3-Clause |
def _line_search_wolfe12(
f, fprime, xk, pk, gfk, old_fval, old_old_fval, verbose=0, **kwargs
):
"""
Same as line_search_wolfe1, but fall back to line_search_wolfe2 if
suitable step length is not found, and raise an exception if a
suitable step length is not found.
Raises
------
_LineSe... |
Same as line_search_wolfe1, but fall back to line_search_wolfe2 if
suitable step length is not found, and raise an exception if a
suitable step length is not found.
Raises
------
_LineSearchError
If no suitable step size is found.
| _line_search_wolfe12 | python | scikit-learn/scikit-learn | sklearn/utils/optimize.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/optimize.py | BSD-3-Clause |
def _cg(fhess_p, fgrad, maxiter, tol, verbose=0):
"""
Solve iteratively the linear system 'fhess_p . xsupi = fgrad'
with a conjugate gradient descent.
Parameters
----------
fhess_p : callable
Function that takes the gradient as a parameter and returns the
matrix product of the H... |
Solve iteratively the linear system 'fhess_p . xsupi = fgrad'
with a conjugate gradient descent.
Parameters
----------
fhess_p : callable
Function that takes the gradient as a parameter and returns the
matrix product of the Hessian and gradient.
fgrad : ndarray of shape (n_fea... | _cg | python | scikit-learn/scikit-learn | sklearn/utils/optimize.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/optimize.py | BSD-3-Clause |
def _newton_cg(
grad_hess,
func,
grad,
x0,
args=(),
tol=1e-4,
maxiter=100,
maxinner=200,
line_search=True,
warn=True,
verbose=0,
):
"""
Minimization of scalar function of one or more variables using the
Newton-CG algorithm.
Parameters
----------
grad_... |
Minimization of scalar function of one or more variables using the
Newton-CG algorithm.
Parameters
----------
grad_hess : callable
Should return the gradient and a callable returning the matvec product
of the Hessian.
func : callable
Should return the value of the func... | _newton_cg | python | scikit-learn/scikit-learn | sklearn/utils/optimize.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/optimize.py | BSD-3-Clause |
def _check_optimize_result(solver, result, max_iter=None, extra_warning_msg=None):
"""Check the OptimizeResult for successful convergence
Parameters
----------
solver : str
Solver name. Currently only `lbfgs` is supported.
result : OptimizeResult
Result of the scipy.optimize.minimize... | Check the OptimizeResult for successful convergence
Parameters
----------
solver : str
Solver name. Currently only `lbfgs` is supported.
result : OptimizeResult
Result of the scipy.optimize.minimize function.
max_iter : int, default=None
Expected maximum number of iterations.... | _check_optimize_result | python | scikit-learn/scikit-learn | sklearn/utils/optimize.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/optimize.py | BSD-3-Clause |
def _with_config_and_warning_filters(delayed_func, config, warning_filters):
"""Helper function that intends to attach a config to a delayed function."""
if hasattr(delayed_func, "with_config_and_warning_filters"):
return delayed_func.with_config_and_warning_filters(config, warning_filters)
else:
... | Helper function that intends to attach a config to a delayed function. | _with_config_and_warning_filters | python | scikit-learn/scikit-learn | sklearn/utils/parallel.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/parallel.py | BSD-3-Clause |
def __call__(self, iterable):
"""Dispatch the tasks and return the results.
Parameters
----------
iterable : iterable
Iterable containing tuples of (delayed_function, args, kwargs) that should
be consumed.
Returns
-------
results : list
... | Dispatch the tasks and return the results.
Parameters
----------
iterable : iterable
Iterable containing tuples of (delayed_function, args, kwargs) that should
be consumed.
Returns
-------
results : list
List of results of the tasks.
... | __call__ | python | scikit-learn/scikit-learn | sklearn/utils/parallel.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/parallel.py | BSD-3-Clause |
def delayed(function):
"""Decorator used to capture the arguments of a function.
This alternative to `joblib.delayed` is meant to be used in conjunction
with `sklearn.utils.parallel.Parallel`. The latter captures the scikit-
learn configuration by calling `sklearn.get_config()` in the current
threa... | Decorator used to capture the arguments of a function.
This alternative to `joblib.delayed` is meant to be used in conjunction
with `sklearn.utils.parallel.Parallel`. The latter captures the scikit-
learn configuration by calling `sklearn.get_config()` in the current
thread, prior to dispatching the fi... | delayed | python | scikit-learn/scikit-learn | sklearn/utils/parallel.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/parallel.py | BSD-3-Clause |
def _get_threadpool_controller():
"""Return the global threadpool controller instance."""
global _threadpool_controller
if _threadpool_controller is None:
_threadpool_controller = ThreadpoolController()
return _threadpool_controller | Return the global threadpool controller instance. | _get_threadpool_controller | python | scikit-learn/scikit-learn | sklearn/utils/parallel.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/parallel.py | BSD-3-Clause |
def _random_choice_csc(n_samples, classes, class_probability=None, random_state=None):
"""Generate a sparse random matrix given column class distributions
Parameters
----------
n_samples : int,
Number of samples to draw in each column.
classes : list of size n_outputs of arrays of size (n_... | Generate a sparse random matrix given column class distributions
Parameters
----------
n_samples : int,
Number of samples to draw in each column.
classes : list of size n_outputs of arrays of size (n_classes,)
List of classes for each column.
class_probability : list of size n_out... | _random_choice_csc | python | scikit-learn/scikit-learn | sklearn/utils/random.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/random.py | BSD-3-Clause |
def _raise_typeerror(X):
"""Raises a TypeError if X is not a CSR or CSC matrix"""
input_type = X.format if sp.issparse(X) else type(X)
err = "Expected a CSR or CSC sparse matrix, got %s." % input_type
raise TypeError(err) | Raises a TypeError if X is not a CSR or CSC matrix | _raise_typeerror | python | scikit-learn/scikit-learn | sklearn/utils/sparsefuncs.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/sparsefuncs.py | BSD-3-Clause |
def inplace_csr_column_scale(X, scale):
"""Inplace column scaling of a CSR matrix.
Scale each feature of the data matrix by multiplying with specific scale
provided by the caller assuming a (n_samples, n_features) shape.
Parameters
----------
X : sparse matrix of shape (n_samples, n_features)
... | Inplace column scaling of a CSR matrix.
Scale each feature of the data matrix by multiplying with specific scale
provided by the caller assuming a (n_samples, n_features) shape.
Parameters
----------
X : sparse matrix of shape (n_samples, n_features)
Matrix to normalize using the variance ... | inplace_csr_column_scale | python | scikit-learn/scikit-learn | sklearn/utils/sparsefuncs.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/sparsefuncs.py | BSD-3-Clause |
def inplace_csr_row_scale(X, scale):
"""Inplace row scaling of a CSR matrix.
Scale each sample of the data matrix by multiplying with specific scale
provided by the caller assuming a (n_samples, n_features) shape.
Parameters
----------
X : sparse matrix of shape (n_samples, n_features)
... | Inplace row scaling of a CSR matrix.
Scale each sample of the data matrix by multiplying with specific scale
provided by the caller assuming a (n_samples, n_features) shape.
Parameters
----------
X : sparse matrix of shape (n_samples, n_features)
Matrix to be scaled. It should be of CSR fo... | inplace_csr_row_scale | python | scikit-learn/scikit-learn | sklearn/utils/sparsefuncs.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/sparsefuncs.py | BSD-3-Clause |
def mean_variance_axis(X, axis, weights=None, return_sum_weights=False):
"""Compute mean and variance along an axis on a CSR or CSC matrix.
Parameters
----------
X : sparse matrix of shape (n_samples, n_features)
Input data. It can be of CSR or CSC format.
axis : {0, 1}
Axis along ... | Compute mean and variance along an axis on a CSR or CSC matrix.
Parameters
----------
X : sparse matrix of shape (n_samples, n_features)
Input data. It can be of CSR or CSC format.
axis : {0, 1}
Axis along which the axis should be computed.
weights : ndarray of shape (n_samples,) ... | mean_variance_axis | python | scikit-learn/scikit-learn | sklearn/utils/sparsefuncs.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/sparsefuncs.py | BSD-3-Clause |
def incr_mean_variance_axis(X, *, axis, last_mean, last_var, last_n, weights=None):
"""Compute incremental mean and variance along an axis on a CSR or CSC matrix.
last_mean, last_var are the statistics computed at the last step by this
function. Both must be initialized to 0-arrays of the proper size, i.e.... | Compute incremental mean and variance along an axis on a CSR or CSC matrix.
last_mean, last_var are the statistics computed at the last step by this
function. Both must be initialized to 0-arrays of the proper size, i.e.
the number of features in X. last_n is the number of samples encountered
until now... | incr_mean_variance_axis | python | scikit-learn/scikit-learn | sklearn/utils/sparsefuncs.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/sparsefuncs.py | BSD-3-Clause |
def inplace_column_scale(X, scale):
"""Inplace column scaling of a CSC/CSR matrix.
Scale each feature of the data matrix by multiplying with specific scale
provided by the caller assuming a (n_samples, n_features) shape.
Parameters
----------
X : sparse matrix of shape (n_samples, n_features)
... | Inplace column scaling of a CSC/CSR matrix.
Scale each feature of the data matrix by multiplying with specific scale
provided by the caller assuming a (n_samples, n_features) shape.
Parameters
----------
X : sparse matrix of shape (n_samples, n_features)
Matrix to normalize using the varia... | inplace_column_scale | python | scikit-learn/scikit-learn | sklearn/utils/sparsefuncs.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/sparsefuncs.py | BSD-3-Clause |
def inplace_row_scale(X, scale):
"""Inplace row scaling of a CSR or CSC matrix.
Scale each row of the data matrix by multiplying with specific scale
provided by the caller assuming a (n_samples, n_features) shape.
Parameters
----------
X : sparse matrix of shape (n_samples, n_features)
... | Inplace row scaling of a CSR or CSC matrix.
Scale each row of the data matrix by multiplying with specific scale
provided by the caller assuming a (n_samples, n_features) shape.
Parameters
----------
X : sparse matrix of shape (n_samples, n_features)
Matrix to be scaled. It should be of CS... | inplace_row_scale | python | scikit-learn/scikit-learn | sklearn/utils/sparsefuncs.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/sparsefuncs.py | BSD-3-Clause |
def inplace_swap_row_csc(X, m, n):
"""Swap two rows of a CSC matrix in-place.
Parameters
----------
X : sparse matrix of shape (n_samples, n_features)
Matrix whose two rows are to be swapped. It should be of
CSC format.
m : int
Index of the row of X to be swapped.
n : ... | Swap two rows of a CSC matrix in-place.
Parameters
----------
X : sparse matrix of shape (n_samples, n_features)
Matrix whose two rows are to be swapped. It should be of
CSC format.
m : int
Index of the row of X to be swapped.
n : int
Index of the row of X to be sw... | inplace_swap_row_csc | python | scikit-learn/scikit-learn | sklearn/utils/sparsefuncs.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/sparsefuncs.py | BSD-3-Clause |
def inplace_swap_row_csr(X, m, n):
"""Swap two rows of a CSR matrix in-place.
Parameters
----------
X : sparse matrix of shape (n_samples, n_features)
Matrix whose two rows are to be swapped. It should be of
CSR format.
m : int
Index of the row of X to be swapped.
n : ... | Swap two rows of a CSR matrix in-place.
Parameters
----------
X : sparse matrix of shape (n_samples, n_features)
Matrix whose two rows are to be swapped. It should be of
CSR format.
m : int
Index of the row of X to be swapped.
n : int
Index of the row of X to be sw... | inplace_swap_row_csr | python | scikit-learn/scikit-learn | sklearn/utils/sparsefuncs.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/sparsefuncs.py | BSD-3-Clause |
def inplace_swap_row(X, m, n):
"""
Swap two rows of a CSC/CSR matrix in-place.
Parameters
----------
X : sparse matrix of shape (n_samples, n_features)
Matrix whose two rows are to be swapped. It should be of CSR or
CSC format.
m : int
Index of the row of X to be swappe... |
Swap two rows of a CSC/CSR matrix in-place.
Parameters
----------
X : sparse matrix of shape (n_samples, n_features)
Matrix whose two rows are to be swapped. It should be of CSR or
CSC format.
m : int
Index of the row of X to be swapped.
n : int
Index of the r... | inplace_swap_row | python | scikit-learn/scikit-learn | sklearn/utils/sparsefuncs.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/sparsefuncs.py | BSD-3-Clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.