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 set_score_request(self, **kwargs):
"""Set requested parameters by the scorer.
Please see :ref:`User Guide <metadata_routing>` on how the routing
mechanism works.
.. versionadded:: 1.5
Parameters
----------
kwargs : dict
Arguments should be of th... | Set requested parameters by the scorer.
Please see :ref:`User Guide <metadata_routing>` on how the routing
mechanism works.
.. versionadded:: 1.5
Parameters
----------
kwargs : dict
Arguments should be of the form ``param_name=alias``, and `alias`
... | set_score_request | python | scikit-learn/scikit-learn | sklearn/metrics/_scorer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_scorer.py | BSD-3-Clause |
def _check_multimetric_scoring(estimator, scoring):
"""Check the scoring parameter in cases when multiple metrics are allowed.
In addition, multimetric scoring leverages a caching mechanism to not call the same
estimator response method multiple times. Hence, the scorer is modified to only use
a single... | Check the scoring parameter in cases when multiple metrics are allowed.
In addition, multimetric scoring leverages a caching mechanism to not call the same
estimator response method multiple times. Hence, the scorer is modified to only use
a single response method given a list of response methods and the e... | _check_multimetric_scoring | python | scikit-learn/scikit-learn | sklearn/metrics/_scorer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_scorer.py | BSD-3-Clause |
def make_scorer(
score_func, *, response_method="default", greater_is_better=True, **kwargs
):
"""Make a scorer from a performance metric or loss function.
A scorer is a wrapper around an arbitrary metric or loss function that is called
with the signature `scorer(estimator, X, y_true, **kwargs)`.
... | Make a scorer from a performance metric or loss function.
A scorer is a wrapper around an arbitrary metric or loss function that is called
with the signature `scorer(estimator, X, y_true, **kwargs)`.
It is accepted in all scikit-learn estimators or functions allowing a `scoring`
parameter.
The pa... | make_scorer | python | scikit-learn/scikit-learn | sklearn/metrics/_scorer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_scorer.py | BSD-3-Clause |
def check_scoring(estimator=None, scoring=None, *, allow_none=False, raise_exc=True):
"""Determine scorer from user options.
A TypeError will be thrown if the estimator cannot be scored.
Parameters
----------
estimator : estimator object implementing 'fit' or None, default=None
The object ... | Determine scorer from user options.
A TypeError will be thrown if the estimator cannot be scored.
Parameters
----------
estimator : estimator object implementing 'fit' or None, default=None
The object to use to fit the data. If `None`, then this function may error
depending on `allow_n... | check_scoring | python | scikit-learn/scikit-learn | sklearn/metrics/_scorer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_scorer.py | BSD-3-Clause |
def _threshold_scores_to_class_labels(y_score, threshold, classes, pos_label):
"""Threshold `y_score` and return the associated class labels."""
if pos_label is None:
map_thresholded_score_to_label = np.array([0, 1])
else:
pos_label_idx = np.flatnonzero(classes == pos_label)[0]
neg_l... | Threshold `y_score` and return the associated class labels. | _threshold_scores_to_class_labels | python | scikit-learn/scikit-learn | sklearn/metrics/_scorer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_scorer.py | BSD-3-Clause |
def from_scorer(cls, scorer, response_method, thresholds):
"""Create a continuous scorer from a normal scorer."""
instance = cls(
score_func=scorer._score_func,
sign=scorer._sign,
response_method=response_method,
thresholds=thresholds,
kwargs=s... | Create a continuous scorer from a normal scorer. | from_scorer | python | scikit-learn/scikit-learn | sklearn/metrics/_scorer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_scorer.py | BSD-3-Clause |
def _score(self, method_caller, estimator, X, y_true, **kwargs):
"""Evaluate predicted target values for X relative to y_true.
Parameters
----------
method_caller : callable
Returns predictions given an estimator, method name, and other
arguments, potentially cac... | Evaluate predicted target values for X relative to y_true.
Parameters
----------
method_caller : callable
Returns predictions given an estimator, method name, and other
arguments, potentially caching results.
estimator : object
Trained estimator to u... | _score | python | scikit-learn/scikit-learn | sklearn/metrics/_scorer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_scorer.py | BSD-3-Clause |
def _check_rows_and_columns(a, b):
"""Unpacks the row and column arrays and checks their shape."""
check_consistent_length(*a)
check_consistent_length(*b)
checks = lambda x: check_array(x, ensure_2d=False)
a_rows, a_cols = map(checks, a)
b_rows, b_cols = map(checks, b)
return a_rows, a_cols,... | Unpacks the row and column arrays and checks their shape. | _check_rows_and_columns | python | scikit-learn/scikit-learn | sklearn/metrics/cluster/_bicluster.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/cluster/_bicluster.py | BSD-3-Clause |
def _jaccard(a_rows, a_cols, b_rows, b_cols):
"""Jaccard coefficient on the elements of the two biclusters."""
intersection = (a_rows * b_rows).sum() * (a_cols * b_cols).sum()
a_size = a_rows.sum() * a_cols.sum()
b_size = b_rows.sum() * b_cols.sum()
return intersection / (a_size + b_size - interse... | Jaccard coefficient on the elements of the two biclusters. | _jaccard | python | scikit-learn/scikit-learn | sklearn/metrics/cluster/_bicluster.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/cluster/_bicluster.py | BSD-3-Clause |
def _pairwise_similarity(a, b, similarity):
"""Computes pairwise similarity matrix.
result[i, j] is the Jaccard coefficient of a's bicluster i and b's
bicluster j.
"""
a_rows, a_cols, b_rows, b_cols = _check_rows_and_columns(a, b)
n_a = a_rows.shape[0]
n_b = b_rows.shape[0]
result = np... | Computes pairwise similarity matrix.
result[i, j] is the Jaccard coefficient of a's bicluster i and b's
bicluster j.
| _pairwise_similarity | python | scikit-learn/scikit-learn | sklearn/metrics/cluster/_bicluster.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/cluster/_bicluster.py | BSD-3-Clause |
def consensus_score(a, b, *, similarity="jaccard"):
"""The similarity of two sets of biclusters.
Similarity between individual biclusters is computed. Then the best
matching between sets is found by solving a linear sum assignment problem,
using a modified Jonker-Volgenant algorithm.
The final scor... | The similarity of two sets of biclusters.
Similarity between individual biclusters is computed. Then the best
matching between sets is found by solving a linear sum assignment problem,
using a modified Jonker-Volgenant algorithm.
The final score is the sum of similarities divided by the size of
the... | consensus_score | python | scikit-learn/scikit-learn | sklearn/metrics/cluster/_bicluster.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/cluster/_bicluster.py | BSD-3-Clause |
def check_clusterings(labels_true, labels_pred):
"""Check that the labels arrays are 1D and of same dimension.
Parameters
----------
labels_true : array-like of shape (n_samples,)
The true labels.
labels_pred : array-like of shape (n_samples,)
The predicted labels.
"""
labe... | Check that the labels arrays are 1D and of same dimension.
Parameters
----------
labels_true : array-like of shape (n_samples,)
The true labels.
labels_pred : array-like of shape (n_samples,)
The predicted labels.
| check_clusterings | python | scikit-learn/scikit-learn | sklearn/metrics/cluster/_supervised.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/cluster/_supervised.py | BSD-3-Clause |
def _generalized_average(U, V, average_method):
"""Return a particular mean of two numbers."""
if average_method == "min":
return min(U, V)
elif average_method == "geometric":
return np.sqrt(U * V)
elif average_method == "arithmetic":
return np.mean([U, V])
elif average_metho... | Return a particular mean of two numbers. | _generalized_average | python | scikit-learn/scikit-learn | sklearn/metrics/cluster/_supervised.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/cluster/_supervised.py | BSD-3-Clause |
def contingency_matrix(
labels_true, labels_pred, *, eps=None, sparse=False, dtype=np.int64
):
"""Build a contingency matrix describing the relationship between labels.
Read more in the :ref:`User Guide <contingency_matrix>`.
Parameters
----------
labels_true : array-like of shape (n_samples,)... | Build a contingency matrix describing the relationship between labels.
Read more in the :ref:`User Guide <contingency_matrix>`.
Parameters
----------
labels_true : array-like of shape (n_samples,)
Ground truth class labels to be used as a reference.
labels_pred : array-like of shape (n_sa... | contingency_matrix | python | scikit-learn/scikit-learn | sklearn/metrics/cluster/_supervised.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/cluster/_supervised.py | BSD-3-Clause |
def homogeneity_completeness_v_measure(labels_true, labels_pred, *, beta=1.0):
"""Compute the homogeneity and completeness and V-Measure scores at once.
Those metrics are based on normalized conditional entropy measures of
the clustering labeling to evaluate given the knowledge of a Ground
Truth class ... | Compute the homogeneity and completeness and V-Measure scores at once.
Those metrics are based on normalized conditional entropy measures of
the clustering labeling to evaluate given the knowledge of a Ground
Truth class labels of the same samples.
A clustering result satisfies homogeneity if all of i... | homogeneity_completeness_v_measure | python | scikit-learn/scikit-learn | sklearn/metrics/cluster/_supervised.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/cluster/_supervised.py | BSD-3-Clause |
def mutual_info_score(labels_true, labels_pred, *, contingency=None):
"""Mutual Information between two clusterings.
The Mutual Information is a measure of the similarity between two labels
of the same data. Where :math:`|U_i|` is the number of the samples
in cluster :math:`U_i` and :math:`|V_j|` is th... | Mutual Information between two clusterings.
The Mutual Information is a measure of the similarity between two labels
of the same data. Where :math:`|U_i|` is the number of the samples
in cluster :math:`U_i` and :math:`|V_j|` is the number of the
samples in cluster :math:`V_j`, the Mutual Information
... | mutual_info_score | python | scikit-learn/scikit-learn | sklearn/metrics/cluster/_supervised.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/cluster/_supervised.py | BSD-3-Clause |
def normalized_mutual_info_score(
labels_true, labels_pred, *, average_method="arithmetic"
):
"""Normalized Mutual Information between two clusterings.
Normalized Mutual Information (NMI) is a normalization of the Mutual
Information (MI) score to scale the results between 0 (no mutual
information) ... | Normalized Mutual Information between two clusterings.
Normalized Mutual Information (NMI) is a normalization of the Mutual
Information (MI) score to scale the results between 0 (no mutual
information) and 1 (perfect correlation). In this function, mutual
information is normalized by some generalized m... | normalized_mutual_info_score | python | scikit-learn/scikit-learn | sklearn/metrics/cluster/_supervised.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/cluster/_supervised.py | BSD-3-Clause |
def fowlkes_mallows_score(labels_true, labels_pred, *, sparse="deprecated"):
"""Measure the similarity of two clusterings of a set of points.
.. versionadded:: 0.18
The Fowlkes-Mallows index (FMI) is defined as the geometric mean of
the precision and recall::
FMI = TP / sqrt((TP + FP) * (TP +... | Measure the similarity of two clusterings of a set of points.
.. versionadded:: 0.18
The Fowlkes-Mallows index (FMI) is defined as the geometric mean of
the precision and recall::
FMI = TP / sqrt((TP + FP) * (TP + FN))
Where ``TP`` is the number of **True Positive** (i.e. the number of pairs... | fowlkes_mallows_score | python | scikit-learn/scikit-learn | sklearn/metrics/cluster/_supervised.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/cluster/_supervised.py | BSD-3-Clause |
def entropy(labels):
"""Calculate the entropy for a labeling.
Parameters
----------
labels : array-like of shape (n_samples,), dtype=int
The labels.
Returns
-------
entropy : float
The entropy for a labeling.
Notes
-----
The logarithm used is the natural logarit... | Calculate the entropy for a labeling.
Parameters
----------
labels : array-like of shape (n_samples,), dtype=int
The labels.
Returns
-------
entropy : float
The entropy for a labeling.
Notes
-----
The logarithm used is the natural logarithm (base-e).
| entropy | python | scikit-learn/scikit-learn | sklearn/metrics/cluster/_supervised.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/cluster/_supervised.py | BSD-3-Clause |
def check_number_of_labels(n_labels, n_samples):
"""Check that number of labels are valid.
Parameters
----------
n_labels : int
Number of labels.
n_samples : int
Number of samples.
"""
if not 1 < n_labels < n_samples:
raise ValueError(
"Number of labels ... | Check that number of labels are valid.
Parameters
----------
n_labels : int
Number of labels.
n_samples : int
Number of samples.
| check_number_of_labels | python | scikit-learn/scikit-learn | sklearn/metrics/cluster/_unsupervised.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/cluster/_unsupervised.py | BSD-3-Clause |
def silhouette_score(
X, labels, *, metric="euclidean", sample_size=None, random_state=None, **kwds
):
"""Compute the mean Silhouette Coefficient of all samples.
The Silhouette Coefficient is calculated using the mean intra-cluster
distance (``a``) and the mean nearest-cluster distance (``b``) for each... | Compute the mean Silhouette Coefficient of all samples.
The Silhouette Coefficient is calculated using the mean intra-cluster
distance (``a``) and the mean nearest-cluster distance (``b``) for each
sample. The Silhouette Coefficient for a sample is ``(b - a) / max(a,
b)``. To clarify, ``b`` is the di... | silhouette_score | python | scikit-learn/scikit-learn | sklearn/metrics/cluster/_unsupervised.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/cluster/_unsupervised.py | BSD-3-Clause |
def _silhouette_reduce(D_chunk, start, labels, label_freqs):
"""Accumulate silhouette statistics for vertical chunk of X.
Parameters
----------
D_chunk : {array-like, sparse matrix} of shape (n_chunk_samples, n_samples)
Precomputed distances for a chunk. If a sparse matrix is provided,
... | Accumulate silhouette statistics for vertical chunk of X.
Parameters
----------
D_chunk : {array-like, sparse matrix} of shape (n_chunk_samples, n_samples)
Precomputed distances for a chunk. If a sparse matrix is provided,
only CSR format is accepted.
start : int
First index in ... | _silhouette_reduce | python | scikit-learn/scikit-learn | sklearn/metrics/cluster/_unsupervised.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/cluster/_unsupervised.py | BSD-3-Clause |
def silhouette_samples(X, labels, *, metric="euclidean", **kwds):
"""Compute the Silhouette Coefficient for each sample.
The Silhouette Coefficient is a measure of how well samples are clustered
with samples that are similar to themselves. Clustering models with a high
Silhouette Coefficient are said t... | Compute the Silhouette Coefficient for each sample.
The Silhouette Coefficient is a measure of how well samples are clustered
with samples that are similar to themselves. Clustering models with a high
Silhouette Coefficient are said to be dense, where samples in the same
cluster are similar to each oth... | silhouette_samples | python | scikit-learn/scikit-learn | sklearn/metrics/cluster/_unsupervised.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/cluster/_unsupervised.py | BSD-3-Clause |
def calinski_harabasz_score(X, labels):
"""Compute the Calinski and Harabasz score.
It is also known as the Variance Ratio Criterion.
The score is defined as ratio of the sum of between-cluster dispersion and
of within-cluster dispersion.
Read more in the :ref:`User Guide <calinski_harabasz_index... | Compute the Calinski and Harabasz score.
It is also known as the Variance Ratio Criterion.
The score is defined as ratio of the sum of between-cluster dispersion and
of within-cluster dispersion.
Read more in the :ref:`User Guide <calinski_harabasz_index>`.
Parameters
----------
X : arra... | calinski_harabasz_score | python | scikit-learn/scikit-learn | sklearn/metrics/cluster/_unsupervised.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/cluster/_unsupervised.py | BSD-3-Clause |
def davies_bouldin_score(X, labels):
"""Compute the Davies-Bouldin score.
The score is defined as the average similarity measure of each cluster with
its most similar cluster, where similarity is the ratio of within-cluster
distances to between-cluster distances. Thus, clusters which are farther
ap... | Compute the Davies-Bouldin score.
The score is defined as the average similarity measure of each cluster with
its most similar cluster, where similarity is the ratio of within-cluster
distances to between-cluster distances. Thus, clusters which are farther
apart and less dispersed will result in a bett... | davies_bouldin_score | python | scikit-learn/scikit-learn | sklearn/metrics/cluster/_unsupervised.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/cluster/_unsupervised.py | BSD-3-Clause |
def test_consensus_score_issue2445():
"""Different number of biclusters in A and B"""
a_rows = np.array(
[
[True, True, False, False],
[False, False, True, True],
[False, False, False, True],
]
)
a_cols = np.array(
[
[True, True, Fa... | Different number of biclusters in A and B | test_consensus_score_issue2445 | python | scikit-learn/scikit-learn | sklearn/metrics/cluster/tests/test_bicluster.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/cluster/tests/test_bicluster.py | BSD-3-Clause |
def test_returned_value_consistency(name):
"""Ensure that the returned values of all metrics are consistent.
It can only be a float. It should not be a numpy float64 or float32.
"""
rng = np.random.RandomState(0)
X = rng.randint(10, size=(20, 10))
labels_true = rng.randint(0, 3, size=(20,))
... | Ensure that the returned values of all metrics are consistent.
It can only be a float. It should not be a numpy float64 or float32.
| test_returned_value_consistency | python | scikit-learn/scikit-learn | sklearn/metrics/cluster/tests/test_common.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/cluster/tests/test_common.py | BSD-3-Clause |
def test_adjusted_rand_score_overflow():
"""Check that large amount of data will not lead to overflow in
`adjusted_rand_score`.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/20305
"""
rng = np.random.RandomState(0)
y_true = rng.randint(0, 2, 100_000, dtype=np.i... | Check that large amount of data will not lead to overflow in
`adjusted_rand_score`.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/20305
| test_adjusted_rand_score_overflow | python | scikit-learn/scikit-learn | sklearn/metrics/cluster/tests/test_supervised.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/cluster/tests/test_supervised.py | BSD-3-Clause |
def test_normalized_mutual_info_score_bounded(average_method):
"""Check that nmi returns a score between 0 (included) and 1 (excluded
for non-perfect match)
Non-regression test for issue #13836
"""
labels1 = [0] * 469
labels2 = [1] + labels1[1:]
labels3 = [0, 1] + labels1[2:]
# labels1... | Check that nmi returns a score between 0 (included) and 1 (excluded
for non-perfect match)
Non-regression test for issue #13836
| test_normalized_mutual_info_score_bounded | python | scikit-learn/scikit-learn | sklearn/metrics/cluster/tests/test_supervised.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/cluster/tests/test_supervised.py | BSD-3-Clause |
def test_fowlkes_mallows_sparse_deprecated(sparse):
"""Check deprecation warning for 'sparse' parameter of fowlkes_mallows_score."""
with pytest.warns(
FutureWarning, match="The 'sparse' parameter was deprecated in 1.7"
):
fowlkes_mallows_score([0, 1], [1, 1], sparse=sparse) | Check deprecation warning for 'sparse' parameter of fowlkes_mallows_score. | test_fowlkes_mallows_sparse_deprecated | python | scikit-learn/scikit-learn | sklearn/metrics/cluster/tests/test_supervised.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/cluster/tests/test_supervised.py | BSD-3-Clause |
def test_silhouette_samples_precomputed_sparse(sparse_container):
"""Check that silhouette_samples works for sparse matrices correctly."""
X = np.array([[0.2, 0.1, 0.1, 0.2, 0.1, 1.6, 0.2, 0.1]], dtype=np.float32).T
y = [0, 0, 0, 0, 1, 1, 1, 1]
pdist_dense = pairwise_distances(X)
pdist_sparse = spar... | Check that silhouette_samples works for sparse matrices correctly. | test_silhouette_samples_precomputed_sparse | python | scikit-learn/scikit-learn | sklearn/metrics/cluster/tests/test_unsupervised.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/cluster/tests/test_unsupervised.py | BSD-3-Clause |
def test_silhouette_samples_euclidean_sparse(sparse_container):
"""Check that silhouette_samples works for sparse matrices correctly."""
X = np.array([[0.2, 0.1, 0.1, 0.2, 0.1, 1.6, 0.2, 0.1]], dtype=np.float32).T
y = [0, 0, 0, 0, 1, 1, 1, 1]
pdist_dense = pairwise_distances(X)
pdist_sparse = sparse... | Check that silhouette_samples works for sparse matrices correctly. | test_silhouette_samples_euclidean_sparse | python | scikit-learn/scikit-learn | sklearn/metrics/cluster/tests/test_unsupervised.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/cluster/tests/test_unsupervised.py | BSD-3-Clause |
def test_silhouette_reduce(sparse_container):
"""Check for non-CSR input to private method `_silhouette_reduce`."""
X = np.array([[0.2, 0.1, 0.1, 0.2, 0.1, 1.6, 0.2, 0.1]], dtype=np.float32).T
pdist_dense = pairwise_distances(X)
pdist_sparse = sparse_container(pdist_dense)
y = [0, 0, 0, 0, 1, 1, 1, ... | Check for non-CSR input to private method `_silhouette_reduce`. | test_silhouette_reduce | python | scikit-learn/scikit-learn | sklearn/metrics/cluster/tests/test_unsupervised.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/cluster/tests/test_unsupervised.py | BSD-3-Clause |
def assert_raises_on_only_one_label(func):
"""Assert message when there is only one label"""
rng = np.random.RandomState(seed=0)
with pytest.raises(ValueError, match="Number of labels is"):
func(rng.rand(10, 2), np.zeros(10)) | Assert message when there is only one label | assert_raises_on_only_one_label | python | scikit-learn/scikit-learn | sklearn/metrics/cluster/tests/test_unsupervised.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/cluster/tests/test_unsupervised.py | BSD-3-Clause |
def assert_raises_on_all_points_same_cluster(func):
"""Assert message when all point are in different clusters"""
rng = np.random.RandomState(seed=0)
with pytest.raises(ValueError, match="Number of labels is"):
func(rng.rand(10, 2), np.arange(10)) | Assert message when all point are in different clusters | assert_raises_on_all_points_same_cluster | python | scikit-learn/scikit-learn | sklearn/metrics/cluster/tests/test_unsupervised.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/cluster/tests/test_unsupervised.py | BSD-3-Clause |
def test_silhouette_score_integer_precomputed():
"""Check that silhouette_score works for precomputed metrics that are integers.
Non-regression test for #22107.
"""
result = silhouette_score(
[[0, 1, 2], [1, 0, 1], [2, 1, 0]], [0, 0, 1], metric="precomputed"
)
assert result == pytest.ap... | Check that silhouette_score works for precomputed metrics that are integers.
Non-regression test for #22107.
| test_silhouette_score_integer_precomputed | python | scikit-learn/scikit-learn | sklearn/metrics/cluster/tests/test_unsupervised.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/cluster/tests/test_unsupervised.py | BSD-3-Clause |
def make_prediction(dataset=None, binary=False):
"""Make some classification predictions on a toy dataset using a SVC
If binary is True restrict to a binary classification problem instead of a
multiclass classification problem
"""
if dataset is None:
# import some data to play with
... | Make some classification predictions on a toy dataset using a SVC
If binary is True restrict to a binary classification problem instead of a
multiclass classification problem
| make_prediction | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_classification.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py | BSD-3-Clause |
def test_classification_report_labels_subset_superset(labels, show_micro_avg):
"""Check the behaviour of passing `labels` as a superset or subset of the labels.
WHen a superset, we expect to show the "accuracy" in the report while it should be
the micro-averaging if this is a subset.
Non-regression tes... | Check the behaviour of passing `labels` as a superset or subset of the labels.
WHen a superset, we expect to show the "accuracy" in the report while it should be
the micro-averaging if this is a subset.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/27927
| test_classification_report_labels_subset_superset | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_classification.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py | BSD-3-Clause |
def test_confusion_matrix_single_label():
"""Test `confusion_matrix` warns when only one label found."""
y_test = [0, 0, 0, 0]
y_pred = [0, 0, 0, 0]
with pytest.warns(UserWarning, match="A single label was found in"):
confusion_matrix(y_pred, y_test) | Test `confusion_matrix` warns when only one label found. | test_confusion_matrix_single_label | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_classification.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py | BSD-3-Clause |
def test_likelihood_ratios_raise_warning_deprecation(raise_warning):
"""Test that class_likelihood_ratios raises a `FutureWarning` when `raise_warning`
param is set."""
y_true = np.array([1, 0])
y_pred = np.array([1, 0])
msg = "`raise_warning` was deprecated in version 1.7 and will be removed in 1.... | Test that class_likelihood_ratios raises a `FutureWarning` when `raise_warning`
param is set. | test_likelihood_ratios_raise_warning_deprecation | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_classification.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py | BSD-3-Clause |
def test_likelihood_ratios_replace_undefined_by_worst():
"""Test that class_likelihood_ratios returns the worst scores `1.0` for both LR+ and
LR- when `replace_undefined_by=1` is set."""
# This data causes fp=0 (0 false positives) in the confusion_matrix and a division
# by zero that affects the positiv... | Test that class_likelihood_ratios returns the worst scores `1.0` for both LR+ and
LR- when `replace_undefined_by=1` is set. | test_likelihood_ratios_replace_undefined_by_worst | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_classification.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py | BSD-3-Clause |
def test_likelihood_ratios_wrong_dict_replace_undefined_by(replace_undefined_by):
"""Test that class_likelihood_ratios raises a `ValueError` if the input dict for
`replace_undefined_by` is in the wrong format or contains impossible values."""
y_true = np.array([1, 0])
y_pred = np.array([1, 0])
msg ... | Test that class_likelihood_ratios raises a `ValueError` if the input dict for
`replace_undefined_by` is in the wrong format or contains impossible values. | test_likelihood_ratios_wrong_dict_replace_undefined_by | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_classification.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py | BSD-3-Clause |
def test_likelihood_ratios_replace_undefined_by_0_fp(replace_undefined_by, expected):
"""Test that the `replace_undefined_by` param returns the right value for the
positive_likelihood_ratio as defined by the user."""
# This data causes fp=0 (0 false positives) in the confusion_matrix and a division
# by... | Test that the `replace_undefined_by` param returns the right value for the
positive_likelihood_ratio as defined by the user. | test_likelihood_ratios_replace_undefined_by_0_fp | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_classification.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py | BSD-3-Clause |
def test_likelihood_ratios_replace_undefined_by_0_tn(replace_undefined_by, expected):
"""Test that the `replace_undefined_by` param returns the right value for the
negative_likelihood_ratio as defined by the user."""
# This data causes tn=0 (0 true negatives) in the confusion_matrix and a division
# by ... | Test that the `replace_undefined_by` param returns the right value for the
negative_likelihood_ratio as defined by the user. | test_likelihood_ratios_replace_undefined_by_0_tn | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_classification.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py | BSD-3-Clause |
def test_cohen_kappa_score_error_wrong_label():
"""Test that correct error is raised when users pass labels that are not in y1."""
labels = [1, 2]
y1 = np.array(["a"] * 5 + ["b"] * 5)
y2 = np.array(["b"] * 10)
with pytest.raises(
ValueError, match="At least one label in `labels` must be pres... | Test that correct error is raised when users pass labels that are not in y1. | test_cohen_kappa_score_error_wrong_label | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_classification.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py | BSD-3-Clause |
def test_zero_division_nan_no_warning(metric, y_true, y_pred, zero_division):
"""Check the behaviour of `zero_division` when setting to 0, 1 or np.nan.
No warnings should be raised.
"""
with warnings.catch_warnings():
warnings.simplefilter("error")
result = metric(y_true, y_pred, zero_di... | Check the behaviour of `zero_division` when setting to 0, 1 or np.nan.
No warnings should be raised.
| test_zero_division_nan_no_warning | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_classification.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py | BSD-3-Clause |
def test_zero_division_nan_warning(metric, y_true, y_pred):
"""Check the behaviour of `zero_division` when setting to "warn".
A `UndefinedMetricWarning` should be raised.
"""
with pytest.warns(UndefinedMetricWarning):
result = metric(y_true, y_pred, zero_division="warn")
assert result == 0.0 | Check the behaviour of `zero_division` when setting to "warn".
A `UndefinedMetricWarning` should be raised.
| test_zero_division_nan_warning | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_classification.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py | BSD-3-Clause |
def test_confusion_matrix_pandas_nullable(dtype):
"""Checks that confusion_matrix works with pandas nullable dtypes.
Non-regression test for gh-25635.
"""
pd = pytest.importorskip("pandas")
y_ndarray = np.array([1, 0, 0, 1, 0, 1, 1, 0, 1])
y_true = pd.Series(y_ndarray, dtype=dtype)
y_predi... | Checks that confusion_matrix works with pandas nullable dtypes.
Non-regression test for gh-25635.
| test_confusion_matrix_pandas_nullable | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_classification.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py | BSD-3-Clause |
def test_log_loss_eps(dtype):
"""Check the behaviour internal eps that changes depending on the input dtype.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/24315
"""
y_true = np.array([0, 1], dtype=dtype)
y_pred = np.array([1, 0], dtype=dtype)
loss = log_loss(... | Check the behaviour internal eps that changes depending on the input dtype.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/24315
| test_log_loss_eps | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_classification.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py | BSD-3-Clause |
def test_log_loss_not_probabilities_warning(dtype):
"""Check that log_loss raises a warning when y_pred values don't sum to 1."""
y_true = np.array([0, 1, 1, 0])
y_pred = np.array([[0.2, 0.7], [0.6, 0.3], [0.4, 0.7], [0.8, 0.3]], dtype=dtype)
with pytest.warns(UserWarning, match="The y_prob values do n... | Check that log_loss raises a warning when y_pred values don't sum to 1. | test_log_loss_not_probabilities_warning | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_classification.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py | BSD-3-Clause |
def test_log_loss_perfect_predictions(y_true, y_pred):
"""Check that log_loss returns 0 for perfect predictions."""
# Because of the clipping, the result is not exactly 0
assert log_loss(y_true, y_pred) == pytest.approx(0) | Check that log_loss returns 0 for perfect predictions. | test_log_loss_perfect_predictions | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_classification.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py | BSD-3-Clause |
def test_classification_metric_pos_label_types(metric, classes):
"""Check that the metric works with different types of `pos_label`.
We can expect `pos_label` to be a bool, an integer, a float, a string.
No error should be raised for those types.
"""
rng = np.random.RandomState(42)
n_samples, p... | Check that the metric works with different types of `pos_label`.
We can expect `pos_label` to be a bool, an integer, a float, a string.
No error should be raised for those types.
| test_classification_metric_pos_label_types | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_classification.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py | BSD-3-Clause |
def test_classification_metric_division_by_zero_nan_validaton(scoring):
"""Check that we validate `np.nan` properly for classification metrics.
With `n_jobs=2` in cross-validation, the `np.nan` used for the singleton will be
different in the sub-process and we should not use the `is` operator but
`math... | Check that we validate `np.nan` properly for classification metrics.
With `n_jobs=2` in cross-validation, the `np.nan` used for the singleton will be
different in the sub-process and we should not use the `is` operator but
`math.isnan`.
Non-regression test for:
https://github.com/scikit-learn/scik... | test_classification_metric_division_by_zero_nan_validaton | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_classification.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py | BSD-3-Clause |
def test_d2_log_loss_score_missing_labels():
"""Check that d2_log_loss_score works when not all labels are present in y_true
non-regression test for https://github.com/scikit-learn/scikit-learn/issues/30713
"""
y_true = [2, 0, 2, 0]
labels = [0, 1, 2]
sample_weight = [1.4, 0.6, 0.7, 0.3]
y_... | Check that d2_log_loss_score works when not all labels are present in y_true
non-regression test for https://github.com/scikit-learn/scikit-learn/issues/30713
| test_d2_log_loss_score_missing_labels | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_classification.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py | BSD-3-Clause |
def test_d2_log_loss_score_label_order():
"""Check that d2_log_loss_score doesn't depend on the order of the labels."""
y_true = [2, 0, 2, 0]
y_pred = np.tile([1, 0, 0], (4, 1))
d2_score = d2_log_loss_score(y_true, y_pred, labels=[0, 1, 2])
d2_score_other = d2_log_loss_score(y_true, y_pred, labels=... | Check that d2_log_loss_score doesn't depend on the order of the labels. | test_d2_log_loss_score_label_order | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_classification.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py | BSD-3-Clause |
def test_d2_log_loss_score_raises():
"""Test that d2_log_loss_score raises the appropriate errors on
invalid inputs."""
y_true = [0, 1, 2]
y_pred = [[0.2, 0.8], [0.5, 0.5], [0.4, 0.6]]
err = "contain different number of classes"
with pytest.raises(ValueError, match=err):
d2_log_loss_scor... | Test that d2_log_loss_score raises the appropriate errors on
invalid inputs. | test_d2_log_loss_score_raises | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_classification.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py | BSD-3-Clause |
def precision_recall_curve_padded_thresholds(*args, **kwargs):
"""
The dimensions of precision-recall pairs and the threshold array as
returned by the precision_recall_curve do not match. See
func:`sklearn.metrics.precision_recall_curve`
This prevents implicit conversion of return value triple to a... |
The dimensions of precision-recall pairs and the threshold array as
returned by the precision_recall_curve do not match. See
func:`sklearn.metrics.precision_recall_curve`
This prevents implicit conversion of return value triple to an higher
dimensional np.array of dtype('float64') (it will be of d... | precision_recall_curve_padded_thresholds | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_common.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_common.py | BSD-3-Clause |
def test_classification_inf_nan_input(metric, y_true, y_score):
"""check that classification metrics raise a message mentioning the
occurrence of non-finite values in the target vectors."""
if not np.isfinite(y_true).all():
input_name = "y_true"
if np.isnan(y_true).any():
unexpec... | check that classification metrics raise a message mentioning the
occurrence of non-finite values in the target vectors. | test_classification_inf_nan_input | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_common.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_common.py | BSD-3-Clause |
def test_classification_binary_continuous_input(metric):
"""check that classification metrics raise a message of mixed type data
with continuous/binary target vectors."""
y_true, y_score = ["a", "b", "a"], [0.1, 0.2, 0.3]
err_msg = (
"Classification metrics can't handle a mix of binary and conti... | check that classification metrics raise a message of mixed type data
with continuous/binary target vectors. | test_classification_binary_continuous_input | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_common.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_common.py | BSD-3-Clause |
def _get_metric_kwargs_for_array_api_testing(metric, params):
"""Helper function to enable specifying a variety of additional params and
their corresponding values, so that they can be passed to a metric function
when testing for array api compliance."""
metric_kwargs_combinations = [{}]
for param, ... | Helper function to enable specifying a variety of additional params and
their corresponding values, so that they can be passed to a metric function
when testing for array api compliance. | _get_metric_kwargs_for_array_api_testing | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_common.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_common.py | BSD-3-Clause |
def test_returned_value_consistency(name):
"""Ensure that the returned values of all metrics are consistent.
It can either be a float, a numpy array, or a tuple of floats or numpy arrays.
It should not be a numpy float64 or float32.
"""
rng = np.random.RandomState(0)
y_true = rng.randint(0, 2,... | Ensure that the returned values of all metrics are consistent.
It can either be a float, a numpy array, or a tuple of floats or numpy arrays.
It should not be a numpy float64 or float32.
| test_returned_value_consistency | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_common.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_common.py | BSD-3-Clause |
def test_nan_euclidean_support(pairwise_distances_func):
"""Check that `nan_euclidean` is lenient with `nan` values."""
X = [[0, 1], [1, np.nan], [2, 3], [3, 5]]
output = pairwise_distances_func(X, X, metric="nan_euclidean")
assert not np.isnan(output).any() | Check that `nan_euclidean` is lenient with `nan` values. | test_nan_euclidean_support | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_pairwise.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_pairwise.py | BSD-3-Clause |
def test_nan_euclidean_constant_input_argmin():
"""Check that the behavior of constant input is the same in the case of
full of nan vector and full of zero vector.
"""
X_nan = [[np.nan, np.nan], [np.nan, np.nan], [np.nan, np.nan]]
argmin_nan = pairwise_distances_argmin(X_nan, X_nan, metric="nan_euc... | Check that the behavior of constant input is the same in the case of
full of nan vector and full of zero vector.
| test_nan_euclidean_constant_input_argmin | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_pairwise.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_pairwise.py | BSD-3-Clause |
def test_pairwise_dist_custom_metric_for_string(X, Y, expected_distance):
"""Check pairwise_distances with lists of strings as input."""
def dummy_string_similarity(x, y):
return np.abs(len(x) - len(y))
actual_distance = pairwise_distances(X=X, Y=Y, metric=dummy_string_similarity)
assert_allcl... | Check pairwise_distances with lists of strings as input. | test_pairwise_dist_custom_metric_for_string | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_pairwise.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_pairwise.py | BSD-3-Clause |
def test_pairwise_dist_custom_metric_for_bool():
"""Check that pairwise_distances does not convert boolean input to float
when using a custom metric.
"""
def dummy_bool_dist(v1, v2):
# dummy distance func using `&` and thus relying on the input data being boolean
return 1 - (v1 & v2).su... | Check that pairwise_distances does not convert boolean input to float
when using a custom metric.
| test_pairwise_dist_custom_metric_for_bool | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_pairwise.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_pairwise.py | BSD-3-Clause |
def _get_metric_params_list(metric: str, n_features: int, seed: int = 1):
"""Return list of dummy DistanceMetric kwargs for tests."""
# Distinguishing on cases not to compute unneeded datastructures.
rng = np.random.RandomState(seed)
if metric == "minkowski":
minkowski_kwargs = [
d... | Return list of dummy DistanceMetric kwargs for tests. | _get_metric_params_list | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_pairwise_distances_reduction.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_pairwise_distances_reduction.py | BSD-3-Clause |
def assert_same_distances_for_common_neighbors(
query_idx,
dist_row_a,
dist_row_b,
indices_row_a,
indices_row_b,
rtol,
atol,
):
"""Check that the distances of common neighbors are equal up to tolerance.
This does not check if there are missing neighbors in either result set.
Mis... | Check that the distances of common neighbors are equal up to tolerance.
This does not check if there are missing neighbors in either result set.
Missingness is handled by assert_no_missing_neighbors.
| assert_same_distances_for_common_neighbors | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_pairwise_distances_reduction.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_pairwise_distances_reduction.py | BSD-3-Clause |
def assert_no_missing_neighbors(
query_idx,
dist_row_a,
dist_row_b,
indices_row_a,
indices_row_b,
threshold,
):
"""Compare the indices of neighbors in two results sets.
Any neighbor index with a distance below the precision threshold should
match one in the other result set. We igno... | Compare the indices of neighbors in two results sets.
Any neighbor index with a distance below the precision threshold should
match one in the other result set. We ignore the last few neighbors beyond
the threshold as those can typically be missing due to rounding errors.
For radius queries, the thres... | assert_no_missing_neighbors | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_pairwise_distances_reduction.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_pairwise_distances_reduction.py | BSD-3-Clause |
def assert_compatible_argkmin_results(
neighbors_dists_a,
neighbors_dists_b,
neighbors_indices_a,
neighbors_indices_b,
rtol=1e-5,
atol=1e-6,
):
"""Assert that argkmin results are valid up to rounding errors.
This function asserts that the results of argkmin queries are valid up to:
... | Assert that argkmin results are valid up to rounding errors.
This function asserts that the results of argkmin queries are valid up to:
- rounding error tolerance on distance values;
- permutations of indices for distances values that differ up to the
expected precision level.
Furthermore, the d... | assert_compatible_argkmin_results | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_pairwise_distances_reduction.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_pairwise_distances_reduction.py | BSD-3-Clause |
def assert_compatible_radius_results(
neighbors_dists_a,
neighbors_dists_b,
neighbors_indices_a,
neighbors_indices_b,
radius,
check_sorted=True,
rtol=1e-5,
atol=1e-6,
):
"""Assert that radius neighborhood results are valid up to:
- relative and absolute tolerance on computed d... | Assert that radius neighborhood results are valid up to:
- relative and absolute tolerance on computed distance values
- permutations of indices for distances values that differ up to
a precision level
- missing or extra last elements if their distance is
close to the radius
To b... | assert_compatible_radius_results | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_pairwise_distances_reduction.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_pairwise_distances_reduction.py | BSD-3-Clause |
def test_chunk_size_agnosticism(
global_random_seed,
Dispatcher,
dtype,
n_features=100,
):
"""Check that results do not depend on the chunk size."""
rng = np.random.RandomState(global_random_seed)
spread = 100
n_samples_X, n_samples_Y = rng.choice([97, 100, 101, 500], size=2, replace=Fal... | Check that results do not depend on the chunk size. | test_chunk_size_agnosticism | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_pairwise_distances_reduction.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_pairwise_distances_reduction.py | BSD-3-Clause |
def test_n_threads_agnosticism(
global_random_seed,
Dispatcher,
dtype,
n_features=100,
):
"""Check that results do not depend on the number of threads."""
rng = np.random.RandomState(global_random_seed)
n_samples_X, n_samples_Y = rng.choice([97, 100, 101, 500], size=2, replace=False)
spr... | Check that results do not depend on the number of threads. | test_n_threads_agnosticism | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_pairwise_distances_reduction.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_pairwise_distances_reduction.py | BSD-3-Clause |
def test_format_agnosticism(
global_random_seed,
Dispatcher,
dtype,
csr_container,
):
"""Check that results do not depend on the format (dense, sparse) of the input."""
rng = np.random.RandomState(global_random_seed)
spread = 100
n_samples, n_features = 100, 100
X = rng.rand(n_sampl... | Check that results do not depend on the format (dense, sparse) of the input. | test_format_agnosticism | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_pairwise_distances_reduction.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_pairwise_distances_reduction.py | BSD-3-Clause |
def test_strategies_consistency(
global_random_seed,
global_dtype,
Dispatcher,
n_features=10,
):
"""Check that the results do not depend on the strategy used."""
rng = np.random.RandomState(global_random_seed)
metric = rng.choice(
np.array(
[
"euclidean",
... | Check that the results do not depend on the strategy used. | test_strategies_consistency | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_pairwise_distances_reduction.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_pairwise_distances_reduction.py | BSD-3-Clause |
def test_memmap_backed_data(
metric,
Dispatcher,
dtype,
):
"""Check that the results do not depend on the datasets writability."""
rng = np.random.RandomState(0)
spread = 100
n_samples, n_features = 128, 10
X = rng.rand(n_samples, n_features).astype(dtype) * spread
Y = rng.rand(n_sam... | Check that the results do not depend on the datasets writability. | test_memmap_backed_data | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_pairwise_distances_reduction.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_pairwise_distances_reduction.py | BSD-3-Clause |
def make_prediction(dataset=None, binary=False):
"""Make some classification predictions on a toy dataset using a SVC
If binary is True restrict to a binary classification problem instead of a
multiclass classification problem
"""
if dataset is None:
# import some data to play with
... | Make some classification predictions on a toy dataset using a SVC
If binary is True restrict to a binary classification problem instead of a
multiclass classification problem
| make_prediction | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_ranking.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_ranking.py | BSD-3-Clause |
def _auc(y_true, y_score):
"""Alternative implementation to check for correctness of
`roc_auc_score`."""
pos_label = np.unique(y_true)[1]
# Count the number of times positive samples are correctly ranked above
# negative samples.
pos = y_score[y_true == pos_label]
neg = y_score[y_true != po... | Alternative implementation to check for correctness of
`roc_auc_score`. | _auc | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_ranking.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_ranking.py | BSD-3-Clause |
def _average_precision(y_true, y_score):
"""Alternative implementation to check for correctness of
`average_precision_score`.
Note that this implementation fails on some edge cases.
For example, for constant predictions e.g. [0.5, 0.5, 0.5],
y_true = [1, 0, 0] returns an average precision of 0.33..... | Alternative implementation to check for correctness of
`average_precision_score`.
Note that this implementation fails on some edge cases.
For example, for constant predictions e.g. [0.5, 0.5, 0.5],
y_true = [1, 0, 0] returns an average precision of 0.33...
but y_true = [0, 0, 1] returns 1.0.
| _average_precision | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_ranking.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_ranking.py | BSD-3-Clause |
def _average_precision_slow(y_true, y_score):
"""A second alternative implementation of average precision that closely
follows the Wikipedia article's definition (see References). This should
give identical results as `average_precision_score` for all inputs.
References
----------
.. [1] `Wikip... | A second alternative implementation of average precision that closely
follows the Wikipedia article's definition (see References). This should
give identical results as `average_precision_score` for all inputs.
References
----------
.. [1] `Wikipedia entry for the Average precision
<https://... | _average_precision_slow | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_ranking.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_ranking.py | BSD-3-Clause |
def _partial_roc_auc_score(y_true, y_predict, max_fpr):
"""Alternative implementation to check for correctness of `roc_auc_score`
with `max_fpr` set.
"""
def _partial_roc(y_true, y_predict, max_fpr):
fpr, tpr, _ = roc_curve(y_true, y_predict)
new_fpr = fpr[fpr <= max_fpr]
new_fp... | Alternative implementation to check for correctness of `roc_auc_score`
with `max_fpr` set.
| _partial_roc_auc_score | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_ranking.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_ranking.py | BSD-3-Clause |
def test_precision_recall_curve_drop_intermediate():
"""Check the behaviour of the `drop_intermediate` parameter."""
y_true = [0, 0, 0, 0, 1, 1]
y_score = [0.0, 0.2, 0.5, 0.6, 0.7, 1.0]
precision, recall, thresholds = precision_recall_curve(
y_true, y_score, drop_intermediate=True
)
asse... | Check the behaviour of the `drop_intermediate` parameter. | test_precision_recall_curve_drop_intermediate | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_ranking.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_ranking.py | BSD-3-Clause |
def _my_lrap(y_true, y_score):
"""Simple implementation of label ranking average precision"""
check_consistent_length(y_true, y_score)
y_true = check_array(y_true)
y_score = check_array(y_score)
n_samples, n_labels = y_true.shape
score = np.empty((n_samples,))
for i in range(n_samples):
... | Simple implementation of label ranking average precision | _my_lrap | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_ranking.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_ranking.py | BSD-3-Clause |
def test_ndcg_negative_ndarray_error():
"""Check `ndcg_score` exception when `y_true` contains negative values."""
y_true = np.array([[-0.89, -0.53, -0.47, 0.39, 0.56]])
y_score = np.array([[0.07, 0.31, 0.75, 0.33, 0.27]])
expected_message = "ndcg_score should not be used on negative y_true values"
... | Check `ndcg_score` exception when `y_true` contains negative values. | test_ndcg_negative_ndarray_error | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_ranking.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_ranking.py | BSD-3-Clause |
def test_ndcg_error_single_document():
"""Check that we raise an informative error message when trying to
compute NDCG with a single document."""
err_msg = (
"Computing NDCG is only meaningful when there is more than 1 document. "
"Got 1 instead."
)
with pytest.raises(ValueError, mat... | Check that we raise an informative error message when trying to
compute NDCG with a single document. | test_ndcg_error_single_document | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_ranking.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_ranking.py | BSD-3-Clause |
def test_top_k_accuracy_score_multiclass_with_labels(
y_true, true_score, labels, labels_as_ndarray
):
"""Test when labels and y_score are multiclass."""
if labels_as_ndarray:
labels = np.asarray(labels)
y_score = np.array(
[
[0.4, 0.3, 0.2, 0.1],
[0.1, 0.3, 0.4, ... | Test when labels and y_score are multiclass. | test_top_k_accuracy_score_multiclass_with_labels | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_ranking.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_ranking.py | BSD-3-Clause |
def test_ranking_metric_pos_label_types(metric, classes):
"""Check that the metric works with different types of `pos_label`.
We can expect `pos_label` to be a bool, an integer, a float, a string.
No error should be raised for those types.
"""
rng = np.random.RandomState(42)
n_samples, pos_labe... | Check that the metric works with different types of `pos_label`.
We can expect `pos_label` to be a bool, an integer, a float, a string.
No error should be raised for those types.
| test_ranking_metric_pos_label_types | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_ranking.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_ranking.py | BSD-3-Clause |
def test_roc_curve_with_probablity_estimates(global_random_seed):
"""Check that thresholds do not exceed 1.0 when `y_score` is a probability
estimate.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/26193
"""
rng = np.random.RandomState(global_random_seed)
y_tru... | Check that thresholds do not exceed 1.0 when `y_score` is a probability
estimate.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/26193
| test_roc_curve_with_probablity_estimates | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_ranking.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_ranking.py | BSD-3-Clause |
def test_multimetric_scorer_exception_handling(raise_exc):
"""Check that the calling of the `_MultimetricScorer` returns
exception messages in the result dict for the failing scorers
in case of `raise_exc` is `False` and if `raise_exc` is `True`,
then the proper exception is raised.
"""
scorers ... | Check that the calling of the `_MultimetricScorer` returns
exception messages in the result dict for the failing scorers
in case of `raise_exc` is `False` and if `raise_exc` is `True`,
then the proper exception is raised.
| test_multimetric_scorer_exception_handling | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_score_objects.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_score_objects.py | BSD-3-Clause |
def string_labeled_classification_problem():
"""Train a classifier on binary problem with string target.
The classifier is trained on a binary classification problem where the
minority class of interest has a string label that is intentionally not the
greatest class label using the lexicographic order.... | Train a classifier on binary problem with string target.
The classifier is trained on a binary classification problem where the
minority class of interest has a string label that is intentionally not the
greatest class label using the lexicographic order. In this case, "cancer"
is the positive label, a... | string_labeled_classification_problem | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_score_objects.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_score_objects.py | BSD-3-Clause |
def test_scorer_set_score_request_raises(name):
"""Test that set_score_request is only available when feature flag is on."""
# Make sure they expose the routing methods.
scorer = get_scorer(name)
with pytest.raises(RuntimeError, match="This method is only available"):
scorer.set_score_request() | Test that set_score_request is only available when feature flag is on. | test_scorer_set_score_request_raises | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_score_objects.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_score_objects.py | BSD-3-Clause |
def test_scorer_metadata_request(name):
"""Testing metadata requests for scorers.
This test checks many small things in a large test, to reduce the
boilerplate required for each section.
"""
# Make sure they expose the routing methods.
scorer = get_scorer(name)
assert hasattr(scorer, "set_s... | Testing metadata requests for scorers.
This test checks many small things in a large test, to reduce the
boilerplate required for each section.
| test_scorer_metadata_request | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_score_objects.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_score_objects.py | BSD-3-Clause |
def test_metadata_kwarg_conflict():
"""This test makes sure the right warning is raised if the user passes
some metadata both as a constructor to make_scorer, and during __call__.
"""
X, y = make_classification(
n_classes=3, n_informative=3, n_samples=20, random_state=0
)
lr = LogisticRe... | This test makes sure the right warning is raised if the user passes
some metadata both as a constructor to make_scorer, and during __call__.
| test_metadata_kwarg_conflict | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_score_objects.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_score_objects.py | BSD-3-Clause |
def test_PassthroughScorer_set_score_request():
"""Test that _PassthroughScorer.set_score_request adds the correct metadata request
on itself and doesn't change its estimator's routing."""
est = LogisticRegression().set_score_request(sample_weight="estimator_weights")
# make a `_PassthroughScorer` with ... | Test that _PassthroughScorer.set_score_request adds the correct metadata request
on itself and doesn't change its estimator's routing. | test_PassthroughScorer_set_score_request | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_score_objects.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_score_objects.py | BSD-3-Clause |
def test_PassthroughScorer_set_score_request_raises_without_routing_enabled():
"""Test that _PassthroughScorer.set_score_request raises if metadata routing is
disabled."""
scorer = check_scoring(LogisticRegression(), None)
msg = "This method is only available when metadata routing is enabled."
with... | Test that _PassthroughScorer.set_score_request raises if metadata routing is
disabled. | test_PassthroughScorer_set_score_request_raises_without_routing_enabled | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_score_objects.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_score_objects.py | BSD-3-Clause |
def test_get_scorer_multilabel_indicator():
"""Check that our scorer deal with multi-label indicator matrices.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/26817
"""
X, Y = make_multilabel_classification(n_samples=72, n_classes=3, random_state=0)
X_train, X_test,... | Check that our scorer deal with multi-label indicator matrices.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/26817
| test_get_scorer_multilabel_indicator | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_score_objects.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_score_objects.py | BSD-3-Clause |
def test_get_scorer_multimetric(pass_estimator):
"""Check that check_scoring is compatible with multi-metric configurations."""
X, y = make_classification(n_samples=150, n_features=10, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
clf = LogisticRegression(rand... | Check that check_scoring is compatible with multi-metric configurations. | test_get_scorer_multimetric | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_score_objects.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_score_objects.py | BSD-3-Clause |
def test_check_scoring_multimetric_raise_exc():
"""Test that check_scoring returns error code for a subset of scorers in
multimetric scoring if raise_exc=False and raises otherwise."""
def raising_scorer(estimator, X, y):
raise ValueError("That doesn't work.")
X, y = make_classification(n_samp... | Test that check_scoring returns error code for a subset of scorers in
multimetric scoring if raise_exc=False and raises otherwise. | test_check_scoring_multimetric_raise_exc | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_score_objects.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_score_objects.py | BSD-3-Clause |
def test_metadata_routing_multimetric_metadata_routing(enable_metadata_routing):
"""Test multimetric scorer works with and without metadata routing enabled when
there is no actual metadata to pass.
Non-regression test for https://github.com/scikit-learn/scikit-learn/issues/28256
"""
X, y = make_cla... | Test multimetric scorer works with and without metadata routing enabled when
there is no actual metadata to pass.
Non-regression test for https://github.com/scikit-learn/scikit-learn/issues/28256
| test_metadata_routing_multimetric_metadata_routing | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_score_objects.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_score_objects.py | BSD-3-Clause |
def test_curve_scorer():
"""Check the behaviour of the `_CurveScorer` class."""
X, y = make_classification(random_state=0)
estimator = LogisticRegression().fit(X, y)
curve_scorer = _CurveScorer(
balanced_accuracy_score,
sign=1,
response_method="predict_proba",
thresholds=... | Check the behaviour of the `_CurveScorer` class. | test_curve_scorer | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_score_objects.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_score_objects.py | BSD-3-Clause |
def test_curve_scorer_pos_label(global_random_seed):
"""Check that we propagate properly the `pos_label` parameter to the scorer."""
n_samples = 30
X, y = make_classification(
n_samples=n_samples, weights=[0.9, 0.1], random_state=global_random_seed
)
estimator = LogisticRegression().fit(X, y... | Check that we propagate properly the `pos_label` parameter to the scorer. | test_curve_scorer_pos_label | python | scikit-learn/scikit-learn | sklearn/metrics/tests/test_score_objects.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_score_objects.py | BSD-3-Clause |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves Python code examples from Django repository that contain 'django' in the code, which helps identify Django-specific code snippets but provides limited analytical insights beyond basic filtering.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.