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_tsne_n_jobs(method): """Make sure that the n_jobs parameter doesn't impact the output""" random_state = check_random_state(0) n_features = 10 X = random_state.randn(30, n_features) X_tr_ref = TSNE( n_components=2, method=method, perplexity=25.0, angle=0, ...
Make sure that the n_jobs parameter doesn't impact the output
test_tsne_n_jobs
python
scikit-learn/scikit-learn
sklearn/manifold/tests/test_t_sne.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/tests/test_t_sne.py
BSD-3-Clause
def test_tsne_with_mahalanobis_distance(): """Make sure that method_parameters works with mahalanobis distance.""" random_state = check_random_state(0) n_samples, n_features = 300, 10 X = random_state.randn(n_samples, n_features) default_params = { "perplexity": 40, "max_iter": 250, ...
Make sure that method_parameters works with mahalanobis distance.
test_tsne_with_mahalanobis_distance
python
scikit-learn/scikit-learn
sklearn/manifold/tests/test_t_sne.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/tests/test_t_sne.py
BSD-3-Clause
def test_tsne_perplexity_validation(perplexity): """Make sure that perplexity > n_samples results in a ValueError""" random_state = check_random_state(0) X = random_state.randn(20, 2) est = TSNE( learning_rate="auto", init="pca", perplexity=perplexity, random_state=rando...
Make sure that perplexity > n_samples results in a ValueError
test_tsne_perplexity_validation
python
scikit-learn/scikit-learn
sklearn/manifold/tests/test_t_sne.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/tests/test_t_sne.py
BSD-3-Clause
def test_tsne_works_with_pandas_output(): """Make sure that TSNE works when the output is set to "pandas". Non-regression test for gh-25365. """ pytest.importorskip("pandas") with config_context(transform_output="pandas"): arr = np.arange(35 * 4).reshape(35, 4) TSNE(n_components=2)....
Make sure that TSNE works when the output is set to "pandas". Non-regression test for gh-25365.
test_tsne_works_with_pandas_output
python
scikit-learn/scikit-learn
sklearn/manifold/tests/test_t_sne.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/tests/test_t_sne.py
BSD-3-Clause
def _return_float_dtype(X, Y): """ 1. If dtype of X and Y is float32, then dtype float32 is returned. 2. Else dtype float is returned. """ if not issparse(X) and not isinstance(X, np.ndarray): X = np.asarray(X) if Y is None: Y_dtype = X.dtype elif not issparse(Y) and not isi...
1. If dtype of X and Y is float32, then dtype float32 is returned. 2. Else dtype float is returned.
_return_float_dtype
python
scikit-learn/scikit-learn
sklearn/metrics/pairwise.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/pairwise.py
BSD-3-Clause
def check_pairwise_arrays( X, Y, *, precomputed=False, dtype="infer_float", accept_sparse="csr", force_all_finite="deprecated", ensure_all_finite=None, ensure_2d=True, copy=False, ): """Set X and Y appropriately and checks inputs. If Y is None, it is set as a pointer to ...
Set X and Y appropriately and checks inputs. If Y is None, it is set as a pointer to X (i.e. not a copy). If Y is given, this does not happen. All distance metrics should use this function first to assert that the given parameters are correct and safe to use. Specifically, this function first ensu...
check_pairwise_arrays
python
scikit-learn/scikit-learn
sklearn/metrics/pairwise.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/pairwise.py
BSD-3-Clause
def check_paired_arrays(X, Y): """Set X and Y appropriately and checks inputs for paired distances. All paired distance metrics should use this function first to assert that the given parameters are correct and safe to use. Specifically, this function first ensures that both X and Y are arrays, th...
Set X and Y appropriately and checks inputs for paired distances. All paired distance metrics should use this function first to assert that the given parameters are correct and safe to use. Specifically, this function first ensures that both X and Y are arrays, then checks that they are at least two d...
check_paired_arrays
python
scikit-learn/scikit-learn
sklearn/metrics/pairwise.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/pairwise.py
BSD-3-Clause
def euclidean_distances( X, Y=None, *, Y_norm_squared=None, squared=False, X_norm_squared=None ): """ Compute the distance matrix between each pair from a feature array X and Y. For efficiency reasons, the euclidean distance between a pair of row vector x and y is computed as:: dist(x, y) ...
Compute the distance matrix between each pair from a feature array X and Y. For efficiency reasons, the euclidean distance between a pair of row vector x and y is computed as:: dist(x, y) = sqrt(dot(x, x) - 2 * dot(x, y) + dot(y, y)) This formulation has two advantages over other ways of com...
euclidean_distances
python
scikit-learn/scikit-learn
sklearn/metrics/pairwise.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/pairwise.py
BSD-3-Clause
def _euclidean_distances(X, Y, X_norm_squared=None, Y_norm_squared=None, squared=False): """Computational part of euclidean_distances Assumes inputs are already checked. If norms are passed as float32, they are unused. If arrays are passed as float32, norms needs to be recomputed on upcast chunks. ...
Computational part of euclidean_distances Assumes inputs are already checked. If norms are passed as float32, they are unused. If arrays are passed as float32, norms needs to be recomputed on upcast chunks. TODO: use a float64 accumulator in row_norms to avoid the latter.
_euclidean_distances
python
scikit-learn/scikit-learn
sklearn/metrics/pairwise.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/pairwise.py
BSD-3-Clause
def nan_euclidean_distances( X, Y=None, *, squared=False, missing_values=np.nan, copy=True ): """Calculate the euclidean distances in the presence of missing values. Compute the euclidean distance between each pair of samples in X and Y, where Y=X is assumed if Y=None. When calculating the distance bet...
Calculate the euclidean distances in the presence of missing values. Compute the euclidean distance between each pair of samples in X and Y, where Y=X is assumed if Y=None. When calculating the distance between a pair of samples, this formulation ignores feature coordinates with a missing value in eith...
nan_euclidean_distances
python
scikit-learn/scikit-learn
sklearn/metrics/pairwise.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/pairwise.py
BSD-3-Clause
def pairwise_distances_argmin_min( X, Y, *, axis=1, metric="euclidean", metric_kwargs=None ): """Compute minimum distances between one point and a set of points. This function computes for each row in X, the index of the row of Y which is closest (according to the specified distance). The minimal dista...
Compute minimum distances between one point and a set of points. This function computes for each row in X, the index of the row of Y which is closest (according to the specified distance). The minimal distances are also returned. This is mostly equivalent to calling:: (pairwise_distances(X, Y...
pairwise_distances_argmin_min
python
scikit-learn/scikit-learn
sklearn/metrics/pairwise.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/pairwise.py
BSD-3-Clause
def pairwise_distances_argmin(X, Y, *, axis=1, metric="euclidean", metric_kwargs=None): """Compute minimum distances between one point and a set of points. This function computes for each row in X, the index of the row of Y which is closest (according to the specified distance). This is mostly equival...
Compute minimum distances between one point and a set of points. This function computes for each row in X, the index of the row of Y which is closest (according to the specified distance). This is mostly equivalent to calling:: pairwise_distances(X, Y=Y, metric=metric).argmin(axis=axis) but ...
pairwise_distances_argmin
python
scikit-learn/scikit-learn
sklearn/metrics/pairwise.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/pairwise.py
BSD-3-Clause
def haversine_distances(X, Y=None): """Compute the Haversine distance between samples in X and Y. The Haversine (or great circle) distance is the angular distance between two points on the surface of a sphere. The first coordinate of each point is assumed to be the latitude, the second is the longitude...
Compute the Haversine distance between samples in X and Y. The Haversine (or great circle) distance is the angular distance between two points on the surface of a sphere. The first coordinate of each point is assumed to be the latitude, the second is the longitude, given in radians. The dimension of th...
haversine_distances
python
scikit-learn/scikit-learn
sklearn/metrics/pairwise.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/pairwise.py
BSD-3-Clause
def manhattan_distances(X, Y=None): """Compute the L1 distances between the vectors in X and Y. Read more in the :ref:`User Guide <metrics>`. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples_X, n_features) An array where each row is a sample and each column is a fe...
Compute the L1 distances between the vectors in X and Y. Read more in the :ref:`User Guide <metrics>`. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples_X, n_features) An array where each row is a sample and each column is a feature. Y : {array-like, sparse matrix}...
manhattan_distances
python
scikit-learn/scikit-learn
sklearn/metrics/pairwise.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/pairwise.py
BSD-3-Clause
def cosine_distances(X, Y=None): """Compute cosine distance between samples in X and Y. Cosine distance is defined as 1.0 minus the cosine similarity. Read more in the :ref:`User Guide <metrics>`. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples_X, n_features) ...
Compute cosine distance between samples in X and Y. Cosine distance is defined as 1.0 minus the cosine similarity. Read more in the :ref:`User Guide <metrics>`. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples_X, n_features) Matrix `X`. Y : {array-like, spars...
cosine_distances
python
scikit-learn/scikit-learn
sklearn/metrics/pairwise.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/pairwise.py
BSD-3-Clause
def paired_euclidean_distances(X, Y): """Compute the paired euclidean distances between X and Y. Read more in the :ref:`User Guide <metrics>`. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Input array/matrix X. Y : {array-like, sparse matrix} o...
Compute the paired euclidean distances between X and Y. Read more in the :ref:`User Guide <metrics>`. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Input array/matrix X. Y : {array-like, sparse matrix} of shape (n_samples, n_features) Input...
paired_euclidean_distances
python
scikit-learn/scikit-learn
sklearn/metrics/pairwise.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/pairwise.py
BSD-3-Clause
def paired_manhattan_distances(X, Y): """Compute the paired L1 distances between X and Y. Distances are calculated between (X[0], Y[0]), (X[1], Y[1]), ..., (X[n_samples], Y[n_samples]). Read more in the :ref:`User Guide <metrics>`. Parameters ---------- X : {array-like, sparse matrix} of ...
Compute the paired L1 distances between X and Y. Distances are calculated between (X[0], Y[0]), (X[1], Y[1]), ..., (X[n_samples], Y[n_samples]). Read more in the :ref:`User Guide <metrics>`. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) An arra...
paired_manhattan_distances
python
scikit-learn/scikit-learn
sklearn/metrics/pairwise.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/pairwise.py
BSD-3-Clause
def paired_cosine_distances(X, Y): """ Compute the paired cosine distances between X and Y. Read more in the :ref:`User Guide <metrics>`. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) An array where each row is a sample and each column is a feat...
Compute the paired cosine distances between X and Y. Read more in the :ref:`User Guide <metrics>`. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) An array where each row is a sample and each column is a feature. Y : {array-like, sparse matrix} ...
paired_cosine_distances
python
scikit-learn/scikit-learn
sklearn/metrics/pairwise.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/pairwise.py
BSD-3-Clause
def paired_distances(X, Y, *, metric="euclidean", **kwds): """ Compute the paired distances between X and Y. Compute the distances between (X[0], Y[0]), (X[1], Y[1]), etc... Read more in the :ref:`User Guide <metrics>`. Parameters ---------- X : ndarray of shape (n_samples, n_features) ...
Compute the paired distances between X and Y. Compute the distances between (X[0], Y[0]), (X[1], Y[1]), etc... Read more in the :ref:`User Guide <metrics>`. Parameters ---------- X : ndarray of shape (n_samples, n_features) Array 1 for distance computation. Y : ndarray of shape ...
paired_distances
python
scikit-learn/scikit-learn
sklearn/metrics/pairwise.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/pairwise.py
BSD-3-Clause
def linear_kernel(X, Y=None, dense_output=True): """ Compute the linear kernel between X and Y. Read more in the :ref:`User Guide <linear_kernel>`. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples_X, n_features) A feature array. Y : {array-like, sparse mat...
Compute the linear kernel between X and Y. Read more in the :ref:`User Guide <linear_kernel>`. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples_X, n_features) A feature array. Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), default=None ...
linear_kernel
python
scikit-learn/scikit-learn
sklearn/metrics/pairwise.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/pairwise.py
BSD-3-Clause
def polynomial_kernel(X, Y=None, degree=3, gamma=None, coef0=1): """ Compute the polynomial kernel between X and Y. .. code-block:: text K(X, Y) = (gamma <X, Y> + coef0) ^ degree Read more in the :ref:`User Guide <polynomial_kernel>`. Parameters ---------- X : {array-like, sparse...
Compute the polynomial kernel between X and Y. .. code-block:: text K(X, Y) = (gamma <X, Y> + coef0) ^ degree Read more in the :ref:`User Guide <polynomial_kernel>`. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples_X, n_features) A feature array. ...
polynomial_kernel
python
scikit-learn/scikit-learn
sklearn/metrics/pairwise.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/pairwise.py
BSD-3-Clause
def sigmoid_kernel(X, Y=None, gamma=None, coef0=1): """Compute the sigmoid kernel between X and Y. .. code-block:: text K(X, Y) = tanh(gamma <X, Y> + coef0) Read more in the :ref:`User Guide <sigmoid_kernel>`. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples_...
Compute the sigmoid kernel between X and Y. .. code-block:: text K(X, Y) = tanh(gamma <X, Y> + coef0) Read more in the :ref:`User Guide <sigmoid_kernel>`. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples_X, n_features) A feature array. Y : {array-lik...
sigmoid_kernel
python
scikit-learn/scikit-learn
sklearn/metrics/pairwise.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/pairwise.py
BSD-3-Clause
def rbf_kernel(X, Y=None, gamma=None): """Compute the rbf (gaussian) kernel between X and Y. .. code-block:: text K(x, y) = exp(-gamma ||x-y||^2) for each pair of rows x in X and y in Y. Read more in the :ref:`User Guide <rbf_kernel>`. Parameters ---------- X : {array-like, spar...
Compute the rbf (gaussian) kernel between X and Y. .. code-block:: text K(x, y) = exp(-gamma ||x-y||^2) for each pair of rows x in X and y in Y. Read more in the :ref:`User Guide <rbf_kernel>`. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples_X, n_features) ...
rbf_kernel
python
scikit-learn/scikit-learn
sklearn/metrics/pairwise.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/pairwise.py
BSD-3-Clause
def laplacian_kernel(X, Y=None, gamma=None): """Compute the laplacian kernel between X and Y. The laplacian kernel is defined as: .. code-block:: text K(x, y) = exp(-gamma ||x-y||_1) for each pair of rows x in X and y in Y. Read more in the :ref:`User Guide <laplacian_kernel>`. .. v...
Compute the laplacian kernel between X and Y. The laplacian kernel is defined as: .. code-block:: text K(x, y) = exp(-gamma ||x-y||_1) for each pair of rows x in X and y in Y. Read more in the :ref:`User Guide <laplacian_kernel>`. .. versionadded:: 0.17 Parameters ---------- ...
laplacian_kernel
python
scikit-learn/scikit-learn
sklearn/metrics/pairwise.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/pairwise.py
BSD-3-Clause
def cosine_similarity(X, Y=None, dense_output=True): """Compute cosine similarity between samples in X and Y. Cosine similarity, or the cosine kernel, computes similarity as the normalized dot product of X and Y: .. code-block:: text K(X, Y) = <X, Y> / (||X||*||Y||) On L2-normalized data...
Compute cosine similarity between samples in X and Y. Cosine similarity, or the cosine kernel, computes similarity as the normalized dot product of X and Y: .. code-block:: text K(X, Y) = <X, Y> / (||X||*||Y||) On L2-normalized data, this function is equivalent to linear_kernel. Read mo...
cosine_similarity
python
scikit-learn/scikit-learn
sklearn/metrics/pairwise.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/pairwise.py
BSD-3-Clause
def additive_chi2_kernel(X, Y=None): """Compute the additive chi-squared kernel between observations in X and Y. The chi-squared kernel is computed between each pair of rows in X and Y. X and Y have to be non-negative. This kernel is most commonly applied to histograms. The chi-squared kernel is ...
Compute the additive chi-squared kernel between observations in X and Y. The chi-squared kernel is computed between each pair of rows in X and Y. X and Y have to be non-negative. This kernel is most commonly applied to histograms. The chi-squared kernel is given by: .. code-block:: text ...
additive_chi2_kernel
python
scikit-learn/scikit-learn
sklearn/metrics/pairwise.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/pairwise.py
BSD-3-Clause
def chi2_kernel(X, Y=None, gamma=1.0): """Compute the exponential chi-squared kernel between X and Y. The chi-squared kernel is computed between each pair of rows in X and Y. X and Y have to be non-negative. This kernel is most commonly applied to histograms. The chi-squared kernel is given by: ...
Compute the exponential chi-squared kernel between X and Y. The chi-squared kernel is computed between each pair of rows in X and Y. X and Y have to be non-negative. This kernel is most commonly applied to histograms. The chi-squared kernel is given by: .. code-block:: text k(x, y) = ex...
chi2_kernel
python
scikit-learn/scikit-learn
sklearn/metrics/pairwise.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/pairwise.py
BSD-3-Clause
def _parallel_pairwise(X, Y, func, n_jobs, **kwds): """Break the pairwise matrix in n_jobs even slices and compute them using multithreading.""" if Y is None: Y = X X, Y, dtype = _return_float_dtype(X, Y) if effective_n_jobs(n_jobs) == 1: return func(X, Y, **kwds) # enforce a ...
Break the pairwise matrix in n_jobs even slices and compute them using multithreading.
_parallel_pairwise
python
scikit-learn/scikit-learn
sklearn/metrics/pairwise.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/pairwise.py
BSD-3-Clause
def _pairwise_callable(X, Y, metric, ensure_all_finite=True, **kwds): """Handle the callable case for pairwise_{distances,kernels}.""" X, Y = check_pairwise_arrays( X, Y, dtype=None, ensure_all_finite=ensure_all_finite, # No input dimension checking done for custom metric...
Handle the callable case for pairwise_{distances,kernels}.
_pairwise_callable
python
scikit-learn/scikit-learn
sklearn/metrics/pairwise.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/pairwise.py
BSD-3-Clause
def _check_chunk_size(reduced, chunk_size): """Checks chunk is a sequence of expected size or a tuple of same.""" if reduced is None: return is_tuple = isinstance(reduced, tuple) if not is_tuple: reduced = (reduced,) if any(isinstance(r, tuple) or not hasattr(r, "__iter__") for r in ...
Checks chunk is a sequence of expected size or a tuple of same.
_check_chunk_size
python
scikit-learn/scikit-learn
sklearn/metrics/pairwise.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/pairwise.py
BSD-3-Clause
def _precompute_metric_params(X, Y, metric=None, **kwds): """Precompute data-derived metric parameters if not provided.""" if metric == "seuclidean" and "V" not in kwds: if X is Y: V = np.var(X, axis=0, ddof=1) else: raise ValueError( "The 'V' parameter is...
Precompute data-derived metric parameters if not provided.
_precompute_metric_params
python
scikit-learn/scikit-learn
sklearn/metrics/pairwise.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/pairwise.py
BSD-3-Clause
def pairwise_distances_chunked( X, Y=None, *, reduce_func=None, metric="euclidean", n_jobs=None, working_memory=None, **kwds, ): """Generate a distance matrix chunk by chunk with optional reduction. In cases where not all of a pairwise distance matrix needs to be stored at o...
Generate a distance matrix chunk by chunk with optional reduction. In cases where not all of a pairwise distance matrix needs to be stored at once, this is used to calculate pairwise distances in ``working_memory``-sized chunks. If ``reduce_func`` is given, it is run on each chunk and its return value...
pairwise_distances_chunked
python
scikit-learn/scikit-learn
sklearn/metrics/pairwise.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/pairwise.py
BSD-3-Clause
def pairwise_kernels( X, Y=None, metric="linear", *, filter_params=False, n_jobs=None, **kwds ): """Compute the kernel between arrays X and optional array Y. This function takes one or two feature arrays or a kernel matrix, and returns a kernel matrix. - If `X` is a feature array, of shape (n_samp...
Compute the kernel between arrays X and optional array Y. This function takes one or two feature arrays or a kernel matrix, and returns a kernel matrix. - If `X` is a feature array, of shape (n_samples_X, n_features), and: - `Y` is `None` and `metric` is not 'precomputed', the pairwise kernels ...
pairwise_kernels
python
scikit-learn/scikit-learn
sklearn/metrics/pairwise.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/pairwise.py
BSD-3-Clause
def _average_binary_score(binary_metric, y_true, y_score, average, sample_weight=None): """Average a binary metric for multilabel classification. Parameters ---------- y_true : array, shape = [n_samples] or [n_samples, n_classes] True binary labels in binary label indicators. y_score : arr...
Average a binary metric for multilabel classification. Parameters ---------- y_true : array, shape = [n_samples] or [n_samples, n_classes] True binary labels in binary label indicators. y_score : array, shape = [n_samples] or [n_samples, n_classes] Target scores, can either be probabil...
_average_binary_score
python
scikit-learn/scikit-learn
sklearn/metrics/_base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_base.py
BSD-3-Clause
def _average_multiclass_ovo_score(binary_metric, y_true, y_score, average="macro"): """Average one-versus-one scores for multiclass classification. Uses the binary metric for one-vs-one multiclass classification, where the score is computed according to the Hand & Till (2001) algorithm. Parameters ...
Average one-versus-one scores for multiclass classification. Uses the binary metric for one-vs-one multiclass classification, where the score is computed according to the Hand & Till (2001) algorithm. Parameters ---------- binary_metric : callable The binary metric function to use that acc...
_average_multiclass_ovo_score
python
scikit-learn/scikit-learn
sklearn/metrics/_base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_base.py
BSD-3-Clause
def _check_targets(y_true, y_pred): """Check that y_true and y_pred belong to the same classification task. This converts multiclass or binary types to a common shape, and raises a ValueError for a mix of multilabel and multiclass targets, a mix of multilabel formats, for the presence of continuous-val...
Check that y_true and y_pred belong to the same classification task. This converts multiclass or binary types to a common shape, and raises a ValueError for a mix of multilabel and multiclass targets, a mix of multilabel formats, for the presence of continuous-valued or multioutput targets, or for targ...
_check_targets
python
scikit-learn/scikit-learn
sklearn/metrics/_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_classification.py
BSD-3-Clause
def _validate_multiclass_probabilistic_prediction( y_true, y_prob, sample_weight, labels ): r"""Convert y_true and y_prob to shape (n_samples, n_classes) 1. Verify that y_true, y_prob, and sample_weights have the same first dim 2. Ensure 2 or more classes in y_true i.e. valid classification task. The ...
Convert y_true and y_prob to shape (n_samples, n_classes) 1. Verify that y_true, y_prob, and sample_weights have the same first dim 2. Ensure 2 or more classes in y_true i.e. valid classification task. The classes are provided by the labels argument, or inferred using y_true. When inferring y_tru...
_validate_multiclass_probabilistic_prediction
python
scikit-learn/scikit-learn
sklearn/metrics/_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_classification.py
BSD-3-Clause
def accuracy_score(y_true, y_pred, *, normalize=True, sample_weight=None): """Accuracy classification score. In multilabel classification, this function computes subset accuracy: the set of labels predicted for a sample must *exactly* match the corresponding set of labels in y_true. Read more in t...
Accuracy classification score. In multilabel classification, this function computes subset accuracy: the set of labels predicted for a sample must *exactly* match the corresponding set of labels in y_true. Read more in the :ref:`User Guide <accuracy_score>`. Parameters ---------- y_true :...
accuracy_score
python
scikit-learn/scikit-learn
sklearn/metrics/_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_classification.py
BSD-3-Clause
def confusion_matrix( y_true, y_pred, *, labels=None, sample_weight=None, normalize=None ): """Compute confusion matrix to evaluate the accuracy of a classification. By definition a confusion matrix :math:`C` is such that :math:`C_{i, j}` is equal to the number of observations known to be in group :mat...
Compute confusion matrix to evaluate the accuracy of a classification. By definition a confusion matrix :math:`C` is such that :math:`C_{i, j}` is equal to the number of observations known to be in group :math:`i` and predicted to be in group :math:`j`. Thus in binary classification, the count of true...
confusion_matrix
python
scikit-learn/scikit-learn
sklearn/metrics/_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_classification.py
BSD-3-Clause
def multilabel_confusion_matrix( y_true, y_pred, *, sample_weight=None, labels=None, samplewise=False ): """Compute a confusion matrix for each class or sample. .. versionadded:: 0.21 Compute class-wise (default) or sample-wise (samplewise=True) multilabel confusion matrix to evaluate the accuracy...
Compute a confusion matrix for each class or sample. .. versionadded:: 0.21 Compute class-wise (default) or sample-wise (samplewise=True) multilabel confusion matrix to evaluate the accuracy of a classification, and output confusion matrices for each class or sample. In multilabel confusion matri...
multilabel_confusion_matrix
python
scikit-learn/scikit-learn
sklearn/metrics/_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_classification.py
BSD-3-Clause
def jaccard_score( y_true, y_pred, *, labels=None, pos_label=1, average="binary", sample_weight=None, zero_division="warn", ): """Jaccard similarity coefficient score. The Jaccard index [1], or Jaccard similarity coefficient, defined as the size of the intersection divided b...
Jaccard similarity coefficient score. The Jaccard index [1], or Jaccard similarity coefficient, defined as the size of the intersection divided by the size of the union of two label sets, is used to compare set of predicted labels for a sample to the corresponding set of labels in ``y_true``. Supp...
jaccard_score
python
scikit-learn/scikit-learn
sklearn/metrics/_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_classification.py
BSD-3-Clause
def matthews_corrcoef(y_true, y_pred, *, sample_weight=None): """Compute the Matthews correlation coefficient (MCC). The Matthews correlation coefficient is used in machine learning as a measure of the quality of binary and multiclass classifications. It takes into account true and false positives and ...
Compute the Matthews correlation coefficient (MCC). The Matthews correlation coefficient is used in machine learning as a measure of the quality of binary and multiclass classifications. It takes into account true and false positives and negatives and is generally regarded as a balanced measure which c...
matthews_corrcoef
python
scikit-learn/scikit-learn
sklearn/metrics/_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_classification.py
BSD-3-Clause
def zero_one_loss(y_true, y_pred, *, normalize=True, sample_weight=None): """Zero-one classification loss. If normalize is ``True``, return the fraction of misclassifications (float), else it returns the number of misclassifications (int). The best performance is 0. Read more in the :ref:`User Gui...
Zero-one classification loss. If normalize is ``True``, return the fraction of misclassifications (float), else it returns the number of misclassifications (int). The best performance is 0. Read more in the :ref:`User Guide <zero_one_loss>`. Parameters ---------- y_true : 1d array-like, o...
zero_one_loss
python
scikit-learn/scikit-learn
sklearn/metrics/_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_classification.py
BSD-3-Clause
def f1_score( y_true, y_pred, *, labels=None, pos_label=1, average="binary", sample_weight=None, zero_division="warn", ): """Compute the F1 score, also known as balanced F-score or F-measure. The F1 score can be interpreted as a harmonic mean of the precision and recall, whe...
Compute the F1 score, also known as balanced F-score or F-measure. The F1 score can be interpreted as a harmonic mean of the precision and recall, where an F1 score reaches its best value at 1 and worst score at 0. The relative contribution of precision and recall to the F1 score are equal. The formula...
f1_score
python
scikit-learn/scikit-learn
sklearn/metrics/_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_classification.py
BSD-3-Clause
def fbeta_score( y_true, y_pred, *, beta, labels=None, pos_label=1, average="binary", sample_weight=None, zero_division="warn", ): """Compute the F-beta score. The F-beta score is the weighted harmonic mean of precision and recall, reaching its optimal value at 1 and its...
Compute the F-beta score. The F-beta score is the weighted harmonic mean of precision and recall, reaching its optimal value at 1 and its worst value at 0. The `beta` parameter represents the ratio of recall importance to precision importance. `beta > 1` gives more weight to recall, while `beta < ...
fbeta_score
python
scikit-learn/scikit-learn
sklearn/metrics/_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_classification.py
BSD-3-Clause
def _prf_divide( numerator, denominator, metric, modifier, average, warn_for, zero_division="warn" ): """Performs division and handles divide-by-zero. On zero-division, sets the corresponding result elements equal to 0, 1 or np.nan (according to ``zero_division``). Plus, if ``zero_division != "warn...
Performs division and handles divide-by-zero. On zero-division, sets the corresponding result elements equal to 0, 1 or np.nan (according to ``zero_division``). Plus, if ``zero_division != "warn"`` raises a warning. The metric, modifier and average arguments are used only for determining an approp...
_prf_divide
python
scikit-learn/scikit-learn
sklearn/metrics/_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_classification.py
BSD-3-Clause
def _check_set_wise_labels(y_true, y_pred, average, labels, pos_label): """Validation associated with set-wise metrics. Returns identified labels. """ average_options = (None, "micro", "macro", "weighted", "samples") if average not in average_options and average != "binary": raise ValueErro...
Validation associated with set-wise metrics. Returns identified labels.
_check_set_wise_labels
python
scikit-learn/scikit-learn
sklearn/metrics/_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_classification.py
BSD-3-Clause
def precision_recall_fscore_support( y_true, y_pred, *, beta=1.0, labels=None, pos_label=1, average=None, warn_for=("precision", "recall", "f-score"), sample_weight=None, zero_division="warn", ): """Compute precision, recall, F-measure and support for each class. The pre...
Compute precision, recall, F-measure and support for each class. The precision is the ratio ``tp / (tp + fp)`` where ``tp`` is the number of true positives and ``fp`` the number of false positives. The precision is intuitively the ability of the classifier not to label a negative sample as positive. ...
precision_recall_fscore_support
python
scikit-learn/scikit-learn
sklearn/metrics/_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_classification.py
BSD-3-Clause
def class_likelihood_ratios( y_true, y_pred, *, labels=None, sample_weight=None, raise_warning="deprecated", replace_undefined_by=np.nan, ): """Compute binary classification positive and negative likelihood ratios. The positive likelihood ratio is `LR+ = sensitivity / (1 - specifici...
Compute binary classification positive and negative likelihood ratios. The positive likelihood ratio is `LR+ = sensitivity / (1 - specificity)` where the sensitivity or recall is the ratio `tp / (tp + fn)` and the specificity is `tn / (tn + fp)`. The negative likelihood ratio is `LR- = (1 - sensitivity...
class_likelihood_ratios
python
scikit-learn/scikit-learn
sklearn/metrics/_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_classification.py
BSD-3-Clause
def precision_score( y_true, y_pred, *, labels=None, pos_label=1, average="binary", sample_weight=None, zero_division="warn", ): """Compute the precision. The precision is the ratio ``tp / (tp + fp)`` where ``tp`` is the number of true positives and ``fp`` the number of fals...
Compute the precision. The precision is the ratio ``tp / (tp + fp)`` where ``tp`` is the number of true positives and ``fp`` the number of false positives. The precision is intuitively the ability of the classifier not to label as positive a sample that is negative. The best value is 1 and the wor...
precision_score
python
scikit-learn/scikit-learn
sklearn/metrics/_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_classification.py
BSD-3-Clause
def recall_score( y_true, y_pred, *, labels=None, pos_label=1, average="binary", sample_weight=None, zero_division="warn", ): """Compute the recall. The recall is the ratio ``tp / (tp + fn)`` where ``tp`` is the number of true positives and ``fn`` the number of false negativ...
Compute the recall. The recall is the ratio ``tp / (tp + fn)`` where ``tp`` is the number of true positives and ``fn`` the number of false negatives. The recall is intuitively the ability of the classifier to find all the positive samples. The best value is 1 and the worst value is 0. Support bey...
recall_score
python
scikit-learn/scikit-learn
sklearn/metrics/_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_classification.py
BSD-3-Clause
def classification_report( y_true, y_pred, *, labels=None, target_names=None, sample_weight=None, digits=2, output_dict=False, zero_division="warn", ): """Build a text report showing the main classification metrics. Read more in the :ref:`User Guide <classification_report>`....
Build a text report showing the main classification metrics. Read more in the :ref:`User Guide <classification_report>`. Parameters ---------- y_true : 1d array-like, or label indicator array / sparse matrix Ground truth (correct) target values. y_pred : 1d array-like, or label indicator ...
classification_report
python
scikit-learn/scikit-learn
sklearn/metrics/_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_classification.py
BSD-3-Clause
def hamming_loss(y_true, y_pred, *, sample_weight=None): """Compute the average Hamming loss. The Hamming loss is the fraction of labels that are incorrectly predicted. Read more in the :ref:`User Guide <hamming_loss>`. Parameters ---------- y_true : 1d array-like, or label indicator array / ...
Compute the average Hamming loss. The Hamming loss is the fraction of labels that are incorrectly predicted. Read more in the :ref:`User Guide <hamming_loss>`. Parameters ---------- y_true : 1d array-like, or label indicator array / sparse matrix Ground truth (correct) labels. y_pred...
hamming_loss
python
scikit-learn/scikit-learn
sklearn/metrics/_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_classification.py
BSD-3-Clause
def log_loss(y_true, y_pred, *, normalize=True, sample_weight=None, labels=None): r"""Log loss, aka logistic loss or cross-entropy loss. This is the loss function used in (multinomial) logistic regression and extensions of it such as neural networks, defined as the negative log-likelihood of a logistic...
Log loss, aka logistic loss or cross-entropy loss. This is the loss function used in (multinomial) logistic regression and extensions of it such as neural networks, defined as the negative log-likelihood of a logistic model that returns ``y_pred`` probabilities for its training data ``y_true``. The...
log_loss
python
scikit-learn/scikit-learn
sklearn/metrics/_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_classification.py
BSD-3-Clause
def hinge_loss(y_true, pred_decision, *, labels=None, sample_weight=None): """Average hinge loss (non-regularized). In binary class case, assuming labels in y_true are encoded with +1 and -1, when a prediction mistake is made, ``margin = y_true * pred_decision`` is always negative (since the signs disa...
Average hinge loss (non-regularized). In binary class case, assuming labels in y_true are encoded with +1 and -1, when a prediction mistake is made, ``margin = y_true * pred_decision`` is always negative (since the signs disagree), implying ``1 - margin`` is always greater than 1. The cumulated hinge ...
hinge_loss
python
scikit-learn/scikit-learn
sklearn/metrics/_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_classification.py
BSD-3-Clause
def _validate_binary_probabilistic_prediction(y_true, y_prob, sample_weight, pos_label): r"""Convert y_true and y_prob in binary classification to shape (n_samples, 2) Parameters ---------- y_true : array-like of shape (n_samples,) True labels. y_prob : array-like of shape (n_samples,) ...
Convert y_true and y_prob in binary classification to shape (n_samples, 2) Parameters ---------- y_true : array-like of shape (n_samples,) True labels. y_prob : array-like of shape (n_samples,) Probabilities of the positive class. sample_weight : array-like of shape (n_samples,), ...
_validate_binary_probabilistic_prediction
python
scikit-learn/scikit-learn
sklearn/metrics/_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_classification.py
BSD-3-Clause
def brier_score_loss( y_true, y_proba, *, sample_weight=None, pos_label=None, labels=None, scale_by_half="auto", ): r"""Compute the Brier score loss. The smaller the Brier score loss, the better, hence the naming with "loss". The Brier score measures the mean squared difference ...
Compute the Brier score loss. The smaller the Brier score loss, the better, hence the naming with "loss". The Brier score measures the mean squared difference between the predicted probability and the actual outcome. The Brier score is a strictly proper scoring rule. Read more in the :ref:`User Gu...
brier_score_loss
python
scikit-learn/scikit-learn
sklearn/metrics/_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_classification.py
BSD-3-Clause
def d2_log_loss_score(y_true, y_pred, *, sample_weight=None, labels=None): """ :math:`D^2` score function, fraction of log loss explained. Best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A model that always predicts the per-class proportions of `y_tru...
:math:`D^2` score function, fraction of log loss explained. Best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A model that always predicts the per-class proportions of `y_true`, disregarding the input features, gets a D^2 score of 0.0. Read more in th...
d2_log_loss_score
python
scikit-learn/scikit-learn
sklearn/metrics/_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_classification.py
BSD-3-Clause
def auc(x, y): """Compute Area Under the Curve (AUC) using the trapezoidal rule. This is a general function, given points on a curve. For computing the area under the ROC-curve, see :func:`roc_auc_score`. For an alternative way to summarize a precision-recall curve, see :func:`average_precision_s...
Compute Area Under the Curve (AUC) using the trapezoidal rule. This is a general function, given points on a curve. For computing the area under the ROC-curve, see :func:`roc_auc_score`. For an alternative way to summarize a precision-recall curve, see :func:`average_precision_score`. Parameters...
auc
python
scikit-learn/scikit-learn
sklearn/metrics/_ranking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_ranking.py
BSD-3-Clause
def average_precision_score( y_true, y_score, *, average="macro", pos_label=1, sample_weight=None ): """Compute average precision (AP) from prediction scores. AP summarizes a precision-recall curve as the weighted mean of precisions achieved at each threshold, with the increase in recall from the previ...
Compute average precision (AP) from prediction scores. AP summarizes a precision-recall curve as the weighted mean of precisions achieved at each threshold, with the increase in recall from the previous threshold used as the weight: .. math:: \text{AP} = \sum_n (R_n - R_{n-1}) P_n where :...
average_precision_score
python
scikit-learn/scikit-learn
sklearn/metrics/_ranking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_ranking.py
BSD-3-Clause
def det_curve( y_true, y_score, pos_label=None, sample_weight=None, drop_intermediate=False ): """Compute Detection Error Tradeoff (DET) for different probability thresholds. .. note:: This metric is used for evaluation of ranking and error tradeoffs of a binary classification task. Read...
Compute Detection Error Tradeoff (DET) for different probability thresholds. .. note:: This metric is used for evaluation of ranking and error tradeoffs of a binary classification task. Read more in the :ref:`User Guide <det_curve>`. .. versionadded:: 0.24 .. versionchanged:: 1.7 ...
det_curve
python
scikit-learn/scikit-learn
sklearn/metrics/_ranking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_ranking.py
BSD-3-Clause
def roc_auc_score( y_true, y_score, *, average="macro", sample_weight=None, max_fpr=None, multi_class="raise", labels=None, ): """Compute Area Under the Receiver Operating Characteristic Curve (ROC AUC) \ from prediction scores. Note: this implementation can be used with bin...
Compute Area Under the Receiver Operating Characteristic Curve (ROC AUC) from prediction scores. Note: this implementation can be used with binary, multiclass and multilabel classification, but some restrictions apply (see Parameters). Read more in the :ref:`User Guide <roc_metrics>`. Parameters ...
roc_auc_score
python
scikit-learn/scikit-learn
sklearn/metrics/_ranking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_ranking.py
BSD-3-Clause
def _multiclass_roc_auc_score( y_true, y_score, labels, multi_class, average, sample_weight ): """Multiclass roc auc score. Parameters ---------- y_true : array-like of shape (n_samples,) True multiclass labels. y_score : array-like of shape (n_samples, n_classes) Target scores...
Multiclass roc auc score. Parameters ---------- y_true : array-like of shape (n_samples,) True multiclass labels. y_score : array-like of shape (n_samples, n_classes) Target scores corresponding to probability estimates of a sample belonging to a particular class labels : ...
_multiclass_roc_auc_score
python
scikit-learn/scikit-learn
sklearn/metrics/_ranking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_ranking.py
BSD-3-Clause
def _binary_clf_curve(y_true, y_score, pos_label=None, sample_weight=None): """Calculate true and false positives per binary classification threshold. Parameters ---------- y_true : ndarray of shape (n_samples,) True targets of binary classification. y_score : ndarray of shape (n_samples,)...
Calculate true and false positives per binary classification threshold. Parameters ---------- y_true : ndarray of shape (n_samples,) True targets of binary classification. y_score : ndarray of shape (n_samples,) Estimated probabilities or output of a decision function. pos_label :...
_binary_clf_curve
python
scikit-learn/scikit-learn
sklearn/metrics/_ranking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_ranking.py
BSD-3-Clause
def precision_recall_curve( y_true, y_score, *, pos_label=None, sample_weight=None, drop_intermediate=False, ): """Compute precision-recall pairs for different probability thresholds. Note: this implementation is restricted to the binary classification task. The precision is the ra...
Compute precision-recall pairs for different probability thresholds. Note: this implementation is restricted to the binary classification task. The precision is the ratio ``tp / (tp + fp)`` where ``tp`` is the number of true positives and ``fp`` the number of false positives. The precision is intuitiv...
precision_recall_curve
python
scikit-learn/scikit-learn
sklearn/metrics/_ranking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_ranking.py
BSD-3-Clause
def roc_curve( y_true, y_score, *, pos_label=None, sample_weight=None, drop_intermediate=True ): """Compute Receiver operating characteristic (ROC). Note: this implementation is restricted to the binary classification task. Read more in the :ref:`User Guide <roc_metrics>`. Parameters --------...
Compute Receiver operating characteristic (ROC). Note: this implementation is restricted to the binary classification task. Read more in the :ref:`User Guide <roc_metrics>`. Parameters ---------- y_true : array-like of shape (n_samples,) True binary labels. If labels are not either {-1, 1...
roc_curve
python
scikit-learn/scikit-learn
sklearn/metrics/_ranking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_ranking.py
BSD-3-Clause
def label_ranking_average_precision_score(y_true, y_score, *, sample_weight=None): """Compute ranking-based average precision. Label ranking average precision (LRAP) is the average over each ground truth label assigned to each sample, of the ratio of true vs. total labels with lower score. This me...
Compute ranking-based average precision. Label ranking average precision (LRAP) is the average over each ground truth label assigned to each sample, of the ratio of true vs. total labels with lower score. This metric is used in multilabel ranking problem, where the goal is to give better rank to t...
label_ranking_average_precision_score
python
scikit-learn/scikit-learn
sklearn/metrics/_ranking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_ranking.py
BSD-3-Clause
def coverage_error(y_true, y_score, *, sample_weight=None): """Coverage error measure. Compute how far we need to go through the ranked scores to cover all true labels. The best value is equal to the average number of labels in ``y_true`` per sample. Ties in ``y_scores`` are broken by giving maxim...
Coverage error measure. Compute how far we need to go through the ranked scores to cover all true labels. The best value is equal to the average number of labels in ``y_true`` per sample. Ties in ``y_scores`` are broken by giving maximal rank that would have been assigned to all tied values. ...
coverage_error
python
scikit-learn/scikit-learn
sklearn/metrics/_ranking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_ranking.py
BSD-3-Clause
def label_ranking_loss(y_true, y_score, *, sample_weight=None): """Compute Ranking loss measure. Compute the average number of label pairs that are incorrectly ordered given y_score weighted by the size of the label set and the number of labels not in the label set. This is similar to the error se...
Compute Ranking loss measure. Compute the average number of label pairs that are incorrectly ordered given y_score weighted by the size of the label set and the number of labels not in the label set. This is similar to the error set size, but weighted by the number of relevant and irrelevant label...
label_ranking_loss
python
scikit-learn/scikit-learn
sklearn/metrics/_ranking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_ranking.py
BSD-3-Clause
def _dcg_sample_scores(y_true, y_score, k=None, log_base=2, ignore_ties=False): """Compute Discounted Cumulative Gain. Sum the true scores ranked in the order induced by the predicted scores, after applying a logarithmic discount. This ranking metric yields a high value if true labels are ranked high ...
Compute Discounted Cumulative Gain. Sum the true scores ranked in the order induced by the predicted scores, after applying a logarithmic discount. This ranking metric yields a high value if true labels are ranked high by ``y_score``. Parameters ---------- y_true : ndarray of shape (n_sam...
_dcg_sample_scores
python
scikit-learn/scikit-learn
sklearn/metrics/_ranking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_ranking.py
BSD-3-Clause
def _tie_averaged_dcg(y_true, y_score, discount_cumsum): """ Compute DCG by averaging over possible permutations of ties. The gain (`y_true`) of an index falling inside a tied group (in the order induced by `y_score`) is replaced by the average gain within this group. The discounted gain for a tied...
Compute DCG by averaging over possible permutations of ties. The gain (`y_true`) of an index falling inside a tied group (in the order induced by `y_score`) is replaced by the average gain within this group. The discounted gain for a tied group is then the average `y_true` within this group times ...
_tie_averaged_dcg
python
scikit-learn/scikit-learn
sklearn/metrics/_ranking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_ranking.py
BSD-3-Clause
def dcg_score( y_true, y_score, *, k=None, log_base=2, sample_weight=None, ignore_ties=False ): """Compute Discounted Cumulative Gain. Sum the true scores ranked in the order induced by the predicted scores, after applying a logarithmic discount. This ranking metric yields a high value if true lab...
Compute Discounted Cumulative Gain. Sum the true scores ranked in the order induced by the predicted scores, after applying a logarithmic discount. This ranking metric yields a high value if true labels are ranked high by ``y_score``. Usually the Normalized Discounted Cumulative Gain (NDCG, compu...
dcg_score
python
scikit-learn/scikit-learn
sklearn/metrics/_ranking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_ranking.py
BSD-3-Clause
def _ndcg_sample_scores(y_true, y_score, k=None, ignore_ties=False): """Compute Normalized Discounted Cumulative Gain. Sum the true scores ranked in the order induced by the predicted scores, after applying a logarithmic discount. Then divide by the best possible score (Ideal DCG, obtained for a perfec...
Compute Normalized Discounted Cumulative Gain. Sum the true scores ranked in the order induced by the predicted scores, after applying a logarithmic discount. Then divide by the best possible score (Ideal DCG, obtained for a perfect ranking) to obtain a score between 0 and 1. This ranking metric y...
_ndcg_sample_scores
python
scikit-learn/scikit-learn
sklearn/metrics/_ranking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_ranking.py
BSD-3-Clause
def ndcg_score(y_true, y_score, *, k=None, sample_weight=None, ignore_ties=False): """Compute Normalized Discounted Cumulative Gain. Sum the true scores ranked in the order induced by the predicted scores, after applying a logarithmic discount. Then divide by the best possible score (Ideal DCG, obtaine...
Compute Normalized Discounted Cumulative Gain. Sum the true scores ranked in the order induced by the predicted scores, after applying a logarithmic discount. Then divide by the best possible score (Ideal DCG, obtained for a perfect ranking) to obtain a score between 0 and 1. This ranking metric r...
ndcg_score
python
scikit-learn/scikit-learn
sklearn/metrics/_ranking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_ranking.py
BSD-3-Clause
def top_k_accuracy_score( y_true, y_score, *, k=2, normalize=True, sample_weight=None, labels=None ): """Top-k Accuracy classification score. This metric computes the number of times where the correct label is among the top `k` labels predicted (ranked by predicted scores). Note that the multilabel...
Top-k Accuracy classification score. This metric computes the number of times where the correct label is among the top `k` labels predicted (ranked by predicted scores). Note that the multilabel case isn't covered here. Read more in the :ref:`User Guide <top_k_accuracy_score>` Parameters ----...
top_k_accuracy_score
python
scikit-learn/scikit-learn
sklearn/metrics/_ranking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_ranking.py
BSD-3-Clause
def _check_reg_targets( y_true, y_pred, sample_weight, multioutput, dtype="numeric", xp=None ): """Check that y_true, y_pred and sample_weight belong to the same regression task. To reduce redundancy when calling `_find_matching_floating_dtype`, please use `_check_reg_targets_with_floating_dtype` inste...
Check that y_true, y_pred and sample_weight belong to the same regression task. To reduce redundancy when calling `_find_matching_floating_dtype`, please use `_check_reg_targets_with_floating_dtype` instead. Parameters ---------- y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) ...
_check_reg_targets
python
scikit-learn/scikit-learn
sklearn/metrics/_regression.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_regression.py
BSD-3-Clause
def _check_reg_targets_with_floating_dtype( y_true, y_pred, sample_weight, multioutput, xp=None ): """Ensures y_true, y_pred, and sample_weight correspond to same regression task. Extends `_check_reg_targets` by automatically selecting a suitable floating-point data type for inputs using `_find_matchin...
Ensures y_true, y_pred, and sample_weight correspond to same regression task. Extends `_check_reg_targets` by automatically selecting a suitable floating-point data type for inputs using `_find_matching_floating_dtype`. Use this private method only when converting inputs to array API-compatibles. Par...
_check_reg_targets_with_floating_dtype
python
scikit-learn/scikit-learn
sklearn/metrics/_regression.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_regression.py
BSD-3-Clause
def mean_absolute_error( y_true, y_pred, *, sample_weight=None, multioutput="uniform_average" ): """Mean absolute error regression loss. The mean absolute error is a non-negative floating point value, where best value is 0.0. Read more in the :ref:`User Guide <mean_absolute_error>`. Parameters ...
Mean absolute error regression loss. The mean absolute error is a non-negative floating point value, where best value is 0.0. Read more in the :ref:`User Guide <mean_absolute_error>`. Parameters ---------- y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) Ground truth (co...
mean_absolute_error
python
scikit-learn/scikit-learn
sklearn/metrics/_regression.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_regression.py
BSD-3-Clause
def mean_pinball_loss( y_true, y_pred, *, sample_weight=None, alpha=0.5, multioutput="uniform_average" ): """Pinball loss for quantile regression. Read more in the :ref:`User Guide <pinball_loss>`. Parameters ---------- y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) ...
Pinball loss for quantile regression. Read more in the :ref:`User Guide <pinball_loss>`. Parameters ---------- y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) Ground truth (correct) target values. y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) ...
mean_pinball_loss
python
scikit-learn/scikit-learn
sklearn/metrics/_regression.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_regression.py
BSD-3-Clause
def mean_absolute_percentage_error( y_true, y_pred, *, sample_weight=None, multioutput="uniform_average" ): """Mean absolute percentage error (MAPE) regression loss. Note that we are not using the common "percentage" definition: the percentage in the range [0, 100] is converted to a relative value in t...
Mean absolute percentage error (MAPE) regression loss. Note that we are not using the common "percentage" definition: the percentage in the range [0, 100] is converted to a relative value in the range [0, 1] by dividing by 100. Thus, an error of 200% corresponds to a relative error of 2. Read more in ...
mean_absolute_percentage_error
python
scikit-learn/scikit-learn
sklearn/metrics/_regression.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_regression.py
BSD-3-Clause
def mean_squared_error( y_true, y_pred, *, sample_weight=None, multioutput="uniform_average", ): """Mean squared error regression loss. Read more in the :ref:`User Guide <mean_squared_error>`. Parameters ---------- y_true : array-like of shape (n_samples,) or (n_samples, n_outp...
Mean squared error regression loss. Read more in the :ref:`User Guide <mean_squared_error>`. Parameters ---------- y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) Ground truth (correct) target values. y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) ...
mean_squared_error
python
scikit-learn/scikit-learn
sklearn/metrics/_regression.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_regression.py
BSD-3-Clause
def root_mean_squared_error( y_true, y_pred, *, sample_weight=None, multioutput="uniform_average" ): """Root mean squared error regression loss. Read more in the :ref:`User Guide <mean_squared_error>`. .. versionadded:: 1.4 Parameters ---------- y_true : array-like of shape (n_samples,) o...
Root mean squared error regression loss. Read more in the :ref:`User Guide <mean_squared_error>`. .. versionadded:: 1.4 Parameters ---------- y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) Ground truth (correct) target values. y_pred : array-like of shape (n_samp...
root_mean_squared_error
python
scikit-learn/scikit-learn
sklearn/metrics/_regression.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_regression.py
BSD-3-Clause
def mean_squared_log_error( y_true, y_pred, *, sample_weight=None, multioutput="uniform_average", ): """Mean squared logarithmic error regression loss. Read more in the :ref:`User Guide <mean_squared_log_error>`. Parameters ---------- y_true : array-like of shape (n_samples,) o...
Mean squared logarithmic error regression loss. Read more in the :ref:`User Guide <mean_squared_log_error>`. Parameters ---------- y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) Ground truth (correct) target values. y_pred : array-like of shape (n_samples,) or (n_samp...
mean_squared_log_error
python
scikit-learn/scikit-learn
sklearn/metrics/_regression.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_regression.py
BSD-3-Clause
def root_mean_squared_log_error( y_true, y_pred, *, sample_weight=None, multioutput="uniform_average" ): """Root mean squared logarithmic error regression loss. Read more in the :ref:`User Guide <mean_squared_log_error>`. .. versionadded:: 1.4 Parameters ---------- y_true : array-like of ...
Root mean squared logarithmic error regression loss. Read more in the :ref:`User Guide <mean_squared_log_error>`. .. versionadded:: 1.4 Parameters ---------- y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) Ground truth (correct) target values. y_pred : array-like ...
root_mean_squared_log_error
python
scikit-learn/scikit-learn
sklearn/metrics/_regression.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_regression.py
BSD-3-Clause
def median_absolute_error( y_true, y_pred, *, multioutput="uniform_average", sample_weight=None ): """Median absolute error regression loss. Median absolute error output is non-negative floating point. The best value is 0.0. Read more in the :ref:`User Guide <median_absolute_error>`. Parameters ...
Median absolute error regression loss. Median absolute error output is non-negative floating point. The best value is 0.0. Read more in the :ref:`User Guide <median_absolute_error>`. Parameters ---------- y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) Ground truth (cor...
median_absolute_error
python
scikit-learn/scikit-learn
sklearn/metrics/_regression.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_regression.py
BSD-3-Clause
def _assemble_r2_explained_variance( numerator, denominator, n_outputs, multioutput, force_finite, xp, device ): """Common part used by explained variance score and :math:`R^2` score.""" dtype = numerator.dtype nonzero_denominator = denominator != 0 if not force_finite: # Standard formula,...
Common part used by explained variance score and :math:`R^2` score.
_assemble_r2_explained_variance
python
scikit-learn/scikit-learn
sklearn/metrics/_regression.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_regression.py
BSD-3-Clause
def explained_variance_score( y_true, y_pred, *, sample_weight=None, multioutput="uniform_average", force_finite=True, ): """Explained variance regression score function. Best possible score is 1.0, lower values are worse. In the particular case when ``y_true`` is constant, the exp...
Explained variance regression score function. Best possible score is 1.0, lower values are worse. In the particular case when ``y_true`` is constant, the explained variance score is not finite: it is either ``NaN`` (perfect predictions) or ``-Inf`` (imperfect predictions). To prevent such non-finite n...
explained_variance_score
python
scikit-learn/scikit-learn
sklearn/metrics/_regression.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_regression.py
BSD-3-Clause
def r2_score( y_true, y_pred, *, sample_weight=None, multioutput="uniform_average", force_finite=True, ): """:math:`R^2` (coefficient of determination) regression score function. Best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). In the g...
:math:`R^2` (coefficient of determination) regression score function. Best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). In the general case when the true y is non-constant, a constant model that always predicts the average y disregarding the input features ...
r2_score
python
scikit-learn/scikit-learn
sklearn/metrics/_regression.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_regression.py
BSD-3-Clause
def max_error(y_true, y_pred): """ The max_error metric calculates the maximum residual error. Read more in the :ref:`User Guide <max_error>`. Parameters ---------- y_true : array-like of shape (n_samples,) Ground truth (correct) target values. y_pred : array-like of shape (n_samp...
The max_error metric calculates the maximum residual error. Read more in the :ref:`User Guide <max_error>`. Parameters ---------- y_true : array-like of shape (n_samples,) Ground truth (correct) target values. y_pred : array-like of shape (n_samples,) Estimated target values....
max_error
python
scikit-learn/scikit-learn
sklearn/metrics/_regression.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_regression.py
BSD-3-Clause
def mean_tweedie_deviance(y_true, y_pred, *, sample_weight=None, power=0): """Mean Tweedie deviance regression loss. Read more in the :ref:`User Guide <mean_tweedie_deviance>`. Parameters ---------- y_true : array-like of shape (n_samples,) Ground truth (correct) target values. y_pred...
Mean Tweedie deviance regression loss. Read more in the :ref:`User Guide <mean_tweedie_deviance>`. Parameters ---------- y_true : array-like of shape (n_samples,) Ground truth (correct) target values. y_pred : array-like of shape (n_samples,) Estimated target values. sample_w...
mean_tweedie_deviance
python
scikit-learn/scikit-learn
sklearn/metrics/_regression.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_regression.py
BSD-3-Clause
def d2_tweedie_score(y_true, y_pred, *, sample_weight=None, power=0): """ :math:`D^2` regression score function, fraction of Tweedie deviance explained. Best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A model that always uses the empirical mean of `y_true...
:math:`D^2` regression score function, fraction of Tweedie deviance explained. Best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A model that always uses the empirical mean of `y_true` as constant prediction, disregarding the input features, gets a D^2 sco...
d2_tweedie_score
python
scikit-learn/scikit-learn
sklearn/metrics/_regression.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_regression.py
BSD-3-Clause
def d2_absolute_error_score( y_true, y_pred, *, sample_weight=None, multioutput="uniform_average" ): """ :math:`D^2` regression score function, fraction of absolute error explained. Best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A model that always u...
:math:`D^2` regression score function, fraction of absolute error explained. Best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A model that always uses the empirical median of `y_true` as constant prediction, disregarding the input features, gets a :ma...
d2_absolute_error_score
python
scikit-learn/scikit-learn
sklearn/metrics/_regression.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_regression.py
BSD-3-Clause
def _cached_call(cache, estimator, response_method, *args, **kwargs): """Call estimator with method and args and kwargs.""" if cache is not None and response_method in cache: return cache[response_method] result, _ = _get_response_values( estimator, *args, response_method=response_method, *...
Call estimator with method and args and kwargs.
_cached_call
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 _use_cache(self, estimator): """Return True if using a cache is beneficial, thus when a response method will be called several time. """ if len(self._scorers) == 1: # Only one scorer return False counter = Counter( [ _check_response_m...
Return True if using a cache is beneficial, thus when a response method will be called several time.
_use_cache
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 get_metadata_routing(self): """Get metadata routing of this object. Please check :ref:`User Guide <metadata_routing>` on how the routing mechanism works. .. versionadded:: 1.3 Returns ------- routing : MetadataRouter A :class:`~utils.metadata_ro...
Get metadata routing of this object. Please check :ref:`User Guide <metadata_routing>` on how the routing mechanism works. .. versionadded:: 1.3 Returns ------- routing : MetadataRouter A :class:`~utils.metadata_routing.MetadataRouter` encapsulating ...
get_metadata_routing
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 __call__(self, estimator, X, y_true, sample_weight=None, **kwargs): """Evaluate predicted target values for X relative to y_true. Parameters ---------- estimator : object Trained estimator to use for scoring. Must have a predict_proba method; the output of th...
Evaluate predicted target values for X relative to y_true. Parameters ---------- estimator : object Trained estimator to use for scoring. Must have a predict_proba method; the output of that is used to compute the score. X : {array-like, sparse matrix} ...
__call__
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 _warn_overlap(self, message, kwargs): """Warn if there is any overlap between ``self._kwargs`` and ``kwargs``. This method is intended to be used to check for overlap between ``self._kwargs`` and ``kwargs`` passed as metadata. """ _kwargs = set() if self._kwargs is None else...
Warn if there is any overlap between ``self._kwargs`` and ``kwargs``. This method is intended to be used to check for overlap between ``self._kwargs`` and ``kwargs`` passed as metadata.
_warn_overlap
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 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.3 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.3 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 _score(self, method_caller, estimator, X, y_true, **kwargs): """Evaluate the response method of `estimator` on `X` and `y_true`. Parameters ---------- method_caller : callable Returns predictions given an estimator, method name, and other arguments, potential...
Evaluate the response method of `estimator` on `X` and `y_true`. Parameters ---------- method_caller : callable Returns predictions given an estimator, method name, and other arguments, potentially caching results. estimator : object Trained estimato...
_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 get_scorer(scoring): """Get a scorer from string. Read more in the :ref:`User Guide <scoring_parameter>`. :func:`~sklearn.metrics.get_scorer_names` can be used to retrieve the names of all available scorers. Parameters ---------- scoring : str, callable or None Scoring method a...
Get a scorer from string. Read more in the :ref:`User Guide <scoring_parameter>`. :func:`~sklearn.metrics.get_scorer_names` can be used to retrieve the names of all available scorers. Parameters ---------- scoring : str, callable or None Scoring method as string. If callable it is retu...
get_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