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, n_jobs=1, random_state=0, init="random", learning_rate="auto", ).fit_transform(X) X_tr = TSNE( n_components=2, method=method, perplexity=25.0, angle=0, n_jobs=2, random_state=0, init="random", learning_rate="auto", ).fit_transform(X) assert_allclose(X_tr_ref, X_tr)
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, "learning_rate": "auto", "init": "random", "n_components": 3, "random_state": 0, } tsne = TSNE(metric="mahalanobis", **default_params) msg = "Must provide either V or VI for Mahalanobis distance" with pytest.raises(ValueError, match=msg): tsne.fit_transform(X) precomputed_X = squareform(pdist(X, metric="mahalanobis"), checks=True) X_trans_expected = TSNE(metric="precomputed", **default_params).fit_transform( precomputed_X ) X_trans = TSNE( metric="mahalanobis", metric_params={"V": np.cov(X.T)}, **default_params ).fit_transform(X) assert_allclose(X_trans, X_trans_expected)
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=random_state, ) msg = re.escape(f"perplexity ({perplexity}) must be less than n_samples (20)") with pytest.raises(ValueError, match=msg): est.fit_transform(X)
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).fit_transform(arr)
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 isinstance(Y, np.ndarray): Y = np.asarray(Y) Y_dtype = Y.dtype else: Y_dtype = Y.dtype if X.dtype == Y_dtype == np.float32: dtype = np.float32 else: dtype = float return X, Y, dtype
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 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 ensures that both X and Y are arrays, then checks that they are at least two dimensional while ensuring that their elements are floats (or dtype if provided). Finally, the function checks that the size of the second dimension of the two arrays is equal, or the equivalent check for a precomputed distance matrix. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples_X, n_features) Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features) precomputed : bool, default=False True if X is to be treated as precomputed distances to the samples in Y. dtype : str, type, list of type or None default="infer_float" Data type required for X and Y. If "infer_float", the dtype will be an appropriate float type selected by _return_float_dtype. If None, the dtype of the input is preserved. .. versionadded:: 0.18 accept_sparse : str, bool or list/tuple of str, default='csr' String[s] representing allowed sparse matrix formats, such as 'csc', 'csr', etc. If the input is sparse but not in the allowed format, it will be converted to the first listed format. True allows the input to be any format. False means that a sparse matrix input will raise an error. force_all_finite : bool or 'allow-nan', default=True Whether to raise an error on np.inf, np.nan, pd.NA in array. The possibilities are: - True: Force all values of array to be finite. - False: accepts np.inf, np.nan, pd.NA in array. - 'allow-nan': accepts only np.nan and pd.NA values in array. Values cannot be infinite. .. versionadded:: 0.22 ``force_all_finite`` accepts the string ``'allow-nan'``. .. versionchanged:: 0.23 Accepts `pd.NA` and converts it into `np.nan`. .. deprecated:: 1.6 `force_all_finite` was renamed to `ensure_all_finite` and will be removed in 1.8. ensure_all_finite : bool or 'allow-nan', default=True Whether to raise an error on np.inf, np.nan, pd.NA in array. The possibilities are: - True: Force all values of array to be finite. - False: accepts np.inf, np.nan, pd.NA in array. - 'allow-nan': accepts only np.nan and pd.NA values in array. Values cannot be infinite. .. versionadded:: 1.6 `force_all_finite` was renamed to `ensure_all_finite`. ensure_2d : bool, default=True Whether to raise an error when the input arrays are not 2-dimensional. Setting this to `False` is necessary when using a custom metric with certain non-numerical inputs (e.g. a list of strings). .. versionadded:: 1.5 copy : bool, default=False Whether a forced copy will be triggered. If copy=False, a copy might be triggered by a conversion. .. versionadded:: 0.22 Returns ------- safe_X : {array-like, sparse matrix} of shape (n_samples_X, n_features) An array equal to X, guaranteed to be a numpy array. safe_Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features) An array equal to Y if Y was not None, guaranteed to be a numpy array. If Y was None, safe_Y will be a pointer to X. """ ensure_all_finite = _deprecate_force_all_finite(force_all_finite, ensure_all_finite) xp, _ = get_namespace(X, Y) if any([issparse(X), issparse(Y)]) or _is_numpy_namespace(xp): X, Y, dtype_float = _return_float_dtype(X, Y) else: dtype_float = _find_matching_floating_dtype(X, Y, xp=xp) estimator = "check_pairwise_arrays" if dtype == "infer_float": dtype = dtype_float if Y is X or Y is None: X = Y = check_array( X, accept_sparse=accept_sparse, dtype=dtype, copy=copy, ensure_all_finite=ensure_all_finite, estimator=estimator, ensure_2d=ensure_2d, ) else: X = check_array( X, accept_sparse=accept_sparse, dtype=dtype, copy=copy, ensure_all_finite=ensure_all_finite, estimator=estimator, ensure_2d=ensure_2d, ) Y = check_array( Y, accept_sparse=accept_sparse, dtype=dtype, copy=copy, ensure_all_finite=ensure_all_finite, estimator=estimator, ensure_2d=ensure_2d, ) if precomputed: if X.shape[1] != Y.shape[0]: raise ValueError( "Precomputed metric requires shape " "(n_queries, n_indexed). Got (%d, %d) " "for %d indexed." % (X.shape[0], X.shape[1], Y.shape[0]) ) elif ensure_2d and X.shape[1] != Y.shape[1]: # Only check the number of features if 2d arrays are enforced. Otherwise, # validation is left to the user for custom metrics. raise ValueError( "Incompatible dimension for X and Y matrices: " "X.shape[1] == %d while Y.shape[1] == %d" % (X.shape[1], Y.shape[1]) ) return X, Y
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 ensures that both X and Y are arrays, then checks that they are at least two dimensional while ensuring that their elements are floats (or dtype if provided). Finally, the function checks that the size of the second dimension of the two arrays is equal, or the equivalent check for a precomputed distance matrix. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples_X, n_features) Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features) precomputed : bool, default=False True if X is to be treated as precomputed distances to the samples in Y. dtype : str, type, list of type or None default="infer_float" Data type required for X and Y. If "infer_float", the dtype will be an appropriate float type selected by _return_float_dtype. If None, the dtype of the input is preserved. .. versionadded:: 0.18 accept_sparse : str, bool or list/tuple of str, default='csr' String[s] representing allowed sparse matrix formats, such as 'csc', 'csr', etc. If the input is sparse but not in the allowed format, it will be converted to the first listed format. True allows the input to be any format. False means that a sparse matrix input will raise an error. force_all_finite : bool or 'allow-nan', default=True Whether to raise an error on np.inf, np.nan, pd.NA in array. The possibilities are: - True: Force all values of array to be finite. - False: accepts np.inf, np.nan, pd.NA in array. - 'allow-nan': accepts only np.nan and pd.NA values in array. Values cannot be infinite. .. versionadded:: 0.22 ``force_all_finite`` accepts the string ``'allow-nan'``. .. versionchanged:: 0.23 Accepts `pd.NA` and converts it into `np.nan`. .. deprecated:: 1.6 `force_all_finite` was renamed to `ensure_all_finite` and will be removed in 1.8. ensure_all_finite : bool or 'allow-nan', default=True Whether to raise an error on np.inf, np.nan, pd.NA in array. The possibilities are: - True: Force all values of array to be finite. - False: accepts np.inf, np.nan, pd.NA in array. - 'allow-nan': accepts only np.nan and pd.NA values in array. Values cannot be infinite. .. versionadded:: 1.6 `force_all_finite` was renamed to `ensure_all_finite`. ensure_2d : bool, default=True Whether to raise an error when the input arrays are not 2-dimensional. Setting this to `False` is necessary when using a custom metric with certain non-numerical inputs (e.g. a list of strings). .. versionadded:: 1.5 copy : bool, default=False Whether a forced copy will be triggered. If copy=False, a copy might be triggered by a conversion. .. versionadded:: 0.22 Returns ------- safe_X : {array-like, sparse matrix} of shape (n_samples_X, n_features) An array equal to X, guaranteed to be a numpy array. safe_Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features) An array equal to Y if Y was not None, guaranteed to be a numpy array. If Y was None, safe_Y will be a pointer to X.
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, then checks that they are at least two dimensional while ensuring that their elements are floats. Finally, the function checks that the size of the dimensions of the two arrays are equal. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples_X, n_features) Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features) Returns ------- safe_X : {array-like, sparse matrix} of shape (n_samples_X, n_features) An array equal to X, guaranteed to be a numpy array. safe_Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features) An array equal to Y if Y was not None, guaranteed to be a numpy array. If Y was None, safe_Y will be a pointer to X. """ X, Y = check_pairwise_arrays(X, Y) if X.shape != Y.shape: raise ValueError( "X and Y should be of same shape. They were respectively %r and %r long." % (X.shape, Y.shape) ) return 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, then checks that they are at least two dimensional while ensuring that their elements are floats. Finally, the function checks that the size of the dimensions of the two arrays are equal. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples_X, n_features) Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features) Returns ------- safe_X : {array-like, sparse matrix} of shape (n_samples_X, n_features) An array equal to X, guaranteed to be a numpy array. safe_Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features) An array equal to Y if Y was not None, guaranteed to be a numpy array. If Y was None, safe_Y will be a pointer to X.
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) = sqrt(dot(x, x) - 2 * dot(x, y) + dot(y, y)) This formulation has two advantages over other ways of computing distances. First, it is computationally efficient when dealing with sparse data. Second, if one argument varies but the other remains unchanged, then `dot(x, x)` and/or `dot(y, y)` can be pre-computed. However, this is not the most precise way of doing this computation, because this equation potentially suffers from "catastrophic cancellation". Also, the distance matrix returned by this function may not be exactly symmetric as required by, e.g., ``scipy.spatial.distance`` functions. 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} of shape (n_samples_Y, n_features), \ default=None An array where each row is a sample and each column is a feature. If `None`, method uses `Y=X`. Y_norm_squared : array-like of shape (n_samples_Y,) or (n_samples_Y, 1) \ or (1, n_samples_Y), default=None Pre-computed dot-products of vectors in Y (e.g., ``(Y**2).sum(axis=1)``) May be ignored in some cases, see the note below. squared : bool, default=False Return squared Euclidean distances. X_norm_squared : array-like of shape (n_samples_X,) or (n_samples_X, 1) \ or (1, n_samples_X), default=None Pre-computed dot-products of vectors in X (e.g., ``(X**2).sum(axis=1)``) May be ignored in some cases, see the note below. Returns ------- distances : ndarray of shape (n_samples_X, n_samples_Y) Returns the distances between the row vectors of `X` and the row vectors of `Y`. See Also -------- paired_distances : Distances between pairs of elements of X and Y. Notes ----- To achieve a better accuracy, `X_norm_squared` and `Y_norm_squared` may be unused if they are passed as `np.float32`. Examples -------- >>> from sklearn.metrics.pairwise import euclidean_distances >>> X = [[0, 1], [1, 1]] >>> # distance between rows of X >>> euclidean_distances(X, X) array([[0., 1.], [1., 0.]]) >>> # get distance to origin >>> euclidean_distances(X, [[0, 0]]) array([[1. ], [1.41421356]]) """ xp, _ = get_namespace(X, Y) X, Y = check_pairwise_arrays(X, Y) if X_norm_squared is not None: X_norm_squared = check_array(X_norm_squared, ensure_2d=False) original_shape = X_norm_squared.shape if X_norm_squared.shape == (X.shape[0],): X_norm_squared = xp.reshape(X_norm_squared, (-1, 1)) if X_norm_squared.shape == (1, X.shape[0]): X_norm_squared = X_norm_squared.T if X_norm_squared.shape != (X.shape[0], 1): raise ValueError( f"Incompatible dimensions for X of shape {X.shape} and " f"X_norm_squared of shape {original_shape}." ) if Y_norm_squared is not None: Y_norm_squared = check_array(Y_norm_squared, ensure_2d=False) original_shape = Y_norm_squared.shape if Y_norm_squared.shape == (Y.shape[0],): Y_norm_squared = xp.reshape(Y_norm_squared, (1, -1)) if Y_norm_squared.shape == (Y.shape[0], 1): Y_norm_squared = Y_norm_squared.T if Y_norm_squared.shape != (1, Y.shape[0]): raise ValueError( f"Incompatible dimensions for Y of shape {Y.shape} and " f"Y_norm_squared of shape {original_shape}." ) return _euclidean_distances(X, Y, X_norm_squared, Y_norm_squared, squared)
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 computing distances. First, it is computationally efficient when dealing with sparse data. Second, if one argument varies but the other remains unchanged, then `dot(x, x)` and/or `dot(y, y)` can be pre-computed. However, this is not the most precise way of doing this computation, because this equation potentially suffers from "catastrophic cancellation". Also, the distance matrix returned by this function may not be exactly symmetric as required by, e.g., ``scipy.spatial.distance`` functions. 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} of shape (n_samples_Y, n_features), default=None An array where each row is a sample and each column is a feature. If `None`, method uses `Y=X`. Y_norm_squared : array-like of shape (n_samples_Y,) or (n_samples_Y, 1) or (1, n_samples_Y), default=None Pre-computed dot-products of vectors in Y (e.g., ``(Y**2).sum(axis=1)``) May be ignored in some cases, see the note below. squared : bool, default=False Return squared Euclidean distances. X_norm_squared : array-like of shape (n_samples_X,) or (n_samples_X, 1) or (1, n_samples_X), default=None Pre-computed dot-products of vectors in X (e.g., ``(X**2).sum(axis=1)``) May be ignored in some cases, see the note below. Returns ------- distances : ndarray of shape (n_samples_X, n_samples_Y) Returns the distances between the row vectors of `X` and the row vectors of `Y`. See Also -------- paired_distances : Distances between pairs of elements of X and Y. Notes ----- To achieve a better accuracy, `X_norm_squared` and `Y_norm_squared` may be unused if they are passed as `np.float32`. Examples -------- >>> from sklearn.metrics.pairwise import euclidean_distances >>> X = [[0, 1], [1, 1]] >>> # distance between rows of X >>> euclidean_distances(X, X) array([[0., 1.], [1., 0.]]) >>> # get distance to origin >>> euclidean_distances(X, [[0, 0]]) array([[1. ], [1.41421356]])
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. TODO: use a float64 accumulator in row_norms to avoid the latter. """ xp, _, device_ = get_namespace_and_device(X, Y) if X_norm_squared is not None and X_norm_squared.dtype != xp.float32: XX = xp.reshape(X_norm_squared, (-1, 1)) elif X.dtype != xp.float32: XX = row_norms(X, squared=True)[:, None] else: XX = None if Y is X: YY = None if XX is None else XX.T else: if Y_norm_squared is not None and Y_norm_squared.dtype != xp.float32: YY = xp.reshape(Y_norm_squared, (1, -1)) elif Y.dtype != xp.float32: YY = row_norms(Y, squared=True)[None, :] else: YY = None if X.dtype == xp.float32 or Y.dtype == xp.float32: # To minimize precision issues with float32, we compute the distance # matrix on chunks of X and Y upcast to float64 distances = _euclidean_distances_upcast(X, XX, Y, YY) else: # if dtype is already float64, no need to chunk and upcast distances = -2 * safe_sparse_dot(X, Y.T, dense_output=True) distances += XX distances += YY xp_zero = xp.asarray(0, device=device_, dtype=distances.dtype) distances = _modify_in_place_if_numpy( xp, xp.maximum, distances, xp_zero, out=distances ) # Ensure that distances between vectors and themselves are set to 0.0. # This may not be the case due to floating point rounding errors. if X is Y: _fill_or_add_to_diagonal(distances, 0, xp=xp, add_value=False) if squared: return distances distances = _modify_in_place_if_numpy(xp, xp.sqrt, distances, out=distances) return distances
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 between a pair of samples, this formulation ignores feature coordinates with a missing value in either sample and scales up the weight of the remaining coordinates: .. code-block:: text dist(x,y) = sqrt(weight * sq. distance from present coordinates) where: .. code-block:: text weight = Total # of coordinates / # of present coordinates For example, the distance between ``[3, na, na, 6]`` and ``[1, na, 4, 5]`` is: .. math:: \\sqrt{\\frac{4}{2}((3-1)^2 + (6-5)^2)} If all the coordinates are missing or if there are no common present coordinates then NaN is returned for that pair. Read more in the :ref:`User Guide <metrics>`. .. versionadded:: 0.22 Parameters ---------- X : array-like of shape (n_samples_X, n_features) An array where each row is a sample and each column is a feature. Y : array-like of shape (n_samples_Y, n_features), default=None An array where each row is a sample and each column is a feature. If `None`, method uses `Y=X`. squared : bool, default=False Return squared Euclidean distances. missing_values : np.nan, float or int, default=np.nan Representation of missing value. copy : bool, default=True Make and use a deep copy of X and Y (if Y exists). Returns ------- distances : ndarray of shape (n_samples_X, n_samples_Y) Returns the distances between the row vectors of `X` and the row vectors of `Y`. See Also -------- paired_distances : Distances between pairs of elements of X and Y. References ---------- * John K. Dixon, "Pattern Recognition with Partly Missing Data", IEEE Transactions on Systems, Man, and Cybernetics, Volume: 9, Issue: 10, pp. 617 - 621, Oct. 1979. http://ieeexplore.ieee.org/abstract/document/4310090/ Examples -------- >>> from sklearn.metrics.pairwise import nan_euclidean_distances >>> nan = float("NaN") >>> X = [[0, 1], [1, nan]] >>> nan_euclidean_distances(X, X) # distance between rows of X array([[0. , 1.41421356], [1.41421356, 0. ]]) >>> # get distance to origin >>> nan_euclidean_distances(X, [[0, 0]]) array([[1. ], [1.41421356]]) """ ensure_all_finite = "allow-nan" if is_scalar_nan(missing_values) else True X, Y = check_pairwise_arrays( X, Y, accept_sparse=False, ensure_all_finite=ensure_all_finite, copy=copy ) # Get missing mask for X missing_X = _get_mask(X, missing_values) # Get missing mask for Y missing_Y = missing_X if Y is X else _get_mask(Y, missing_values) # set missing values to zero X[missing_X] = 0 Y[missing_Y] = 0 distances = euclidean_distances(X, Y, squared=True) # Adjust distances for missing values XX = X * X YY = Y * Y distances -= np.dot(XX, missing_Y.T) distances -= np.dot(missing_X, YY.T) np.clip(distances, 0, None, out=distances) if X is Y: # Ensure that distances between vectors and themselves are set to 0.0. # This may not be the case due to floating point rounding errors. np.fill_diagonal(distances, 0.0) present_X = 1 - missing_X present_Y = present_X if Y is X else ~missing_Y present_count = np.dot(present_X, present_Y.T) distances[present_count == 0] = np.nan # avoid divide by zero np.maximum(1, present_count, out=present_count) distances /= present_count distances *= X.shape[1] if not squared: np.sqrt(distances, out=distances) return distances
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 either sample and scales up the weight of the remaining coordinates: .. code-block:: text dist(x,y) = sqrt(weight * sq. distance from present coordinates) where: .. code-block:: text weight = Total # of coordinates / # of present coordinates For example, the distance between ``[3, na, na, 6]`` and ``[1, na, 4, 5]`` is: .. math:: \sqrt{\frac{4}{2}((3-1)^2 + (6-5)^2)} If all the coordinates are missing or if there are no common present coordinates then NaN is returned for that pair. Read more in the :ref:`User Guide <metrics>`. .. versionadded:: 0.22 Parameters ---------- X : array-like of shape (n_samples_X, n_features) An array where each row is a sample and each column is a feature. Y : array-like of shape (n_samples_Y, n_features), default=None An array where each row is a sample and each column is a feature. If `None`, method uses `Y=X`. squared : bool, default=False Return squared Euclidean distances. missing_values : np.nan, float or int, default=np.nan Representation of missing value. copy : bool, default=True Make and use a deep copy of X and Y (if Y exists). Returns ------- distances : ndarray of shape (n_samples_X, n_samples_Y) Returns the distances between the row vectors of `X` and the row vectors of `Y`. See Also -------- paired_distances : Distances between pairs of elements of X and Y. References ---------- * John K. Dixon, "Pattern Recognition with Partly Missing Data", IEEE Transactions on Systems, Man, and Cybernetics, Volume: 9, Issue: 10, pp. 617 - 621, Oct. 1979. http://ieeexplore.ieee.org/abstract/document/4310090/ Examples -------- >>> from sklearn.metrics.pairwise import nan_euclidean_distances >>> nan = float("NaN") >>> X = [[0, 1], [1, nan]] >>> nan_euclidean_distances(X, X) # distance between rows of X array([[0. , 1.41421356], [1.41421356, 0. ]]) >>> # get distance to origin >>> nan_euclidean_distances(X, [[0, 0]]) array([[1. ], [1.41421356]])
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 distances are also returned. This is mostly equivalent to calling:: (pairwise_distances(X, Y=Y, metric=metric).argmin(axis=axis), pairwise_distances(X, Y=Y, metric=metric).min(axis=axis)) but uses much less memory, and is faster for large arrays. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples_X, n_features) Array containing points. Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features) Array containing points. axis : int, default=1 Axis along which the argmin and distances are to be computed. metric : str or callable, default='euclidean' Metric to use for distance computation. Any metric from scikit-learn or scipy.spatial.distance can be used. If metric is a callable function, it is called on each pair of instances (rows) and the resulting value recorded. The callable should take two arrays as input and return one value indicating the distance between them. This works for Scipy's metrics, but is less efficient than passing the metric name as a string. Distance matrices are not supported. Valid values for metric are: - from scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2', 'manhattan', 'nan_euclidean'] - from scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev', 'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski', 'mahalanobis', 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'yule'] See the documentation for scipy.spatial.distance for details on these metrics. .. note:: `'kulsinski'` is deprecated from SciPy 1.9 and will be removed in SciPy 1.11. .. note:: `'matching'` has been removed in SciPy 1.9 (use `'hamming'` instead). metric_kwargs : dict, default=None Keyword arguments to pass to specified metric function. Returns ------- argmin : ndarray Y[argmin[i], :] is the row in Y that is closest to X[i, :]. distances : ndarray The array of minimum distances. `distances[i]` is the distance between the i-th row in X and the argmin[i]-th row in Y. See Also -------- pairwise_distances : Distances between every pair of samples of X and Y. pairwise_distances_argmin : Same as `pairwise_distances_argmin_min` but only returns the argmins. Examples -------- >>> from sklearn.metrics.pairwise import pairwise_distances_argmin_min >>> X = [[0, 0, 0], [1, 1, 1]] >>> Y = [[1, 0, 0], [1, 1, 0]] >>> argmin, distances = pairwise_distances_argmin_min(X, Y) >>> argmin array([0, 1]) >>> distances array([1., 1.]) """ ensure_all_finite = "allow-nan" if metric == "nan_euclidean" else True X, Y = check_pairwise_arrays(X, Y, ensure_all_finite=ensure_all_finite) if axis == 0: X, Y = Y, X if metric_kwargs is None: metric_kwargs = {} if ArgKmin.is_usable_for(X, Y, metric): # This is an adaptor for one "sqeuclidean" specification. # For this backend, we can directly use "sqeuclidean". if metric_kwargs.get("squared", False) and metric == "euclidean": metric = "sqeuclidean" metric_kwargs = {} values, indices = ArgKmin.compute( X=X, Y=Y, k=1, metric=metric, metric_kwargs=metric_kwargs, strategy="auto", return_distance=True, ) values = values.flatten() indices = indices.flatten() else: # Joblib-based backend, which is used when user-defined callable # are passed for metric. # This won't be used in the future once PairwiseDistancesReductions support: # - DistanceMetrics which work on supposedly binary data # - CSR-dense and dense-CSR case if 'euclidean' in metric. # Turn off check for finiteness because this is costly and because arrays # have already been validated. with config_context(assume_finite=True): indices, values = zip( *pairwise_distances_chunked( X, Y, reduce_func=_argmin_min_reduce, metric=metric, **metric_kwargs ) ) indices = np.concatenate(indices) values = np.concatenate(values) return indices, values
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=Y, metric=metric).argmin(axis=axis), pairwise_distances(X, Y=Y, metric=metric).min(axis=axis)) but uses much less memory, and is faster for large arrays. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples_X, n_features) Array containing points. Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features) Array containing points. axis : int, default=1 Axis along which the argmin and distances are to be computed. metric : str or callable, default='euclidean' Metric to use for distance computation. Any metric from scikit-learn or scipy.spatial.distance can be used. If metric is a callable function, it is called on each pair of instances (rows) and the resulting value recorded. The callable should take two arrays as input and return one value indicating the distance between them. This works for Scipy's metrics, but is less efficient than passing the metric name as a string. Distance matrices are not supported. Valid values for metric are: - from scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2', 'manhattan', 'nan_euclidean'] - from scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev', 'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski', 'mahalanobis', 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'yule'] See the documentation for scipy.spatial.distance for details on these metrics. .. note:: `'kulsinski'` is deprecated from SciPy 1.9 and will be removed in SciPy 1.11. .. note:: `'matching'` has been removed in SciPy 1.9 (use `'hamming'` instead). metric_kwargs : dict, default=None Keyword arguments to pass to specified metric function. Returns ------- argmin : ndarray Y[argmin[i], :] is the row in Y that is closest to X[i, :]. distances : ndarray The array of minimum distances. `distances[i]` is the distance between the i-th row in X and the argmin[i]-th row in Y. See Also -------- pairwise_distances : Distances between every pair of samples of X and Y. pairwise_distances_argmin : Same as `pairwise_distances_argmin_min` but only returns the argmins. Examples -------- >>> from sklearn.metrics.pairwise import pairwise_distances_argmin_min >>> X = [[0, 0, 0], [1, 1, 1]] >>> Y = [[1, 0, 0], [1, 1, 0]] >>> argmin, distances = pairwise_distances_argmin_min(X, Y) >>> argmin array([0, 1]) >>> distances array([1., 1.])
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 equivalent to calling:: pairwise_distances(X, Y=Y, metric=metric).argmin(axis=axis) but uses much less memory, and is faster for large arrays. This function works with dense 2D arrays only. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples_X, n_features) Array containing points. Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features) Arrays containing points. axis : int, default=1 Axis along which the argmin and distances are to be computed. metric : str or callable, default="euclidean" Metric to use for distance computation. Any metric from scikit-learn or scipy.spatial.distance can be used. If metric is a callable function, it is called on each pair of instances (rows) and the resulting value recorded. The callable should take two arrays as input and return one value indicating the distance between them. This works for Scipy's metrics, but is less efficient than passing the metric name as a string. Distance matrices are not supported. Valid values for metric are: - from scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2', 'manhattan', 'nan_euclidean'] - from scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev', 'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski', 'mahalanobis', 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'yule'] See the documentation for scipy.spatial.distance for details on these metrics. .. note:: `'kulsinski'` is deprecated from SciPy 1.9 and will be removed in SciPy 1.11. .. note:: `'matching'` has been removed in SciPy 1.9 (use `'hamming'` instead). metric_kwargs : dict, default=None Keyword arguments to pass to specified metric function. Returns ------- argmin : numpy.ndarray Y[argmin[i], :] is the row in Y that is closest to X[i, :]. See Also -------- pairwise_distances : Distances between every pair of samples of X and Y. pairwise_distances_argmin_min : Same as `pairwise_distances_argmin` but also returns the distances. Examples -------- >>> from sklearn.metrics.pairwise import pairwise_distances_argmin >>> X = [[0, 0, 0], [1, 1, 1]] >>> Y = [[1, 0, 0], [1, 1, 0]] >>> pairwise_distances_argmin(X, Y) array([0, 1]) """ ensure_all_finite = "allow-nan" if metric == "nan_euclidean" else True X, Y = check_pairwise_arrays(X, Y, ensure_all_finite=ensure_all_finite) if axis == 0: X, Y = Y, X if metric_kwargs is None: metric_kwargs = {} if ArgKmin.is_usable_for(X, Y, metric): # This is an adaptor for one "sqeuclidean" specification. # For this backend, we can directly use "sqeuclidean". if metric_kwargs.get("squared", False) and metric == "euclidean": metric = "sqeuclidean" metric_kwargs = {} indices = ArgKmin.compute( X=X, Y=Y, k=1, metric=metric, metric_kwargs=metric_kwargs, strategy="auto", return_distance=False, ) indices = indices.flatten() else: # Joblib-based backend, which is used when user-defined callable # are passed for metric. # This won't be used in the future once PairwiseDistancesReductions support: # - DistanceMetrics which work on supposedly binary data # - CSR-dense and dense-CSR case if 'euclidean' in metric. # Turn off check for finiteness because this is costly and because arrays # have already been validated. with config_context(assume_finite=True): indices = np.concatenate( list( # This returns a np.ndarray generator whose arrays we need # to flatten into one. pairwise_distances_chunked( X, Y, reduce_func=_argmin_reduce, metric=metric, **metric_kwargs ) ) ) return indices
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 uses much less memory, and is faster for large arrays. This function works with dense 2D arrays only. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples_X, n_features) Array containing points. Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features) Arrays containing points. axis : int, default=1 Axis along which the argmin and distances are to be computed. metric : str or callable, default="euclidean" Metric to use for distance computation. Any metric from scikit-learn or scipy.spatial.distance can be used. If metric is a callable function, it is called on each pair of instances (rows) and the resulting value recorded. The callable should take two arrays as input and return one value indicating the distance between them. This works for Scipy's metrics, but is less efficient than passing the metric name as a string. Distance matrices are not supported. Valid values for metric are: - from scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2', 'manhattan', 'nan_euclidean'] - from scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev', 'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski', 'mahalanobis', 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'yule'] See the documentation for scipy.spatial.distance for details on these metrics. .. note:: `'kulsinski'` is deprecated from SciPy 1.9 and will be removed in SciPy 1.11. .. note:: `'matching'` has been removed in SciPy 1.9 (use `'hamming'` instead). metric_kwargs : dict, default=None Keyword arguments to pass to specified metric function. Returns ------- argmin : numpy.ndarray Y[argmin[i], :] is the row in Y that is closest to X[i, :]. See Also -------- pairwise_distances : Distances between every pair of samples of X and Y. pairwise_distances_argmin_min : Same as `pairwise_distances_argmin` but also returns the distances. Examples -------- >>> from sklearn.metrics.pairwise import pairwise_distances_argmin >>> X = [[0, 0, 0], [1, 1, 1]] >>> Y = [[1, 0, 0], [1, 1, 0]] >>> pairwise_distances_argmin(X, Y) array([0, 1])
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, given in radians. The dimension of the data must be 2. .. math:: D(x, y) = 2\\arcsin[\\sqrt{\\sin^2((x_{lat} - y_{lat}) / 2) + \\cos(x_{lat})\\cos(y_{lat})\\ sin^2((x_{lon} - y_{lon}) / 2)}] Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples_X, 2) A feature array. Y : {array-like, sparse matrix} of shape (n_samples_Y, 2), default=None An optional second feature array. If `None`, uses `Y=X`. Returns ------- distances : ndarray of shape (n_samples_X, n_samples_Y) The distance matrix. Notes ----- As the Earth is nearly spherical, the haversine formula provides a good approximation of the distance between two points of the Earth surface, with a less than 1% error on average. Examples -------- We want to calculate the distance between the Ezeiza Airport (Buenos Aires, Argentina) and the Charles de Gaulle Airport (Paris, France). >>> from sklearn.metrics.pairwise import haversine_distances >>> from math import radians >>> bsas = [-34.83333, -58.5166646] >>> paris = [49.0083899664, 2.53844117956] >>> bsas_in_radians = [radians(_) for _ in bsas] >>> paris_in_radians = [radians(_) for _ in paris] >>> result = haversine_distances([bsas_in_radians, paris_in_radians]) >>> result * 6371000/1000 # multiply by Earth radius to get kilometers array([[ 0. , 11099.54035582], [11099.54035582, 0. ]]) """ from ..metrics import DistanceMetric return DistanceMetric.get_metric("haversine").pairwise(X, Y)
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 the data must be 2. .. math:: D(x, y) = 2\arcsin[\sqrt{\sin^2((x_{lat} - y_{lat}) / 2) + \cos(x_{lat})\cos(y_{lat})\ sin^2((x_{lon} - y_{lon}) / 2)}] Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples_X, 2) A feature array. Y : {array-like, sparse matrix} of shape (n_samples_Y, 2), default=None An optional second feature array. If `None`, uses `Y=X`. Returns ------- distances : ndarray of shape (n_samples_X, n_samples_Y) The distance matrix. Notes ----- As the Earth is nearly spherical, the haversine formula provides a good approximation of the distance between two points of the Earth surface, with a less than 1% error on average. Examples -------- We want to calculate the distance between the Ezeiza Airport (Buenos Aires, Argentina) and the Charles de Gaulle Airport (Paris, France). >>> from sklearn.metrics.pairwise import haversine_distances >>> from math import radians >>> bsas = [-34.83333, -58.5166646] >>> paris = [49.0083899664, 2.53844117956] >>> bsas_in_radians = [radians(_) for _ in bsas] >>> paris_in_radians = [radians(_) for _ in paris] >>> result = haversine_distances([bsas_in_radians, paris_in_radians]) >>> result * 6371000/1000 # multiply by Earth radius to get kilometers array([[ 0. , 11099.54035582], [11099.54035582, 0. ]])
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 feature. Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), default=None An array where each row is a sample and each column is a feature. If `None`, method uses `Y=X`. Returns ------- distances : ndarray of shape (n_samples_X, n_samples_Y) Pairwise L1 distances. Notes ----- When X and/or Y are CSR sparse matrices and they are not already in canonical format, this function modifies them in-place to make them canonical. Examples -------- >>> from sklearn.metrics.pairwise import manhattan_distances >>> manhattan_distances([[3]], [[3]]) array([[0.]]) >>> manhattan_distances([[3]], [[2]]) array([[1.]]) >>> manhattan_distances([[2]], [[3]]) array([[1.]]) >>> manhattan_distances([[1, 2], [3, 4]],\ [[1, 2], [0, 3]]) array([[0., 2.], [4., 4.]]) """ X, Y = check_pairwise_arrays(X, Y) if issparse(X) or issparse(Y): X = csr_matrix(X, copy=False) Y = csr_matrix(Y, copy=False) X.sum_duplicates() # this also sorts indices in-place Y.sum_duplicates() D = np.zeros((X.shape[0], Y.shape[0])) _sparse_manhattan(X.data, X.indices, X.indptr, Y.data, Y.indices, Y.indptr, D) return D return distance.cdist(X, Y, "cityblock")
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} of shape (n_samples_Y, n_features), default=None An array where each row is a sample and each column is a feature. If `None`, method uses `Y=X`. Returns ------- distances : ndarray of shape (n_samples_X, n_samples_Y) Pairwise L1 distances. Notes ----- When X and/or Y are CSR sparse matrices and they are not already in canonical format, this function modifies them in-place to make them canonical. Examples -------- >>> from sklearn.metrics.pairwise import manhattan_distances >>> manhattan_distances([[3]], [[3]]) array([[0.]]) >>> manhattan_distances([[3]], [[2]]) array([[1.]]) >>> manhattan_distances([[2]], [[3]]) array([[1.]]) >>> manhattan_distances([[1, 2], [3, 4]], [[1, 2], [0, 3]]) array([[0., 2.], [4., 4.]])
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) Matrix `X`. Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), \ default=None Matrix `Y`. Returns ------- distances : ndarray of shape (n_samples_X, n_samples_Y) Returns the cosine distance between samples in X and Y. See Also -------- cosine_similarity : Compute cosine similarity between samples in X and Y. scipy.spatial.distance.cosine : Dense matrices only. Examples -------- >>> from sklearn.metrics.pairwise import cosine_distances >>> X = [[0, 0, 0], [1, 1, 1]] >>> Y = [[1, 0, 0], [1, 1, 0]] >>> cosine_distances(X, Y) array([[1. , 1. ], [0.422, 0.183]]) """ xp, _ = get_namespace(X, Y) # 1.0 - cosine_similarity(X, Y) without copy S = cosine_similarity(X, Y) S *= -1 S += 1 S = xp.clip(S, 0.0, 2.0) if X is Y or Y is None: # Ensure that distances between vectors and themselves are set to 0.0. # This may not be the case due to floating point rounding errors. _fill_or_add_to_diagonal(S, 0.0, xp, add_value=False) return S
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, sparse matrix} of shape (n_samples_Y, n_features), default=None Matrix `Y`. Returns ------- distances : ndarray of shape (n_samples_X, n_samples_Y) Returns the cosine distance between samples in X and Y. See Also -------- cosine_similarity : Compute cosine similarity between samples in X and Y. scipy.spatial.distance.cosine : Dense matrices only. Examples -------- >>> from sklearn.metrics.pairwise import cosine_distances >>> X = [[0, 0, 0], [1, 1, 1]] >>> Y = [[1, 0, 0], [1, 1, 0]] >>> cosine_distances(X, Y) array([[1. , 1. ], [0.422, 0.183]])
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} of shape (n_samples, n_features) Input array/matrix Y. Returns ------- distances : ndarray of shape (n_samples,) Output array/matrix containing the calculated paired euclidean distances. Examples -------- >>> from sklearn.metrics.pairwise import paired_euclidean_distances >>> X = [[0, 0, 0], [1, 1, 1]] >>> Y = [[1, 0, 0], [1, 1, 0]] >>> paired_euclidean_distances(X, Y) array([1., 1.]) """ X, Y = check_paired_arrays(X, Y) return row_norms(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} of shape (n_samples, n_features) Input array/matrix Y. Returns ------- distances : ndarray of shape (n_samples,) Output array/matrix containing the calculated paired euclidean distances. Examples -------- >>> from sklearn.metrics.pairwise import paired_euclidean_distances >>> X = [[0, 0, 0], [1, 1, 1]] >>> Y = [[1, 0, 0], [1, 1, 0]] >>> paired_euclidean_distances(X, Y) array([1., 1.])
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 shape (n_samples, n_features) An array-like where each row is a sample and each column is a feature. Y : {array-like, sparse matrix} of shape (n_samples, n_features) An array-like where each row is a sample and each column is a feature. Returns ------- distances : ndarray of shape (n_samples,) L1 paired distances between the row vectors of `X` and the row vectors of `Y`. Examples -------- >>> from sklearn.metrics.pairwise import paired_manhattan_distances >>> import numpy as np >>> X = np.array([[1, 1, 0], [0, 1, 0], [0, 0, 1]]) >>> Y = np.array([[0, 1, 0], [0, 0, 1], [0, 0, 0]]) >>> paired_manhattan_distances(X, Y) array([1., 2., 1.]) """ X, Y = check_paired_arrays(X, Y) diff = X - Y if issparse(diff): diff.data = np.abs(diff.data) return np.squeeze(np.array(diff.sum(axis=1))) else: return np.abs(diff).sum(axis=-1)
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 array-like where each row is a sample and each column is a feature. Y : {array-like, sparse matrix} of shape (n_samples, n_features) An array-like where each row is a sample and each column is a feature. Returns ------- distances : ndarray of shape (n_samples,) L1 paired distances between the row vectors of `X` and the row vectors of `Y`. Examples -------- >>> from sklearn.metrics.pairwise import paired_manhattan_distances >>> import numpy as np >>> X = np.array([[1, 1, 0], [0, 1, 0], [0, 0, 1]]) >>> Y = np.array([[0, 1, 0], [0, 0, 1], [0, 0, 0]]) >>> paired_manhattan_distances(X, Y) array([1., 2., 1.])
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 feature. Y : {array-like, sparse matrix} of shape (n_samples, n_features) An array where each row is a sample and each column is a feature. Returns ------- distances : ndarray of shape (n_samples,) Returns the distances between the row vectors of `X` and the row vectors of `Y`, where `distances[i]` is the distance between `X[i]` and `Y[i]`. Notes ----- The cosine distance is equivalent to the half the squared euclidean distance if each sample is normalized to unit norm. Examples -------- >>> from sklearn.metrics.pairwise import paired_cosine_distances >>> X = [[0, 0, 0], [1, 1, 1]] >>> Y = [[1, 0, 0], [1, 1, 0]] >>> paired_cosine_distances(X, Y) array([0.5 , 0.184]) """ X, Y = check_paired_arrays(X, Y) return 0.5 * row_norms(normalize(X) - normalize(Y), squared=True)
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} of shape (n_samples, n_features) An array where each row is a sample and each column is a feature. Returns ------- distances : ndarray of shape (n_samples,) Returns the distances between the row vectors of `X` and the row vectors of `Y`, where `distances[i]` is the distance between `X[i]` and `Y[i]`. Notes ----- The cosine distance is equivalent to the half the squared euclidean distance if each sample is normalized to unit norm. Examples -------- >>> from sklearn.metrics.pairwise import paired_cosine_distances >>> X = [[0, 0, 0], [1, 1, 1]] >>> Y = [[1, 0, 0], [1, 1, 0]] >>> paired_cosine_distances(X, Y) array([0.5 , 0.184])
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) Array 1 for distance computation. Y : ndarray of shape (n_samples, n_features) Array 2 for distance computation. metric : str or callable, default="euclidean" The metric to use when calculating distance between instances in a feature array. If metric is a string, it must be one of the options specified in PAIRED_DISTANCES, including "euclidean", "manhattan", or "cosine". Alternatively, if metric is a callable function, it is called on each pair of instances (rows) and the resulting value recorded. The callable should take two arrays from `X` as input and return a value indicating the distance between them. **kwds : dict Unused parameters. Returns ------- distances : ndarray of shape (n_samples,) Returns the distances between the row vectors of `X` and the row vectors of `Y`. See Also -------- sklearn.metrics.pairwise_distances : Computes the distance between every pair of samples. Examples -------- >>> from sklearn.metrics.pairwise import paired_distances >>> X = [[0, 1], [1, 1]] >>> Y = [[0, 1], [2, 1]] >>> paired_distances(X, Y) array([0., 1.]) """ if metric in PAIRED_DISTANCES: func = PAIRED_DISTANCES[metric] return func(X, Y) elif callable(metric): # Check the matrix first (it is usually done by the metric) X, Y = check_paired_arrays(X, Y) distances = np.zeros(len(X)) for i in range(len(X)): distances[i] = metric(X[i], Y[i]) return distances
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 (n_samples, n_features) Array 2 for distance computation. metric : str or callable, default="euclidean" The metric to use when calculating distance between instances in a feature array. If metric is a string, it must be one of the options specified in PAIRED_DISTANCES, including "euclidean", "manhattan", or "cosine". Alternatively, if metric is a callable function, it is called on each pair of instances (rows) and the resulting value recorded. The callable should take two arrays from `X` as input and return a value indicating the distance between them. **kwds : dict Unused parameters. Returns ------- distances : ndarray of shape (n_samples,) Returns the distances between the row vectors of `X` and the row vectors of `Y`. See Also -------- sklearn.metrics.pairwise_distances : Computes the distance between every pair of samples. Examples -------- >>> from sklearn.metrics.pairwise import paired_distances >>> X = [[0, 1], [1, 1]] >>> Y = [[0, 1], [2, 1]] >>> paired_distances(X, Y) array([0., 1.])
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 matrix} of shape (n_samples_Y, n_features), default=None An optional second feature array. If `None`, uses `Y=X`. dense_output : bool, default=True Whether to return dense output even when the input is sparse. If ``False``, the output is sparse if both input arrays are sparse. .. versionadded:: 0.20 Returns ------- kernel : ndarray of shape (n_samples_X, n_samples_Y) The Gram matrix of the linear kernel, i.e. `X @ Y.T`. Examples -------- >>> from sklearn.metrics.pairwise import linear_kernel >>> X = [[0, 0, 0], [1, 1, 1]] >>> Y = [[1, 0, 0], [1, 1, 0]] >>> linear_kernel(X, Y) array([[0., 0.], [1., 2.]]) """ X, Y = check_pairwise_arrays(X, Y) return safe_sparse_dot(X, Y.T, dense_output=dense_output)
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 An optional second feature array. If `None`, uses `Y=X`. dense_output : bool, default=True Whether to return dense output even when the input is sparse. If ``False``, the output is sparse if both input arrays are sparse. .. versionadded:: 0.20 Returns ------- kernel : ndarray of shape (n_samples_X, n_samples_Y) The Gram matrix of the linear kernel, i.e. `X @ Y.T`. Examples -------- >>> from sklearn.metrics.pairwise import linear_kernel >>> X = [[0, 0, 0], [1, 1, 1]] >>> Y = [[1, 0, 0], [1, 1, 0]] >>> linear_kernel(X, Y) array([[0., 0.], [1., 2.]])
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 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 An optional second feature array. If `None`, uses `Y=X`. degree : float, default=3 Kernel degree. gamma : float, default=None Coefficient of the vector inner product. If None, defaults to 1.0 / n_features. coef0 : float, default=1 Constant offset added to scaled inner product. Returns ------- kernel : ndarray of shape (n_samples_X, n_samples_Y) The polynomial kernel. Examples -------- >>> from sklearn.metrics.pairwise import polynomial_kernel >>> X = [[0, 0, 0], [1, 1, 1]] >>> Y = [[1, 0, 0], [1, 1, 0]] >>> polynomial_kernel(X, Y, degree=2) array([[1. , 1. ], [1.77, 2.77]]) """ X, Y = check_pairwise_arrays(X, Y) if gamma is None: gamma = 1.0 / X.shape[1] K = safe_sparse_dot(X, Y.T, dense_output=True) K *= gamma K += coef0 K **= degree return K
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. Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), default=None An optional second feature array. If `None`, uses `Y=X`. degree : float, default=3 Kernel degree. gamma : float, default=None Coefficient of the vector inner product. If None, defaults to 1.0 / n_features. coef0 : float, default=1 Constant offset added to scaled inner product. Returns ------- kernel : ndarray of shape (n_samples_X, n_samples_Y) The polynomial kernel. Examples -------- >>> from sklearn.metrics.pairwise import polynomial_kernel >>> X = [[0, 0, 0], [1, 1, 1]] >>> Y = [[1, 0, 0], [1, 1, 0]] >>> polynomial_kernel(X, Y, degree=2) array([[1. , 1. ], [1.77, 2.77]])
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_X, n_features) A feature array. Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), default=None An optional second feature array. If `None`, uses `Y=X`. gamma : float, default=None Coefficient of the vector inner product. If None, defaults to 1.0 / n_features. coef0 : float, default=1 Constant offset added to scaled inner product. Returns ------- kernel : ndarray of shape (n_samples_X, n_samples_Y) Sigmoid kernel between two arrays. Examples -------- >>> from sklearn.metrics.pairwise import sigmoid_kernel >>> X = [[0, 0, 0], [1, 1, 1]] >>> Y = [[1, 0, 0], [1, 1, 0]] >>> sigmoid_kernel(X, Y) array([[0.76, 0.76], [0.87, 0.93]]) """ xp, _ = get_namespace(X, Y) X, Y = check_pairwise_arrays(X, Y) if gamma is None: gamma = 1.0 / X.shape[1] K = safe_sparse_dot(X, Y.T, dense_output=True) K *= gamma K += coef0 # compute tanh in-place for numpy K = _modify_in_place_if_numpy(xp, xp.tanh, K, out=K) return K
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-like, sparse matrix} of shape (n_samples_Y, n_features), default=None An optional second feature array. If `None`, uses `Y=X`. gamma : float, default=None Coefficient of the vector inner product. If None, defaults to 1.0 / n_features. coef0 : float, default=1 Constant offset added to scaled inner product. Returns ------- kernel : ndarray of shape (n_samples_X, n_samples_Y) Sigmoid kernel between two arrays. Examples -------- >>> from sklearn.metrics.pairwise import sigmoid_kernel >>> X = [[0, 0, 0], [1, 1, 1]] >>> Y = [[1, 0, 0], [1, 1, 0]] >>> sigmoid_kernel(X, Y) array([[0.76, 0.76], [0.87, 0.93]])
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, 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 An optional second feature array. If `None`, uses `Y=X`. gamma : float, default=None If None, defaults to 1.0 / n_features. Returns ------- kernel : ndarray of shape (n_samples_X, n_samples_Y) The RBF kernel. Examples -------- >>> from sklearn.metrics.pairwise import rbf_kernel >>> X = [[0, 0, 0], [1, 1, 1]] >>> Y = [[1, 0, 0], [1, 1, 0]] >>> rbf_kernel(X, Y) array([[0.71, 0.51], [0.51, 0.71]]) """ xp, _ = get_namespace(X, Y) X, Y = check_pairwise_arrays(X, Y) if gamma is None: gamma = 1.0 / X.shape[1] K = euclidean_distances(X, Y, squared=True) K *= -gamma # exponentiate K in-place when using numpy K = _modify_in_place_if_numpy(xp, xp.exp, K, out=K) return K
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) A feature array. Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), default=None An optional second feature array. If `None`, uses `Y=X`. gamma : float, default=None If None, defaults to 1.0 / n_features. Returns ------- kernel : ndarray of shape (n_samples_X, n_samples_Y) The RBF kernel. Examples -------- >>> from sklearn.metrics.pairwise import rbf_kernel >>> X = [[0, 0, 0], [1, 1, 1]] >>> Y = [[1, 0, 0], [1, 1, 0]] >>> rbf_kernel(X, Y) array([[0.71, 0.51], [0.51, 0.71]])
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>`. .. versionadded:: 0.17 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 An optional second feature array. If `None`, uses `Y=X`. gamma : float, default=None If None, defaults to 1.0 / n_features. Otherwise it should be strictly positive. Returns ------- kernel : ndarray of shape (n_samples_X, n_samples_Y) The kernel matrix. Examples -------- >>> from sklearn.metrics.pairwise import laplacian_kernel >>> X = [[0, 0, 0], [1, 1, 1]] >>> Y = [[1, 0, 0], [1, 1, 0]] >>> laplacian_kernel(X, Y) array([[0.71, 0.51], [0.51, 0.71]]) """ X, Y = check_pairwise_arrays(X, Y) if gamma is None: gamma = 1.0 / X.shape[1] K = -gamma * manhattan_distances(X, Y) np.exp(K, K) # exponentiate K in-place return K
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 ---------- 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 An optional second feature array. If `None`, uses `Y=X`. gamma : float, default=None If None, defaults to 1.0 / n_features. Otherwise it should be strictly positive. Returns ------- kernel : ndarray of shape (n_samples_X, n_samples_Y) The kernel matrix. Examples -------- >>> from sklearn.metrics.pairwise import laplacian_kernel >>> X = [[0, 0, 0], [1, 1, 1]] >>> Y = [[1, 0, 0], [1, 1, 0]] >>> laplacian_kernel(X, Y) array([[0.71, 0.51], [0.51, 0.71]])
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, this function is equivalent to linear_kernel. Read more in the :ref:`User Guide <cosine_similarity>`. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples_X, n_features) Input data. Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), \ default=None Input data. If ``None``, the output will be the pairwise similarities between all samples in ``X``. dense_output : bool, default=True Whether to return dense output even when the input is sparse. If ``False``, the output is sparse if both input arrays are sparse. .. versionadded:: 0.17 parameter ``dense_output`` for dense output. Returns ------- similarities : ndarray or sparse matrix of shape (n_samples_X, n_samples_Y) Returns the cosine similarity between samples in X and Y. Examples -------- >>> from sklearn.metrics.pairwise import cosine_similarity >>> X = [[0, 0, 0], [1, 1, 1]] >>> Y = [[1, 0, 0], [1, 1, 0]] >>> cosine_similarity(X, Y) array([[0. , 0. ], [0.577, 0.816]]) """ X, Y = check_pairwise_arrays(X, Y) X_normalized = normalize(X, copy=True) if X is Y: Y_normalized = X_normalized else: Y_normalized = normalize(Y, copy=True) K = safe_sparse_dot(X_normalized, Y_normalized.T, dense_output=dense_output) return K
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 more in the :ref:`User Guide <cosine_similarity>`. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples_X, n_features) Input data. Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), default=None Input data. If ``None``, the output will be the pairwise similarities between all samples in ``X``. dense_output : bool, default=True Whether to return dense output even when the input is sparse. If ``False``, the output is sparse if both input arrays are sparse. .. versionadded:: 0.17 parameter ``dense_output`` for dense output. Returns ------- similarities : ndarray or sparse matrix of shape (n_samples_X, n_samples_Y) Returns the cosine similarity between samples in X and Y. Examples -------- >>> from sklearn.metrics.pairwise import cosine_similarity >>> X = [[0, 0, 0], [1, 1, 1]] >>> Y = [[1, 0, 0], [1, 1, 0]] >>> cosine_similarity(X, Y) array([[0. , 0. ], [0.577, 0.816]])
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 given by: .. code-block:: text k(x, y) = -Sum [(x - y)^2 / (x + y)] It can be interpreted as a weighted difference per entry. Read more in the :ref:`User Guide <chi2_kernel>`. Parameters ---------- X : array-like of shape (n_samples_X, n_features) A feature array. Y : array-like of shape (n_samples_Y, n_features), default=None An optional second feature array. If `None`, uses `Y=X`. Returns ------- kernel : array-like of shape (n_samples_X, n_samples_Y) The kernel matrix. See Also -------- chi2_kernel : The exponentiated version of the kernel, which is usually preferable. sklearn.kernel_approximation.AdditiveChi2Sampler : A Fourier approximation to this kernel. Notes ----- As the negative of a distance, this kernel is only conditionally positive definite. References ---------- * Zhang, J. and Marszalek, M. and Lazebnik, S. and Schmid, C. Local features and kernels for classification of texture and object categories: A comprehensive study International Journal of Computer Vision 2007 https://hal.archives-ouvertes.fr/hal-00171412/document Examples -------- >>> from sklearn.metrics.pairwise import additive_chi2_kernel >>> X = [[0, 0, 0], [1, 1, 1]] >>> Y = [[1, 0, 0], [1, 1, 0]] >>> additive_chi2_kernel(X, Y) array([[-1., -2.], [-2., -1.]]) """ xp, _, device_ = get_namespace_and_device(X, Y) X, Y = check_pairwise_arrays(X, Y, accept_sparse=False) if xp.any(X < 0): raise ValueError("X contains negative values.") if Y is not X and xp.any(Y < 0): raise ValueError("Y contains negative values.") if _is_numpy_namespace(xp): result = np.zeros((X.shape[0], Y.shape[0]), dtype=X.dtype) _chi2_kernel_fast(X, Y, result) return result else: dtype = _find_matching_floating_dtype(X, Y, xp=xp) xb = X[:, None, :] yb = Y[None, :, :] nom = -((xb - yb) ** 2) denom = xb + yb nom = xp.where(denom == 0, xp.asarray(0, dtype=dtype, device=device_), nom) denom = xp.where(denom == 0, xp.asarray(1, dtype=dtype, device=device_), denom) return xp.sum(nom / denom, axis=2)
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 k(x, y) = -Sum [(x - y)^2 / (x + y)] It can be interpreted as a weighted difference per entry. Read more in the :ref:`User Guide <chi2_kernel>`. Parameters ---------- X : array-like of shape (n_samples_X, n_features) A feature array. Y : array-like of shape (n_samples_Y, n_features), default=None An optional second feature array. If `None`, uses `Y=X`. Returns ------- kernel : array-like of shape (n_samples_X, n_samples_Y) The kernel matrix. See Also -------- chi2_kernel : The exponentiated version of the kernel, which is usually preferable. sklearn.kernel_approximation.AdditiveChi2Sampler : A Fourier approximation to this kernel. Notes ----- As the negative of a distance, this kernel is only conditionally positive definite. References ---------- * Zhang, J. and Marszalek, M. and Lazebnik, S. and Schmid, C. Local features and kernels for classification of texture and object categories: A comprehensive study International Journal of Computer Vision 2007 https://hal.archives-ouvertes.fr/hal-00171412/document Examples -------- >>> from sklearn.metrics.pairwise import additive_chi2_kernel >>> X = [[0, 0, 0], [1, 1, 1]] >>> Y = [[1, 0, 0], [1, 1, 0]] >>> additive_chi2_kernel(X, Y) array([[-1., -2.], [-2., -1.]])
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: .. code-block:: text k(x, y) = exp(-gamma Sum [(x - y)^2 / (x + y)]) It can be interpreted as a weighted difference per entry. Read more in the :ref:`User Guide <chi2_kernel>`. Parameters ---------- X : array-like of shape (n_samples_X, n_features) A feature array. Y : array-like of shape (n_samples_Y, n_features), default=None An optional second feature array. If `None`, uses `Y=X`. gamma : float, default=1 Scaling parameter of the chi2 kernel. Returns ------- kernel : ndarray of shape (n_samples_X, n_samples_Y) The kernel matrix. See Also -------- additive_chi2_kernel : The additive version of this kernel. sklearn.kernel_approximation.AdditiveChi2Sampler : A Fourier approximation to the additive version of this kernel. References ---------- * Zhang, J. and Marszalek, M. and Lazebnik, S. and Schmid, C. Local features and kernels for classification of texture and object categories: A comprehensive study International Journal of Computer Vision 2007 https://hal.archives-ouvertes.fr/hal-00171412/document Examples -------- >>> from sklearn.metrics.pairwise import chi2_kernel >>> X = [[0, 0, 0], [1, 1, 1]] >>> Y = [[1, 0, 0], [1, 1, 0]] >>> chi2_kernel(X, Y) array([[0.368, 0.135], [0.135, 0.368]]) """ xp, _ = get_namespace(X, Y) K = additive_chi2_kernel(X, Y) K *= gamma if _is_numpy_namespace(xp): return np.exp(K, out=K) return xp.exp(K)
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) = exp(-gamma Sum [(x - y)^2 / (x + y)]) It can be interpreted as a weighted difference per entry. Read more in the :ref:`User Guide <chi2_kernel>`. Parameters ---------- X : array-like of shape (n_samples_X, n_features) A feature array. Y : array-like of shape (n_samples_Y, n_features), default=None An optional second feature array. If `None`, uses `Y=X`. gamma : float, default=1 Scaling parameter of the chi2 kernel. Returns ------- kernel : ndarray of shape (n_samples_X, n_samples_Y) The kernel matrix. See Also -------- additive_chi2_kernel : The additive version of this kernel. sklearn.kernel_approximation.AdditiveChi2Sampler : A Fourier approximation to the additive version of this kernel. References ---------- * Zhang, J. and Marszalek, M. and Lazebnik, S. and Schmid, C. Local features and kernels for classification of texture and object categories: A comprehensive study International Journal of Computer Vision 2007 https://hal.archives-ouvertes.fr/hal-00171412/document Examples -------- >>> from sklearn.metrics.pairwise import chi2_kernel >>> X = [[0, 0, 0], [1, 1, 1]] >>> Y = [[1, 0, 0], [1, 1, 0]] >>> chi2_kernel(X, Y) array([[0.368, 0.135], [0.135, 0.368]])
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 threading backend to prevent data communication overhead fd = delayed(_dist_wrapper) ret = np.empty((X.shape[0], Y.shape[0]), dtype=dtype, order="F") Parallel(backend="threading", n_jobs=n_jobs)( fd(func, ret, s, X, Y[s], **kwds) for s in gen_even_slices(_num_samples(Y), effective_n_jobs(n_jobs)) ) if (X is Y or Y is None) and func is euclidean_distances: # zeroing diagonal for euclidean norm. # TODO: do it also for other norms. np.fill_diagonal(ret, 0) return ret
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 metrics (left to user) ensure_2d=False, ) if X is Y: # Only calculate metric for upper triangle out = np.zeros((X.shape[0], Y.shape[0]), dtype="float") iterator = itertools.combinations(range(X.shape[0]), 2) for i, j in iterator: # scipy has not yet implemented 1D sparse slices; once implemented this can # be removed and `arr[ind]` can be simply used. x = X[[i], :] if issparse(X) else X[i] y = Y[[j], :] if issparse(Y) else Y[j] out[i, j] = metric(x, y, **kwds) # Make symmetric # NB: out += out.T will produce incorrect results out = out + out.T # Calculate diagonal # NB: nonzero diagonals are allowed for both metrics and kernels for i in range(X.shape[0]): # scipy has not yet implemented 1D sparse slices; once implemented this can # be removed and `arr[ind]` can be simply used. x = X[[i], :] if issparse(X) else X[i] out[i, i] = metric(x, x, **kwds) else: # Calculate all cells out = np.empty((X.shape[0], Y.shape[0]), dtype="float") iterator = itertools.product(range(X.shape[0]), range(Y.shape[0])) for i, j in iterator: # scipy has not yet implemented 1D sparse slices; once implemented this can # be removed and `arr[ind]` can be simply used. x = X[[i], :] if issparse(X) else X[i] y = Y[[j], :] if issparse(Y) else Y[j] out[i, j] = metric(x, y, **kwds) return out
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 reduced): raise TypeError( "reduce_func returned %r. Expected sequence(s) of length %d." % (reduced if is_tuple else reduced[0], chunk_size) ) if any(_num_samples(r) != chunk_size for r in reduced): actual_size = tuple(_num_samples(r) for r in reduced) raise ValueError( "reduce_func returned object of length %s. " "Expected same length as input: %d." % (actual_size if is_tuple else actual_size[0], chunk_size) )
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 required for the seuclidean metric " "when Y is passed." ) return {"V": V} if metric == "mahalanobis" and "VI" not in kwds: if X is Y: VI = np.linalg.inv(np.cov(X.T)).T else: raise ValueError( "The 'VI' parameter is required for the mahalanobis metric " "when Y is passed." ) return {"VI": VI} return {}
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 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 values are concatenated into lists, arrays or sparse matrices. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples_X, n_samples_X) or \ (n_samples_X, n_features) Array of pairwise distances between samples, or a feature array. The shape the array should be (n_samples_X, n_samples_X) if metric='precomputed' and (n_samples_X, n_features) otherwise. Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), default=None An optional second feature array. Only allowed if metric != "precomputed". reduce_func : callable, default=None The function which is applied on each chunk of the distance matrix, reducing it to needed values. ``reduce_func(D_chunk, start)`` is called repeatedly, where ``D_chunk`` is a contiguous vertical slice of the pairwise distance matrix, starting at row ``start``. It should return one of: None; an array, a list, or a sparse matrix of length ``D_chunk.shape[0]``; or a tuple of such objects. Returning None is useful for in-place operations, rather than reductions. If None, pairwise_distances_chunked returns a generator of vertical chunks of the distance matrix. metric : str or callable, default='euclidean' The metric to use when calculating distance between instances in a feature array. If metric is a string, it must be one of the options allowed by scipy.spatial.distance.pdist for its metric parameter, or a metric listed in pairwise.PAIRWISE_DISTANCE_FUNCTIONS. If metric is "precomputed", X is assumed to be a distance matrix. Alternatively, if metric is a callable function, it is called on each pair of instances (rows) and the resulting value recorded. The callable should take two arrays from X as input and return a value indicating the distance between them. n_jobs : int, default=None The number of jobs to use for the computation. This works by breaking down the pairwise matrix into n_jobs even slices and computing them in parallel. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. working_memory : float, default=None The sought maximum memory for temporary distance matrix chunks. When None (default), the value of ``sklearn.get_config()['working_memory']`` is used. **kwds : optional keyword parameters Any further parameters are passed directly to the distance function. If using a scipy.spatial.distance metric, the parameters are still metric dependent. See the scipy docs for usage examples. Yields ------ D_chunk : {ndarray, sparse matrix} A contiguous slice of distance matrix, optionally processed by ``reduce_func``. Examples -------- Without reduce_func: >>> import numpy as np >>> from sklearn.metrics import pairwise_distances_chunked >>> X = np.random.RandomState(0).rand(5, 3) >>> D_chunk = next(pairwise_distances_chunked(X)) >>> D_chunk array([[0. , 0.295, 0.417, 0.197, 0.572], [0.295, 0. , 0.576, 0.419, 0.764], [0.417, 0.576, 0. , 0.449, 0.903], [0.197, 0.419, 0.449, 0. , 0.512], [0.572, 0.764, 0.903, 0.512, 0. ]]) Retrieve all neighbors and average distance within radius r: >>> r = .2 >>> def reduce_func(D_chunk, start): ... neigh = [np.flatnonzero(d < r) for d in D_chunk] ... avg_dist = (D_chunk * (D_chunk < r)).mean(axis=1) ... return neigh, avg_dist >>> gen = pairwise_distances_chunked(X, reduce_func=reduce_func) >>> neigh, avg_dist = next(gen) >>> neigh [array([0, 3]), array([1]), array([2]), array([0, 3]), array([4])] >>> avg_dist array([0.039, 0. , 0. , 0.039, 0. ]) Where r is defined per sample, we need to make use of ``start``: >>> r = [.2, .4, .4, .3, .1] >>> def reduce_func(D_chunk, start): ... neigh = [np.flatnonzero(d < r[i]) ... for i, d in enumerate(D_chunk, start)] ... return neigh >>> neigh = next(pairwise_distances_chunked(X, reduce_func=reduce_func)) >>> neigh [array([0, 3]), array([0, 1]), array([2]), array([0, 3]), array([4])] Force row-by-row generation by reducing ``working_memory``: >>> gen = pairwise_distances_chunked(X, reduce_func=reduce_func, ... working_memory=0) >>> next(gen) [array([0, 3])] >>> next(gen) [array([0, 1])] """ n_samples_X = _num_samples(X) if metric == "precomputed": slices = (slice(0, n_samples_X),) else: if Y is None: Y = X # We get as many rows as possible within our working_memory budget to # store len(Y) distances in each row of output. # # Note: # - this will get at least 1 row, even if 1 row of distances will # exceed working_memory. # - this does not account for any temporary memory usage while # calculating distances (e.g. difference of vectors in manhattan # distance. chunk_n_rows = get_chunk_n_rows( row_bytes=8 * _num_samples(Y), max_n_rows=n_samples_X, working_memory=working_memory, ) slices = gen_batches(n_samples_X, chunk_n_rows) # precompute data-derived metric params params = _precompute_metric_params(X, Y, metric=metric, **kwds) kwds.update(**params) for sl in slices: if sl.start == 0 and sl.stop == n_samples_X: X_chunk = X # enable optimised paths for X is Y else: X_chunk = X[sl] D_chunk = pairwise_distances(X_chunk, Y, metric=metric, n_jobs=n_jobs, **kwds) if (X is Y or Y is None) and PAIRWISE_DISTANCE_FUNCTIONS.get( metric, None ) is euclidean_distances: # zeroing diagonal, taking care of aliases of "euclidean", # i.e. "l2" D_chunk.flat[sl.start :: _num_samples(X) + 1] = 0 if reduce_func is not None: chunk_size = D_chunk.shape[0] D_chunk = reduce_func(D_chunk, sl.start) _check_chunk_size(D_chunk, chunk_size) yield D_chunk
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 values are concatenated into lists, arrays or sparse matrices. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples_X, n_samples_X) or (n_samples_X, n_features) Array of pairwise distances between samples, or a feature array. The shape the array should be (n_samples_X, n_samples_X) if metric='precomputed' and (n_samples_X, n_features) otherwise. Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), default=None An optional second feature array. Only allowed if metric != "precomputed". reduce_func : callable, default=None The function which is applied on each chunk of the distance matrix, reducing it to needed values. ``reduce_func(D_chunk, start)`` is called repeatedly, where ``D_chunk`` is a contiguous vertical slice of the pairwise distance matrix, starting at row ``start``. It should return one of: None; an array, a list, or a sparse matrix of length ``D_chunk.shape[0]``; or a tuple of such objects. Returning None is useful for in-place operations, rather than reductions. If None, pairwise_distances_chunked returns a generator of vertical chunks of the distance matrix. metric : str or callable, default='euclidean' The metric to use when calculating distance between instances in a feature array. If metric is a string, it must be one of the options allowed by scipy.spatial.distance.pdist for its metric parameter, or a metric listed in pairwise.PAIRWISE_DISTANCE_FUNCTIONS. If metric is "precomputed", X is assumed to be a distance matrix. Alternatively, if metric is a callable function, it is called on each pair of instances (rows) and the resulting value recorded. The callable should take two arrays from X as input and return a value indicating the distance between them. n_jobs : int, default=None The number of jobs to use for the computation. This works by breaking down the pairwise matrix into n_jobs even slices and computing them in parallel. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. working_memory : float, default=None The sought maximum memory for temporary distance matrix chunks. When None (default), the value of ``sklearn.get_config()['working_memory']`` is used. **kwds : optional keyword parameters Any further parameters are passed directly to the distance function. If using a scipy.spatial.distance metric, the parameters are still metric dependent. See the scipy docs for usage examples. Yields ------ D_chunk : {ndarray, sparse matrix} A contiguous slice of distance matrix, optionally processed by ``reduce_func``. Examples -------- Without reduce_func: >>> import numpy as np >>> from sklearn.metrics import pairwise_distances_chunked >>> X = np.random.RandomState(0).rand(5, 3) >>> D_chunk = next(pairwise_distances_chunked(X)) >>> D_chunk array([[0. , 0.295, 0.417, 0.197, 0.572], [0.295, 0. , 0.576, 0.419, 0.764], [0.417, 0.576, 0. , 0.449, 0.903], [0.197, 0.419, 0.449, 0. , 0.512], [0.572, 0.764, 0.903, 0.512, 0. ]]) Retrieve all neighbors and average distance within radius r: >>> r = .2 >>> def reduce_func(D_chunk, start): ... neigh = [np.flatnonzero(d < r) for d in D_chunk] ... avg_dist = (D_chunk * (D_chunk < r)).mean(axis=1) ... return neigh, avg_dist >>> gen = pairwise_distances_chunked(X, reduce_func=reduce_func) >>> neigh, avg_dist = next(gen) >>> neigh [array([0, 3]), array([1]), array([2]), array([0, 3]), array([4])] >>> avg_dist array([0.039, 0. , 0. , 0.039, 0. ]) Where r is defined per sample, we need to make use of ``start``: >>> r = [.2, .4, .4, .3, .1] >>> def reduce_func(D_chunk, start): ... neigh = [np.flatnonzero(d < r[i]) ... for i, d in enumerate(D_chunk, start)] ... return neigh >>> neigh = next(pairwise_distances_chunked(X, reduce_func=reduce_func)) >>> neigh [array([0, 3]), array([0, 1]), array([2]), array([0, 3]), array([4])] Force row-by-row generation by reducing ``working_memory``: >>> gen = pairwise_distances_chunked(X, reduce_func=reduce_func, ... working_memory=0) >>> next(gen) [array([0, 3])] >>> next(gen) [array([0, 1])]
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_samples_X, n_features), and: - `Y` is `None` and `metric` is not 'precomputed', the pairwise kernels between `X` and itself are returned. - `Y` is a feature array of shape (n_samples_Y, n_features), the pairwise kernels between `X` and `Y` is returned. - If `X` is a kernel matrix, of shape (n_samples_X, n_samples_X), `metric` should be 'precomputed'. `Y` is thus ignored and `X` is returned as is. This method provides a safe way to take a kernel matrix as input, while preserving compatibility with many other algorithms that take a vector array. Valid values for metric are: ['additive_chi2', 'chi2', 'linear', 'poly', 'polynomial', 'rbf', 'laplacian', 'sigmoid', 'cosine'] Read more in the :ref:`User Guide <metrics>`. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples_X, n_samples_X) or \ (n_samples_X, n_features) Array of pairwise kernels between samples, or a feature array. The shape of the array should be (n_samples_X, n_samples_X) if metric == "precomputed" and (n_samples_X, n_features) otherwise. Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), default=None A second feature array only if X has shape (n_samples_X, n_features). metric : str or callable, default="linear" The metric to use when calculating kernel between instances in a feature array. If metric is a string, it must be one of the metrics in ``pairwise.PAIRWISE_KERNEL_FUNCTIONS``. If metric is "precomputed", X is assumed to be a kernel matrix. Alternatively, if metric is a callable function, it is called on each pair of instances (rows) and the resulting value recorded. The callable should take two rows from X as input and return the corresponding kernel value as a single number. This means that callables from :mod:`sklearn.metrics.pairwise` are not allowed, as they operate on matrices, not single samples. Use the string identifying the kernel instead. filter_params : bool, default=False Whether to filter invalid parameters or not. n_jobs : int, default=None The number of jobs to use for the computation. This works by breaking down the pairwise matrix into n_jobs even slices and computing them using multithreading. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. **kwds : optional keyword parameters Any further parameters are passed directly to the kernel function. Returns ------- K : ndarray of shape (n_samples_X, n_samples_X) or (n_samples_X, n_samples_Y) A kernel matrix K such that K_{i, j} is the kernel between the ith and jth vectors of the given matrix X, if Y is None. If Y is not None, then K_{i, j} is the kernel between the ith array from X and the jth array from Y. Notes ----- If metric is a callable, no restrictions are placed on `X` and `Y` dimensions. Examples -------- >>> from sklearn.metrics.pairwise import pairwise_kernels >>> X = [[0, 0, 0], [1, 1, 1]] >>> Y = [[1, 0, 0], [1, 1, 0]] >>> pairwise_kernels(X, Y, metric='linear') array([[0., 0.], [1., 2.]]) """ # import GPKernel locally to prevent circular imports from ..gaussian_process.kernels import Kernel as GPKernel if metric == "precomputed": X, _ = check_pairwise_arrays(X, Y, precomputed=True) return X elif isinstance(metric, GPKernel): func = metric.__call__ elif metric in PAIRWISE_KERNEL_FUNCTIONS: if filter_params: kwds = {k: kwds[k] for k in kwds if k in KERNEL_PARAMS[metric]} func = PAIRWISE_KERNEL_FUNCTIONS[metric] elif callable(metric): func = partial(_pairwise_callable, metric=metric, **kwds) return _parallel_pairwise(X, Y, func, n_jobs, **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_samples_X, n_features), and: - `Y` is `None` and `metric` is not 'precomputed', the pairwise kernels between `X` and itself are returned. - `Y` is a feature array of shape (n_samples_Y, n_features), the pairwise kernels between `X` and `Y` is returned. - If `X` is a kernel matrix, of shape (n_samples_X, n_samples_X), `metric` should be 'precomputed'. `Y` is thus ignored and `X` is returned as is. This method provides a safe way to take a kernel matrix as input, while preserving compatibility with many other algorithms that take a vector array. Valid values for metric are: ['additive_chi2', 'chi2', 'linear', 'poly', 'polynomial', 'rbf', 'laplacian', 'sigmoid', 'cosine'] Read more in the :ref:`User Guide <metrics>`. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples_X, n_samples_X) or (n_samples_X, n_features) Array of pairwise kernels between samples, or a feature array. The shape of the array should be (n_samples_X, n_samples_X) if metric == "precomputed" and (n_samples_X, n_features) otherwise. Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), default=None A second feature array only if X has shape (n_samples_X, n_features). metric : str or callable, default="linear" The metric to use when calculating kernel between instances in a feature array. If metric is a string, it must be one of the metrics in ``pairwise.PAIRWISE_KERNEL_FUNCTIONS``. If metric is "precomputed", X is assumed to be a kernel matrix. Alternatively, if metric is a callable function, it is called on each pair of instances (rows) and the resulting value recorded. The callable should take two rows from X as input and return the corresponding kernel value as a single number. This means that callables from :mod:`sklearn.metrics.pairwise` are not allowed, as they operate on matrices, not single samples. Use the string identifying the kernel instead. filter_params : bool, default=False Whether to filter invalid parameters or not. n_jobs : int, default=None The number of jobs to use for the computation. This works by breaking down the pairwise matrix into n_jobs even slices and computing them using multithreading. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. **kwds : optional keyword parameters Any further parameters are passed directly to the kernel function. Returns ------- K : ndarray of shape (n_samples_X, n_samples_X) or (n_samples_X, n_samples_Y) A kernel matrix K such that K_{i, j} is the kernel between the ith and jth vectors of the given matrix X, if Y is None. If Y is not None, then K_{i, j} is the kernel between the ith array from X and the jth array from Y. Notes ----- If metric is a callable, no restrictions are placed on `X` and `Y` dimensions. Examples -------- >>> from sklearn.metrics.pairwise import pairwise_kernels >>> X = [[0, 0, 0], [1, 1, 1]] >>> Y = [[1, 0, 0], [1, 1, 0]] >>> pairwise_kernels(X, Y, metric='linear') array([[0., 0.], [1., 2.]])
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 : array, shape = [n_samples] or [n_samples, n_classes] Target scores, can either be probability estimates of the positive class, confidence values, or binary decisions. average : {None, 'micro', 'macro', 'samples', 'weighted'}, default='macro' If ``None``, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data: ``'micro'``: Calculate metrics globally by considering each element of the label indicator matrix as a label. ``'macro'``: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. ``'weighted'``: Calculate metrics for each label, and find their average, weighted by support (the number of true instances for each label). ``'samples'``: Calculate metrics for each instance, and find their average. Will be ignored when ``y_true`` is binary. sample_weight : array-like of shape (n_samples,), default=None Sample weights. binary_metric : callable, returns shape [n_classes] The binary metric function to use. Returns ------- score : float or array of shape [n_classes] If not ``None``, average the score, else return the score for each classes. """ average_options = (None, "micro", "macro", "weighted", "samples") if average not in average_options: raise ValueError("average has to be one of {0}".format(average_options)) y_type = type_of_target(y_true) if y_type not in ("binary", "multilabel-indicator"): raise ValueError("{0} format is not supported".format(y_type)) if y_type == "binary": return binary_metric(y_true, y_score, sample_weight=sample_weight) check_consistent_length(y_true, y_score, sample_weight) y_true = check_array(y_true) y_score = check_array(y_score) not_average_axis = 1 score_weight = sample_weight average_weight = None if average == "micro": if score_weight is not None: score_weight = np.repeat(score_weight, y_true.shape[1]) y_true = y_true.ravel() y_score = y_score.ravel() elif average == "weighted": if score_weight is not None: average_weight = np.sum( np.multiply(y_true, np.reshape(score_weight, (-1, 1))), axis=0 ) else: average_weight = np.sum(y_true, axis=0) if np.isclose(average_weight.sum(), 0.0): return 0 elif average == "samples": # swap average_weight <-> score_weight average_weight = score_weight score_weight = None not_average_axis = 0 if y_true.ndim == 1: y_true = y_true.reshape((-1, 1)) if y_score.ndim == 1: y_score = y_score.reshape((-1, 1)) n_classes = y_score.shape[not_average_axis] score = np.zeros((n_classes,)) for c in range(n_classes): y_true_c = y_true.take([c], axis=not_average_axis).ravel() y_score_c = y_score.take([c], axis=not_average_axis).ravel() score[c] = binary_metric(y_true_c, y_score_c, sample_weight=score_weight) # Average the results if average is not None: if average_weight is not None: # Scores with 0 weights are forced to be 0, preventing the average # score from being affected by 0-weighted NaN elements. average_weight = np.asarray(average_weight) score[average_weight == 0] = 0 return float(np.average(score, weights=average_weight)) else: return score
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 probability estimates of the positive class, confidence values, or binary decisions. average : {None, 'micro', 'macro', 'samples', 'weighted'}, default='macro' If ``None``, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data: ``'micro'``: Calculate metrics globally by considering each element of the label indicator matrix as a label. ``'macro'``: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. ``'weighted'``: Calculate metrics for each label, and find their average, weighted by support (the number of true instances for each label). ``'samples'``: Calculate metrics for each instance, and find their average. Will be ignored when ``y_true`` is binary. sample_weight : array-like of shape (n_samples,), default=None Sample weights. binary_metric : callable, returns shape [n_classes] The binary metric function to use. Returns ------- score : float or array of shape [n_classes] If not ``None``, average the score, else return the score for each classes.
_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 ---------- binary_metric : callable The binary metric function to use that accepts the following as input: y_true_target : array, shape = [n_samples_target] Some sub-array of y_true for a pair of classes designated positive and negative in the one-vs-one scheme. y_score_target : array, shape = [n_samples_target] Scores corresponding to the probability estimates of a sample belonging to the designated positive class label 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. average : {'macro', 'weighted'}, default='macro' Determines the type of averaging performed on the pairwise binary metric scores: ``'macro'``: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. Classes are assumed to be uniformly distributed. ``'weighted'``: Calculate metrics for each label, taking into account the prevalence of the classes. Returns ------- score : float Average of the pairwise binary metric scores. """ check_consistent_length(y_true, y_score) y_true_unique = np.unique(y_true) n_classes = y_true_unique.shape[0] n_pairs = n_classes * (n_classes - 1) // 2 pair_scores = np.empty(n_pairs) is_weighted = average == "weighted" prevalence = np.empty(n_pairs) if is_weighted else None # Compute scores treating a as positive class and b as negative class, # then b as positive class and a as negative class for ix, (a, b) in enumerate(combinations(y_true_unique, 2)): a_mask = y_true == a b_mask = y_true == b ab_mask = np.logical_or(a_mask, b_mask) if is_weighted: prevalence[ix] = np.average(ab_mask) a_true = a_mask[ab_mask] b_true = b_mask[ab_mask] a_true_score = binary_metric(a_true, y_score[ab_mask, a]) b_true_score = binary_metric(b_true, y_score[ab_mask, b]) pair_scores[ix] = (a_true_score + b_true_score) / 2 return np.average(pair_scores, weights=prevalence)
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 accepts the following as input: y_true_target : array, shape = [n_samples_target] Some sub-array of y_true for a pair of classes designated positive and negative in the one-vs-one scheme. y_score_target : array, shape = [n_samples_target] Scores corresponding to the probability estimates of a sample belonging to the designated positive class label 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. average : {'macro', 'weighted'}, default='macro' Determines the type of averaging performed on the pairwise binary metric scores: ``'macro'``: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. Classes are assumed to be uniformly distributed. ``'weighted'``: Calculate metrics for each label, taking into account the prevalence of the classes. Returns ------- score : float Average of the pairwise binary metric scores.
_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-valued or multioutput targets, or for targets of different lengths. Column vectors are squeezed to 1d, while multilabel formats are returned as CSR sparse label indicators. Parameters ---------- y_true : array-like y_pred : array-like Returns ------- type_true : one of {'multilabel-indicator', 'multiclass', 'binary'} The type of the true target data, as output by ``utils.multiclass.type_of_target``. y_true : array or indicator matrix y_pred : array or indicator matrix """ xp, _ = get_namespace(y_true, y_pred) check_consistent_length(y_true, y_pred) type_true = type_of_target(y_true, input_name="y_true") type_pred = type_of_target(y_pred, input_name="y_pred") y_type = {type_true, type_pred} if y_type == {"binary", "multiclass"}: y_type = {"multiclass"} if len(y_type) > 1: raise ValueError( "Classification metrics can't handle a mix of {0} and {1} targets".format( type_true, type_pred ) ) # We can't have more than one value on y_type => The set is no more needed y_type = y_type.pop() # No metrics support "multiclass-multioutput" format if y_type not in ["binary", "multiclass", "multilabel-indicator"]: raise ValueError("{0} is not supported".format(y_type)) if y_type in ["binary", "multiclass"]: xp, _ = get_namespace(y_true, y_pred) y_true = column_or_1d(y_true) y_pred = column_or_1d(y_pred) if y_type == "binary": try: unique_values = _union1d(y_true, y_pred, xp) except TypeError as e: # We expect y_true and y_pred to be of the same data type. # If `y_true` was provided to the classifier as strings, # `y_pred` given by the classifier will also be encoded with # strings. So we raise a meaningful error raise TypeError( "Labels in y_true and y_pred should be of the same type. " f"Got y_true={xp.unique(y_true)} and " f"y_pred={xp.unique(y_pred)}. Make sure that the " "predictions provided by the classifier coincides with " "the true labels." ) from e if unique_values.shape[0] > 2: y_type = "multiclass" if y_type.startswith("multilabel"): if _is_numpy_namespace(xp): # XXX: do we really want to sparse-encode multilabel indicators when # they are passed as a dense arrays? This is not possible for array # API inputs in general hence we only do it for NumPy inputs. But even # for NumPy the usefulness is questionable. y_true = csr_matrix(y_true) y_pred = csr_matrix(y_pred) y_type = "multilabel-indicator" return y_type, 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-valued or multioutput targets, or for targets of different lengths. Column vectors are squeezed to 1d, while multilabel formats are returned as CSR sparse label indicators. Parameters ---------- y_true : array-like y_pred : array-like Returns ------- type_true : one of {'multilabel-indicator', 'multiclass', 'binary'} The type of the true target data, as output by ``utils.multiclass.type_of_target``. y_true : array or indicator matrix y_pred : array or indicator matrix
_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 classes are provided by the labels argument, or inferred using y_true. When inferring y_true is assumed binary if it has shape (n_samples, ). 3. Validate y_true, and y_prob have the same number of classes. Convert to shape (n_samples, n_classes) Parameters ---------- y_true : array-like or label indicator matrix Ground truth (correct) labels for n_samples samples. y_prob : array-like of float, shape=(n_samples, n_classes) or (n_samples,) Predicted probabilities, as returned by a classifier's predict_proba method. If `y_prob.shape = (n_samples,)` the probabilities provided are assumed to be that of the positive class. The labels in `y_prob` are assumed to be ordered lexicographically, as done by :class:`preprocessing.LabelBinarizer`. sample_weight : array-like of shape (n_samples,), default=None Sample weights. labels : array-like, default=None If not provided, labels will be inferred from y_true. If `labels` is `None` and `y_prob` has shape `(n_samples,)` the labels are assumed to be binary and are inferred from `y_true`. Returns ------- transformed_labels : array of shape (n_samples, n_classes) y_prob : array of shape (n_samples, n_classes) """ y_prob = check_array( y_prob, ensure_2d=False, dtype=[np.float64, np.float32, np.float16] ) if y_prob.max() > 1: raise ValueError(f"y_prob contains values greater than 1: {y_prob.max()}") if y_prob.min() < 0: raise ValueError(f"y_prob contains values lower than 0: {y_prob.min()}") check_consistent_length(y_prob, y_true, sample_weight) lb = LabelBinarizer() if labels is not None: lb = lb.fit(labels) # LabelBinarizer does not respect the order implied by labels, which # can be misleading. if not np.all(lb.classes_ == labels): warnings.warn( f"Labels passed were {labels}. But this function " "assumes labels are ordered lexicographically. " f"Pass the ordered labels={lb.classes_.tolist()} and ensure that " "the columns of y_prob correspond to this ordering.", UserWarning, ) if not np.isin(y_true, labels).all(): undeclared_labels = set(y_true) - set(labels) raise ValueError( f"y_true contains values {undeclared_labels} not belonging " f"to the passed labels {labels}." ) else: lb = lb.fit(y_true) if len(lb.classes_) == 1: if labels is None: raise ValueError( "y_true contains only one label ({0}). Please " "provide the list of all expected class labels explicitly through the " "labels argument.".format(lb.classes_[0]) ) else: raise ValueError( "The labels array needs to contain at least two " "labels, got {0}.".format(lb.classes_) ) transformed_labels = lb.transform(y_true) if transformed_labels.shape[1] == 1: transformed_labels = np.append( 1 - transformed_labels, transformed_labels, axis=1 ) # If y_prob is of single dimension, assume y_true to be binary # and then check. if y_prob.ndim == 1: y_prob = y_prob[:, np.newaxis] if y_prob.shape[1] == 1: y_prob = np.append(1 - y_prob, y_prob, axis=1) eps = np.finfo(y_prob.dtype).eps # Make sure y_prob is normalized y_prob_sum = y_prob.sum(axis=1) if not np.allclose(y_prob_sum, 1, rtol=np.sqrt(eps)): warnings.warn( "The y_prob values do not sum to one. Make sure to pass probabilities.", UserWarning, ) # Check if dimensions are consistent. transformed_labels = check_array(transformed_labels) if len(lb.classes_) != y_prob.shape[1]: if labels is None: raise ValueError( "y_true and y_prob contain different number of " "classes: {0} vs {1}. Please provide the true " "labels explicitly through the labels argument. " "Classes found in " "y_true: {2}".format( transformed_labels.shape[1], y_prob.shape[1], lb.classes_ ) ) else: raise ValueError( "The number of classes in labels is different " "from that in y_prob. Classes found in " "labels: {0}".format(lb.classes_) ) return transformed_labels, y_prob
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_true is assumed binary if it has shape (n_samples, ). 3. Validate y_true, and y_prob have the same number of classes. Convert to shape (n_samples, n_classes) Parameters ---------- y_true : array-like or label indicator matrix Ground truth (correct) labels for n_samples samples. y_prob : array-like of float, shape=(n_samples, n_classes) or (n_samples,) Predicted probabilities, as returned by a classifier's predict_proba method. If `y_prob.shape = (n_samples,)` the probabilities provided are assumed to be that of the positive class. The labels in `y_prob` are assumed to be ordered lexicographically, as done by :class:`preprocessing.LabelBinarizer`. sample_weight : array-like of shape (n_samples,), default=None Sample weights. labels : array-like, default=None If not provided, labels will be inferred from y_true. If `labels` is `None` and `y_prob` has shape `(n_samples,)` the labels are assumed to be binary and are inferred from `y_true`. Returns ------- transformed_labels : array of shape (n_samples, n_classes) y_prob : array of shape (n_samples, n_classes)
_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 the :ref:`User Guide <accuracy_score>`. Parameters ---------- y_true : 1d array-like, or label indicator array / sparse matrix Ground truth (correct) labels. y_pred : 1d array-like, or label indicator array / sparse matrix Predicted labels, as returned by a classifier. normalize : bool, default=True If ``False``, return the number of correctly classified samples. Otherwise, return the fraction of correctly classified samples. sample_weight : array-like of shape (n_samples,), default=None Sample weights. Returns ------- score : float or int If ``normalize == True``, return the fraction of correctly classified samples (float), else returns the number of correctly classified samples (int). The best performance is 1 with ``normalize == True`` and the number of samples with ``normalize == False``. See Also -------- balanced_accuracy_score : Compute the balanced accuracy to deal with imbalanced datasets. jaccard_score : Compute the Jaccard similarity coefficient score. hamming_loss : Compute the average Hamming loss or Hamming distance between two sets of samples. zero_one_loss : Compute the Zero-one classification loss. By default, the function will return the percentage of imperfectly predicted subsets. Examples -------- >>> from sklearn.metrics import accuracy_score >>> y_pred = [0, 2, 1, 3] >>> y_true = [0, 1, 2, 3] >>> accuracy_score(y_true, y_pred) 0.5 >>> accuracy_score(y_true, y_pred, normalize=False) 2.0 In the multilabel case with binary label indicators: >>> import numpy as np >>> accuracy_score(np.array([[0, 1], [1, 1]]), np.ones((2, 2))) 0.5 """ xp, _, device = get_namespace_and_device(y_true, y_pred, sample_weight) # Compute accuracy for each possible representation y_true, y_pred = attach_unique(y_true, y_pred) y_type, y_true, y_pred = _check_targets(y_true, y_pred) check_consistent_length(y_true, y_pred, sample_weight) if y_type.startswith("multilabel"): differing_labels = _count_nonzero(y_true - y_pred, xp=xp, device=device, axis=1) score = xp.asarray(differing_labels == 0, device=device) else: score = y_true == y_pred return float(_average(score, weights=sample_weight, normalize=normalize))
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 : 1d array-like, or label indicator array / sparse matrix Ground truth (correct) labels. y_pred : 1d array-like, or label indicator array / sparse matrix Predicted labels, as returned by a classifier. normalize : bool, default=True If ``False``, return the number of correctly classified samples. Otherwise, return the fraction of correctly classified samples. sample_weight : array-like of shape (n_samples,), default=None Sample weights. Returns ------- score : float or int If ``normalize == True``, return the fraction of correctly classified samples (float), else returns the number of correctly classified samples (int). The best performance is 1 with ``normalize == True`` and the number of samples with ``normalize == False``. See Also -------- balanced_accuracy_score : Compute the balanced accuracy to deal with imbalanced datasets. jaccard_score : Compute the Jaccard similarity coefficient score. hamming_loss : Compute the average Hamming loss or Hamming distance between two sets of samples. zero_one_loss : Compute the Zero-one classification loss. By default, the function will return the percentage of imperfectly predicted subsets. Examples -------- >>> from sklearn.metrics import accuracy_score >>> y_pred = [0, 2, 1, 3] >>> y_true = [0, 1, 2, 3] >>> accuracy_score(y_true, y_pred) 0.5 >>> accuracy_score(y_true, y_pred, normalize=False) 2.0 In the multilabel case with binary label indicators: >>> import numpy as np >>> accuracy_score(np.array([[0, 1], [1, 1]]), np.ones((2, 2))) 0.5
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 :math:`i` and predicted to be in group :math:`j`. Thus in binary classification, the count of true negatives is :math:`C_{0,0}`, false negatives is :math:`C_{1,0}`, true positives is :math:`C_{1,1}` and false positives is :math:`C_{0,1}`. Read more in the :ref:`User Guide <confusion_matrix>`. Parameters ---------- y_true : array-like of shape (n_samples,) Ground truth (correct) target values. y_pred : array-like of shape (n_samples,) Estimated targets as returned by a classifier. labels : array-like of shape (n_classes), default=None List of labels to index the matrix. This may be used to reorder or select a subset of labels. If ``None`` is given, those that appear at least once in ``y_true`` or ``y_pred`` are used in sorted order. sample_weight : array-like of shape (n_samples,), default=None Sample weights. .. versionadded:: 0.18 normalize : {'true', 'pred', 'all'}, default=None Normalizes confusion matrix over the true (rows), predicted (columns) conditions or all the population. If None, confusion matrix will not be normalized. Returns ------- C : ndarray of shape (n_classes, n_classes) Confusion matrix whose i-th row and j-th column entry indicates the number of samples with true label being i-th class and predicted label being j-th class. See Also -------- ConfusionMatrixDisplay.from_estimator : Plot the confusion matrix given an estimator, the data, and the label. ConfusionMatrixDisplay.from_predictions : Plot the confusion matrix given the true and predicted labels. ConfusionMatrixDisplay : Confusion Matrix visualization. References ---------- .. [1] `Wikipedia entry for the Confusion matrix <https://en.wikipedia.org/wiki/Confusion_matrix>`_ (Wikipedia and other references may use a different convention for axes). Examples -------- >>> from sklearn.metrics import confusion_matrix >>> y_true = [2, 0, 2, 2, 0, 1] >>> y_pred = [0, 0, 2, 2, 0, 2] >>> confusion_matrix(y_true, y_pred) array([[2, 0, 0], [0, 0, 1], [1, 0, 2]]) >>> y_true = ["cat", "ant", "cat", "cat", "ant", "bird"] >>> y_pred = ["ant", "ant", "cat", "cat", "ant", "cat"] >>> confusion_matrix(y_true, y_pred, labels=["ant", "bird", "cat"]) array([[2, 0, 0], [0, 0, 1], [1, 0, 2]]) In the binary case, we can extract true positives, etc. as follows: >>> tn, fp, fn, tp = confusion_matrix([0, 1, 0, 1], [1, 1, 1, 0]).ravel().tolist() >>> (tn, fp, fn, tp) (0, 2, 1, 1) """ y_true, y_pred = attach_unique(y_true, y_pred) y_type, y_true, y_pred = _check_targets(y_true, y_pred) if y_type not in ("binary", "multiclass"): raise ValueError("%s is not supported" % y_type) if labels is None: labels = unique_labels(y_true, y_pred) else: labels = np.asarray(labels) n_labels = labels.size if n_labels == 0: raise ValueError("'labels' should contains at least one label.") elif y_true.size == 0: return np.zeros((n_labels, n_labels), dtype=int) elif len(np.intersect1d(y_true, labels)) == 0: raise ValueError("At least one label specified must be in y_true") if sample_weight is None: sample_weight = np.ones(y_true.shape[0], dtype=np.int64) else: sample_weight = np.asarray(sample_weight) check_consistent_length(y_true, y_pred, sample_weight) n_labels = labels.size # If labels are not consecutive integers starting from zero, then # y_true and y_pred must be converted into index form need_index_conversion = not ( labels.dtype.kind in {"i", "u", "b"} and np.all(labels == np.arange(n_labels)) and y_true.min() >= 0 and y_pred.min() >= 0 ) if need_index_conversion: label_to_ind = {y: x for x, y in enumerate(labels)} y_pred = np.array([label_to_ind.get(x, n_labels + 1) for x in y_pred]) y_true = np.array([label_to_ind.get(x, n_labels + 1) for x in y_true]) # intersect y_pred, y_true with labels, eliminate items not in labels ind = np.logical_and(y_pred < n_labels, y_true < n_labels) if not np.all(ind): y_pred = y_pred[ind] y_true = y_true[ind] # also eliminate weights of eliminated items sample_weight = sample_weight[ind] # Choose the accumulator dtype to always have high precision if sample_weight.dtype.kind in {"i", "u", "b"}: dtype = np.int64 else: dtype = np.float64 cm = coo_matrix( (sample_weight, (y_true, y_pred)), shape=(n_labels, n_labels), dtype=dtype, ).toarray() with np.errstate(all="ignore"): if normalize == "true": cm = cm / cm.sum(axis=1, keepdims=True) elif normalize == "pred": cm = cm / cm.sum(axis=0, keepdims=True) elif normalize == "all": cm = cm / cm.sum() cm = np.nan_to_num(cm) if cm.shape == (1, 1): warnings.warn( ( "A single label was found in 'y_true' and 'y_pred'. For the confusion " "matrix to have the correct shape, use the 'labels' parameter to pass " "all known labels." ), UserWarning, ) return cm
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 negatives is :math:`C_{0,0}`, false negatives is :math:`C_{1,0}`, true positives is :math:`C_{1,1}` and false positives is :math:`C_{0,1}`. Read more in the :ref:`User Guide <confusion_matrix>`. Parameters ---------- y_true : array-like of shape (n_samples,) Ground truth (correct) target values. y_pred : array-like of shape (n_samples,) Estimated targets as returned by a classifier. labels : array-like of shape (n_classes), default=None List of labels to index the matrix. This may be used to reorder or select a subset of labels. If ``None`` is given, those that appear at least once in ``y_true`` or ``y_pred`` are used in sorted order. sample_weight : array-like of shape (n_samples,), default=None Sample weights. .. versionadded:: 0.18 normalize : {'true', 'pred', 'all'}, default=None Normalizes confusion matrix over the true (rows), predicted (columns) conditions or all the population. If None, confusion matrix will not be normalized. Returns ------- C : ndarray of shape (n_classes, n_classes) Confusion matrix whose i-th row and j-th column entry indicates the number of samples with true label being i-th class and predicted label being j-th class. See Also -------- ConfusionMatrixDisplay.from_estimator : Plot the confusion matrix given an estimator, the data, and the label. ConfusionMatrixDisplay.from_predictions : Plot the confusion matrix given the true and predicted labels. ConfusionMatrixDisplay : Confusion Matrix visualization. References ---------- .. [1] `Wikipedia entry for the Confusion matrix <https://en.wikipedia.org/wiki/Confusion_matrix>`_ (Wikipedia and other references may use a different convention for axes). Examples -------- >>> from sklearn.metrics import confusion_matrix >>> y_true = [2, 0, 2, 2, 0, 1] >>> y_pred = [0, 0, 2, 2, 0, 2] >>> confusion_matrix(y_true, y_pred) array([[2, 0, 0], [0, 0, 1], [1, 0, 2]]) >>> y_true = ["cat", "ant", "cat", "cat", "ant", "bird"] >>> y_pred = ["ant", "ant", "cat", "cat", "ant", "cat"] >>> confusion_matrix(y_true, y_pred, labels=["ant", "bird", "cat"]) array([[2, 0, 0], [0, 0, 1], [1, 0, 2]]) In the binary case, we can extract true positives, etc. as follows: >>> tn, fp, fn, tp = confusion_matrix([0, 1, 0, 1], [1, 1, 1, 0]).ravel().tolist() >>> (tn, fp, fn, tp) (0, 2, 1, 1)
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 of a classification, and output confusion matrices for each class or sample. In multilabel confusion matrix :math:`MCM`, the count of true negatives is :math:`MCM_{:,0,0}`, false negatives is :math:`MCM_{:,1,0}`, true positives is :math:`MCM_{:,1,1}` and false positives is :math:`MCM_{:,0,1}`. Multiclass data will be treated as if binarized under a one-vs-rest transformation. Returned confusion matrices will be in the order of sorted unique labels in the union of (y_true, y_pred). Read more in the :ref:`User Guide <multilabel_confusion_matrix>`. Parameters ---------- y_true : {array-like, sparse matrix} of shape (n_samples, n_outputs) or \ (n_samples,) Ground truth (correct) target values. y_pred : {array-like, sparse matrix} of shape (n_samples, n_outputs) or \ (n_samples,) Estimated targets as returned by a classifier. sample_weight : array-like of shape (n_samples,), default=None Sample weights. labels : array-like of shape (n_classes,), default=None A list of classes or column indices to select some (or to force inclusion of classes absent from the data). samplewise : bool, default=False In the multilabel case, this calculates a confusion matrix per sample. Returns ------- multi_confusion : ndarray of shape (n_outputs, 2, 2) A 2x2 confusion matrix corresponding to each output in the input. When calculating class-wise multi_confusion (default), then n_outputs = n_labels; when calculating sample-wise multi_confusion (samplewise=True), n_outputs = n_samples. If ``labels`` is defined, the results will be returned in the order specified in ``labels``, otherwise the results will be returned in sorted order by default. See Also -------- confusion_matrix : Compute confusion matrix to evaluate the accuracy of a classifier. Notes ----- The `multilabel_confusion_matrix` calculates class-wise or sample-wise multilabel confusion matrices, and in multiclass tasks, labels are binarized under a one-vs-rest way; while :func:`~sklearn.metrics.confusion_matrix` calculates one confusion matrix for confusion between every two classes. Examples -------- Multilabel-indicator case: >>> import numpy as np >>> from sklearn.metrics import multilabel_confusion_matrix >>> y_true = np.array([[1, 0, 1], ... [0, 1, 0]]) >>> y_pred = np.array([[1, 0, 0], ... [0, 1, 1]]) >>> multilabel_confusion_matrix(y_true, y_pred) array([[[1, 0], [0, 1]], <BLANKLINE> [[1, 0], [0, 1]], <BLANKLINE> [[0, 1], [1, 0]]]) Multiclass case: >>> y_true = ["cat", "ant", "cat", "cat", "ant", "bird"] >>> y_pred = ["ant", "ant", "cat", "cat", "ant", "cat"] >>> multilabel_confusion_matrix(y_true, y_pred, ... labels=["ant", "bird", "cat"]) array([[[3, 1], [0, 2]], <BLANKLINE> [[5, 0], [1, 0]], <BLANKLINE> [[2, 1], [1, 2]]]) """ y_true, y_pred = attach_unique(y_true, y_pred) xp, _, device_ = get_namespace_and_device(y_true, y_pred) y_type, y_true, y_pred = _check_targets(y_true, y_pred) if sample_weight is not None: sample_weight = column_or_1d(sample_weight, device=device_) check_consistent_length(y_true, y_pred, sample_weight) if y_type not in ("binary", "multiclass", "multilabel-indicator"): raise ValueError("%s is not supported" % y_type) present_labels = unique_labels(y_true, y_pred) if labels is None: labels = present_labels n_labels = None else: labels = xp.asarray(labels, device=device_) n_labels = labels.shape[0] labels = xp.concat( [labels, xpx.setdiff1d(present_labels, labels, assume_unique=True, xp=xp)], axis=-1, ) if y_true.ndim == 1: if samplewise: raise ValueError( "Samplewise metrics are not available outside of " "multilabel classification." ) le = LabelEncoder() le.fit(labels) y_true = le.transform(y_true) y_pred = le.transform(y_pred) sorted_labels = le.classes_ # labels are now from 0 to len(labels) - 1 -> use bincount tp = y_true == y_pred tp_bins = y_true[tp] if sample_weight is not None: tp_bins_weights = sample_weight[tp] else: tp_bins_weights = None if tp_bins.shape[0]: tp_sum = _bincount( tp_bins, weights=tp_bins_weights, minlength=labels.shape[0], xp=xp ) else: # Pathological case true_sum = pred_sum = tp_sum = xp.zeros(labels.shape[0]) if y_pred.shape[0]: pred_sum = _bincount( y_pred, weights=sample_weight, minlength=labels.shape[0], xp=xp ) if y_true.shape[0]: true_sum = _bincount( y_true, weights=sample_weight, minlength=labels.shape[0], xp=xp ) # Retain only selected labels indices = _searchsorted(sorted_labels, labels[:n_labels], xp=xp) tp_sum = xp.take(tp_sum, indices, axis=0) true_sum = xp.take(true_sum, indices, axis=0) pred_sum = xp.take(pred_sum, indices, axis=0) else: sum_axis = 1 if samplewise else 0 # All labels are index integers for multilabel. # Select labels: if labels.shape != present_labels.shape or xp.any( xp.not_equal(labels, present_labels) ): if xp.max(labels) > xp.max(present_labels): raise ValueError( "All labels must be in [0, n labels) for " "multilabel targets. " "Got %d > %d" % (xp.max(labels), xp.max(present_labels)) ) if xp.min(labels) < 0: raise ValueError( "All labels must be in [0, n labels) for " "multilabel targets. " "Got %d < 0" % xp.min(labels) ) if n_labels is not None: y_true = y_true[:, labels[:n_labels]] y_pred = y_pred[:, labels[:n_labels]] if issparse(y_true) or issparse(y_pred): true_and_pred = y_true.multiply(y_pred) else: true_and_pred = xp.multiply(y_true, y_pred) # calculate weighted counts tp_sum = _count_nonzero( true_and_pred, axis=sum_axis, sample_weight=sample_weight, xp=xp, device=device_, ) pred_sum = _count_nonzero( y_pred, axis=sum_axis, sample_weight=sample_weight, xp=xp, device=device_, ) true_sum = _count_nonzero( y_true, axis=sum_axis, sample_weight=sample_weight, xp=xp, device=device_, ) fp = pred_sum - tp_sum fn = true_sum - tp_sum tp = tp_sum if sample_weight is not None and samplewise: tp = xp.asarray(tp) fp = xp.asarray(fp) fn = xp.asarray(fn) tn = sample_weight * y_true.shape[1] - tp - fp - fn elif sample_weight is not None: tn = xp.sum(sample_weight) - tp - fp - fn elif samplewise: tn = y_true.shape[1] - tp - fp - fn else: tn = y_true.shape[0] - tp - fp - fn return xp.reshape(xp.stack([tn, fp, fn, tp]).T, (-1, 2, 2))
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 matrix :math:`MCM`, the count of true negatives is :math:`MCM_{:,0,0}`, false negatives is :math:`MCM_{:,1,0}`, true positives is :math:`MCM_{:,1,1}` and false positives is :math:`MCM_{:,0,1}`. Multiclass data will be treated as if binarized under a one-vs-rest transformation. Returned confusion matrices will be in the order of sorted unique labels in the union of (y_true, y_pred). Read more in the :ref:`User Guide <multilabel_confusion_matrix>`. Parameters ---------- y_true : {array-like, sparse matrix} of shape (n_samples, n_outputs) or (n_samples,) Ground truth (correct) target values. y_pred : {array-like, sparse matrix} of shape (n_samples, n_outputs) or (n_samples,) Estimated targets as returned by a classifier. sample_weight : array-like of shape (n_samples,), default=None Sample weights. labels : array-like of shape (n_classes,), default=None A list of classes or column indices to select some (or to force inclusion of classes absent from the data). samplewise : bool, default=False In the multilabel case, this calculates a confusion matrix per sample. Returns ------- multi_confusion : ndarray of shape (n_outputs, 2, 2) A 2x2 confusion matrix corresponding to each output in the input. When calculating class-wise multi_confusion (default), then n_outputs = n_labels; when calculating sample-wise multi_confusion (samplewise=True), n_outputs = n_samples. If ``labels`` is defined, the results will be returned in the order specified in ``labels``, otherwise the results will be returned in sorted order by default. See Also -------- confusion_matrix : Compute confusion matrix to evaluate the accuracy of a classifier. Notes ----- The `multilabel_confusion_matrix` calculates class-wise or sample-wise multilabel confusion matrices, and in multiclass tasks, labels are binarized under a one-vs-rest way; while :func:`~sklearn.metrics.confusion_matrix` calculates one confusion matrix for confusion between every two classes. Examples -------- Multilabel-indicator case: >>> import numpy as np >>> from sklearn.metrics import multilabel_confusion_matrix >>> y_true = np.array([[1, 0, 1], ... [0, 1, 0]]) >>> y_pred = np.array([[1, 0, 0], ... [0, 1, 1]]) >>> multilabel_confusion_matrix(y_true, y_pred) array([[[1, 0], [0, 1]], <BLANKLINE> [[1, 0], [0, 1]], <BLANKLINE> [[0, 1], [1, 0]]]) Multiclass case: >>> y_true = ["cat", "ant", "cat", "cat", "ant", "bird"] >>> y_pred = ["ant", "ant", "cat", "cat", "ant", "cat"] >>> multilabel_confusion_matrix(y_true, y_pred, ... labels=["ant", "bird", "cat"]) array([[[3, 1], [0, 2]], <BLANKLINE> [[5, 0], [1, 0]], <BLANKLINE> [[2, 1], [1, 2]]])
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 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``. Support beyond term:`binary` targets is achieved by treating :term:`multiclass` and :term:`multilabel` data as a collection of binary problems, one for each label. For the :term:`binary` case, setting `average='binary'` will return the Jaccard similarity coefficient for `pos_label`. If `average` is not `'binary'`, `pos_label` is ignored and scores for both classes are computed, then averaged or both returned (when `average=None`). Similarly, for :term:`multiclass` and :term:`multilabel` targets, scores for all `labels` are either returned or averaged depending on the `average` parameter. Use `labels` specify the set of labels to calculate the score for. Read more in the :ref:`User Guide <jaccard_similarity_score>`. Parameters ---------- y_true : 1d array-like, or label indicator array / sparse matrix Ground truth (correct) labels. y_pred : 1d array-like, or label indicator array / sparse matrix Predicted labels, as returned by a classifier. labels : array-like of shape (n_classes,), default=None The set of labels to include when `average != 'binary'`, and their order if `average is None`. Labels present in the data can be excluded, for example in multiclass classification to exclude a "negative class". Labels not present in the data can be included and will be "assigned" 0 samples. For multilabel targets, labels are column indices. By default, all labels in `y_true` and `y_pred` are used in sorted order. pos_label : int, float, bool or str, default=1 The class to report if `average='binary'` and the data is binary, otherwise this parameter is ignored. For multiclass or multilabel targets, set `labels=[pos_label]` and `average != 'binary'` to report metrics for one label only. average : {'micro', 'macro', 'samples', 'weighted', \ 'binary'} or None, default='binary' If ``None``, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data: ``'binary'``: Only report results for the class specified by ``pos_label``. This is applicable only if targets (``y_{true,pred}``) are binary. ``'micro'``: Calculate metrics globally by counting the total true positives, false negatives and false positives. ``'macro'``: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. ``'weighted'``: Calculate metrics for each label, and find their average, weighted by support (the number of true instances for each label). This alters 'macro' to account for label imbalance. ``'samples'``: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification). sample_weight : array-like of shape (n_samples,), default=None Sample weights. zero_division : "warn", {0.0, 1.0}, default="warn" Sets the value to return when there is a zero division, i.e. when there there are no negative values in predictions and labels. If set to "warn", this acts like 0, but a warning is also raised. .. versionadded:: 0.24 Returns ------- score : float or ndarray of shape (n_unique_labels,), dtype=np.float64 The Jaccard score. When `average` is not `None`, a single scalar is returned. See Also -------- accuracy_score : Function for calculating the accuracy score. f1_score : Function for calculating the F1 score. multilabel_confusion_matrix : Function for computing a confusion matrix\ for each class or sample. Notes ----- :func:`jaccard_score` may be a poor metric if there are no positives for some samples or classes. Jaccard is undefined if there are no true or predicted labels, and our implementation will return a score of 0 with a warning. References ---------- .. [1] `Wikipedia entry for the Jaccard index <https://en.wikipedia.org/wiki/Jaccard_index>`_. Examples -------- >>> import numpy as np >>> from sklearn.metrics import jaccard_score >>> y_true = np.array([[0, 1, 1], ... [1, 1, 0]]) >>> y_pred = np.array([[1, 1, 1], ... [1, 0, 0]]) In the binary case: >>> jaccard_score(y_true[0], y_pred[0]) 0.6666 In the 2D comparison case (e.g. image similarity): >>> jaccard_score(y_true, y_pred, average="micro") 0.6 In the multilabel case: >>> jaccard_score(y_true, y_pred, average='samples') 0.5833 >>> jaccard_score(y_true, y_pred, average='macro') 0.6666 >>> jaccard_score(y_true, y_pred, average=None) array([0.5, 0.5, 1. ]) In the multiclass case: >>> y_pred = [0, 2, 1, 2] >>> y_true = [0, 1, 2, 2] >>> jaccard_score(y_true, y_pred, average=None) array([1. , 0. , 0.33]) """ labels = _check_set_wise_labels(y_true, y_pred, average, labels, pos_label) samplewise = average == "samples" MCM = multilabel_confusion_matrix( y_true, y_pred, sample_weight=sample_weight, labels=labels, samplewise=samplewise, ) numerator = MCM[:, 1, 1] denominator = MCM[:, 1, 1] + MCM[:, 0, 1] + MCM[:, 1, 0] xp, _, device_ = get_namespace_and_device(y_true, y_pred) if average == "micro": numerator = xp.asarray(xp.sum(numerator, keepdims=True), device=device_) denominator = xp.asarray(xp.sum(denominator, keepdims=True), device=device_) jaccard = _prf_divide( numerator, denominator, "jaccard", "true or predicted", average, ("jaccard",), zero_division=zero_division, ) if average is None: return jaccard if average == "weighted": weights = MCM[:, 1, 0] + MCM[:, 1, 1] if not xp.any(weights): # numerator is 0, and warning should have already been issued weights = None elif average == "samples" and sample_weight is not None: weights = sample_weight else: weights = None return float(_average(jaccard, weights=weights, xp=xp))
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``. Support beyond term:`binary` targets is achieved by treating :term:`multiclass` and :term:`multilabel` data as a collection of binary problems, one for each label. For the :term:`binary` case, setting `average='binary'` will return the Jaccard similarity coefficient for `pos_label`. If `average` is not `'binary'`, `pos_label` is ignored and scores for both classes are computed, then averaged or both returned (when `average=None`). Similarly, for :term:`multiclass` and :term:`multilabel` targets, scores for all `labels` are either returned or averaged depending on the `average` parameter. Use `labels` specify the set of labels to calculate the score for. Read more in the :ref:`User Guide <jaccard_similarity_score>`. Parameters ---------- y_true : 1d array-like, or label indicator array / sparse matrix Ground truth (correct) labels. y_pred : 1d array-like, or label indicator array / sparse matrix Predicted labels, as returned by a classifier. labels : array-like of shape (n_classes,), default=None The set of labels to include when `average != 'binary'`, and their order if `average is None`. Labels present in the data can be excluded, for example in multiclass classification to exclude a "negative class". Labels not present in the data can be included and will be "assigned" 0 samples. For multilabel targets, labels are column indices. By default, all labels in `y_true` and `y_pred` are used in sorted order. pos_label : int, float, bool or str, default=1 The class to report if `average='binary'` and the data is binary, otherwise this parameter is ignored. For multiclass or multilabel targets, set `labels=[pos_label]` and `average != 'binary'` to report metrics for one label only. average : {'micro', 'macro', 'samples', 'weighted', 'binary'} or None, default='binary' If ``None``, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data: ``'binary'``: Only report results for the class specified by ``pos_label``. This is applicable only if targets (``y_{true,pred}``) are binary. ``'micro'``: Calculate metrics globally by counting the total true positives, false negatives and false positives. ``'macro'``: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. ``'weighted'``: Calculate metrics for each label, and find their average, weighted by support (the number of true instances for each label). This alters 'macro' to account for label imbalance. ``'samples'``: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification). sample_weight : array-like of shape (n_samples,), default=None Sample weights. zero_division : "warn", {0.0, 1.0}, default="warn" Sets the value to return when there is a zero division, i.e. when there there are no negative values in predictions and labels. If set to "warn", this acts like 0, but a warning is also raised. .. versionadded:: 0.24 Returns ------- score : float or ndarray of shape (n_unique_labels,), dtype=np.float64 The Jaccard score. When `average` is not `None`, a single scalar is returned. See Also -------- accuracy_score : Function for calculating the accuracy score. f1_score : Function for calculating the F1 score. multilabel_confusion_matrix : Function for computing a confusion matrix for each class or sample. Notes ----- :func:`jaccard_score` may be a poor metric if there are no positives for some samples or classes. Jaccard is undefined if there are no true or predicted labels, and our implementation will return a score of 0 with a warning. References ---------- .. [1] `Wikipedia entry for the Jaccard index <https://en.wikipedia.org/wiki/Jaccard_index>`_. Examples -------- >>> import numpy as np >>> from sklearn.metrics import jaccard_score >>> y_true = np.array([[0, 1, 1], ... [1, 1, 0]]) >>> y_pred = np.array([[1, 1, 1], ... [1, 0, 0]]) In the binary case: >>> jaccard_score(y_true[0], y_pred[0]) 0.6666 In the 2D comparison case (e.g. image similarity): >>> jaccard_score(y_true, y_pred, average="micro") 0.6 In the multilabel case: >>> jaccard_score(y_true, y_pred, average='samples') 0.5833 >>> jaccard_score(y_true, y_pred, average='macro') 0.6666 >>> jaccard_score(y_true, y_pred, average=None) array([0.5, 0.5, 1. ]) In the multiclass case: >>> y_pred = [0, 2, 1, 2] >>> y_true = [0, 1, 2, 2] >>> jaccard_score(y_true, y_pred, average=None) array([1. , 0. , 0.33])
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 negatives and is generally regarded as a balanced measure which can be used even if the classes are of very different sizes. The MCC is in essence a correlation coefficient value between -1 and +1. A coefficient of +1 represents a perfect prediction, 0 an average random prediction and -1 an inverse prediction. The statistic is also known as the phi coefficient. [source: Wikipedia] Binary and multiclass labels are supported. Only in the binary case does this relate to information about true and false positives and negatives. See references below. Read more in the :ref:`User Guide <matthews_corrcoef>`. Parameters ---------- y_true : array-like of shape (n_samples,) Ground truth (correct) target values. y_pred : array-like of shape (n_samples,) Estimated targets as returned by a classifier. sample_weight : array-like of shape (n_samples,), default=None Sample weights. .. versionadded:: 0.18 Returns ------- mcc : float The Matthews correlation coefficient (+1 represents a perfect prediction, 0 an average random prediction and -1 and inverse prediction). References ---------- .. [1] :doi:`Baldi, Brunak, Chauvin, Andersen and Nielsen, (2000). Assessing the accuracy of prediction algorithms for classification: an overview. <10.1093/bioinformatics/16.5.412>` .. [2] `Wikipedia entry for the Matthews Correlation Coefficient (phi coefficient) <https://en.wikipedia.org/wiki/Phi_coefficient>`_. .. [3] `Gorodkin, (2004). Comparing two K-category assignments by a K-category correlation coefficient <https://www.sciencedirect.com/science/article/pii/S1476927104000799>`_. .. [4] `Jurman, Riccadonna, Furlanello, (2012). A Comparison of MCC and CEN Error Measures in MultiClass Prediction <https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0041882>`_. Examples -------- >>> from sklearn.metrics import matthews_corrcoef >>> y_true = [+1, +1, +1, -1] >>> y_pred = [+1, -1, +1, +1] >>> matthews_corrcoef(y_true, y_pred) -0.33 """ y_true, y_pred = attach_unique(y_true, y_pred) y_type, y_true, y_pred = _check_targets(y_true, y_pred) check_consistent_length(y_true, y_pred, sample_weight) if y_type not in {"binary", "multiclass"}: raise ValueError("%s is not supported" % y_type) lb = LabelEncoder() lb.fit(np.hstack([y_true, y_pred])) y_true = lb.transform(y_true) y_pred = lb.transform(y_pred) C = confusion_matrix(y_true, y_pred, sample_weight=sample_weight) t_sum = C.sum(axis=1, dtype=np.float64) p_sum = C.sum(axis=0, dtype=np.float64) n_correct = np.trace(C, dtype=np.float64) n_samples = p_sum.sum() cov_ytyp = n_correct * n_samples - np.dot(t_sum, p_sum) cov_ypyp = n_samples**2 - np.dot(p_sum, p_sum) cov_ytyt = n_samples**2 - np.dot(t_sum, t_sum) cov_ypyp_ytyt = cov_ypyp * cov_ytyt if cov_ypyp_ytyt == 0: return 0.0 else: return float(cov_ytyp / np.sqrt(cov_ypyp_ytyt))
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 can be used even if the classes are of very different sizes. The MCC is in essence a correlation coefficient value between -1 and +1. A coefficient of +1 represents a perfect prediction, 0 an average random prediction and -1 an inverse prediction. The statistic is also known as the phi coefficient. [source: Wikipedia] Binary and multiclass labels are supported. Only in the binary case does this relate to information about true and false positives and negatives. See references below. Read more in the :ref:`User Guide <matthews_corrcoef>`. Parameters ---------- y_true : array-like of shape (n_samples,) Ground truth (correct) target values. y_pred : array-like of shape (n_samples,) Estimated targets as returned by a classifier. sample_weight : array-like of shape (n_samples,), default=None Sample weights. .. versionadded:: 0.18 Returns ------- mcc : float The Matthews correlation coefficient (+1 represents a perfect prediction, 0 an average random prediction and -1 and inverse prediction). References ---------- .. [1] :doi:`Baldi, Brunak, Chauvin, Andersen and Nielsen, (2000). Assessing the accuracy of prediction algorithms for classification: an overview. <10.1093/bioinformatics/16.5.412>` .. [2] `Wikipedia entry for the Matthews Correlation Coefficient (phi coefficient) <https://en.wikipedia.org/wiki/Phi_coefficient>`_. .. [3] `Gorodkin, (2004). Comparing two K-category assignments by a K-category correlation coefficient <https://www.sciencedirect.com/science/article/pii/S1476927104000799>`_. .. [4] `Jurman, Riccadonna, Furlanello, (2012). A Comparison of MCC and CEN Error Measures in MultiClass Prediction <https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0041882>`_. Examples -------- >>> from sklearn.metrics import matthews_corrcoef >>> y_true = [+1, +1, +1, -1] >>> y_pred = [+1, -1, +1, +1] >>> matthews_corrcoef(y_true, y_pred) -0.33
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 Guide <zero_one_loss>`. Parameters ---------- y_true : 1d array-like, or label indicator array / sparse matrix Ground truth (correct) labels. y_pred : 1d array-like, or label indicator array / sparse matrix Predicted labels, as returned by a classifier. normalize : bool, default=True If ``False``, return the number of misclassifications. Otherwise, return the fraction of misclassifications. sample_weight : array-like of shape (n_samples,), default=None Sample weights. Returns ------- loss : float or int, If ``normalize == True``, return the fraction of misclassifications (float), else it returns the number of misclassifications (int). See Also -------- accuracy_score : Compute the accuracy score. By default, the function will return the fraction of correct predictions divided by the total number of predictions. hamming_loss : Compute the average Hamming loss or Hamming distance between two sets of samples. jaccard_score : Compute the Jaccard similarity coefficient score. Notes ----- In multilabel classification, the zero_one_loss function corresponds to the subset zero-one loss: for each sample, the entire set of labels must be correctly predicted, otherwise the loss for that sample is equal to one. Examples -------- >>> from sklearn.metrics import zero_one_loss >>> y_pred = [1, 2, 3, 4] >>> y_true = [2, 2, 3, 4] >>> zero_one_loss(y_true, y_pred) 0.25 >>> zero_one_loss(y_true, y_pred, normalize=False) 1.0 In the multilabel case with binary label indicators: >>> import numpy as np >>> zero_one_loss(np.array([[0, 1], [1, 1]]), np.ones((2, 2))) 0.5 """ xp, _ = get_namespace(y_true, y_pred) score = accuracy_score( y_true, y_pred, normalize=normalize, sample_weight=sample_weight ) if normalize: return 1 - score else: if sample_weight is not None: n_samples = xp.sum(sample_weight) else: n_samples = _num_samples(y_true) return n_samples - score
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, or label indicator array / sparse matrix Ground truth (correct) labels. y_pred : 1d array-like, or label indicator array / sparse matrix Predicted labels, as returned by a classifier. normalize : bool, default=True If ``False``, return the number of misclassifications. Otherwise, return the fraction of misclassifications. sample_weight : array-like of shape (n_samples,), default=None Sample weights. Returns ------- loss : float or int, If ``normalize == True``, return the fraction of misclassifications (float), else it returns the number of misclassifications (int). See Also -------- accuracy_score : Compute the accuracy score. By default, the function will return the fraction of correct predictions divided by the total number of predictions. hamming_loss : Compute the average Hamming loss or Hamming distance between two sets of samples. jaccard_score : Compute the Jaccard similarity coefficient score. Notes ----- In multilabel classification, the zero_one_loss function corresponds to the subset zero-one loss: for each sample, the entire set of labels must be correctly predicted, otherwise the loss for that sample is equal to one. Examples -------- >>> from sklearn.metrics import zero_one_loss >>> y_pred = [1, 2, 3, 4] >>> y_true = [2, 2, 3, 4] >>> zero_one_loss(y_true, y_pred) 0.25 >>> zero_one_loss(y_true, y_pred, normalize=False) 1.0 In the multilabel case with binary label indicators: >>> import numpy as np >>> zero_one_loss(np.array([[0, 1], [1, 1]]), np.ones((2, 2))) 0.5
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, 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 for the F1 score is: .. math:: \\text{F1} = \\frac{2 * \\text{TP}}{2 * \\text{TP} + \\text{FP} + \\text{FN}} Where :math:`\\text{TP}` is the number of true positives, :math:`\\text{FN}` is the number of false negatives, and :math:`\\text{FP}` is the number of false positives. F1 is by default calculated as 0.0 when there are no true positives, false negatives, or false positives. Support beyond :term:`binary` targets is achieved by treating :term:`multiclass` and :term:`multilabel` data as a collection of binary problems, one for each label. For the :term:`binary` case, setting `average='binary'` will return F1 score for `pos_label`. If `average` is not `'binary'`, `pos_label` is ignored and F1 score for both classes are computed, then averaged or both returned (when `average=None`). Similarly, for :term:`multiclass` and :term:`multilabel` targets, F1 score for all `labels` are either returned or averaged depending on the `average` parameter. Use `labels` specify the set of labels to calculate F1 score for. Read more in the :ref:`User Guide <precision_recall_f_measure_metrics>`. 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 array / sparse matrix Estimated targets as returned by a classifier. labels : array-like, default=None The set of labels to include when `average != 'binary'`, and their order if `average is None`. Labels present in the data can be excluded, for example in multiclass classification to exclude a "negative class". Labels not present in the data can be included and will be "assigned" 0 samples. For multilabel targets, labels are column indices. By default, all labels in `y_true` and `y_pred` are used in sorted order. .. versionchanged:: 0.17 Parameter `labels` improved for multiclass problem. pos_label : int, float, bool or str, default=1 The class to report if `average='binary'` and the data is binary, otherwise this parameter is ignored. For multiclass or multilabel targets, set `labels=[pos_label]` and `average != 'binary'` to report metrics for one label only. average : {'micro', 'macro', 'samples', 'weighted', 'binary'} or None, \ default='binary' This parameter is required for multiclass/multilabel targets. If ``None``, the metrics for each class are returned. Otherwise, this determines the type of averaging performed on the data: ``'binary'``: Only report results for the class specified by ``pos_label``. This is applicable only if targets (``y_{true,pred}``) are binary. ``'micro'``: Calculate metrics globally by counting the total true positives, false negatives and false positives. ``'macro'``: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. ``'weighted'``: Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters 'macro' to account for label imbalance; it can result in an F-score that is not between precision and recall. ``'samples'``: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification where this differs from :func:`accuracy_score`). sample_weight : array-like of shape (n_samples,), default=None Sample weights. zero_division : {"warn", 0.0, 1.0, np.nan}, default="warn" Sets the value to return when there is a zero division, i.e. when all predictions and labels are negative. Notes: - If set to "warn", this acts like 0, but a warning is also raised. - If set to `np.nan`, such values will be excluded from the average. .. versionadded:: 1.3 `np.nan` option was added. Returns ------- f1_score : float or array of float, shape = [n_unique_labels] F1 score of the positive class in binary classification or weighted average of the F1 scores of each class for the multiclass task. See Also -------- fbeta_score : Compute the F-beta score. precision_recall_fscore_support : Compute the precision, recall, F-score, and support. jaccard_score : Compute the Jaccard similarity coefficient score. multilabel_confusion_matrix : Compute a confusion matrix for each class or sample. Notes ----- When ``true positive + false positive + false negative == 0`` (i.e. a class is completely absent from both ``y_true`` or ``y_pred``), f-score is undefined. In such cases, by default f-score will be set to 0.0, and ``UndefinedMetricWarning`` will be raised. This behavior can be modified by setting the ``zero_division`` parameter. References ---------- .. [1] `Wikipedia entry for the F1-score <https://en.wikipedia.org/wiki/F1_score>`_. Examples -------- >>> import numpy as np >>> from sklearn.metrics import f1_score >>> y_true = [0, 1, 2, 0, 1, 2] >>> y_pred = [0, 2, 1, 0, 0, 1] >>> f1_score(y_true, y_pred, average='macro') 0.267 >>> f1_score(y_true, y_pred, average='micro') 0.33 >>> f1_score(y_true, y_pred, average='weighted') 0.267 >>> f1_score(y_true, y_pred, average=None) array([0.8, 0. , 0. ]) >>> # binary classification >>> y_true_empty = [0, 0, 0, 0, 0, 0] >>> y_pred_empty = [0, 0, 0, 0, 0, 0] >>> f1_score(y_true_empty, y_pred_empty) 0.0... >>> f1_score(y_true_empty, y_pred_empty, zero_division=1.0) 1.0... >>> f1_score(y_true_empty, y_pred_empty, zero_division=np.nan) nan... >>> # multilabel classification >>> y_true = [[0, 0, 0], [1, 1, 1], [0, 1, 1]] >>> y_pred = [[0, 0, 0], [1, 1, 1], [1, 1, 0]] >>> f1_score(y_true, y_pred, average=None) array([0.66666667, 1. , 0.66666667]) """ return fbeta_score( y_true, y_pred, beta=1, labels=labels, pos_label=pos_label, average=average, sample_weight=sample_weight, zero_division=zero_division, )
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 for the F1 score is: .. math:: \text{F1} = \frac{2 * \text{TP}}{2 * \text{TP} + \text{FP} + \text{FN}} Where :math:`\text{TP}` is the number of true positives, :math:`\text{FN}` is the number of false negatives, and :math:`\text{FP}` is the number of false positives. F1 is by default calculated as 0.0 when there are no true positives, false negatives, or false positives. Support beyond :term:`binary` targets is achieved by treating :term:`multiclass` and :term:`multilabel` data as a collection of binary problems, one for each label. For the :term:`binary` case, setting `average='binary'` will return F1 score for `pos_label`. If `average` is not `'binary'`, `pos_label` is ignored and F1 score for both classes are computed, then averaged or both returned (when `average=None`). Similarly, for :term:`multiclass` and :term:`multilabel` targets, F1 score for all `labels` are either returned or averaged depending on the `average` parameter. Use `labels` specify the set of labels to calculate F1 score for. Read more in the :ref:`User Guide <precision_recall_f_measure_metrics>`. 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 array / sparse matrix Estimated targets as returned by a classifier. labels : array-like, default=None The set of labels to include when `average != 'binary'`, and their order if `average is None`. Labels present in the data can be excluded, for example in multiclass classification to exclude a "negative class". Labels not present in the data can be included and will be "assigned" 0 samples. For multilabel targets, labels are column indices. By default, all labels in `y_true` and `y_pred` are used in sorted order. .. versionchanged:: 0.17 Parameter `labels` improved for multiclass problem. pos_label : int, float, bool or str, default=1 The class to report if `average='binary'` and the data is binary, otherwise this parameter is ignored. For multiclass or multilabel targets, set `labels=[pos_label]` and `average != 'binary'` to report metrics for one label only. average : {'micro', 'macro', 'samples', 'weighted', 'binary'} or None, default='binary' This parameter is required for multiclass/multilabel targets. If ``None``, the metrics for each class are returned. Otherwise, this determines the type of averaging performed on the data: ``'binary'``: Only report results for the class specified by ``pos_label``. This is applicable only if targets (``y_{true,pred}``) are binary. ``'micro'``: Calculate metrics globally by counting the total true positives, false negatives and false positives. ``'macro'``: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. ``'weighted'``: Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters 'macro' to account for label imbalance; it can result in an F-score that is not between precision and recall. ``'samples'``: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification where this differs from :func:`accuracy_score`). sample_weight : array-like of shape (n_samples,), default=None Sample weights. zero_division : {"warn", 0.0, 1.0, np.nan}, default="warn" Sets the value to return when there is a zero division, i.e. when all predictions and labels are negative. Notes: - If set to "warn", this acts like 0, but a warning is also raised. - If set to `np.nan`, such values will be excluded from the average. .. versionadded:: 1.3 `np.nan` option was added. Returns ------- f1_score : float or array of float, shape = [n_unique_labels] F1 score of the positive class in binary classification or weighted average of the F1 scores of each class for the multiclass task. See Also -------- fbeta_score : Compute the F-beta score. precision_recall_fscore_support : Compute the precision, recall, F-score, and support. jaccard_score : Compute the Jaccard similarity coefficient score. multilabel_confusion_matrix : Compute a confusion matrix for each class or sample. Notes ----- When ``true positive + false positive + false negative == 0`` (i.e. a class is completely absent from both ``y_true`` or ``y_pred``), f-score is undefined. In such cases, by default f-score will be set to 0.0, and ``UndefinedMetricWarning`` will be raised. This behavior can be modified by setting the ``zero_division`` parameter. References ---------- .. [1] `Wikipedia entry for the F1-score <https://en.wikipedia.org/wiki/F1_score>`_. Examples -------- >>> import numpy as np >>> from sklearn.metrics import f1_score >>> y_true = [0, 1, 2, 0, 1, 2] >>> y_pred = [0, 2, 1, 0, 0, 1] >>> f1_score(y_true, y_pred, average='macro') 0.267 >>> f1_score(y_true, y_pred, average='micro') 0.33 >>> f1_score(y_true, y_pred, average='weighted') 0.267 >>> f1_score(y_true, y_pred, average=None) array([0.8, 0. , 0. ]) >>> # binary classification >>> y_true_empty = [0, 0, 0, 0, 0, 0] >>> y_pred_empty = [0, 0, 0, 0, 0, 0] >>> f1_score(y_true_empty, y_pred_empty) 0.0... >>> f1_score(y_true_empty, y_pred_empty, zero_division=1.0) 1.0... >>> f1_score(y_true_empty, y_pred_empty, zero_division=np.nan) nan... >>> # multilabel classification >>> y_true = [[0, 0, 0], [1, 1, 1], [0, 1, 1]] >>> y_pred = [[0, 0, 0], [1, 1, 1], [1, 1, 0]] >>> f1_score(y_true, y_pred, average=None) array([0.66666667, 1. , 0.66666667])
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 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 < 1` favors precision. For example, `beta = 2` makes recall twice as important as precision, while `beta = 0.5` does the opposite. Asymptotically, `beta -> +inf` considers only recall, and `beta -> 0` only precision. The formula for F-beta score is: .. math:: F_\\beta = \\frac{(1 + \\beta^2) \\text{tp}} {(1 + \\beta^2) \\text{tp} + \\text{fp} + \\beta^2 \\text{fn}} Where :math:`\\text{tp}` is the number of true positives, :math:`\\text{fp}` is the number of false positives, and :math:`\\text{fn}` is the number of false negatives. Support beyond term:`binary` targets is achieved by treating :term:`multiclass` and :term:`multilabel` data as a collection of binary problems, one for each label. For the :term:`binary` case, setting `average='binary'` will return F-beta score for `pos_label`. If `average` is not `'binary'`, `pos_label` is ignored and F-beta score for both classes are computed, then averaged or both returned (when `average=None`). Similarly, for :term:`multiclass` and :term:`multilabel` targets, F-beta score for all `labels` are either returned or averaged depending on the `average` parameter. Use `labels` specify the set of labels to calculate F-beta score for. Read more in the :ref:`User Guide <precision_recall_f_measure_metrics>`. 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 array / sparse matrix Estimated targets as returned by a classifier. beta : float Determines the weight of recall in the combined score. labels : array-like, default=None The set of labels to include when `average != 'binary'`, and their order if `average is None`. Labels present in the data can be excluded, for example in multiclass classification to exclude a "negative class". Labels not present in the data can be included and will be "assigned" 0 samples. For multilabel targets, labels are column indices. By default, all labels in `y_true` and `y_pred` are used in sorted order. .. versionchanged:: 0.17 Parameter `labels` improved for multiclass problem. pos_label : int, float, bool or str, default=1 The class to report if `average='binary'` and the data is binary, otherwise this parameter is ignored. For multiclass or multilabel targets, set `labels=[pos_label]` and `average != 'binary'` to report metrics for one label only. average : {'micro', 'macro', 'samples', 'weighted', 'binary'} or None, \ default='binary' This parameter is required for multiclass/multilabel targets. If ``None``, the metrics for each class are returned. Otherwise, this determines the type of averaging performed on the data: ``'binary'``: Only report results for the class specified by ``pos_label``. This is applicable only if targets (``y_{true,pred}``) are binary. ``'micro'``: Calculate metrics globally by counting the total true positives, false negatives and false positives. ``'macro'``: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. ``'weighted'``: Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters 'macro' to account for label imbalance; it can result in an F-score that is not between precision and recall. ``'samples'``: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification where this differs from :func:`accuracy_score`). sample_weight : array-like of shape (n_samples,), default=None Sample weights. zero_division : {"warn", 0.0, 1.0, np.nan}, default="warn" Sets the value to return when there is a zero division, i.e. when all predictions and labels are negative. Notes: - If set to "warn", this acts like 0, but a warning is also raised. - If set to `np.nan`, such values will be excluded from the average. .. versionadded:: 1.3 `np.nan` option was added. Returns ------- fbeta_score : float (if average is not None) or array of float, shape =\ [n_unique_labels] F-beta score of the positive class in binary classification or weighted average of the F-beta score of each class for the multiclass task. See Also -------- precision_recall_fscore_support : Compute the precision, recall, F-score, and support. multilabel_confusion_matrix : Compute a confusion matrix for each class or sample. Notes ----- When ``true positive + false positive + false negative == 0``, f-score returns 0.0 and raises ``UndefinedMetricWarning``. This behavior can be modified by setting ``zero_division``. References ---------- .. [1] R. Baeza-Yates and B. Ribeiro-Neto (2011). Modern Information Retrieval. Addison Wesley, pp. 327-328. .. [2] `Wikipedia entry for the F1-score <https://en.wikipedia.org/wiki/F1_score>`_. Examples -------- >>> import numpy as np >>> from sklearn.metrics import fbeta_score >>> y_true = [0, 1, 2, 0, 1, 2] >>> y_pred = [0, 2, 1, 0, 0, 1] >>> fbeta_score(y_true, y_pred, average='macro', beta=0.5) 0.238 >>> fbeta_score(y_true, y_pred, average='micro', beta=0.5) 0.33 >>> fbeta_score(y_true, y_pred, average='weighted', beta=0.5) 0.238 >>> fbeta_score(y_true, y_pred, average=None, beta=0.5) array([0.71, 0. , 0. ]) >>> y_pred_empty = [0, 0, 0, 0, 0, 0] >>> fbeta_score(y_true, y_pred_empty, ... average="macro", zero_division=np.nan, beta=0.5) 0.128 """ _, _, f, _ = precision_recall_fscore_support( y_true, y_pred, beta=beta, labels=labels, pos_label=pos_label, average=average, warn_for=("f-score",), sample_weight=sample_weight, zero_division=zero_division, ) return f
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 < 1` favors precision. For example, `beta = 2` makes recall twice as important as precision, while `beta = 0.5` does the opposite. Asymptotically, `beta -> +inf` considers only recall, and `beta -> 0` only precision. The formula for F-beta score is: .. math:: F_\beta = \frac{(1 + \beta^2) \text{tp}} {(1 + \beta^2) \text{tp} + \text{fp} + \beta^2 \text{fn}} Where :math:`\text{tp}` is the number of true positives, :math:`\text{fp}` is the number of false positives, and :math:`\text{fn}` is the number of false negatives. Support beyond term:`binary` targets is achieved by treating :term:`multiclass` and :term:`multilabel` data as a collection of binary problems, one for each label. For the :term:`binary` case, setting `average='binary'` will return F-beta score for `pos_label`. If `average` is not `'binary'`, `pos_label` is ignored and F-beta score for both classes are computed, then averaged or both returned (when `average=None`). Similarly, for :term:`multiclass` and :term:`multilabel` targets, F-beta score for all `labels` are either returned or averaged depending on the `average` parameter. Use `labels` specify the set of labels to calculate F-beta score for. Read more in the :ref:`User Guide <precision_recall_f_measure_metrics>`. 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 array / sparse matrix Estimated targets as returned by a classifier. beta : float Determines the weight of recall in the combined score. labels : array-like, default=None The set of labels to include when `average != 'binary'`, and their order if `average is None`. Labels present in the data can be excluded, for example in multiclass classification to exclude a "negative class". Labels not present in the data can be included and will be "assigned" 0 samples. For multilabel targets, labels are column indices. By default, all labels in `y_true` and `y_pred` are used in sorted order. .. versionchanged:: 0.17 Parameter `labels` improved for multiclass problem. pos_label : int, float, bool or str, default=1 The class to report if `average='binary'` and the data is binary, otherwise this parameter is ignored. For multiclass or multilabel targets, set `labels=[pos_label]` and `average != 'binary'` to report metrics for one label only. average : {'micro', 'macro', 'samples', 'weighted', 'binary'} or None, default='binary' This parameter is required for multiclass/multilabel targets. If ``None``, the metrics for each class are returned. Otherwise, this determines the type of averaging performed on the data: ``'binary'``: Only report results for the class specified by ``pos_label``. This is applicable only if targets (``y_{true,pred}``) are binary. ``'micro'``: Calculate metrics globally by counting the total true positives, false negatives and false positives. ``'macro'``: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. ``'weighted'``: Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters 'macro' to account for label imbalance; it can result in an F-score that is not between precision and recall. ``'samples'``: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification where this differs from :func:`accuracy_score`). sample_weight : array-like of shape (n_samples,), default=None Sample weights. zero_division : {"warn", 0.0, 1.0, np.nan}, default="warn" Sets the value to return when there is a zero division, i.e. when all predictions and labels are negative. Notes: - If set to "warn", this acts like 0, but a warning is also raised. - If set to `np.nan`, such values will be excluded from the average. .. versionadded:: 1.3 `np.nan` option was added. Returns ------- fbeta_score : float (if average is not None) or array of float, shape = [n_unique_labels] F-beta score of the positive class in binary classification or weighted average of the F-beta score of each class for the multiclass task. See Also -------- precision_recall_fscore_support : Compute the precision, recall, F-score, and support. multilabel_confusion_matrix : Compute a confusion matrix for each class or sample. Notes ----- When ``true positive + false positive + false negative == 0``, f-score returns 0.0 and raises ``UndefinedMetricWarning``. This behavior can be modified by setting ``zero_division``. References ---------- .. [1] R. Baeza-Yates and B. Ribeiro-Neto (2011). Modern Information Retrieval. Addison Wesley, pp. 327-328. .. [2] `Wikipedia entry for the F1-score <https://en.wikipedia.org/wiki/F1_score>`_. Examples -------- >>> import numpy as np >>> from sklearn.metrics import fbeta_score >>> y_true = [0, 1, 2, 0, 1, 2] >>> y_pred = [0, 2, 1, 0, 0, 1] >>> fbeta_score(y_true, y_pred, average='macro', beta=0.5) 0.238 >>> fbeta_score(y_true, y_pred, average='micro', beta=0.5) 0.33 >>> fbeta_score(y_true, y_pred, average='weighted', beta=0.5) 0.238 >>> fbeta_score(y_true, y_pred, average=None, beta=0.5) array([0.71, 0. , 0. ]) >>> y_pred_empty = [0, 0, 0, 0, 0, 0] >>> fbeta_score(y_true, y_pred_empty, ... average="macro", zero_division=np.nan, beta=0.5) 0.128
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"`` raises a warning. The metric, modifier and average arguments are used only for determining an appropriate warning. """ xp, _ = get_namespace(numerator, denominator) dtype_float = _find_matching_floating_dtype(numerator, denominator, xp=xp) mask = denominator == 0 denominator = xp.asarray(denominator, copy=True, dtype=dtype_float) denominator[mask] = 1 # avoid infs/nans result = xp.asarray(numerator, dtype=dtype_float) / denominator if not xp.any(mask): return result # set those with 0 denominator to `zero_division`, and 0 when "warn" zero_division_value = _check_zero_division(zero_division) result[mask] = zero_division_value # we assume the user will be removing warnings if zero_division is set # to something different than "warn". If we are computing only f-score # the warning will be raised only if precision and recall are ill-defined if zero_division != "warn" or metric not in warn_for: return result # build appropriate warning if metric in warn_for: _warn_prf(average, modifier, f"{metric.capitalize()} is", result.shape[0]) return result
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 appropriate warning.
_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 ValueError("average has to be one of " + str(average_options)) y_true, y_pred = attach_unique(y_true, y_pred) y_type, y_true, y_pred = _check_targets(y_true, y_pred) # Convert to Python primitive type to avoid NumPy type / Python str # comparison. See https://github.com/numpy/numpy/issues/6784 present_labels = _tolist(unique_labels(y_true, y_pred)) if average == "binary": if y_type == "binary": if pos_label not in present_labels: if len(present_labels) >= 2: raise ValueError( f"pos_label={pos_label} is not a valid label. It " f"should be one of {present_labels}" ) labels = [pos_label] else: average_options = list(average_options) if y_type == "multiclass": average_options.remove("samples") raise ValueError( "Target is %s but average='binary'. Please " "choose another average setting, one of %r." % (y_type, average_options) ) elif pos_label not in (None, 1): warnings.warn( "Note that pos_label (set to %r) is ignored when " "average != 'binary' (got %r). You may use " "labels=[pos_label] to specify a single positive class." % (pos_label, average), UserWarning, ) return labels
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 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. 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 F-beta score can be interpreted as a weighted harmonic mean of the precision and recall, where an F-beta score reaches its best value at 1 and worst score at 0. The F-beta score weights recall more than precision by a factor of ``beta``. ``beta == 1.0`` means recall and precision are equally important. The support is the number of occurrences of each class in ``y_true``. Support beyond term:`binary` targets is achieved by treating :term:`multiclass` and :term:`multilabel` data as a collection of binary problems, one for each label. For the :term:`binary` case, setting `average='binary'` will return metrics for `pos_label`. If `average` is not `'binary'`, `pos_label` is ignored and metrics for both classes are computed, then averaged or both returned (when `average=None`). Similarly, for :term:`multiclass` and :term:`multilabel` targets, metrics for all `labels` are either returned or averaged depending on the `average` parameter. Use `labels` specify the set of labels to calculate metrics for. Read more in the :ref:`User Guide <precision_recall_f_measure_metrics>`. 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 array / sparse matrix Estimated targets as returned by a classifier. beta : float, default=1.0 The strength of recall versus precision in the F-score. labels : array-like, default=None The set of labels to include when `average != 'binary'`, and their order if `average is None`. Labels present in the data can be excluded, for example in multiclass classification to exclude a "negative class". Labels not present in the data can be included and will be "assigned" 0 samples. For multilabel targets, labels are column indices. By default, all labels in `y_true` and `y_pred` are used in sorted order. .. versionchanged:: 0.17 Parameter `labels` improved for multiclass problem. pos_label : int, float, bool or str, default=1 The class to report if `average='binary'` and the data is binary, otherwise this parameter is ignored. For multiclass or multilabel targets, set `labels=[pos_label]` and `average != 'binary'` to report metrics for one label only. average : {'micro', 'macro', 'samples', 'weighted', 'binary'} or None, \ default='binary' This parameter is required for multiclass/multilabel targets. If ``None``, the metrics for each class are returned. Otherwise, this determines the type of averaging performed on the data: ``'binary'``: Only report results for the class specified by ``pos_label``. This is applicable only if targets (``y_{true,pred}``) are binary. ``'micro'``: Calculate metrics globally by counting the total true positives, false negatives and false positives. ``'macro'``: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. ``'weighted'``: Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters 'macro' to account for label imbalance; it can result in an F-score that is not between precision and recall. ``'samples'``: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification where this differs from :func:`accuracy_score`). warn_for : list, tuple or set, for internal use This determines which warnings will be made in the case that this function is being used to return only one of its metrics. sample_weight : array-like of shape (n_samples,), default=None Sample weights. zero_division : {"warn", 0.0, 1.0, np.nan}, default="warn" Sets the value to return when there is a zero division: - recall: when there are no positive labels - precision: when there are no positive predictions - f-score: both Notes: - If set to "warn", this acts like 0, but a warning is also raised. - If set to `np.nan`, such values will be excluded from the average. .. versionadded:: 1.3 `np.nan` option was added. Returns ------- precision : float (if average is not None) or array of float, shape =\ [n_unique_labels] Precision score. recall : float (if average is not None) or array of float, shape =\ [n_unique_labels] Recall score. fbeta_score : float (if average is not None) or array of float, shape =\ [n_unique_labels] F-beta score. support : None (if average is not None) or array of int, shape =\ [n_unique_labels] The number of occurrences of each label in ``y_true``. Notes ----- When ``true positive + false positive == 0``, precision is undefined. When ``true positive + false negative == 0``, recall is undefined. When ``true positive + false negative + false positive == 0``, f-score is undefined. In such cases, by default the metric will be set to 0, and ``UndefinedMetricWarning`` will be raised. This behavior can be modified with ``zero_division``. References ---------- .. [1] `Wikipedia entry for the Precision and recall <https://en.wikipedia.org/wiki/Precision_and_recall>`_. .. [2] `Wikipedia entry for the F1-score <https://en.wikipedia.org/wiki/F1_score>`_. .. [3] `Discriminative Methods for Multi-labeled Classification Advances in Knowledge Discovery and Data Mining (2004), pp. 22-30 by Shantanu Godbole, Sunita Sarawagi <http://www.godbole.net/shantanu/pubs/multilabelsvm-pakdd04.pdf>`_. Examples -------- >>> import numpy as np >>> from sklearn.metrics import precision_recall_fscore_support >>> y_true = np.array(['cat', 'dog', 'pig', 'cat', 'dog', 'pig']) >>> y_pred = np.array(['cat', 'pig', 'dog', 'cat', 'cat', 'dog']) >>> precision_recall_fscore_support(y_true, y_pred, average='macro') (0.222, 0.333, 0.267, None) >>> precision_recall_fscore_support(y_true, y_pred, average='micro') (0.33, 0.33, 0.33, None) >>> precision_recall_fscore_support(y_true, y_pred, average='weighted') (0.222, 0.333, 0.267, None) It is possible to compute per-label precisions, recalls, F1-scores and supports instead of averaging: >>> precision_recall_fscore_support(y_true, y_pred, average=None, ... labels=['pig', 'dog', 'cat']) (array([0. , 0. , 0.66]), array([0., 0., 1.]), array([0. , 0. , 0.8]), array([2, 2, 2])) """ _check_zero_division(zero_division) labels = _check_set_wise_labels(y_true, y_pred, average, labels, pos_label) # Calculate tp_sum, pred_sum, true_sum ### samplewise = average == "samples" MCM = multilabel_confusion_matrix( y_true, y_pred, sample_weight=sample_weight, labels=labels, samplewise=samplewise, ) tp_sum = MCM[:, 1, 1] pred_sum = tp_sum + MCM[:, 0, 1] true_sum = tp_sum + MCM[:, 1, 0] xp, _, device_ = get_namespace_and_device(y_true, y_pred) if average == "micro": tp_sum = xp.reshape(xp.sum(tp_sum), (1,)) pred_sum = xp.reshape(xp.sum(pred_sum), (1,)) true_sum = xp.reshape(xp.sum(true_sum), (1,)) # Finally, we have all our sufficient statistics. Divide! # beta2 = beta**2 # Divide, and on zero-division, set scores and/or warn according to # zero_division: precision = _prf_divide( tp_sum, pred_sum, "precision", "predicted", average, warn_for, zero_division ) recall = _prf_divide( tp_sum, true_sum, "recall", "true", average, warn_for, zero_division ) if np.isposinf(beta): f_score = recall elif beta == 0: f_score = precision else: # The score is defined as: # score = (1 + beta**2) * precision * recall / (beta**2 * precision + recall) # Therefore, we can express the score in terms of confusion matrix entries as: # score = (1 + beta**2) * tp / ((1 + beta**2) * tp + beta**2 * fn + fp) # Array api strict requires all arrays to be of the same type so we # need to convert true_sum, pred_sum and tp_sum to the max supported # float dtype because beta2 is a float max_float_type = _max_precision_float_dtype(xp=xp, device=device_) denom = beta2 * xp.astype(true_sum, max_float_type) + xp.astype( pred_sum, max_float_type ) f_score = _prf_divide( (1 + beta2) * xp.astype(tp_sum, max_float_type), denom, "f-score", "true nor predicted", average, warn_for, zero_division, ) # Average the results if average == "weighted": weights = true_sum elif average == "samples": weights = sample_weight else: weights = None if average is not None: precision = float(_nanaverage(precision, weights=weights)) recall = float(_nanaverage(recall, weights=weights)) f_score = float(_nanaverage(f_score, weights=weights)) true_sum = None # return no support return precision, recall, f_score, true_sum
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. 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 F-beta score can be interpreted as a weighted harmonic mean of the precision and recall, where an F-beta score reaches its best value at 1 and worst score at 0. The F-beta score weights recall more than precision by a factor of ``beta``. ``beta == 1.0`` means recall and precision are equally important. The support is the number of occurrences of each class in ``y_true``. Support beyond term:`binary` targets is achieved by treating :term:`multiclass` and :term:`multilabel` data as a collection of binary problems, one for each label. For the :term:`binary` case, setting `average='binary'` will return metrics for `pos_label`. If `average` is not `'binary'`, `pos_label` is ignored and metrics for both classes are computed, then averaged or both returned (when `average=None`). Similarly, for :term:`multiclass` and :term:`multilabel` targets, metrics for all `labels` are either returned or averaged depending on the `average` parameter. Use `labels` specify the set of labels to calculate metrics for. Read more in the :ref:`User Guide <precision_recall_f_measure_metrics>`. 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 array / sparse matrix Estimated targets as returned by a classifier. beta : float, default=1.0 The strength of recall versus precision in the F-score. labels : array-like, default=None The set of labels to include when `average != 'binary'`, and their order if `average is None`. Labels present in the data can be excluded, for example in multiclass classification to exclude a "negative class". Labels not present in the data can be included and will be "assigned" 0 samples. For multilabel targets, labels are column indices. By default, all labels in `y_true` and `y_pred` are used in sorted order. .. versionchanged:: 0.17 Parameter `labels` improved for multiclass problem. pos_label : int, float, bool or str, default=1 The class to report if `average='binary'` and the data is binary, otherwise this parameter is ignored. For multiclass or multilabel targets, set `labels=[pos_label]` and `average != 'binary'` to report metrics for one label only. average : {'micro', 'macro', 'samples', 'weighted', 'binary'} or None, default='binary' This parameter is required for multiclass/multilabel targets. If ``None``, the metrics for each class are returned. Otherwise, this determines the type of averaging performed on the data: ``'binary'``: Only report results for the class specified by ``pos_label``. This is applicable only if targets (``y_{true,pred}``) are binary. ``'micro'``: Calculate metrics globally by counting the total true positives, false negatives and false positives. ``'macro'``: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. ``'weighted'``: Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters 'macro' to account for label imbalance; it can result in an F-score that is not between precision and recall. ``'samples'``: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification where this differs from :func:`accuracy_score`). warn_for : list, tuple or set, for internal use This determines which warnings will be made in the case that this function is being used to return only one of its metrics. sample_weight : array-like of shape (n_samples,), default=None Sample weights. zero_division : {"warn", 0.0, 1.0, np.nan}, default="warn" Sets the value to return when there is a zero division: - recall: when there are no positive labels - precision: when there are no positive predictions - f-score: both Notes: - If set to "warn", this acts like 0, but a warning is also raised. - If set to `np.nan`, such values will be excluded from the average. .. versionadded:: 1.3 `np.nan` option was added. Returns ------- precision : float (if average is not None) or array of float, shape = [n_unique_labels] Precision score. recall : float (if average is not None) or array of float, shape = [n_unique_labels] Recall score. fbeta_score : float (if average is not None) or array of float, shape = [n_unique_labels] F-beta score. support : None (if average is not None) or array of int, shape = [n_unique_labels] The number of occurrences of each label in ``y_true``. Notes ----- When ``true positive + false positive == 0``, precision is undefined. When ``true positive + false negative == 0``, recall is undefined. When ``true positive + false negative + false positive == 0``, f-score is undefined. In such cases, by default the metric will be set to 0, and ``UndefinedMetricWarning`` will be raised. This behavior can be modified with ``zero_division``. References ---------- .. [1] `Wikipedia entry for the Precision and recall <https://en.wikipedia.org/wiki/Precision_and_recall>`_. .. [2] `Wikipedia entry for the F1-score <https://en.wikipedia.org/wiki/F1_score>`_. .. [3] `Discriminative Methods for Multi-labeled Classification Advances in Knowledge Discovery and Data Mining (2004), pp. 22-30 by Shantanu Godbole, Sunita Sarawagi <http://www.godbole.net/shantanu/pubs/multilabelsvm-pakdd04.pdf>`_. Examples -------- >>> import numpy as np >>> from sklearn.metrics import precision_recall_fscore_support >>> y_true = np.array(['cat', 'dog', 'pig', 'cat', 'dog', 'pig']) >>> y_pred = np.array(['cat', 'pig', 'dog', 'cat', 'cat', 'dog']) >>> precision_recall_fscore_support(y_true, y_pred, average='macro') (0.222, 0.333, 0.267, None) >>> precision_recall_fscore_support(y_true, y_pred, average='micro') (0.33, 0.33, 0.33, None) >>> precision_recall_fscore_support(y_true, y_pred, average='weighted') (0.222, 0.333, 0.267, None) It is possible to compute per-label precisions, recalls, F1-scores and supports instead of averaging: >>> precision_recall_fscore_support(y_true, y_pred, average=None, ... labels=['pig', 'dog', 'cat']) (array([0. , 0. , 0.66]), array([0., 0., 1.]), array([0. , 0. , 0.8]), array([2, 2, 2]))
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 - 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) / specificity`. Here `tp` is the number of true positives, `fp` the number of false positives, `tn` is the number of true negatives and `fn` the number of false negatives. Both class likelihood ratios can be used to obtain post-test probabilities given a pre-test probability. `LR+` ranges from 1.0 to infinity. A `LR+` of 1.0 indicates that the probability of predicting the positive class is the same for samples belonging to either class; therefore, the test is useless. The greater `LR+` is, the more a positive prediction is likely to be a true positive when compared with the pre-test probability. A value of `LR+` lower than 1.0 is invalid as it would indicate that the odds of a sample being a true positive decrease with respect to the pre-test odds. `LR-` ranges from 0.0 to 1.0. The closer it is to 0.0, the lower the probability of a given sample to be a false negative. A `LR-` of 1.0 means the test is useless because the odds of having the condition did not change after the test. A value of `LR-` greater than 1.0 invalidates the classifier as it indicates an increase in the odds of a sample belonging to the positive class after being classified as negative. This is the case when the classifier systematically predicts the opposite of the true label. A typical application in medicine is to identify the positive/negative class to the presence/absence of a disease, respectively; the classifier being a diagnostic test; the pre-test probability of an individual having the disease can be the prevalence of such disease (proportion of a particular population found to be affected by a medical condition); and the post-test probabilities would be the probability that the condition is truly present given a positive test result. Read more in the :ref:`User Guide <class_likelihood_ratios>`. 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 array / sparse matrix Estimated targets as returned by a classifier. labels : array-like, default=None List of labels to index the matrix. This may be used to select the positive and negative classes with the ordering `labels=[negative_class, positive_class]`. If `None` is given, those that appear at least once in `y_true` or `y_pred` are used in sorted order. sample_weight : array-like of shape (n_samples,), default=None Sample weights. raise_warning : bool, default=True Whether or not a case-specific warning message is raised when there is division by zero. .. deprecated:: 1.7 `raise_warning` was deprecated in version 1.7 and will be removed in 1.9, when an :class:`~sklearn.exceptions.UndefinedMetricWarning` will always raise in case of a division by zero. replace_undefined_by : np.nan, 1.0, or dict, default=np.nan Sets the return values for LR+ and LR- when there is a division by zero. Can take the following values: - `np.nan` to return `np.nan` for both `LR+` and `LR-` - `1.0` to return the worst possible scores: `{"LR+": 1.0, "LR-": 1.0}` - a dict in the format `{"LR+": value_1, "LR-": value_2}` where the values can be non-negative floats, `np.inf` or `np.nan` in the range of the likelihood ratios. For example, `{"LR+": 1.0, "LR-": 1.0}` can be used for returning the worst scores, indicating a useless model, and `{"LR+": np.inf, "LR-": 0.0}` can be used for returning the best scores, indicating a useful model. If a division by zero occurs, only the affected metric is replaced with the set value; the other metric is calculated as usual. .. versionadded:: 1.7 Returns ------- (positive_likelihood_ratio, negative_likelihood_ratio) : tuple A tuple of two floats, the first containing the positive likelihood ratio (LR+) and the second the negative likelihood ratio (LR-). Warns ----- Raises :class:`~sklearn.exceptions.UndefinedMetricWarning` when `y_true` and `y_pred` lead to the following conditions: - The number of false positives is 0 and `raise_warning` is set to `True` (default): positive likelihood ratio is undefined. - The number of true negatives is 0 and `raise_warning` is set to `True` (default): negative likelihood ratio is undefined. - The sum of true positives and false negatives is 0 (no samples of the positive class are present in `y_true`): both likelihood ratios are undefined. For the first two cases, an undefined metric can be defined by setting the `replace_undefined_by` param. References ---------- .. [1] `Wikipedia entry for the Likelihood ratios in diagnostic testing <https://en.wikipedia.org/wiki/Likelihood_ratios_in_diagnostic_testing>`_. Examples -------- >>> import numpy as np >>> from sklearn.metrics import class_likelihood_ratios >>> class_likelihood_ratios([0, 1, 0, 1, 0], [1, 1, 0, 0, 0]) (1.5, 0.75) >>> y_true = np.array(["non-cat", "cat", "non-cat", "cat", "non-cat"]) >>> y_pred = np.array(["cat", "cat", "non-cat", "non-cat", "non-cat"]) >>> class_likelihood_ratios(y_true, y_pred) (1.33, 0.66) >>> y_true = np.array(["non-zebra", "zebra", "non-zebra", "zebra", "non-zebra"]) >>> y_pred = np.array(["zebra", "zebra", "non-zebra", "non-zebra", "non-zebra"]) >>> class_likelihood_ratios(y_true, y_pred) (1.5, 0.75) To avoid ambiguities, use the notation `labels=[negative_class, positive_class]` >>> y_true = np.array(["non-cat", "cat", "non-cat", "cat", "non-cat"]) >>> y_pred = np.array(["cat", "cat", "non-cat", "non-cat", "non-cat"]) >>> class_likelihood_ratios(y_true, y_pred, labels=["non-cat", "cat"]) (1.5, 0.75) """ # TODO(1.9): When `raise_warning` is removed, the following changes need to be made: # The checks for `raise_warning==True` need to be removed and we will always warn, # remove `FutureWarning`, and the Warns section in the docstring should not mention # `raise_warning` anymore. y_true, y_pred = attach_unique(y_true, y_pred) y_type, y_true, y_pred = _check_targets(y_true, y_pred) if y_type != "binary": raise ValueError( "class_likelihood_ratios only supports binary classification " f"problems, got targets of type: {y_type}" ) msg_deprecated_param = ( "`raise_warning` was deprecated in version 1.7 and will be removed in 1.9. An " "`UndefinedMetricWarning` will always be raised in case of a division by zero " "and the value set with the `replace_undefined_by` param will be returned." ) if raise_warning != "deprecated": warnings.warn(msg_deprecated_param, FutureWarning) else: raise_warning = True if replace_undefined_by == 1.0: replace_undefined_by = {"LR+": 1.0, "LR-": 1.0} if isinstance(replace_undefined_by, dict): msg = ( "The dictionary passed as `replace_undefined_by` needs to be in the form " "`{'LR+': `value_1`, 'LR-': `value_2`}` where the value for `LR+` ranges " "from `1.0` to `np.inf` or is `np.nan` and the value for `LR-` ranges from " f"`0.0` to `1.0` or is `np.nan`; got `{replace_undefined_by}`." ) if ("LR+" in replace_undefined_by) and ("LR-" in replace_undefined_by): try: desired_lr_pos = replace_undefined_by.get("LR+", None) check_scalar( desired_lr_pos, "positive_likelihood_ratio", target_type=(Real), min_val=1.0, include_boundaries="left", ) desired_lr_neg = replace_undefined_by.get("LR-", None) check_scalar( desired_lr_neg, "negative_likelihood_ratio", target_type=(Real), min_val=0.0, max_val=1.0, include_boundaries="both", ) except Exception as e: raise ValueError(msg) from e else: raise ValueError(msg) cm = confusion_matrix( y_true, y_pred, sample_weight=sample_weight, labels=labels, ) tn, fp, fn, tp = cm.ravel() support_pos = tp + fn support_neg = tn + fp pos_num = tp * support_neg pos_denom = fp * support_pos neg_num = fn * support_neg neg_denom = tn * support_pos # if `support_pos == 0`a division by zero will occur if support_pos == 0: msg = ( "No samples of the positive class are present in `y_true`. " "`positive_likelihood_ratio` and `negative_likelihood_ratio` are both set " "to `np.nan`. Use the `replace_undefined_by` param to control this " "behavior. To suppress this warning or turn it into an error, see Python's " "`warnings` module and `warnings.catch_warnings()`." ) warnings.warn(msg, UndefinedMetricWarning, stacklevel=2) positive_likelihood_ratio = np.nan negative_likelihood_ratio = np.nan # if `fp == 0`a division by zero will occur if fp == 0: if raise_warning: if tp == 0: msg_beginning = ( "No samples were predicted for the positive class and " "`positive_likelihood_ratio` is " ) else: msg_beginning = "`positive_likelihood_ratio` is ill-defined and " msg_end = "set to `np.nan`. Use the `replace_undefined_by` param to " "control this behavior. To suppress this warning or turn it into an error, " "see Python's `warnings` module and `warnings.catch_warnings()`." warnings.warn(msg_beginning + msg_end, UndefinedMetricWarning, stacklevel=2) if isinstance(replace_undefined_by, float) and np.isnan(replace_undefined_by): positive_likelihood_ratio = replace_undefined_by else: # replace_undefined_by is a dict and # isinstance(replace_undefined_by.get("LR+", None), Real); this includes # `np.inf` and `np.nan` positive_likelihood_ratio = desired_lr_pos else: positive_likelihood_ratio = pos_num / pos_denom # if `tn == 0`a division by zero will occur if tn == 0: if raise_warning: msg = ( "`negative_likelihood_ratio` is ill-defined and set to `np.nan`. " "Use the `replace_undefined_by` param to control this behavior. To " "suppress this warning or turn it into an error, see Python's " "`warnings` module and `warnings.catch_warnings()`." ) warnings.warn(msg, UndefinedMetricWarning, stacklevel=2) if isinstance(replace_undefined_by, float) and np.isnan(replace_undefined_by): negative_likelihood_ratio = replace_undefined_by else: # replace_undefined_by is a dict and # isinstance(replace_undefined_by.get("LR-", None), Real); this includes # `np.nan` negative_likelihood_ratio = desired_lr_neg else: negative_likelihood_ratio = neg_num / neg_denom return float(positive_likelihood_ratio), float(negative_likelihood_ratio)
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) / specificity`. Here `tp` is the number of true positives, `fp` the number of false positives, `tn` is the number of true negatives and `fn` the number of false negatives. Both class likelihood ratios can be used to obtain post-test probabilities given a pre-test probability. `LR+` ranges from 1.0 to infinity. A `LR+` of 1.0 indicates that the probability of predicting the positive class is the same for samples belonging to either class; therefore, the test is useless. The greater `LR+` is, the more a positive prediction is likely to be a true positive when compared with the pre-test probability. A value of `LR+` lower than 1.0 is invalid as it would indicate that the odds of a sample being a true positive decrease with respect to the pre-test odds. `LR-` ranges from 0.0 to 1.0. The closer it is to 0.0, the lower the probability of a given sample to be a false negative. A `LR-` of 1.0 means the test is useless because the odds of having the condition did not change after the test. A value of `LR-` greater than 1.0 invalidates the classifier as it indicates an increase in the odds of a sample belonging to the positive class after being classified as negative. This is the case when the classifier systematically predicts the opposite of the true label. A typical application in medicine is to identify the positive/negative class to the presence/absence of a disease, respectively; the classifier being a diagnostic test; the pre-test probability of an individual having the disease can be the prevalence of such disease (proportion of a particular population found to be affected by a medical condition); and the post-test probabilities would be the probability that the condition is truly present given a positive test result. Read more in the :ref:`User Guide <class_likelihood_ratios>`. 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 array / sparse matrix Estimated targets as returned by a classifier. labels : array-like, default=None List of labels to index the matrix. This may be used to select the positive and negative classes with the ordering `labels=[negative_class, positive_class]`. If `None` is given, those that appear at least once in `y_true` or `y_pred` are used in sorted order. sample_weight : array-like of shape (n_samples,), default=None Sample weights. raise_warning : bool, default=True Whether or not a case-specific warning message is raised when there is division by zero. .. deprecated:: 1.7 `raise_warning` was deprecated in version 1.7 and will be removed in 1.9, when an :class:`~sklearn.exceptions.UndefinedMetricWarning` will always raise in case of a division by zero. replace_undefined_by : np.nan, 1.0, or dict, default=np.nan Sets the return values for LR+ and LR- when there is a division by zero. Can take the following values: - `np.nan` to return `np.nan` for both `LR+` and `LR-` - `1.0` to return the worst possible scores: `{"LR+": 1.0, "LR-": 1.0}` - a dict in the format `{"LR+": value_1, "LR-": value_2}` where the values can be non-negative floats, `np.inf` or `np.nan` in the range of the likelihood ratios. For example, `{"LR+": 1.0, "LR-": 1.0}` can be used for returning the worst scores, indicating a useless model, and `{"LR+": np.inf, "LR-": 0.0}` can be used for returning the best scores, indicating a useful model. If a division by zero occurs, only the affected metric is replaced with the set value; the other metric is calculated as usual. .. versionadded:: 1.7 Returns ------- (positive_likelihood_ratio, negative_likelihood_ratio) : tuple A tuple of two floats, the first containing the positive likelihood ratio (LR+) and the second the negative likelihood ratio (LR-). Warns ----- Raises :class:`~sklearn.exceptions.UndefinedMetricWarning` when `y_true` and `y_pred` lead to the following conditions: - The number of false positives is 0 and `raise_warning` is set to `True` (default): positive likelihood ratio is undefined. - The number of true negatives is 0 and `raise_warning` is set to `True` (default): negative likelihood ratio is undefined. - The sum of true positives and false negatives is 0 (no samples of the positive class are present in `y_true`): both likelihood ratios are undefined. For the first two cases, an undefined metric can be defined by setting the `replace_undefined_by` param. References ---------- .. [1] `Wikipedia entry for the Likelihood ratios in diagnostic testing <https://en.wikipedia.org/wiki/Likelihood_ratios_in_diagnostic_testing>`_. Examples -------- >>> import numpy as np >>> from sklearn.metrics import class_likelihood_ratios >>> class_likelihood_ratios([0, 1, 0, 1, 0], [1, 1, 0, 0, 0]) (1.5, 0.75) >>> y_true = np.array(["non-cat", "cat", "non-cat", "cat", "non-cat"]) >>> y_pred = np.array(["cat", "cat", "non-cat", "non-cat", "non-cat"]) >>> class_likelihood_ratios(y_true, y_pred) (1.33, 0.66) >>> y_true = np.array(["non-zebra", "zebra", "non-zebra", "zebra", "non-zebra"]) >>> y_pred = np.array(["zebra", "zebra", "non-zebra", "non-zebra", "non-zebra"]) >>> class_likelihood_ratios(y_true, y_pred) (1.5, 0.75) To avoid ambiguities, use the notation `labels=[negative_class, positive_class]` >>> y_true = np.array(["non-cat", "cat", "non-cat", "cat", "non-cat"]) >>> y_pred = np.array(["cat", "cat", "non-cat", "non-cat", "non-cat"]) >>> class_likelihood_ratios(y_true, y_pred, labels=["non-cat", "cat"]) (1.5, 0.75)
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 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 worst value is 0. Support beyond term:`binary` targets is achieved by treating :term:`multiclass` and :term:`multilabel` data as a collection of binary problems, one for each label. For the :term:`binary` case, setting `average='binary'` will return precision for `pos_label`. If `average` is not `'binary'`, `pos_label` is ignored and precision for both classes are computed, then averaged or both returned (when `average=None`). Similarly, for :term:`multiclass` and :term:`multilabel` targets, precision for all `labels` are either returned or averaged depending on the `average` parameter. Use `labels` specify the set of labels to calculate precision for. Read more in the :ref:`User Guide <precision_recall_f_measure_metrics>`. 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 array / sparse matrix Estimated targets as returned by a classifier. labels : array-like, default=None The set of labels to include when `average != 'binary'`, and their order if `average is None`. Labels present in the data can be excluded, for example in multiclass classification to exclude a "negative class". Labels not present in the data can be included and will be "assigned" 0 samples. For multilabel targets, labels are column indices. By default, all labels in `y_true` and `y_pred` are used in sorted order. .. versionchanged:: 0.17 Parameter `labels` improved for multiclass problem. pos_label : int, float, bool or str, default=1 The class to report if `average='binary'` and the data is binary, otherwise this parameter is ignored. For multiclass or multilabel targets, set `labels=[pos_label]` and `average != 'binary'` to report metrics for one label only. average : {'micro', 'macro', 'samples', 'weighted', 'binary'} or None, \ default='binary' This parameter is required for multiclass/multilabel targets. If ``None``, the metrics for each class are returned. Otherwise, this determines the type of averaging performed on the data: ``'binary'``: Only report results for the class specified by ``pos_label``. This is applicable only if targets (``y_{true,pred}``) are binary. ``'micro'``: Calculate metrics globally by counting the total true positives, false negatives and false positives. ``'macro'``: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. ``'weighted'``: Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters 'macro' to account for label imbalance; it can result in an F-score that is not between precision and recall. ``'samples'``: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification where this differs from :func:`accuracy_score`). sample_weight : array-like of shape (n_samples,), default=None Sample weights. zero_division : {"warn", 0.0, 1.0, np.nan}, default="warn" Sets the value to return when there is a zero division. Notes: - If set to "warn", this acts like 0, but a warning is also raised. - If set to `np.nan`, such values will be excluded from the average. .. versionadded:: 1.3 `np.nan` option was added. Returns ------- precision : float (if average is not None) or array of float of shape \ (n_unique_labels,) Precision of the positive class in binary classification or weighted average of the precision of each class for the multiclass task. See Also -------- precision_recall_fscore_support : Compute precision, recall, F-measure and support for each class. recall_score : Compute the ratio ``tp / (tp + fn)`` where ``tp`` is the number of true positives and ``fn`` the number of false negatives. PrecisionRecallDisplay.from_estimator : Plot precision-recall curve given an estimator and some data. PrecisionRecallDisplay.from_predictions : Plot precision-recall curve given binary class predictions. multilabel_confusion_matrix : Compute a confusion matrix for each class or sample. Notes ----- When ``true positive + false positive == 0``, precision returns 0 and raises ``UndefinedMetricWarning``. This behavior can be modified with ``zero_division``. Examples -------- >>> import numpy as np >>> from sklearn.metrics import precision_score >>> y_true = [0, 1, 2, 0, 1, 2] >>> y_pred = [0, 2, 1, 0, 0, 1] >>> precision_score(y_true, y_pred, average='macro') 0.22 >>> precision_score(y_true, y_pred, average='micro') 0.33 >>> precision_score(y_true, y_pred, average='weighted') 0.22 >>> precision_score(y_true, y_pred, average=None) array([0.66, 0. , 0. ]) >>> y_pred = [0, 0, 0, 0, 0, 0] >>> precision_score(y_true, y_pred, average=None) array([0.33, 0. , 0. ]) >>> precision_score(y_true, y_pred, average=None, zero_division=1) array([0.33, 1. , 1. ]) >>> precision_score(y_true, y_pred, average=None, zero_division=np.nan) array([0.33, nan, nan]) >>> # multilabel classification >>> y_true = [[0, 0, 0], [1, 1, 1], [0, 1, 1]] >>> y_pred = [[0, 0, 0], [1, 1, 1], [1, 1, 0]] >>> precision_score(y_true, y_pred, average=None) array([0.5, 1. , 1. ]) """ p, _, _, _ = precision_recall_fscore_support( y_true, y_pred, labels=labels, pos_label=pos_label, average=average, warn_for=("precision",), sample_weight=sample_weight, zero_division=zero_division, ) return p
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 worst value is 0. Support beyond term:`binary` targets is achieved by treating :term:`multiclass` and :term:`multilabel` data as a collection of binary problems, one for each label. For the :term:`binary` case, setting `average='binary'` will return precision for `pos_label`. If `average` is not `'binary'`, `pos_label` is ignored and precision for both classes are computed, then averaged or both returned (when `average=None`). Similarly, for :term:`multiclass` and :term:`multilabel` targets, precision for all `labels` are either returned or averaged depending on the `average` parameter. Use `labels` specify the set of labels to calculate precision for. Read more in the :ref:`User Guide <precision_recall_f_measure_metrics>`. 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 array / sparse matrix Estimated targets as returned by a classifier. labels : array-like, default=None The set of labels to include when `average != 'binary'`, and their order if `average is None`. Labels present in the data can be excluded, for example in multiclass classification to exclude a "negative class". Labels not present in the data can be included and will be "assigned" 0 samples. For multilabel targets, labels are column indices. By default, all labels in `y_true` and `y_pred` are used in sorted order. .. versionchanged:: 0.17 Parameter `labels` improved for multiclass problem. pos_label : int, float, bool or str, default=1 The class to report if `average='binary'` and the data is binary, otherwise this parameter is ignored. For multiclass or multilabel targets, set `labels=[pos_label]` and `average != 'binary'` to report metrics for one label only. average : {'micro', 'macro', 'samples', 'weighted', 'binary'} or None, default='binary' This parameter is required for multiclass/multilabel targets. If ``None``, the metrics for each class are returned. Otherwise, this determines the type of averaging performed on the data: ``'binary'``: Only report results for the class specified by ``pos_label``. This is applicable only if targets (``y_{true,pred}``) are binary. ``'micro'``: Calculate metrics globally by counting the total true positives, false negatives and false positives. ``'macro'``: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. ``'weighted'``: Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters 'macro' to account for label imbalance; it can result in an F-score that is not between precision and recall. ``'samples'``: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification where this differs from :func:`accuracy_score`). sample_weight : array-like of shape (n_samples,), default=None Sample weights. zero_division : {"warn", 0.0, 1.0, np.nan}, default="warn" Sets the value to return when there is a zero division. Notes: - If set to "warn", this acts like 0, but a warning is also raised. - If set to `np.nan`, such values will be excluded from the average. .. versionadded:: 1.3 `np.nan` option was added. Returns ------- precision : float (if average is not None) or array of float of shape (n_unique_labels,) Precision of the positive class in binary classification or weighted average of the precision of each class for the multiclass task. See Also -------- precision_recall_fscore_support : Compute precision, recall, F-measure and support for each class. recall_score : Compute the ratio ``tp / (tp + fn)`` where ``tp`` is the number of true positives and ``fn`` the number of false negatives. PrecisionRecallDisplay.from_estimator : Plot precision-recall curve given an estimator and some data. PrecisionRecallDisplay.from_predictions : Plot precision-recall curve given binary class predictions. multilabel_confusion_matrix : Compute a confusion matrix for each class or sample. Notes ----- When ``true positive + false positive == 0``, precision returns 0 and raises ``UndefinedMetricWarning``. This behavior can be modified with ``zero_division``. Examples -------- >>> import numpy as np >>> from sklearn.metrics import precision_score >>> y_true = [0, 1, 2, 0, 1, 2] >>> y_pred = [0, 2, 1, 0, 0, 1] >>> precision_score(y_true, y_pred, average='macro') 0.22 >>> precision_score(y_true, y_pred, average='micro') 0.33 >>> precision_score(y_true, y_pred, average='weighted') 0.22 >>> precision_score(y_true, y_pred, average=None) array([0.66, 0. , 0. ]) >>> y_pred = [0, 0, 0, 0, 0, 0] >>> precision_score(y_true, y_pred, average=None) array([0.33, 0. , 0. ]) >>> precision_score(y_true, y_pred, average=None, zero_division=1) array([0.33, 1. , 1. ]) >>> precision_score(y_true, y_pred, average=None, zero_division=np.nan) array([0.33, nan, nan]) >>> # multilabel classification >>> y_true = [[0, 0, 0], [1, 1, 1], [0, 1, 1]] >>> y_pred = [[0, 0, 0], [1, 1, 1], [1, 1, 0]] >>> precision_score(y_true, y_pred, average=None) array([0.5, 1. , 1. ])
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 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 beyond term:`binary` targets is achieved by treating :term:`multiclass` and :term:`multilabel` data as a collection of binary problems, one for each label. For the :term:`binary` case, setting `average='binary'` will return recall for `pos_label`. If `average` is not `'binary'`, `pos_label` is ignored and recall for both classes are computed then averaged or both returned (when `average=None`). Similarly, for :term:`multiclass` and :term:`multilabel` targets, recall for all `labels` are either returned or averaged depending on the `average` parameter. Use `labels` specify the set of labels to calculate recall for. Read more in the :ref:`User Guide <precision_recall_f_measure_metrics>`. 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 array / sparse matrix Estimated targets as returned by a classifier. labels : array-like, default=None The set of labels to include when `average != 'binary'`, and their order if `average is None`. Labels present in the data can be excluded, for example in multiclass classification to exclude a "negative class". Labels not present in the data can be included and will be "assigned" 0 samples. For multilabel targets, labels are column indices. By default, all labels in `y_true` and `y_pred` are used in sorted order. .. versionchanged:: 0.17 Parameter `labels` improved for multiclass problem. pos_label : int, float, bool or str, default=1 The class to report if `average='binary'` and the data is binary, otherwise this parameter is ignored. For multiclass or multilabel targets, set `labels=[pos_label]` and `average != 'binary'` to report metrics for one label only. average : {'micro', 'macro', 'samples', 'weighted', 'binary'} or None, \ default='binary' This parameter is required for multiclass/multilabel targets. If ``None``, the metrics for each class are returned. Otherwise, this determines the type of averaging performed on the data: ``'binary'``: Only report results for the class specified by ``pos_label``. This is applicable only if targets (``y_{true,pred}``) are binary. ``'micro'``: Calculate metrics globally by counting the total true positives, false negatives and false positives. ``'macro'``: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. ``'weighted'``: Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters 'macro' to account for label imbalance; it can result in an F-score that is not between precision and recall. Weighted recall is equal to accuracy. ``'samples'``: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification where this differs from :func:`accuracy_score`). sample_weight : array-like of shape (n_samples,), default=None Sample weights. zero_division : {"warn", 0.0, 1.0, np.nan}, default="warn" Sets the value to return when there is a zero division. Notes: - If set to "warn", this acts like 0, but a warning is also raised. - If set to `np.nan`, such values will be excluded from the average. .. versionadded:: 1.3 `np.nan` option was added. Returns ------- recall : float (if average is not None) or array of float of shape \ (n_unique_labels,) Recall of the positive class in binary classification or weighted average of the recall of each class for the multiclass task. See Also -------- precision_recall_fscore_support : Compute precision, recall, F-measure and support for each class. precision_score : Compute the ratio ``tp / (tp + fp)`` where ``tp`` is the number of true positives and ``fp`` the number of false positives. balanced_accuracy_score : Compute balanced accuracy to deal with imbalanced datasets. multilabel_confusion_matrix : Compute a confusion matrix for each class or sample. PrecisionRecallDisplay.from_estimator : Plot precision-recall curve given an estimator and some data. PrecisionRecallDisplay.from_predictions : Plot precision-recall curve given binary class predictions. Notes ----- When ``true positive + false negative == 0``, recall returns 0 and raises ``UndefinedMetricWarning``. This behavior can be modified with ``zero_division``. Examples -------- >>> import numpy as np >>> from sklearn.metrics import recall_score >>> y_true = [0, 1, 2, 0, 1, 2] >>> y_pred = [0, 2, 1, 0, 0, 1] >>> recall_score(y_true, y_pred, average='macro') 0.33 >>> recall_score(y_true, y_pred, average='micro') 0.33 >>> recall_score(y_true, y_pred, average='weighted') 0.33 >>> recall_score(y_true, y_pred, average=None) array([1., 0., 0.]) >>> y_true = [0, 0, 0, 0, 0, 0] >>> recall_score(y_true, y_pred, average=None) array([0.5, 0. , 0. ]) >>> recall_score(y_true, y_pred, average=None, zero_division=1) array([0.5, 1. , 1. ]) >>> recall_score(y_true, y_pred, average=None, zero_division=np.nan) array([0.5, nan, nan]) >>> # multilabel classification >>> y_true = [[0, 0, 0], [1, 1, 1], [0, 1, 1]] >>> y_pred = [[0, 0, 0], [1, 1, 1], [1, 1, 0]] >>> recall_score(y_true, y_pred, average=None) array([1. , 1. , 0.5]) """ _, r, _, _ = precision_recall_fscore_support( y_true, y_pred, labels=labels, pos_label=pos_label, average=average, warn_for=("recall",), sample_weight=sample_weight, zero_division=zero_division, ) return r
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 beyond term:`binary` targets is achieved by treating :term:`multiclass` and :term:`multilabel` data as a collection of binary problems, one for each label. For the :term:`binary` case, setting `average='binary'` will return recall for `pos_label`. If `average` is not `'binary'`, `pos_label` is ignored and recall for both classes are computed then averaged or both returned (when `average=None`). Similarly, for :term:`multiclass` and :term:`multilabel` targets, recall for all `labels` are either returned or averaged depending on the `average` parameter. Use `labels` specify the set of labels to calculate recall for. Read more in the :ref:`User Guide <precision_recall_f_measure_metrics>`. 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 array / sparse matrix Estimated targets as returned by a classifier. labels : array-like, default=None The set of labels to include when `average != 'binary'`, and their order if `average is None`. Labels present in the data can be excluded, for example in multiclass classification to exclude a "negative class". Labels not present in the data can be included and will be "assigned" 0 samples. For multilabel targets, labels are column indices. By default, all labels in `y_true` and `y_pred` are used in sorted order. .. versionchanged:: 0.17 Parameter `labels` improved for multiclass problem. pos_label : int, float, bool or str, default=1 The class to report if `average='binary'` and the data is binary, otherwise this parameter is ignored. For multiclass or multilabel targets, set `labels=[pos_label]` and `average != 'binary'` to report metrics for one label only. average : {'micro', 'macro', 'samples', 'weighted', 'binary'} or None, default='binary' This parameter is required for multiclass/multilabel targets. If ``None``, the metrics for each class are returned. Otherwise, this determines the type of averaging performed on the data: ``'binary'``: Only report results for the class specified by ``pos_label``. This is applicable only if targets (``y_{true,pred}``) are binary. ``'micro'``: Calculate metrics globally by counting the total true positives, false negatives and false positives. ``'macro'``: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. ``'weighted'``: Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters 'macro' to account for label imbalance; it can result in an F-score that is not between precision and recall. Weighted recall is equal to accuracy. ``'samples'``: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification where this differs from :func:`accuracy_score`). sample_weight : array-like of shape (n_samples,), default=None Sample weights. zero_division : {"warn", 0.0, 1.0, np.nan}, default="warn" Sets the value to return when there is a zero division. Notes: - If set to "warn", this acts like 0, but a warning is also raised. - If set to `np.nan`, such values will be excluded from the average. .. versionadded:: 1.3 `np.nan` option was added. Returns ------- recall : float (if average is not None) or array of float of shape (n_unique_labels,) Recall of the positive class in binary classification or weighted average of the recall of each class for the multiclass task. See Also -------- precision_recall_fscore_support : Compute precision, recall, F-measure and support for each class. precision_score : Compute the ratio ``tp / (tp + fp)`` where ``tp`` is the number of true positives and ``fp`` the number of false positives. balanced_accuracy_score : Compute balanced accuracy to deal with imbalanced datasets. multilabel_confusion_matrix : Compute a confusion matrix for each class or sample. PrecisionRecallDisplay.from_estimator : Plot precision-recall curve given an estimator and some data. PrecisionRecallDisplay.from_predictions : Plot precision-recall curve given binary class predictions. Notes ----- When ``true positive + false negative == 0``, recall returns 0 and raises ``UndefinedMetricWarning``. This behavior can be modified with ``zero_division``. Examples -------- >>> import numpy as np >>> from sklearn.metrics import recall_score >>> y_true = [0, 1, 2, 0, 1, 2] >>> y_pred = [0, 2, 1, 0, 0, 1] >>> recall_score(y_true, y_pred, average='macro') 0.33 >>> recall_score(y_true, y_pred, average='micro') 0.33 >>> recall_score(y_true, y_pred, average='weighted') 0.33 >>> recall_score(y_true, y_pred, average=None) array([1., 0., 0.]) >>> y_true = [0, 0, 0, 0, 0, 0] >>> recall_score(y_true, y_pred, average=None) array([0.5, 0. , 0. ]) >>> recall_score(y_true, y_pred, average=None, zero_division=1) array([0.5, 1. , 1. ]) >>> recall_score(y_true, y_pred, average=None, zero_division=np.nan) array([0.5, nan, nan]) >>> # multilabel classification >>> y_true = [[0, 0, 0], [1, 1, 1], [0, 1, 1]] >>> y_pred = [[0, 0, 0], [1, 1, 1], [1, 1, 0]] >>> recall_score(y_true, y_pred, average=None) array([1. , 1. , 0.5])
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>`. 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 array / sparse matrix Estimated targets as returned by a classifier. labels : array-like of shape (n_labels,), default=None Optional list of label indices to include in the report. target_names : array-like of shape (n_labels,), default=None Optional display names matching the labels (same order). sample_weight : array-like of shape (n_samples,), default=None Sample weights. digits : int, default=2 Number of digits for formatting output floating point values. When ``output_dict`` is ``True``, this will be ignored and the returned values will not be rounded. output_dict : bool, default=False If True, return output as dict. .. versionadded:: 0.20 zero_division : {"warn", 0.0, 1.0, np.nan}, default="warn" Sets the value to return when there is a zero division. If set to "warn", this acts as 0, but warnings are also raised. .. versionadded:: 1.3 `np.nan` option was added. Returns ------- report : str or dict Text summary of the precision, recall, F1 score for each class. Dictionary returned if output_dict is True. Dictionary has the following structure:: {'label 1': {'precision':0.5, 'recall':1.0, 'f1-score':0.67, 'support':1}, 'label 2': { ... }, ... } The reported averages include macro average (averaging the unweighted mean per label), weighted average (averaging the support-weighted mean per label), and sample average (only for multilabel classification). Micro average (averaging the total true positives, false negatives and false positives) is only shown for multi-label or multi-class with a subset of classes, because it corresponds to accuracy otherwise and would be the same for all metrics. See also :func:`precision_recall_fscore_support` for more details on averages. Note that in binary classification, recall of the positive class is also known as "sensitivity"; recall of the negative class is "specificity". See Also -------- precision_recall_fscore_support: Compute precision, recall, F-measure and support for each class. confusion_matrix: Compute confusion matrix to evaluate the accuracy of a classification. multilabel_confusion_matrix: Compute a confusion matrix for each class or sample. Examples -------- >>> from sklearn.metrics import classification_report >>> y_true = [0, 1, 2, 2, 2] >>> y_pred = [0, 0, 2, 2, 1] >>> target_names = ['class 0', 'class 1', 'class 2'] >>> print(classification_report(y_true, y_pred, target_names=target_names)) precision recall f1-score support <BLANKLINE> class 0 0.50 1.00 0.67 1 class 1 0.00 0.00 0.00 1 class 2 1.00 0.67 0.80 3 <BLANKLINE> accuracy 0.60 5 macro avg 0.50 0.56 0.49 5 weighted avg 0.70 0.60 0.61 5 <BLANKLINE> >>> y_pred = [1, 1, 0] >>> y_true = [1, 1, 1] >>> print(classification_report(y_true, y_pred, labels=[1, 2, 3])) precision recall f1-score support <BLANKLINE> 1 1.00 0.67 0.80 3 2 0.00 0.00 0.00 0 3 0.00 0.00 0.00 0 <BLANKLINE> micro avg 1.00 0.67 0.80 3 macro avg 0.33 0.22 0.27 3 weighted avg 1.00 0.67 0.80 3 <BLANKLINE> """ y_true, y_pred = attach_unique(y_true, y_pred) y_type, y_true, y_pred = _check_targets(y_true, y_pred) if labels is None: labels = unique_labels(y_true, y_pred) labels_given = False else: labels = np.asarray(labels) labels_given = True # labelled micro average micro_is_accuracy = (y_type == "multiclass" or y_type == "binary") and ( not labels_given or (set(labels) >= set(unique_labels(y_true, y_pred))) ) if target_names is not None and len(labels) != len(target_names): if labels_given: warnings.warn( "labels size, {0}, does not match size of target_names, {1}".format( len(labels), len(target_names) ) ) else: raise ValueError( "Number of classes, {0}, does not match size of " "target_names, {1}. Try specifying the labels " "parameter".format(len(labels), len(target_names)) ) if target_names is None: target_names = ["%s" % l for l in labels] headers = ["precision", "recall", "f1-score", "support"] # compute per-class results without averaging p, r, f1, s = precision_recall_fscore_support( y_true, y_pred, labels=labels, average=None, sample_weight=sample_weight, zero_division=zero_division, ) rows = zip(target_names, p, r, f1, s) if y_type.startswith("multilabel"): average_options = ("micro", "macro", "weighted", "samples") else: average_options = ("micro", "macro", "weighted") if output_dict: report_dict = {label[0]: label[1:] for label in rows} for label, scores in report_dict.items(): report_dict[label] = dict(zip(headers, [float(i) for i in scores])) else: longest_last_line_heading = "weighted avg" name_width = max(len(cn) for cn in target_names) width = max(name_width, len(longest_last_line_heading), digits) head_fmt = "{:>{width}s} " + " {:>9}" * len(headers) report = head_fmt.format("", *headers, width=width) report += "\n\n" row_fmt = "{:>{width}s} " + " {:>9.{digits}f}" * 3 + " {:>9}\n" for row in rows: report += row_fmt.format(*row, width=width, digits=digits) report += "\n" # compute all applicable averages for average in average_options: if average.startswith("micro") and micro_is_accuracy: line_heading = "accuracy" else: line_heading = average + " avg" # compute averages with specified averaging method avg_p, avg_r, avg_f1, _ = precision_recall_fscore_support( y_true, y_pred, labels=labels, average=average, sample_weight=sample_weight, zero_division=zero_division, ) avg = [avg_p, avg_r, avg_f1, np.sum(s)] if output_dict: report_dict[line_heading] = dict(zip(headers, [float(i) for i in avg])) else: if line_heading == "accuracy": row_fmt_accuracy = ( "{:>{width}s} " + " {:>9.{digits}}" * 2 + " {:>9.{digits}f}" + " {:>9}\n" ) report += row_fmt_accuracy.format( line_heading, "", "", *avg[2:], width=width, digits=digits ) else: report += row_fmt.format(line_heading, *avg, width=width, digits=digits) if output_dict: if "accuracy" in report_dict.keys(): report_dict["accuracy"] = report_dict["accuracy"]["precision"] return report_dict else: return 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 array / sparse matrix Estimated targets as returned by a classifier. labels : array-like of shape (n_labels,), default=None Optional list of label indices to include in the report. target_names : array-like of shape (n_labels,), default=None Optional display names matching the labels (same order). sample_weight : array-like of shape (n_samples,), default=None Sample weights. digits : int, default=2 Number of digits for formatting output floating point values. When ``output_dict`` is ``True``, this will be ignored and the returned values will not be rounded. output_dict : bool, default=False If True, return output as dict. .. versionadded:: 0.20 zero_division : {"warn", 0.0, 1.0, np.nan}, default="warn" Sets the value to return when there is a zero division. If set to "warn", this acts as 0, but warnings are also raised. .. versionadded:: 1.3 `np.nan` option was added. Returns ------- report : str or dict Text summary of the precision, recall, F1 score for each class. Dictionary returned if output_dict is True. Dictionary has the following structure:: {'label 1': {'precision':0.5, 'recall':1.0, 'f1-score':0.67, 'support':1}, 'label 2': { ... }, ... } The reported averages include macro average (averaging the unweighted mean per label), weighted average (averaging the support-weighted mean per label), and sample average (only for multilabel classification). Micro average (averaging the total true positives, false negatives and false positives) is only shown for multi-label or multi-class with a subset of classes, because it corresponds to accuracy otherwise and would be the same for all metrics. See also :func:`precision_recall_fscore_support` for more details on averages. Note that in binary classification, recall of the positive class is also known as "sensitivity"; recall of the negative class is "specificity". See Also -------- precision_recall_fscore_support: Compute precision, recall, F-measure and support for each class. confusion_matrix: Compute confusion matrix to evaluate the accuracy of a classification. multilabel_confusion_matrix: Compute a confusion matrix for each class or sample. Examples -------- >>> from sklearn.metrics import classification_report >>> y_true = [0, 1, 2, 2, 2] >>> y_pred = [0, 0, 2, 2, 1] >>> target_names = ['class 0', 'class 1', 'class 2'] >>> print(classification_report(y_true, y_pred, target_names=target_names)) precision recall f1-score support <BLANKLINE> class 0 0.50 1.00 0.67 1 class 1 0.00 0.00 0.00 1 class 2 1.00 0.67 0.80 3 <BLANKLINE> accuracy 0.60 5 macro avg 0.50 0.56 0.49 5 weighted avg 0.70 0.60 0.61 5 <BLANKLINE> >>> y_pred = [1, 1, 0] >>> y_true = [1, 1, 1] >>> print(classification_report(y_true, y_pred, labels=[1, 2, 3])) precision recall f1-score support <BLANKLINE> 1 1.00 0.67 0.80 3 2 0.00 0.00 0.00 0 3 0.00 0.00 0.00 0 <BLANKLINE> micro avg 1.00 0.67 0.80 3 macro avg 0.33 0.22 0.27 3 weighted avg 1.00 0.67 0.80 3 <BLANKLINE>
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 / sparse matrix Ground truth (correct) labels. y_pred : 1d array-like, or label indicator array / sparse matrix Predicted labels, as returned by a classifier. sample_weight : array-like of shape (n_samples,), default=None Sample weights. .. versionadded:: 0.18 Returns ------- loss : float or int Return the average Hamming loss between element of ``y_true`` and ``y_pred``. See Also -------- accuracy_score : Compute the accuracy score. By default, the function will return the fraction of correct predictions divided by the total number of predictions. jaccard_score : Compute the Jaccard similarity coefficient score. zero_one_loss : Compute the Zero-one classification loss. By default, the function will return the percentage of imperfectly predicted subsets. Notes ----- In multiclass classification, the Hamming loss corresponds to the Hamming distance between ``y_true`` and ``y_pred`` which is equivalent to the subset ``zero_one_loss`` function, when `normalize` parameter is set to True. In multilabel classification, the Hamming loss is different from the subset zero-one loss. The zero-one loss considers the entire set of labels for a given sample incorrect if it does not entirely match the true set of labels. Hamming loss is more forgiving in that it penalizes only the individual labels. The Hamming loss is upperbounded by the subset zero-one loss, when `normalize` parameter is set to True. It is always between 0 and 1, lower being better. References ---------- .. [1] Grigorios Tsoumakas, Ioannis Katakis. Multi-Label Classification: An Overview. International Journal of Data Warehousing & Mining, 3(3), 1-13, July-September 2007. .. [2] `Wikipedia entry on the Hamming distance <https://en.wikipedia.org/wiki/Hamming_distance>`_. Examples -------- >>> from sklearn.metrics import hamming_loss >>> y_pred = [1, 2, 3, 4] >>> y_true = [2, 2, 3, 4] >>> hamming_loss(y_true, y_pred) 0.25 In the multilabel case with binary label indicators: >>> import numpy as np >>> hamming_loss(np.array([[0, 1], [1, 1]]), np.zeros((2, 2))) 0.75 """ y_true, y_pred = attach_unique(y_true, y_pred) y_type, y_true, y_pred = _check_targets(y_true, y_pred) check_consistent_length(y_true, y_pred, sample_weight) xp, _, device = get_namespace_and_device(y_true, y_pred, sample_weight) if sample_weight is None: weight_average = 1.0 else: sample_weight = xp.asarray(sample_weight, device=device) weight_average = _average(sample_weight, xp=xp) if y_type.startswith("multilabel"): n_differences = _count_nonzero( y_true - y_pred, xp=xp, device=device, sample_weight=sample_weight ) return float(n_differences) / ( y_true.shape[0] * y_true.shape[1] * weight_average ) elif y_type in ["binary", "multiclass"]: return float(_average(y_true != y_pred, weights=sample_weight, normalize=True)) else: raise ValueError("{0} is not supported".format(y_type))
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 : 1d array-like, or label indicator array / sparse matrix Predicted labels, as returned by a classifier. sample_weight : array-like of shape (n_samples,), default=None Sample weights. .. versionadded:: 0.18 Returns ------- loss : float or int Return the average Hamming loss between element of ``y_true`` and ``y_pred``. See Also -------- accuracy_score : Compute the accuracy score. By default, the function will return the fraction of correct predictions divided by the total number of predictions. jaccard_score : Compute the Jaccard similarity coefficient score. zero_one_loss : Compute the Zero-one classification loss. By default, the function will return the percentage of imperfectly predicted subsets. Notes ----- In multiclass classification, the Hamming loss corresponds to the Hamming distance between ``y_true`` and ``y_pred`` which is equivalent to the subset ``zero_one_loss`` function, when `normalize` parameter is set to True. In multilabel classification, the Hamming loss is different from the subset zero-one loss. The zero-one loss considers the entire set of labels for a given sample incorrect if it does not entirely match the true set of labels. Hamming loss is more forgiving in that it penalizes only the individual labels. The Hamming loss is upperbounded by the subset zero-one loss, when `normalize` parameter is set to True. It is always between 0 and 1, lower being better. References ---------- .. [1] Grigorios Tsoumakas, Ioannis Katakis. Multi-Label Classification: An Overview. International Journal of Data Warehousing & Mining, 3(3), 1-13, July-September 2007. .. [2] `Wikipedia entry on the Hamming distance <https://en.wikipedia.org/wiki/Hamming_distance>`_. Examples -------- >>> from sklearn.metrics import hamming_loss >>> y_pred = [1, 2, 3, 4] >>> y_true = [2, 2, 3, 4] >>> hamming_loss(y_true, y_pred) 0.25 In the multilabel case with binary label indicators: >>> import numpy as np >>> hamming_loss(np.array([[0, 1], [1, 1]]), np.zeros((2, 2))) 0.75
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 model that returns ``y_pred`` probabilities for its training data ``y_true``. The log loss is only defined for two or more labels. For a single sample with true label :math:`y \in \{0,1\}` and a probability estimate :math:`p = \operatorname{Pr}(y = 1)`, the log loss is: .. math:: L_{\log}(y, p) = -(y \log (p) + (1 - y) \log (1 - p)) Read more in the :ref:`User Guide <log_loss>`. Parameters ---------- y_true : array-like or label indicator matrix Ground truth (correct) labels for n_samples samples. y_pred : array-like of float, shape = (n_samples, n_classes) or (n_samples,) Predicted probabilities, as returned by a classifier's predict_proba method. If ``y_pred.shape = (n_samples,)`` the probabilities provided are assumed to be that of the positive class. The labels in ``y_pred`` are assumed to be ordered alphabetically, as done by :class:`~sklearn.preprocessing.LabelBinarizer`. `y_pred` values are clipped to `[eps, 1-eps]` where `eps` is the machine precision for `y_pred`'s dtype. normalize : bool, default=True If true, return the mean loss per sample. Otherwise, return the sum of the per-sample losses. sample_weight : array-like of shape (n_samples,), default=None Sample weights. labels : array-like, default=None If not provided, labels will be inferred from y_true. If ``labels`` is ``None`` and ``y_pred`` has shape (n_samples,) the labels are assumed to be binary and are inferred from ``y_true``. .. versionadded:: 0.18 Returns ------- loss : float Log loss, aka logistic loss or cross-entropy loss. Notes ----- The logarithm used is the natural logarithm (base-e). References ---------- C.M. Bishop (2006). Pattern Recognition and Machine Learning. Springer, p. 209. Examples -------- >>> from sklearn.metrics import log_loss >>> log_loss(["spam", "ham", "ham", "spam"], ... [[.1, .9], [.9, .1], [.8, .2], [.35, .65]]) 0.21616 """ transformed_labels, y_pred = _validate_multiclass_probabilistic_prediction( y_true, y_pred, sample_weight, labels ) # Clipping eps = np.finfo(y_pred.dtype).eps y_pred = np.clip(y_pred, eps, 1 - eps) loss = -xlogy(transformed_labels, y_pred).sum(axis=1) return float(_average(loss, weights=sample_weight, normalize=normalize))
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 is only defined for two or more labels. For a single sample with true label :math:`y \in \{0,1\}` and a probability estimate :math:`p = \operatorname{Pr}(y = 1)`, the log loss is: .. math:: L_{\log}(y, p) = -(y \log (p) + (1 - y) \log (1 - p)) Read more in the :ref:`User Guide <log_loss>`. Parameters ---------- y_true : array-like or label indicator matrix Ground truth (correct) labels for n_samples samples. y_pred : array-like of float, shape = (n_samples, n_classes) or (n_samples,) Predicted probabilities, as returned by a classifier's predict_proba method. If ``y_pred.shape = (n_samples,)`` the probabilities provided are assumed to be that of the positive class. The labels in ``y_pred`` are assumed to be ordered alphabetically, as done by :class:`~sklearn.preprocessing.LabelBinarizer`. `y_pred` values are clipped to `[eps, 1-eps]` where `eps` is the machine precision for `y_pred`'s dtype. normalize : bool, default=True If true, return the mean loss per sample. Otherwise, return the sum of the per-sample losses. sample_weight : array-like of shape (n_samples,), default=None Sample weights. labels : array-like, default=None If not provided, labels will be inferred from y_true. If ``labels`` is ``None`` and ``y_pred`` has shape (n_samples,) the labels are assumed to be binary and are inferred from ``y_true``. .. versionadded:: 0.18 Returns ------- loss : float Log loss, aka logistic loss or cross-entropy loss. Notes ----- The logarithm used is the natural logarithm (base-e). References ---------- C.M. Bishop (2006). Pattern Recognition and Machine Learning. Springer, p. 209. Examples -------- >>> from sklearn.metrics import log_loss >>> log_loss(["spam", "ham", "ham", "spam"], ... [[.1, .9], [.9, .1], [.8, .2], [.35, .65]]) 0.21616
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 disagree), implying ``1 - margin`` is always greater than 1. The cumulated hinge loss is therefore an upper bound of the number of mistakes made by the classifier. In multiclass case, the function expects that either all the labels are included in y_true or an optional labels argument is provided which contains all the labels. The multilabel margin is calculated according to Crammer-Singer's method. As in the binary case, the cumulated hinge loss is an upper bound of the number of mistakes made by the classifier. Read more in the :ref:`User Guide <hinge_loss>`. Parameters ---------- y_true : array-like of shape (n_samples,) True target, consisting of integers of two values. The positive label must be greater than the negative label. pred_decision : array-like of shape (n_samples,) or (n_samples, n_classes) Predicted decisions, as output by decision_function (floats). labels : array-like, default=None Contains all the labels for the problem. Used in multiclass hinge loss. sample_weight : array-like of shape (n_samples,), default=None Sample weights. Returns ------- loss : float Average hinge loss. References ---------- .. [1] `Wikipedia entry on the Hinge loss <https://en.wikipedia.org/wiki/Hinge_loss>`_. .. [2] Koby Crammer, Yoram Singer. On the Algorithmic Implementation of Multiclass Kernel-based Vector Machines. Journal of Machine Learning Research 2, (2001), 265-292. .. [3] `L1 AND L2 Regularization for Multiclass Hinge Loss Models by Robert C. Moore, John DeNero <https://storage.googleapis.com/pub-tools-public-publication-data/pdf/37362.pdf>`_. Examples -------- >>> from sklearn import svm >>> from sklearn.metrics import hinge_loss >>> X = [[0], [1]] >>> y = [-1, 1] >>> est = svm.LinearSVC(random_state=0) >>> est.fit(X, y) LinearSVC(random_state=0) >>> pred_decision = est.decision_function([[-2], [3], [0.5]]) >>> pred_decision array([-2.18, 2.36, 0.09]) >>> hinge_loss([-1, 1, 1], pred_decision) 0.30 In the multiclass case: >>> import numpy as np >>> X = np.array([[0], [1], [2], [3]]) >>> Y = np.array([0, 1, 2, 3]) >>> labels = np.array([0, 1, 2, 3]) >>> est = svm.LinearSVC() >>> est.fit(X, Y) LinearSVC() >>> pred_decision = est.decision_function([[-1], [2], [3]]) >>> y_true = [0, 2, 3] >>> hinge_loss(y_true, pred_decision, labels=labels) 0.56 """ check_consistent_length(y_true, pred_decision, sample_weight) pred_decision = check_array(pred_decision, ensure_2d=False) y_true = column_or_1d(y_true) y_true_unique = np.unique(labels if labels is not None else y_true) if y_true_unique.size > 2: if pred_decision.ndim <= 1: raise ValueError( "The shape of pred_decision cannot be 1d array" "with a multiclass target. pred_decision shape " "must be (n_samples, n_classes), that is " f"({y_true.shape[0]}, {y_true_unique.size})." f" Got: {pred_decision.shape}" ) # pred_decision.ndim > 1 is true if y_true_unique.size != pred_decision.shape[1]: if labels is None: raise ValueError( "Please include all labels in y_true " "or pass labels as third argument" ) else: raise ValueError( "The shape of pred_decision is not " "consistent with the number of classes. " "With a multiclass target, pred_decision " "shape must be " "(n_samples, n_classes), that is " f"({y_true.shape[0]}, {y_true_unique.size}). " f"Got: {pred_decision.shape}" ) if labels is None: labels = y_true_unique le = LabelEncoder() le.fit(labels) y_true = le.transform(y_true) mask = np.ones_like(pred_decision, dtype=bool) mask[np.arange(y_true.shape[0]), y_true] = False margin = pred_decision[~mask] margin -= np.max(pred_decision[mask].reshape(y_true.shape[0], -1), axis=1) else: # Handles binary class case # this code assumes that positive and negative labels # are encoded as +1 and -1 respectively pred_decision = column_or_1d(pred_decision) pred_decision = np.ravel(pred_decision) lbin = LabelBinarizer(neg_label=-1) y_true = lbin.fit_transform(y_true)[:, 0] try: margin = y_true * pred_decision except TypeError: raise TypeError("pred_decision should be an array of floats.") losses = 1 - margin # The hinge_loss doesn't penalize good enough predictions. np.clip(losses, 0, None, out=losses) return float(np.average(losses, weights=sample_weight))
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 loss is therefore an upper bound of the number of mistakes made by the classifier. In multiclass case, the function expects that either all the labels are included in y_true or an optional labels argument is provided which contains all the labels. The multilabel margin is calculated according to Crammer-Singer's method. As in the binary case, the cumulated hinge loss is an upper bound of the number of mistakes made by the classifier. Read more in the :ref:`User Guide <hinge_loss>`. Parameters ---------- y_true : array-like of shape (n_samples,) True target, consisting of integers of two values. The positive label must be greater than the negative label. pred_decision : array-like of shape (n_samples,) or (n_samples, n_classes) Predicted decisions, as output by decision_function (floats). labels : array-like, default=None Contains all the labels for the problem. Used in multiclass hinge loss. sample_weight : array-like of shape (n_samples,), default=None Sample weights. Returns ------- loss : float Average hinge loss. References ---------- .. [1] `Wikipedia entry on the Hinge loss <https://en.wikipedia.org/wiki/Hinge_loss>`_. .. [2] Koby Crammer, Yoram Singer. On the Algorithmic Implementation of Multiclass Kernel-based Vector Machines. Journal of Machine Learning Research 2, (2001), 265-292. .. [3] `L1 AND L2 Regularization for Multiclass Hinge Loss Models by Robert C. Moore, John DeNero <https://storage.googleapis.com/pub-tools-public-publication-data/pdf/37362.pdf>`_. Examples -------- >>> from sklearn import svm >>> from sklearn.metrics import hinge_loss >>> X = [[0], [1]] >>> y = [-1, 1] >>> est = svm.LinearSVC(random_state=0) >>> est.fit(X, y) LinearSVC(random_state=0) >>> pred_decision = est.decision_function([[-2], [3], [0.5]]) >>> pred_decision array([-2.18, 2.36, 0.09]) >>> hinge_loss([-1, 1, 1], pred_decision) 0.30 In the multiclass case: >>> import numpy as np >>> X = np.array([[0], [1], [2], [3]]) >>> Y = np.array([0, 1, 2, 3]) >>> labels = np.array([0, 1, 2, 3]) >>> est = svm.LinearSVC() >>> est.fit(X, Y) LinearSVC() >>> pred_decision = est.decision_function([[-1], [2], [3]]) >>> y_true = [0, 2, 3] >>> hinge_loss(y_true, pred_decision, labels=labels) 0.56
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,) Probabilities of the positive class. sample_weight : array-like of shape (n_samples,), default=None Sample weights. pos_label : int, float, bool or str, default=None Label of the positive class. If None, `pos_label` will be inferred in the following manner: * if `y_true` in {-1, 1} or {0, 1}, `pos_label` defaults to 1; * else if `y_true` contains string, an error will be raised and `pos_label` should be explicitly specified; * otherwise, `pos_label` defaults to the greater label, i.e. `np.unique(y_true)[-1]`. Returns ------- transformed_labels : array of shape (n_samples, 2) y_prob : array of shape (n_samples, 2) """ # sanity checks on y_true and y_prob y_true = column_or_1d(y_true) y_prob = column_or_1d(y_prob) assert_all_finite(y_true) assert_all_finite(y_prob) check_consistent_length(y_prob, y_true, sample_weight) y_type = type_of_target(y_true, input_name="y_true") if y_type != "binary": raise ValueError( f"The type of the target inferred from y_true is {y_type} but should be " "binary according to the shape of y_prob." ) if y_prob.max() > 1: raise ValueError(f"y_prob contains values greater than 1: {y_prob.max()}") if y_prob.min() < 0: raise ValueError(f"y_prob contains values less than 0: {y_prob.min()}") # check that pos_label is consistent with y_true try: pos_label = _check_pos_label_consistency(pos_label, y_true) except ValueError: classes = np.unique(y_true) if classes.dtype.kind not in ("O", "U", "S"): # for backward compatibility, if classes are not string then # `pos_label` will correspond to the greater label pos_label = classes[-1] else: raise # convert (n_samples,) to (n_samples, 2) shape y_true = np.array(y_true == pos_label, int) transformed_labels = np.column_stack((1 - y_true, y_true)) y_prob = np.column_stack((1 - y_prob, y_prob)) return transformed_labels, y_prob
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,), default=None Sample weights. pos_label : int, float, bool or str, default=None Label of the positive class. If None, `pos_label` will be inferred in the following manner: * if `y_true` in {-1, 1} or {0, 1}, `pos_label` defaults to 1; * else if `y_true` contains string, an error will be raised and `pos_label` should be explicitly specified; * otherwise, `pos_label` defaults to the greater label, i.e. `np.unique(y_true)[-1]`. Returns ------- transformed_labels : array of shape (n_samples, 2) y_prob : array of shape (n_samples, 2)
_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 between the predicted probability and the actual outcome. The Brier score is a strictly proper scoring rule. Read more in the :ref:`User Guide <brier_score_loss>`. Parameters ---------- y_true : array-like of shape (n_samples,) True targets. y_proba : array-like of shape (n_samples,) or (n_samples, n_classes) Predicted probabilities. If `y_proba.shape = (n_samples,)` the probabilities provided are assumed to be that of the positive class. If `y_proba.shape = (n_samples, n_classes)` the columns in `y_proba` are assumed to correspond to the labels in alphabetical order, as done by :class:`~sklearn.preprocessing.LabelBinarizer`. sample_weight : array-like of shape (n_samples,), default=None Sample weights. pos_label : int, float, bool or str, default=None Label of the positive class when `y_proba.shape = (n_samples,)`. If not provided, `pos_label` will be inferred in the following manner: * if `y_true` in {-1, 1} or {0, 1}, `pos_label` defaults to 1; * else if `y_true` contains string, an error will be raised and `pos_label` should be explicitly specified; * otherwise, `pos_label` defaults to the greater label, i.e. `np.unique(y_true)[-1]`. labels : array-like of shape (n_classes,), default=None Class labels when `y_proba.shape = (n_samples, n_classes)`. If not provided, labels will be inferred from `y_true`. .. versionadded:: 1.7 scale_by_half : bool or "auto", default="auto" When True, scale the Brier score by 1/2 to lie in the [0, 1] range instead of the [0, 2] range. The default "auto" option implements the rescaling to [0, 1] only for binary classification (as customary) but keeps the original [0, 2] range for multiclasss classification. .. versionadded:: 1.7 Returns ------- score : float Brier score loss. Notes ----- For :math:`N` observations labeled from :math:`C` possible classes, the Brier score is defined as: .. math:: \frac{1}{N}\sum_{i=1}^{N}\sum_{c=1}^{C}(y_{ic} - \hat{p}_{ic})^{2} where :math:`y_{ic}` is 1 if observation `i` belongs to class `c`, otherwise 0 and :math:`\hat{p}_{ic}` is the predicted probability for observation `i` to belong to class `c`. The Brier score then ranges between :math:`[0, 2]`. In binary classification tasks the Brier score is usually divided by two and then ranges between :math:`[0, 1]`. It can be alternatively written as: .. math:: \frac{1}{N}\sum_{i=1}^{N}(y_{i} - \hat{p}_{i})^{2} where :math:`y_{i}` is the binary target and :math:`\hat{p}_{i}` is the predicted probability of the positive class. References ---------- .. [1] `Wikipedia entry for the Brier score <https://en.wikipedia.org/wiki/Brier_score>`_. Examples -------- >>> import numpy as np >>> from sklearn.metrics import brier_score_loss >>> y_true = np.array([0, 1, 1, 0]) >>> y_true_categorical = np.array(["spam", "ham", "ham", "spam"]) >>> y_prob = np.array([0.1, 0.9, 0.8, 0.3]) >>> brier_score_loss(y_true, y_prob) 0.0375 >>> brier_score_loss(y_true, 1-y_prob, pos_label=0) 0.0375 >>> brier_score_loss(y_true_categorical, y_prob, pos_label="ham") 0.0375 >>> brier_score_loss(y_true, np.array(y_prob) > 0.5) 0.0 >>> brier_score_loss(y_true, y_prob, scale_by_half=False) 0.075 >>> brier_score_loss( ... ["eggs", "ham", "spam"], ... [[0.8, 0.1, 0.1], [0.2, 0.7, 0.1], [0.2, 0.2, 0.6]], ... labels=["eggs", "ham", "spam"] ... ) 0.146 """ y_proba = check_array( y_proba, ensure_2d=False, dtype=[np.float64, np.float32, np.float16] ) if y_proba.ndim == 1 or y_proba.shape[1] == 1: transformed_labels, y_proba = _validate_binary_probabilistic_prediction( y_true, y_proba, sample_weight, pos_label ) else: transformed_labels, y_proba = _validate_multiclass_probabilistic_prediction( y_true, y_proba, sample_weight, labels ) brier_score = np.average( np.sum((transformed_labels - y_proba) ** 2, axis=1), weights=sample_weight ) if scale_by_half == "auto": scale_by_half = y_proba.ndim == 1 or y_proba.shape[1] < 3 if scale_by_half: brier_score *= 0.5 return float(brier_score)
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 Guide <brier_score_loss>`. Parameters ---------- y_true : array-like of shape (n_samples,) True targets. y_proba : array-like of shape (n_samples,) or (n_samples, n_classes) Predicted probabilities. If `y_proba.shape = (n_samples,)` the probabilities provided are assumed to be that of the positive class. If `y_proba.shape = (n_samples, n_classes)` the columns in `y_proba` are assumed to correspond to the labels in alphabetical order, as done by :class:`~sklearn.preprocessing.LabelBinarizer`. sample_weight : array-like of shape (n_samples,), default=None Sample weights. pos_label : int, float, bool or str, default=None Label of the positive class when `y_proba.shape = (n_samples,)`. If not provided, `pos_label` will be inferred in the following manner: * if `y_true` in {-1, 1} or {0, 1}, `pos_label` defaults to 1; * else if `y_true` contains string, an error will be raised and `pos_label` should be explicitly specified; * otherwise, `pos_label` defaults to the greater label, i.e. `np.unique(y_true)[-1]`. labels : array-like of shape (n_classes,), default=None Class labels when `y_proba.shape = (n_samples, n_classes)`. If not provided, labels will be inferred from `y_true`. .. versionadded:: 1.7 scale_by_half : bool or "auto", default="auto" When True, scale the Brier score by 1/2 to lie in the [0, 1] range instead of the [0, 2] range. The default "auto" option implements the rescaling to [0, 1] only for binary classification (as customary) but keeps the original [0, 2] range for multiclasss classification. .. versionadded:: 1.7 Returns ------- score : float Brier score loss. Notes ----- For :math:`N` observations labeled from :math:`C` possible classes, the Brier score is defined as: .. math:: \frac{1}{N}\sum_{i=1}^{N}\sum_{c=1}^{C}(y_{ic} - \hat{p}_{ic})^{2} where :math:`y_{ic}` is 1 if observation `i` belongs to class `c`, otherwise 0 and :math:`\hat{p}_{ic}` is the predicted probability for observation `i` to belong to class `c`. The Brier score then ranges between :math:`[0, 2]`. In binary classification tasks the Brier score is usually divided by two and then ranges between :math:`[0, 1]`. It can be alternatively written as: .. math:: \frac{1}{N}\sum_{i=1}^{N}(y_{i} - \hat{p}_{i})^{2} where :math:`y_{i}` is the binary target and :math:`\hat{p}_{i}` is the predicted probability of the positive class. References ---------- .. [1] `Wikipedia entry for the Brier score <https://en.wikipedia.org/wiki/Brier_score>`_. Examples -------- >>> import numpy as np >>> from sklearn.metrics import brier_score_loss >>> y_true = np.array([0, 1, 1, 0]) >>> y_true_categorical = np.array(["spam", "ham", "ham", "spam"]) >>> y_prob = np.array([0.1, 0.9, 0.8, 0.3]) >>> brier_score_loss(y_true, y_prob) 0.0375 >>> brier_score_loss(y_true, 1-y_prob, pos_label=0) 0.0375 >>> brier_score_loss(y_true_categorical, y_prob, pos_label="ham") 0.0375 >>> brier_score_loss(y_true, np.array(y_prob) > 0.5) 0.0 >>> brier_score_loss(y_true, y_prob, scale_by_half=False) 0.075 >>> brier_score_loss( ... ["eggs", "ham", "spam"], ... [[0.8, 0.1, 0.1], [0.2, 0.7, 0.1], [0.2, 0.2, 0.6]], ... labels=["eggs", "ham", "spam"] ... ) 0.146
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_true`, disregarding the input features, gets a D^2 score of 0.0. Read more in the :ref:`User Guide <d2_score_classification>`. .. versionadded:: 1.5 Parameters ---------- y_true : array-like or label indicator matrix The actuals labels for the n_samples samples. y_pred : array-like of shape (n_samples, n_classes) or (n_samples,) Predicted probabilities, as returned by a classifier's predict_proba method. If ``y_pred.shape = (n_samples,)`` the probabilities provided are assumed to be that of the positive class. The labels in ``y_pred`` are assumed to be ordered alphabetically, as done by :class:`~sklearn.preprocessing.LabelBinarizer`. sample_weight : array-like of shape (n_samples,), default=None Sample weights. labels : array-like, default=None If not provided, labels will be inferred from y_true. If ``labels`` is ``None`` and ``y_pred`` has shape (n_samples,) the labels are assumed to be binary and are inferred from ``y_true``. Returns ------- d2 : float or ndarray of floats The D^2 score. Notes ----- This is not a symmetric function. Like R^2, D^2 score may be negative (it need not actually be the square of a quantity D). This metric is not well-defined for a single sample and will return a NaN value if n_samples is less than two. """ y_pred = check_array(y_pred, ensure_2d=False, dtype="numeric") check_consistent_length(y_pred, y_true, sample_weight) if _num_samples(y_pred) < 2: msg = "D^2 score is not well-defined with less than two samples." warnings.warn(msg, UndefinedMetricWarning) return float("nan") # log loss of the fitted model numerator = log_loss( y_true=y_true, y_pred=y_pred, normalize=False, sample_weight=sample_weight, labels=labels, ) # Proportion of labels in the dataset weights = _check_sample_weight(sample_weight, y_true) # If labels is passed, augment y_true to ensure that all labels are represented # Use 0 weight for the new samples to not affect the counts y_true_, weights_ = ( ( np.concatenate([y_true, labels]), np.concatenate([weights, np.zeros_like(weights, shape=len(labels))]), ) if labels is not None else (y_true, weights) ) _, y_value_indices = np.unique(y_true_, return_inverse=True) counts = np.bincount(y_value_indices, weights=weights_) y_prob = counts / weights.sum() y_pred_null = np.tile(y_prob, (len(y_true), 1)) # log loss of the null model denominator = log_loss( y_true=y_true, y_pred=y_pred_null, normalize=False, sample_weight=sample_weight, labels=labels, ) return float(1 - (numerator / denominator))
: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 the :ref:`User Guide <d2_score_classification>`. .. versionadded:: 1.5 Parameters ---------- y_true : array-like or label indicator matrix The actuals labels for the n_samples samples. y_pred : array-like of shape (n_samples, n_classes) or (n_samples,) Predicted probabilities, as returned by a classifier's predict_proba method. If ``y_pred.shape = (n_samples,)`` the probabilities provided are assumed to be that of the positive class. The labels in ``y_pred`` are assumed to be ordered alphabetically, as done by :class:`~sklearn.preprocessing.LabelBinarizer`. sample_weight : array-like of shape (n_samples,), default=None Sample weights. labels : array-like, default=None If not provided, labels will be inferred from y_true. If ``labels`` is ``None`` and ``y_pred`` has shape (n_samples,) the labels are assumed to be binary and are inferred from ``y_true``. Returns ------- d2 : float or ndarray of floats The D^2 score. Notes ----- This is not a symmetric function. Like R^2, D^2 score may be negative (it need not actually be the square of a quantity D). This metric is not well-defined for a single sample and will return a NaN value if n_samples is less than two.
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_score`. Parameters ---------- x : array-like of shape (n,) X coordinates. These must be either monotonic increasing or monotonic decreasing. y : array-like of shape (n,) Y coordinates. Returns ------- auc : float Area Under the Curve. See Also -------- roc_auc_score : Compute the area under the ROC curve. average_precision_score : Compute average precision from prediction scores. precision_recall_curve : Compute precision-recall pairs for different probability thresholds. Examples -------- >>> import numpy as np >>> from sklearn import metrics >>> y_true = np.array([1, 1, 2, 2]) >>> y_score = np.array([0.1, 0.4, 0.35, 0.8]) >>> fpr, tpr, thresholds = metrics.roc_curve(y_true, y_score, pos_label=2) >>> metrics.auc(fpr, tpr) 0.75 """ check_consistent_length(x, y) x = column_or_1d(x) y = column_or_1d(y) if x.shape[0] < 2: raise ValueError( "At least 2 points are needed to compute area under curve, but x.shape = %s" % x.shape ) direction = 1 dx = np.diff(x) if np.any(dx < 0): if np.all(dx <= 0): direction = -1 else: raise ValueError("x is neither increasing nor decreasing : {}.".format(x)) area = direction * trapezoid(y, x) if isinstance(area, np.memmap): # Reductions such as .sum used internally in trapezoid do not return a # scalar by default for numpy.memmap instances contrary to # regular numpy.ndarray instances. area = area.dtype.type(area) return float(area)
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 ---------- x : array-like of shape (n,) X coordinates. These must be either monotonic increasing or monotonic decreasing. y : array-like of shape (n,) Y coordinates. Returns ------- auc : float Area Under the Curve. See Also -------- roc_auc_score : Compute the area under the ROC curve. average_precision_score : Compute average precision from prediction scores. precision_recall_curve : Compute precision-recall pairs for different probability thresholds. Examples -------- >>> import numpy as np >>> from sklearn import metrics >>> y_true = np.array([1, 1, 2, 2]) >>> y_score = np.array([0.1, 0.4, 0.35, 0.8]) >>> fpr, tpr, thresholds = metrics.roc_curve(y_true, y_score, pos_label=2) >>> metrics.auc(fpr, tpr) 0.75
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 previous threshold used as the weight: .. math:: \\text{AP} = \\sum_n (R_n - R_{n-1}) P_n where :math:`P_n` and :math:`R_n` are the precision and recall at the nth threshold [1]_. This implementation is not interpolated and is different from computing the area under the precision-recall curve with the trapezoidal rule, which uses linear interpolation and can be too optimistic. Read more in the :ref:`User Guide <precision_recall_f_measure_metrics>`. Parameters ---------- y_true : array-like of shape (n_samples,) or (n_samples, n_classes) True binary labels or binary label indicators. y_score : array-like of shape (n_samples,) or (n_samples, n_classes) Target scores, can either be probability estimates of the positive class, confidence values, or non-thresholded measure of decisions (as returned by :term:`decision_function` on some classifiers). For :term:`decision_function` scores, values greater than or equal to zero should indicate the positive class. average : {'micro', 'samples', 'weighted', 'macro'} or None, \ default='macro' If ``None``, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data: ``'micro'``: Calculate metrics globally by considering each element of the label indicator matrix as a label. ``'macro'``: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. ``'weighted'``: Calculate metrics for each label, and find their average, weighted by support (the number of true instances for each label). ``'samples'``: Calculate metrics for each instance, and find their average. Will be ignored when ``y_true`` is binary. pos_label : int, float, bool or str, default=1 The label of the positive class. Only applied to binary ``y_true``. For multilabel-indicator ``y_true``, ``pos_label`` is fixed to 1. sample_weight : array-like of shape (n_samples,), default=None Sample weights. Returns ------- average_precision : float Average precision score. See Also -------- roc_auc_score : Compute the area under the ROC curve. precision_recall_curve : Compute precision-recall pairs for different probability thresholds. PrecisionRecallDisplay.from_estimator : Plot the precision recall curve using an estimator and data. PrecisionRecallDisplay.from_predictions : Plot the precision recall curve using true and predicted labels. Notes ----- .. versionchanged:: 0.19 Instead of linearly interpolating between operating points, precisions are weighted by the change in recall since the last operating point. References ---------- .. [1] `Wikipedia entry for the Average precision <https://en.wikipedia.org/w/index.php?title=Information_retrieval& oldid=793358396#Average_precision>`_ Examples -------- >>> import numpy as np >>> from sklearn.metrics import average_precision_score >>> y_true = np.array([0, 0, 1, 1]) >>> y_scores = np.array([0.1, 0.4, 0.35, 0.8]) >>> average_precision_score(y_true, y_scores) 0.83 >>> y_true = np.array([0, 0, 1, 1, 2, 2]) >>> y_scores = np.array([ ... [0.7, 0.2, 0.1], ... [0.4, 0.3, 0.3], ... [0.1, 0.8, 0.1], ... [0.2, 0.3, 0.5], ... [0.4, 0.4, 0.2], ... [0.1, 0.2, 0.7], ... ]) >>> average_precision_score(y_true, y_scores) 0.77 """ def _binary_uninterpolated_average_precision( y_true, y_score, pos_label=1, sample_weight=None ): precision, recall, _ = precision_recall_curve( y_true, y_score, pos_label=pos_label, sample_weight=sample_weight ) # Return the step function integral # The following works because the last entry of precision is # guaranteed to be 1, as returned by precision_recall_curve. # Due to numerical error, we can get `-0.0` and we therefore clip it. return float(max(0.0, -np.sum(np.diff(recall) * np.array(precision)[:-1]))) y_type = type_of_target(y_true, input_name="y_true") # Convert to Python primitive type to avoid NumPy type / Python str # comparison. See https://github.com/numpy/numpy/issues/6784 present_labels = np.unique(y_true).tolist() if y_type == "binary": if len(present_labels) == 2 and pos_label not in present_labels: raise ValueError( f"pos_label={pos_label} is not a valid label. It should be " f"one of {present_labels}" ) elif y_type == "multilabel-indicator" and pos_label != 1: raise ValueError( "Parameter pos_label is fixed to 1 for multilabel-indicator y_true. " "Do not set pos_label or set pos_label to 1." ) elif y_type == "multiclass": if pos_label != 1: raise ValueError( "Parameter pos_label is fixed to 1 for multiclass y_true. " "Do not set pos_label or set pos_label to 1." ) y_true = label_binarize(y_true, classes=present_labels) average_precision = partial( _binary_uninterpolated_average_precision, pos_label=pos_label ) return _average_binary_score( average_precision, y_true, y_score, average, sample_weight=sample_weight )
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 :math:`P_n` and :math:`R_n` are the precision and recall at the nth threshold [1]_. This implementation is not interpolated and is different from computing the area under the precision-recall curve with the trapezoidal rule, which uses linear interpolation and can be too optimistic. Read more in the :ref:`User Guide <precision_recall_f_measure_metrics>`. Parameters ---------- y_true : array-like of shape (n_samples,) or (n_samples, n_classes) True binary labels or binary label indicators. y_score : array-like of shape (n_samples,) or (n_samples, n_classes) Target scores, can either be probability estimates of the positive class, confidence values, or non-thresholded measure of decisions (as returned by :term:`decision_function` on some classifiers). For :term:`decision_function` scores, values greater than or equal to zero should indicate the positive class. average : {'micro', 'samples', 'weighted', 'macro'} or None, default='macro' If ``None``, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data: ``'micro'``: Calculate metrics globally by considering each element of the label indicator matrix as a label. ``'macro'``: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. ``'weighted'``: Calculate metrics for each label, and find their average, weighted by support (the number of true instances for each label). ``'samples'``: Calculate metrics for each instance, and find their average. Will be ignored when ``y_true`` is binary. pos_label : int, float, bool or str, default=1 The label of the positive class. Only applied to binary ``y_true``. For multilabel-indicator ``y_true``, ``pos_label`` is fixed to 1. sample_weight : array-like of shape (n_samples,), default=None Sample weights. Returns ------- average_precision : float Average precision score. See Also -------- roc_auc_score : Compute the area under the ROC curve. precision_recall_curve : Compute precision-recall pairs for different probability thresholds. PrecisionRecallDisplay.from_estimator : Plot the precision recall curve using an estimator and data. PrecisionRecallDisplay.from_predictions : Plot the precision recall curve using true and predicted labels. Notes ----- .. versionchanged:: 0.19 Instead of linearly interpolating between operating points, precisions are weighted by the change in recall since the last operating point. References ---------- .. [1] `Wikipedia entry for the Average precision <https://en.wikipedia.org/w/index.php?title=Information_retrieval& oldid=793358396#Average_precision>`_ Examples -------- >>> import numpy as np >>> from sklearn.metrics import average_precision_score >>> y_true = np.array([0, 0, 1, 1]) >>> y_scores = np.array([0.1, 0.4, 0.35, 0.8]) >>> average_precision_score(y_true, y_scores) 0.83 >>> y_true = np.array([0, 0, 1, 1, 2, 2]) >>> y_scores = np.array([ ... [0.7, 0.2, 0.1], ... [0.4, 0.3, 0.3], ... [0.1, 0.8, 0.1], ... [0.2, 0.3, 0.5], ... [0.4, 0.4, 0.2], ... [0.1, 0.2, 0.7], ... ]) >>> average_precision_score(y_true, y_scores) 0.77
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 more in the :ref:`User Guide <det_curve>`. .. versionadded:: 0.24 .. versionchanged:: 1.7 An arbitrary threshold at infinity is added to represent a classifier that always predicts the negative class, i.e. `fpr=0` and `fnr=1`, unless `fpr=0` is already reached at a finite threshold. Parameters ---------- y_true : ndarray of shape (n_samples,) True binary labels. If labels are not either {-1, 1} or {0, 1}, then pos_label should be explicitly given. y_score : ndarray of shape of (n_samples,) Target scores, can either be probability estimates of the positive class, confidence values, or non-thresholded measure of decisions (as returned by "decision_function" on some classifiers). For :term:`decision_function` scores, values greater than or equal to zero should indicate the positive class. pos_label : int, float, bool or str, default=None The label of the positive class. When ``pos_label=None``, if `y_true` is in {-1, 1} or {0, 1}, ``pos_label`` is set to 1, otherwise an error will be raised. sample_weight : array-like of shape (n_samples,), default=None Sample weights. drop_intermediate : bool, default=False Whether to drop thresholds where true positives (tp) do not change from the previous or subsequent threshold. All points with the same tp value have the same `fnr` and thus same y coordinate. .. versionadded:: 1.7 Returns ------- fpr : ndarray of shape (n_thresholds,) False positive rate (FPR) such that element i is the false positive rate of predictions with score >= thresholds[i]. This is occasionally referred to as false acceptance probability or fall-out. fnr : ndarray of shape (n_thresholds,) False negative rate (FNR) such that element i is the false negative rate of predictions with score >= thresholds[i]. This is occasionally referred to as false rejection or miss rate. thresholds : ndarray of shape (n_thresholds,) Decreasing thresholds on the decision function (either `predict_proba` or `decision_function`) used to compute FPR and FNR. .. versionchanged:: 1.7 An arbitrary threshold at infinity is added for the case `fpr=0` and `fnr=1`. See Also -------- DetCurveDisplay.from_estimator : Plot DET curve given an estimator and some data. DetCurveDisplay.from_predictions : Plot DET curve given the true and predicted labels. DetCurveDisplay : DET curve visualization. roc_curve : Compute Receiver operating characteristic (ROC) curve. precision_recall_curve : Compute precision-recall curve. Examples -------- >>> import numpy as np >>> from sklearn.metrics import det_curve >>> y_true = np.array([0, 0, 1, 1]) >>> y_scores = np.array([0.1, 0.4, 0.35, 0.8]) >>> fpr, fnr, thresholds = det_curve(y_true, y_scores) >>> fpr array([0.5, 0.5, 0. ]) >>> fnr array([0. , 0.5, 0.5]) >>> thresholds array([0.35, 0.4 , 0.8 ]) """ fps, tps, thresholds = _binary_clf_curve( y_true, y_score, pos_label=pos_label, sample_weight=sample_weight ) # add a threshold at inf where the clf always predicts the negative class # i.e. tps = fps = 0 tps = np.concatenate(([0], tps)) fps = np.concatenate(([0], fps)) thresholds = np.concatenate(([np.inf], thresholds)) if drop_intermediate and len(fps) > 2: # Drop thresholds where true positives (tp) do not change from the # previous or subsequent threshold. As tp + fn, is fixed for a dataset, # this means the false negative rate (fnr) remains constant while the # false positive rate (fpr) changes, producing horizontal line segments # in the transformed (normal deviate) scale. These intermediate points # can be dropped to create lighter DET curve plots. optimal_idxs = np.where( np.concatenate( [[True], np.logical_or(np.diff(tps[:-1]), np.diff(tps[1:])), [True]] ) )[0] fps = fps[optimal_idxs] tps = tps[optimal_idxs] thresholds = thresholds[optimal_idxs] if len(np.unique(y_true)) != 2: raise ValueError( "Only one class is present in y_true. Detection error " "tradeoff curve is not defined in that case." ) fns = tps[-1] - tps p_count = tps[-1] n_count = fps[-1] # start with false positives zero, which may be at a finite threshold first_ind = ( fps.searchsorted(fps[0], side="right") - 1 if fps.searchsorted(fps[0], side="right") > 0 else None ) # stop with false negatives zero last_ind = tps.searchsorted(tps[-1]) + 1 sl = slice(first_ind, last_ind) # reverse the output such that list of false positives is decreasing return (fps[sl][::-1] / n_count, fns[sl][::-1] / p_count, thresholds[sl][::-1])
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 An arbitrary threshold at infinity is added to represent a classifier that always predicts the negative class, i.e. `fpr=0` and `fnr=1`, unless `fpr=0` is already reached at a finite threshold. Parameters ---------- y_true : ndarray of shape (n_samples,) True binary labels. If labels are not either {-1, 1} or {0, 1}, then pos_label should be explicitly given. y_score : ndarray of shape of (n_samples,) Target scores, can either be probability estimates of the positive class, confidence values, or non-thresholded measure of decisions (as returned by "decision_function" on some classifiers). For :term:`decision_function` scores, values greater than or equal to zero should indicate the positive class. pos_label : int, float, bool or str, default=None The label of the positive class. When ``pos_label=None``, if `y_true` is in {-1, 1} or {0, 1}, ``pos_label`` is set to 1, otherwise an error will be raised. sample_weight : array-like of shape (n_samples,), default=None Sample weights. drop_intermediate : bool, default=False Whether to drop thresholds where true positives (tp) do not change from the previous or subsequent threshold. All points with the same tp value have the same `fnr` and thus same y coordinate. .. versionadded:: 1.7 Returns ------- fpr : ndarray of shape (n_thresholds,) False positive rate (FPR) such that element i is the false positive rate of predictions with score >= thresholds[i]. This is occasionally referred to as false acceptance probability or fall-out. fnr : ndarray of shape (n_thresholds,) False negative rate (FNR) such that element i is the false negative rate of predictions with score >= thresholds[i]. This is occasionally referred to as false rejection or miss rate. thresholds : ndarray of shape (n_thresholds,) Decreasing thresholds on the decision function (either `predict_proba` or `decision_function`) used to compute FPR and FNR. .. versionchanged:: 1.7 An arbitrary threshold at infinity is added for the case `fpr=0` and `fnr=1`. See Also -------- DetCurveDisplay.from_estimator : Plot DET curve given an estimator and some data. DetCurveDisplay.from_predictions : Plot DET curve given the true and predicted labels. DetCurveDisplay : DET curve visualization. roc_curve : Compute Receiver operating characteristic (ROC) curve. precision_recall_curve : Compute precision-recall curve. Examples -------- >>> import numpy as np >>> from sklearn.metrics import det_curve >>> y_true = np.array([0, 0, 1, 1]) >>> y_scores = np.array([0.1, 0.4, 0.35, 0.8]) >>> fpr, fnr, thresholds = det_curve(y_true, y_scores) >>> fpr array([0.5, 0.5, 0. ]) >>> fnr array([0. , 0.5, 0.5]) >>> thresholds array([0.35, 0.4 , 0.8 ])
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 binary, multiclass and multilabel classification, but some restrictions apply (see Parameters). Read more in the :ref:`User Guide <roc_metrics>`. Parameters ---------- y_true : array-like of shape (n_samples,) or (n_samples, n_classes) True labels or binary label indicators. The binary and multiclass cases expect labels with shape (n_samples,) while the multilabel case expects binary label indicators with shape (n_samples, n_classes). y_score : array-like of shape (n_samples,) or (n_samples, n_classes) Target scores. * In the binary case, it corresponds to an array of shape `(n_samples,)`. Both probability estimates and non-thresholded decision values can be provided. The probability estimates correspond to the **probability of the class with the greater label**, i.e. `estimator.classes_[1]` and thus `estimator.predict_proba(X, y)[:, 1]`. The decision values corresponds to the output of `estimator.decision_function(X, y)`. See more information in the :ref:`User guide <roc_auc_binary>`; * In the multiclass case, it corresponds to an array of shape `(n_samples, n_classes)` of probability estimates provided by the `predict_proba` method. The probability estimates **must** sum to 1 across the possible classes. In addition, the order of the class scores must correspond to the order of ``labels``, if provided, or else to the numerical or lexicographical order of the labels in ``y_true``. See more information in the :ref:`User guide <roc_auc_multiclass>`; * In the multilabel case, it corresponds to an array of shape `(n_samples, n_classes)`. Probability estimates are provided by the `predict_proba` method and the non-thresholded decision values by the `decision_function` method. The probability estimates correspond to the **probability of the class with the greater label for each output** of the classifier. See more information in the :ref:`User guide <roc_auc_multilabel>`. average : {'micro', 'macro', 'samples', 'weighted'} or None, \ default='macro' If ``None``, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Note: multiclass ROC AUC currently only handles the 'macro' and 'weighted' averages. For multiclass targets, `average=None` is only implemented for `multi_class='ovr'` and `average='micro'` is only implemented for `multi_class='ovr'`. ``'micro'``: Calculate metrics globally by considering each element of the label indicator matrix as a label. ``'macro'``: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. ``'weighted'``: Calculate metrics for each label, and find their average, weighted by support (the number of true instances for each label). ``'samples'``: Calculate metrics for each instance, and find their average. Will be ignored when ``y_true`` is binary. sample_weight : array-like of shape (n_samples,), default=None Sample weights. max_fpr : float > 0 and <= 1, default=None If not ``None``, the standardized partial AUC [2]_ over the range [0, max_fpr] is returned. For the multiclass case, ``max_fpr``, should be either equal to ``None`` or ``1.0`` as AUC ROC partial computation currently is not supported for multiclass. multi_class : {'raise', 'ovr', 'ovo'}, default='raise' Only used for multiclass targets. Determines the type of configuration to use. The default value raises an error, so either ``'ovr'`` or ``'ovo'`` must be passed explicitly. ``'ovr'``: Stands for One-vs-rest. Computes the AUC of each class against the rest [3]_ [4]_. This treats the multiclass case in the same way as the multilabel case. Sensitive to class imbalance even when ``average == 'macro'``, because class imbalance affects the composition of each of the 'rest' groupings. ``'ovo'``: Stands for One-vs-one. Computes the average AUC of all possible pairwise combinations of classes [5]_. Insensitive to class imbalance when ``average == 'macro'``. labels : array-like of shape (n_classes,), default=None Only used for multiclass targets. List of labels that index the classes in ``y_score``. If ``None``, the numerical or lexicographical order of the labels in ``y_true`` is used. Returns ------- auc : float Area Under the Curve score. See Also -------- average_precision_score : Area under the precision-recall curve. roc_curve : Compute Receiver operating characteristic (ROC) curve. RocCurveDisplay.from_estimator : Plot Receiver Operating Characteristic (ROC) curve given an estimator and some data. RocCurveDisplay.from_predictions : Plot Receiver Operating Characteristic (ROC) curve given the true and predicted values. Notes ----- The Gini Coefficient is a summary measure of the ranking ability of binary classifiers. It is expressed using the area under of the ROC as follows: G = 2 * AUC - 1 Where G is the Gini coefficient and AUC is the ROC-AUC score. This normalisation will ensure that random guessing will yield a score of 0 in expectation, and it is upper bounded by 1. References ---------- .. [1] `Wikipedia entry for the Receiver operating characteristic <https://en.wikipedia.org/wiki/Receiver_operating_characteristic>`_ .. [2] `Analyzing a portion of the ROC curve. McClish, 1989 <https://www.ncbi.nlm.nih.gov/pubmed/2668680>`_ .. [3] Provost, F., Domingos, P. (2000). Well-trained PETs: Improving probability estimation trees (Section 6.2), CeDER Working Paper #IS-00-04, Stern School of Business, New York University. .. [4] `Fawcett, T. (2006). An introduction to ROC analysis. Pattern Recognition Letters, 27(8), 861-874. <https://www.sciencedirect.com/science/article/pii/S016786550500303X>`_ .. [5] `Hand, D.J., Till, R.J. (2001). A Simple Generalisation of the Area Under the ROC Curve for Multiple Class Classification Problems. Machine Learning, 45(2), 171-186. <http://link.springer.com/article/10.1023/A:1010920819831>`_ .. [6] `Wikipedia entry for the Gini coefficient <https://en.wikipedia.org/wiki/Gini_coefficient>`_ Examples -------- Binary case: >>> from sklearn.datasets import load_breast_cancer >>> from sklearn.linear_model import LogisticRegression >>> from sklearn.metrics import roc_auc_score >>> X, y = load_breast_cancer(return_X_y=True) >>> clf = LogisticRegression(solver="newton-cholesky", random_state=0).fit(X, y) >>> roc_auc_score(y, clf.predict_proba(X)[:, 1]) 0.99 >>> roc_auc_score(y, clf.decision_function(X)) 0.99 Multiclass case: >>> from sklearn.datasets import load_iris >>> X, y = load_iris(return_X_y=True) >>> clf = LogisticRegression(solver="newton-cholesky").fit(X, y) >>> roc_auc_score(y, clf.predict_proba(X), multi_class='ovr') 0.99 Multilabel case: >>> import numpy as np >>> from sklearn.datasets import make_multilabel_classification >>> from sklearn.multioutput import MultiOutputClassifier >>> X, y = make_multilabel_classification(random_state=0) >>> clf = MultiOutputClassifier(clf).fit(X, y) >>> # get a list of n_output containing probability arrays of shape >>> # (n_samples, n_classes) >>> y_score = clf.predict_proba(X) >>> # extract the positive columns for each output >>> y_score = np.transpose([score[:, 1] for score in y_score]) >>> roc_auc_score(y, y_score, average=None) array([0.828, 0.852, 0.94, 0.869, 0.95]) >>> from sklearn.linear_model import RidgeClassifierCV >>> clf = RidgeClassifierCV().fit(X, y) >>> roc_auc_score(y, clf.decision_function(X), average=None) array([0.82, 0.847, 0.93, 0.872, 0.944]) """ y_type = type_of_target(y_true, input_name="y_true") y_true = check_array(y_true, ensure_2d=False, dtype=None) y_score = check_array(y_score, ensure_2d=False) if y_type == "multiclass" or ( y_type == "binary" and y_score.ndim == 2 and y_score.shape[1] > 2 ): # do not support partial ROC computation for multiclass if max_fpr is not None and max_fpr != 1.0: raise ValueError( "Partial AUC computation not available in " "multiclass setting, 'max_fpr' must be" " set to `None`, received `max_fpr={0}` " "instead".format(max_fpr) ) if multi_class == "raise": raise ValueError("multi_class must be in ('ovo', 'ovr')") return _multiclass_roc_auc_score( y_true, y_score, labels, multi_class, average, sample_weight ) elif y_type == "binary": labels = np.unique(y_true) y_true = label_binarize(y_true, classes=labels)[:, 0] return _average_binary_score( partial(_binary_roc_auc_score, max_fpr=max_fpr), y_true, y_score, average, sample_weight=sample_weight, ) else: # multilabel-indicator return _average_binary_score( partial(_binary_roc_auc_score, max_fpr=max_fpr), y_true, y_score, average, sample_weight=sample_weight, )
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 ---------- y_true : array-like of shape (n_samples,) or (n_samples, n_classes) True labels or binary label indicators. The binary and multiclass cases expect labels with shape (n_samples,) while the multilabel case expects binary label indicators with shape (n_samples, n_classes). y_score : array-like of shape (n_samples,) or (n_samples, n_classes) Target scores. * In the binary case, it corresponds to an array of shape `(n_samples,)`. Both probability estimates and non-thresholded decision values can be provided. The probability estimates correspond to the **probability of the class with the greater label**, i.e. `estimator.classes_[1]` and thus `estimator.predict_proba(X, y)[:, 1]`. The decision values corresponds to the output of `estimator.decision_function(X, y)`. See more information in the :ref:`User guide <roc_auc_binary>`; * In the multiclass case, it corresponds to an array of shape `(n_samples, n_classes)` of probability estimates provided by the `predict_proba` method. The probability estimates **must** sum to 1 across the possible classes. In addition, the order of the class scores must correspond to the order of ``labels``, if provided, or else to the numerical or lexicographical order of the labels in ``y_true``. See more information in the :ref:`User guide <roc_auc_multiclass>`; * In the multilabel case, it corresponds to an array of shape `(n_samples, n_classes)`. Probability estimates are provided by the `predict_proba` method and the non-thresholded decision values by the `decision_function` method. The probability estimates correspond to the **probability of the class with the greater label for each output** of the classifier. See more information in the :ref:`User guide <roc_auc_multilabel>`. average : {'micro', 'macro', 'samples', 'weighted'} or None, default='macro' If ``None``, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Note: multiclass ROC AUC currently only handles the 'macro' and 'weighted' averages. For multiclass targets, `average=None` is only implemented for `multi_class='ovr'` and `average='micro'` is only implemented for `multi_class='ovr'`. ``'micro'``: Calculate metrics globally by considering each element of the label indicator matrix as a label. ``'macro'``: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. ``'weighted'``: Calculate metrics for each label, and find their average, weighted by support (the number of true instances for each label). ``'samples'``: Calculate metrics for each instance, and find their average. Will be ignored when ``y_true`` is binary. sample_weight : array-like of shape (n_samples,), default=None Sample weights. max_fpr : float > 0 and <= 1, default=None If not ``None``, the standardized partial AUC [2]_ over the range [0, max_fpr] is returned. For the multiclass case, ``max_fpr``, should be either equal to ``None`` or ``1.0`` as AUC ROC partial computation currently is not supported for multiclass. multi_class : {'raise', 'ovr', 'ovo'}, default='raise' Only used for multiclass targets. Determines the type of configuration to use. The default value raises an error, so either ``'ovr'`` or ``'ovo'`` must be passed explicitly. ``'ovr'``: Stands for One-vs-rest. Computes the AUC of each class against the rest [3]_ [4]_. This treats the multiclass case in the same way as the multilabel case. Sensitive to class imbalance even when ``average == 'macro'``, because class imbalance affects the composition of each of the 'rest' groupings. ``'ovo'``: Stands for One-vs-one. Computes the average AUC of all possible pairwise combinations of classes [5]_. Insensitive to class imbalance when ``average == 'macro'``. labels : array-like of shape (n_classes,), default=None Only used for multiclass targets. List of labels that index the classes in ``y_score``. If ``None``, the numerical or lexicographical order of the labels in ``y_true`` is used. Returns ------- auc : float Area Under the Curve score. See Also -------- average_precision_score : Area under the precision-recall curve. roc_curve : Compute Receiver operating characteristic (ROC) curve. RocCurveDisplay.from_estimator : Plot Receiver Operating Characteristic (ROC) curve given an estimator and some data. RocCurveDisplay.from_predictions : Plot Receiver Operating Characteristic (ROC) curve given the true and predicted values. Notes ----- The Gini Coefficient is a summary measure of the ranking ability of binary classifiers. It is expressed using the area under of the ROC as follows: G = 2 * AUC - 1 Where G is the Gini coefficient and AUC is the ROC-AUC score. This normalisation will ensure that random guessing will yield a score of 0 in expectation, and it is upper bounded by 1. References ---------- .. [1] `Wikipedia entry for the Receiver operating characteristic <https://en.wikipedia.org/wiki/Receiver_operating_characteristic>`_ .. [2] `Analyzing a portion of the ROC curve. McClish, 1989 <https://www.ncbi.nlm.nih.gov/pubmed/2668680>`_ .. [3] Provost, F., Domingos, P. (2000). Well-trained PETs: Improving probability estimation trees (Section 6.2), CeDER Working Paper #IS-00-04, Stern School of Business, New York University. .. [4] `Fawcett, T. (2006). An introduction to ROC analysis. Pattern Recognition Letters, 27(8), 861-874. <https://www.sciencedirect.com/science/article/pii/S016786550500303X>`_ .. [5] `Hand, D.J., Till, R.J. (2001). A Simple Generalisation of the Area Under the ROC Curve for Multiple Class Classification Problems. Machine Learning, 45(2), 171-186. <http://link.springer.com/article/10.1023/A:1010920819831>`_ .. [6] `Wikipedia entry for the Gini coefficient <https://en.wikipedia.org/wiki/Gini_coefficient>`_ Examples -------- Binary case: >>> from sklearn.datasets import load_breast_cancer >>> from sklearn.linear_model import LogisticRegression >>> from sklearn.metrics import roc_auc_score >>> X, y = load_breast_cancer(return_X_y=True) >>> clf = LogisticRegression(solver="newton-cholesky", random_state=0).fit(X, y) >>> roc_auc_score(y, clf.predict_proba(X)[:, 1]) 0.99 >>> roc_auc_score(y, clf.decision_function(X)) 0.99 Multiclass case: >>> from sklearn.datasets import load_iris >>> X, y = load_iris(return_X_y=True) >>> clf = LogisticRegression(solver="newton-cholesky").fit(X, y) >>> roc_auc_score(y, clf.predict_proba(X), multi_class='ovr') 0.99 Multilabel case: >>> import numpy as np >>> from sklearn.datasets import make_multilabel_classification >>> from sklearn.multioutput import MultiOutputClassifier >>> X, y = make_multilabel_classification(random_state=0) >>> clf = MultiOutputClassifier(clf).fit(X, y) >>> # get a list of n_output containing probability arrays of shape >>> # (n_samples, n_classes) >>> y_score = clf.predict_proba(X) >>> # extract the positive columns for each output >>> y_score = np.transpose([score[:, 1] for score in y_score]) >>> roc_auc_score(y, y_score, average=None) array([0.828, 0.852, 0.94, 0.869, 0.95]) >>> from sklearn.linear_model import RidgeClassifierCV >>> clf = RidgeClassifierCV().fit(X, y) >>> roc_auc_score(y, clf.decision_function(X), average=None) array([0.82, 0.847, 0.93, 0.872, 0.944])
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 corresponding to probability estimates of a sample belonging to a particular class labels : array-like of shape (n_classes,) or None List of labels to index ``y_score`` used for multiclass. If ``None``, the lexical order of ``y_true`` is used to index ``y_score``. multi_class : {'ovr', 'ovo'} Determines the type of multiclass configuration to use. ``'ovr'``: Calculate metrics for the multiclass case using the one-vs-rest approach. ``'ovo'``: Calculate metrics for the multiclass case using the one-vs-one approach. average : {'micro', 'macro', 'weighted'} Determines the type of averaging performed on the pairwise binary metric scores ``'micro'``: Calculate metrics for the binarized-raveled classes. Only supported for `multi_class='ovr'`. .. versionadded:: 1.2 ``'macro'``: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. Classes are assumed to be uniformly distributed. ``'weighted'``: Calculate metrics for each label, taking into account the prevalence of the classes. sample_weight : array-like of shape (n_samples,) or None Sample weights. """ # validation of the input y_score if not np.allclose(1, y_score.sum(axis=1)): raise ValueError( "Target scores need to be probabilities for multiclass " "roc_auc, i.e. they should sum up to 1.0 over classes" ) # validation for multiclass parameter specifications average_options = ("macro", "weighted", None) if multi_class == "ovr": average_options = ("micro",) + average_options if average not in average_options: raise ValueError( "average must be one of {0} for multiclass problems".format(average_options) ) multiclass_options = ("ovo", "ovr") if multi_class not in multiclass_options: raise ValueError( "multi_class='{0}' is not supported " "for multiclass ROC AUC, multi_class must be " "in {1}".format(multi_class, multiclass_options) ) if average is None and multi_class == "ovo": raise NotImplementedError( "average=None is not implemented for multi_class='ovo'." ) if labels is not None: labels = column_or_1d(labels) classes = _unique(labels) if len(classes) != len(labels): raise ValueError("Parameter 'labels' must be unique") if not np.array_equal(classes, labels): raise ValueError("Parameter 'labels' must be ordered") if len(classes) != y_score.shape[1]: raise ValueError( "Number of given labels, {0}, not equal to the number " "of columns in 'y_score', {1}".format(len(classes), y_score.shape[1]) ) if len(np.setdiff1d(y_true, classes)): raise ValueError("'y_true' contains labels not in parameter 'labels'") else: classes = _unique(y_true) if len(classes) != y_score.shape[1]: raise ValueError( "Number of classes in y_true not equal to the number of " "columns in 'y_score'" ) if multi_class == "ovo": if sample_weight is not None: raise ValueError( "sample_weight is not supported " "for multiclass one-vs-one ROC AUC, " "'sample_weight' must be None in this case." ) y_true_encoded = _encode(y_true, uniques=classes) # Hand & Till (2001) implementation (ovo) return _average_multiclass_ovo_score( _binary_roc_auc_score, y_true_encoded, y_score, average=average ) else: # ovr is same as multi-label y_true_multilabel = label_binarize(y_true, classes=classes) return _average_binary_score( _binary_roc_auc_score, y_true_multilabel, y_score, average, sample_weight=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 corresponding to probability estimates of a sample belonging to a particular class labels : array-like of shape (n_classes,) or None List of labels to index ``y_score`` used for multiclass. If ``None``, the lexical order of ``y_true`` is used to index ``y_score``. multi_class : {'ovr', 'ovo'} Determines the type of multiclass configuration to use. ``'ovr'``: Calculate metrics for the multiclass case using the one-vs-rest approach. ``'ovo'``: Calculate metrics for the multiclass case using the one-vs-one approach. average : {'micro', 'macro', 'weighted'} Determines the type of averaging performed on the pairwise binary metric scores ``'micro'``: Calculate metrics for the binarized-raveled classes. Only supported for `multi_class='ovr'`. .. versionadded:: 1.2 ``'macro'``: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. Classes are assumed to be uniformly distributed. ``'weighted'``: Calculate metrics for each label, taking into account the prevalence of the classes. sample_weight : array-like of shape (n_samples,) or None Sample weights.
_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,) Estimated probabilities or output of a decision function. pos_label : int, float, bool or str, default=None The label of the positive class. sample_weight : array-like of shape (n_samples,), default=None Sample weights. Returns ------- fps : ndarray of shape (n_thresholds,) A count of false positives, at index i being the number of negative samples assigned a score >= thresholds[i]. The total number of negative samples is equal to fps[-1] (thus true negatives are given by fps[-1] - fps). tps : ndarray of shape (n_thresholds,) An increasing count of true positives, at index i being the number of positive samples assigned a score >= thresholds[i]. The total number of positive samples is equal to tps[-1] (thus false negatives are given by tps[-1] - tps). thresholds : ndarray of shape (n_thresholds,) Decreasing score values. """ # Check to make sure y_true is valid y_type = type_of_target(y_true, input_name="y_true") if not (y_type == "binary" or (y_type == "multiclass" and pos_label is not None)): raise ValueError("{0} format is not supported".format(y_type)) check_consistent_length(y_true, y_score, sample_weight) y_true = column_or_1d(y_true) y_score = column_or_1d(y_score) assert_all_finite(y_true) assert_all_finite(y_score) # Filter out zero-weighted samples, as they should not impact the result if sample_weight is not None: sample_weight = column_or_1d(sample_weight) sample_weight = _check_sample_weight(sample_weight, y_true) nonzero_weight_mask = sample_weight != 0 y_true = y_true[nonzero_weight_mask] y_score = y_score[nonzero_weight_mask] sample_weight = sample_weight[nonzero_weight_mask] pos_label = _check_pos_label_consistency(pos_label, y_true) # make y_true a boolean vector y_true = y_true == pos_label # sort scores and corresponding truth values desc_score_indices = np.argsort(y_score, kind="mergesort")[::-1] y_score = y_score[desc_score_indices] y_true = y_true[desc_score_indices] if sample_weight is not None: weight = sample_weight[desc_score_indices] else: weight = 1.0 # y_score typically has many tied values. Here we extract # the indices associated with the distinct values. We also # concatenate a value for the end of the curve. distinct_value_indices = np.where(np.diff(y_score))[0] threshold_idxs = np.r_[distinct_value_indices, y_true.size - 1] # accumulate the true positives with decreasing threshold tps = stable_cumsum(y_true * weight)[threshold_idxs] if sample_weight is not None: # express fps as a cumsum to ensure fps is increasing even in # the presence of floating point errors fps = stable_cumsum((1 - y_true) * weight)[threshold_idxs] else: fps = 1 + threshold_idxs - tps return fps, tps, y_score[threshold_idxs]
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 : int, float, bool or str, default=None The label of the positive class. sample_weight : array-like of shape (n_samples,), default=None Sample weights. Returns ------- fps : ndarray of shape (n_thresholds,) A count of false positives, at index i being the number of negative samples assigned a score >= thresholds[i]. The total number of negative samples is equal to fps[-1] (thus true negatives are given by fps[-1] - fps). tps : ndarray of shape (n_thresholds,) An increasing count of true positives, at index i being the number of positive samples assigned a score >= thresholds[i]. The total number of positive samples is equal to tps[-1] (thus false negatives are given by tps[-1] - tps). thresholds : ndarray of shape (n_thresholds,) Decreasing score values.
_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 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 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 last precision and recall values are 1. and 0. respectively and do not have a corresponding threshold. This ensures that the graph starts on the y axis. The first precision and recall values are precision=class balance and recall=1.0 which corresponds to a classifier that always predicts the positive class. Read more in the :ref:`User Guide <precision_recall_f_measure_metrics>`. Parameters ---------- y_true : array-like of shape (n_samples,) True binary labels. If labels are not either {-1, 1} or {0, 1}, then pos_label should be explicitly given. y_score : array-like of shape (n_samples,) Target scores, can either be probability estimates of the positive class, or non-thresholded measure of decisions (as returned by `decision_function` on some classifiers). For :term:`decision_function` scores, values greater than or equal to zero should indicate the positive class. pos_label : int, float, bool or str, default=None The label of the positive class. When ``pos_label=None``, if y_true is in {-1, 1} or {0, 1}, ``pos_label`` is set to 1, otherwise an error will be raised. sample_weight : array-like of shape (n_samples,), default=None Sample weights. drop_intermediate : bool, default=False Whether to drop some suboptimal thresholds which would not appear on a plotted precision-recall curve. This is useful in order to create lighter precision-recall curves. .. versionadded:: 1.3 Returns ------- precision : ndarray of shape (n_thresholds + 1,) Precision values such that element i is the precision of predictions with score >= thresholds[i] and the last element is 1. recall : ndarray of shape (n_thresholds + 1,) Decreasing recall values such that element i is the recall of predictions with score >= thresholds[i] and the last element is 0. thresholds : ndarray of shape (n_thresholds,) Increasing thresholds on the decision function used to compute precision and recall where `n_thresholds = len(np.unique(y_score))`. See Also -------- PrecisionRecallDisplay.from_estimator : Plot Precision Recall Curve given a binary classifier. PrecisionRecallDisplay.from_predictions : Plot Precision Recall Curve using predictions from a binary classifier. average_precision_score : Compute average precision from prediction scores. det_curve: Compute error rates for different probability thresholds. roc_curve : Compute Receiver operating characteristic (ROC) curve. Examples -------- >>> import numpy as np >>> from sklearn.metrics import precision_recall_curve >>> y_true = np.array([0, 0, 1, 1]) >>> y_scores = np.array([0.1, 0.4, 0.35, 0.8]) >>> precision, recall, thresholds = precision_recall_curve( ... y_true, y_scores) >>> precision array([0.5 , 0.66666667, 0.5 , 1. , 1. ]) >>> recall array([1. , 1. , 0.5, 0.5, 0. ]) >>> thresholds array([0.1 , 0.35, 0.4 , 0.8 ]) """ fps, tps, thresholds = _binary_clf_curve( y_true, y_score, pos_label=pos_label, sample_weight=sample_weight ) if drop_intermediate and len(fps) > 2: # Drop thresholds corresponding to points where true positives (tps) # do not change from the previous or subsequent point. This will keep # only the first and last point for each tps value. All points # with the same tps value have the same recall and thus x coordinate. # They appear as a vertical line on the plot. optimal_idxs = np.where( np.concatenate( [[True], np.logical_or(np.diff(tps[:-1]), np.diff(tps[1:])), [True]] ) )[0] fps = fps[optimal_idxs] tps = tps[optimal_idxs] thresholds = thresholds[optimal_idxs] ps = tps + fps # Initialize the result array with zeros to make sure that precision[ps == 0] # does not contain uninitialized values. precision = np.zeros_like(tps) np.divide(tps, ps, out=precision, where=(ps != 0)) # When no positive label in y_true, recall is set to 1 for all thresholds # tps[-1] == 0 <=> y_true == all negative labels if tps[-1] == 0: warnings.warn( "No positive class found in y_true, " "recall is set to one for all thresholds." ) recall = np.ones_like(tps) else: recall = tps / tps[-1] # reverse the outputs so recall is decreasing sl = slice(None, None, -1) return np.hstack((precision[sl], 1)), np.hstack((recall[sl], 0)), thresholds[sl]
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 intuitively the ability of the classifier not to label as positive a sample that is negative. 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 last precision and recall values are 1. and 0. respectively and do not have a corresponding threshold. This ensures that the graph starts on the y axis. The first precision and recall values are precision=class balance and recall=1.0 which corresponds to a classifier that always predicts the positive class. Read more in the :ref:`User Guide <precision_recall_f_measure_metrics>`. Parameters ---------- y_true : array-like of shape (n_samples,) True binary labels. If labels are not either {-1, 1} or {0, 1}, then pos_label should be explicitly given. y_score : array-like of shape (n_samples,) Target scores, can either be probability estimates of the positive class, or non-thresholded measure of decisions (as returned by `decision_function` on some classifiers). For :term:`decision_function` scores, values greater than or equal to zero should indicate the positive class. pos_label : int, float, bool or str, default=None The label of the positive class. When ``pos_label=None``, if y_true is in {-1, 1} or {0, 1}, ``pos_label`` is set to 1, otherwise an error will be raised. sample_weight : array-like of shape (n_samples,), default=None Sample weights. drop_intermediate : bool, default=False Whether to drop some suboptimal thresholds which would not appear on a plotted precision-recall curve. This is useful in order to create lighter precision-recall curves. .. versionadded:: 1.3 Returns ------- precision : ndarray of shape (n_thresholds + 1,) Precision values such that element i is the precision of predictions with score >= thresholds[i] and the last element is 1. recall : ndarray of shape (n_thresholds + 1,) Decreasing recall values such that element i is the recall of predictions with score >= thresholds[i] and the last element is 0. thresholds : ndarray of shape (n_thresholds,) Increasing thresholds on the decision function used to compute precision and recall where `n_thresholds = len(np.unique(y_score))`. See Also -------- PrecisionRecallDisplay.from_estimator : Plot Precision Recall Curve given a binary classifier. PrecisionRecallDisplay.from_predictions : Plot Precision Recall Curve using predictions from a binary classifier. average_precision_score : Compute average precision from prediction scores. det_curve: Compute error rates for different probability thresholds. roc_curve : Compute Receiver operating characteristic (ROC) curve. Examples -------- >>> import numpy as np >>> from sklearn.metrics import precision_recall_curve >>> y_true = np.array([0, 0, 1, 1]) >>> y_scores = np.array([0.1, 0.4, 0.35, 0.8]) >>> precision, recall, thresholds = precision_recall_curve( ... y_true, y_scores) >>> precision array([0.5 , 0.66666667, 0.5 , 1. , 1. ]) >>> recall array([1. , 1. , 0.5, 0.5, 0. ]) >>> thresholds array([0.1 , 0.35, 0.4 , 0.8 ])
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 ---------- y_true : array-like of shape (n_samples,) True binary labels. If labels are not either {-1, 1} or {0, 1}, then pos_label should be explicitly given. y_score : array-like of shape (n_samples,) Target scores, can either be probability estimates of the positive class, confidence values, or non-thresholded measure of decisions (as returned by "decision_function" on some classifiers). For :term:`decision_function` scores, values greater than or equal to zero should indicate the positive class. pos_label : int, float, bool or str, default=None The label of the positive class. When ``pos_label=None``, if `y_true` is in {-1, 1} or {0, 1}, ``pos_label`` is set to 1, otherwise an error will be raised. sample_weight : array-like of shape (n_samples,), default=None Sample weights. drop_intermediate : bool, default=True Whether to drop thresholds where the resulting point is collinear with its neighbors in ROC space. This has no effect on the ROC AUC or visual shape of the curve, but reduces the number of plotted points. .. versionadded:: 0.17 parameter *drop_intermediate*. Returns ------- fpr : ndarray of shape (>2,) Increasing false positive rates such that element i is the false positive rate of predictions with score >= `thresholds[i]`. tpr : ndarray of shape (>2,) Increasing true positive rates such that element `i` is the true positive rate of predictions with score >= `thresholds[i]`. thresholds : ndarray of shape (n_thresholds,) Decreasing thresholds on the decision function used to compute fpr and tpr. The first threshold is set to `np.inf`. .. versionchanged:: 1.3 An arbitrary threshold at infinity (stored in `thresholds[0]`) is added to represent a classifier that always predicts the negative class, i.e. `fpr=0` and `tpr=0`. See Also -------- RocCurveDisplay.from_estimator : Plot Receiver Operating Characteristic (ROC) curve given an estimator and some data. RocCurveDisplay.from_predictions : Plot Receiver Operating Characteristic (ROC) curve given the true and predicted values. det_curve: Compute error rates for different probability thresholds. roc_auc_score : Compute the area under the ROC curve. Notes ----- Since the thresholds are sorted from low to high values, they are reversed upon returning them to ensure they correspond to both ``fpr`` and ``tpr``, which are sorted in reversed order during their calculation. References ---------- .. [1] `Wikipedia entry for the Receiver operating characteristic <https://en.wikipedia.org/wiki/Receiver_operating_characteristic>`_ .. [2] Fawcett T. An introduction to ROC analysis[J]. Pattern Recognition Letters, 2006, 27(8):861-874. Examples -------- >>> import numpy as np >>> from sklearn import metrics >>> y = np.array([1, 1, 2, 2]) >>> scores = np.array([0.1, 0.4, 0.35, 0.8]) >>> fpr, tpr, thresholds = metrics.roc_curve(y, scores, pos_label=2) >>> fpr array([0. , 0. , 0.5, 0.5, 1. ]) >>> tpr array([0. , 0.5, 0.5, 1. , 1. ]) >>> thresholds array([ inf, 0.8 , 0.4 , 0.35, 0.1 ]) """ fps, tps, thresholds = _binary_clf_curve( y_true, y_score, pos_label=pos_label, sample_weight=sample_weight ) # Attempt to drop thresholds corresponding to points in between and # collinear with other points. These are always suboptimal and do not # appear on a plotted ROC curve (and thus do not affect the AUC). # Here np.diff(_, 2) is used as a "second derivative" to tell if there # is a corner at the point. Both fps and tps must be tested to handle # thresholds with multiple data points (which are combined in # _binary_clf_curve). This keeps all cases where the point should be kept, # but does not drop more complicated cases like fps = [1, 3, 7], # tps = [1, 2, 4]; there is no harm in keeping too many thresholds. if drop_intermediate and len(fps) > 2: optimal_idxs = np.where( np.r_[True, np.logical_or(np.diff(fps, 2), np.diff(tps, 2)), True] )[0] fps = fps[optimal_idxs] tps = tps[optimal_idxs] thresholds = thresholds[optimal_idxs] # Add an extra threshold position # to make sure that the curve starts at (0, 0) tps = np.r_[0, tps] fps = np.r_[0, fps] # get dtype of `y_score` even if it is an array-like thresholds = np.r_[np.inf, thresholds] if fps[-1] <= 0: warnings.warn( "No negative samples in y_true, false positive value should be meaningless", UndefinedMetricWarning, ) fpr = np.repeat(np.nan, fps.shape) else: fpr = fps / fps[-1] if tps[-1] <= 0: warnings.warn( "No positive samples in y_true, true positive value should be meaningless", UndefinedMetricWarning, ) tpr = np.repeat(np.nan, tps.shape) else: tpr = tps / tps[-1] return fpr, tpr, thresholds
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} or {0, 1}, then pos_label should be explicitly given. y_score : array-like of shape (n_samples,) Target scores, can either be probability estimates of the positive class, confidence values, or non-thresholded measure of decisions (as returned by "decision_function" on some classifiers). For :term:`decision_function` scores, values greater than or equal to zero should indicate the positive class. pos_label : int, float, bool or str, default=None The label of the positive class. When ``pos_label=None``, if `y_true` is in {-1, 1} or {0, 1}, ``pos_label`` is set to 1, otherwise an error will be raised. sample_weight : array-like of shape (n_samples,), default=None Sample weights. drop_intermediate : bool, default=True Whether to drop thresholds where the resulting point is collinear with its neighbors in ROC space. This has no effect on the ROC AUC or visual shape of the curve, but reduces the number of plotted points. .. versionadded:: 0.17 parameter *drop_intermediate*. Returns ------- fpr : ndarray of shape (>2,) Increasing false positive rates such that element i is the false positive rate of predictions with score >= `thresholds[i]`. tpr : ndarray of shape (>2,) Increasing true positive rates such that element `i` is the true positive rate of predictions with score >= `thresholds[i]`. thresholds : ndarray of shape (n_thresholds,) Decreasing thresholds on the decision function used to compute fpr and tpr. The first threshold is set to `np.inf`. .. versionchanged:: 1.3 An arbitrary threshold at infinity (stored in `thresholds[0]`) is added to represent a classifier that always predicts the negative class, i.e. `fpr=0` and `tpr=0`. See Also -------- RocCurveDisplay.from_estimator : Plot Receiver Operating Characteristic (ROC) curve given an estimator and some data. RocCurveDisplay.from_predictions : Plot Receiver Operating Characteristic (ROC) curve given the true and predicted values. det_curve: Compute error rates for different probability thresholds. roc_auc_score : Compute the area under the ROC curve. Notes ----- Since the thresholds are sorted from low to high values, they are reversed upon returning them to ensure they correspond to both ``fpr`` and ``tpr``, which are sorted in reversed order during their calculation. References ---------- .. [1] `Wikipedia entry for the Receiver operating characteristic <https://en.wikipedia.org/wiki/Receiver_operating_characteristic>`_ .. [2] Fawcett T. An introduction to ROC analysis[J]. Pattern Recognition Letters, 2006, 27(8):861-874. Examples -------- >>> import numpy as np >>> from sklearn import metrics >>> y = np.array([1, 1, 2, 2]) >>> scores = np.array([0.1, 0.4, 0.35, 0.8]) >>> fpr, tpr, thresholds = metrics.roc_curve(y, scores, pos_label=2) >>> fpr array([0. , 0. , 0.5, 0.5, 1. ]) >>> tpr array([0. , 0.5, 0.5, 1. , 1. ]) >>> thresholds array([ inf, 0.8 , 0.4 , 0.35, 0.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 metric is used in multilabel ranking problem, where the goal is to give better rank to the labels associated to each sample. The obtained score is always strictly greater than 0 and the best value is 1. Read more in the :ref:`User Guide <label_ranking_average_precision>`. Parameters ---------- y_true : {array-like, sparse matrix} of shape (n_samples, n_labels) True binary labels in binary indicator format. y_score : array-like of shape (n_samples, n_labels) Target scores, can either be probability estimates of the positive class, confidence values, or non-thresholded measure of decisions (as returned by "decision_function" on some classifiers). For :term:`decision_function` scores, values greater than or equal to zero should indicate the positive class. sample_weight : array-like of shape (n_samples,), default=None Sample weights. .. versionadded:: 0.20 Returns ------- score : float Ranking-based average precision score. Examples -------- >>> import numpy as np >>> from sklearn.metrics import label_ranking_average_precision_score >>> y_true = np.array([[1, 0, 0], [0, 0, 1]]) >>> y_score = np.array([[0.75, 0.5, 1], [1, 0.2, 0.1]]) >>> label_ranking_average_precision_score(y_true, y_score) 0.416 """ check_consistent_length(y_true, y_score, sample_weight) y_true = check_array(y_true, ensure_2d=False, accept_sparse="csr") y_score = check_array(y_score, ensure_2d=False) if y_true.shape != y_score.shape: raise ValueError("y_true and y_score have different shape") # Handle badly formatted array and the degenerate case with one label y_type = type_of_target(y_true, input_name="y_true") if y_type != "multilabel-indicator" and not ( y_type == "binary" and y_true.ndim == 2 ): raise ValueError("{0} format is not supported".format(y_type)) if not issparse(y_true): y_true = csr_matrix(y_true) y_score = -y_score n_samples, n_labels = y_true.shape out = 0.0 for i, (start, stop) in enumerate(zip(y_true.indptr, y_true.indptr[1:])): relevant = y_true.indices[start:stop] if relevant.size == 0 or relevant.size == n_labels: # If all labels are relevant or unrelevant, the score is also # equal to 1. The label ranking has no meaning. aux = 1.0 else: scores_i = y_score[i] rank = rankdata(scores_i, "max")[relevant] L = rankdata(scores_i[relevant], "max") aux = (L / rank).mean() if sample_weight is not None: aux = aux * sample_weight[i] out += aux if sample_weight is None: out /= n_samples else: out /= np.sum(sample_weight) return float(out)
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 the labels associated to each sample. The obtained score is always strictly greater than 0 and the best value is 1. Read more in the :ref:`User Guide <label_ranking_average_precision>`. Parameters ---------- y_true : {array-like, sparse matrix} of shape (n_samples, n_labels) True binary labels in binary indicator format. y_score : array-like of shape (n_samples, n_labels) Target scores, can either be probability estimates of the positive class, confidence values, or non-thresholded measure of decisions (as returned by "decision_function" on some classifiers). For :term:`decision_function` scores, values greater than or equal to zero should indicate the positive class. sample_weight : array-like of shape (n_samples,), default=None Sample weights. .. versionadded:: 0.20 Returns ------- score : float Ranking-based average precision score. Examples -------- >>> import numpy as np >>> from sklearn.metrics import label_ranking_average_precision_score >>> y_true = np.array([[1, 0, 0], [0, 0, 1]]) >>> y_score = np.array([[0.75, 0.5, 1], [1, 0.2, 0.1]]) >>> label_ranking_average_precision_score(y_true, y_score) 0.416
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 maximal rank that would have been assigned to all tied values. Note: Our implementation's score is 1 greater than the one given in Tsoumakas et al., 2010. This extends it to handle the degenerate case in which an instance has 0 true labels. Read more in the :ref:`User Guide <coverage_error>`. Parameters ---------- y_true : array-like of shape (n_samples, n_labels) True binary labels in binary indicator format. y_score : array-like of shape (n_samples, n_labels) Target scores, can either be probability estimates of the positive class, confidence values, or non-thresholded measure of decisions (as returned by "decision_function" on some classifiers). For :term:`decision_function` scores, values greater than or equal to zero should indicate the positive class. sample_weight : array-like of shape (n_samples,), default=None Sample weights. Returns ------- coverage_error : float The coverage error. References ---------- .. [1] Tsoumakas, G., Katakis, I., & Vlahavas, I. (2010). Mining multi-label data. In Data mining and knowledge discovery handbook (pp. 667-685). Springer US. Examples -------- >>> from sklearn.metrics import coverage_error >>> y_true = [[1, 0, 0], [0, 1, 1]] >>> y_score = [[1, 0, 0], [0, 1, 1]] >>> coverage_error(y_true, y_score) 1.5 """ y_true = check_array(y_true, ensure_2d=True) y_score = check_array(y_score, ensure_2d=True) check_consistent_length(y_true, y_score, sample_weight) y_type = type_of_target(y_true, input_name="y_true") if y_type != "multilabel-indicator": raise ValueError("{0} format is not supported".format(y_type)) if y_true.shape != y_score.shape: raise ValueError("y_true and y_score have different shape") y_score_mask = np.ma.masked_array(y_score, mask=np.logical_not(y_true)) y_min_relevant = y_score_mask.min(axis=1).reshape((-1, 1)) coverage = (y_score >= y_min_relevant).sum(axis=1) coverage = coverage.filled(0) return float(np.average(coverage, weights=sample_weight))
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. Note: Our implementation's score is 1 greater than the one given in Tsoumakas et al., 2010. This extends it to handle the degenerate case in which an instance has 0 true labels. Read more in the :ref:`User Guide <coverage_error>`. Parameters ---------- y_true : array-like of shape (n_samples, n_labels) True binary labels in binary indicator format. y_score : array-like of shape (n_samples, n_labels) Target scores, can either be probability estimates of the positive class, confidence values, or non-thresholded measure of decisions (as returned by "decision_function" on some classifiers). For :term:`decision_function` scores, values greater than or equal to zero should indicate the positive class. sample_weight : array-like of shape (n_samples,), default=None Sample weights. Returns ------- coverage_error : float The coverage error. References ---------- .. [1] Tsoumakas, G., Katakis, I., & Vlahavas, I. (2010). Mining multi-label data. In Data mining and knowledge discovery handbook (pp. 667-685). Springer US. Examples -------- >>> from sklearn.metrics import coverage_error >>> y_true = [[1, 0, 0], [0, 1, 1]] >>> y_score = [[1, 0, 0], [0, 1, 1]] >>> coverage_error(y_true, y_score) 1.5
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 set size, but weighted by the number of relevant and irrelevant labels. The best performance is achieved with a ranking loss of zero. Read more in the :ref:`User Guide <label_ranking_loss>`. .. versionadded:: 0.17 A function *label_ranking_loss* Parameters ---------- y_true : {array-like, sparse matrix} of shape (n_samples, n_labels) True binary labels in binary indicator format. y_score : array-like of shape (n_samples, n_labels) Target scores, can either be probability estimates of the positive class, confidence values, or non-thresholded measure of decisions (as returned by "decision_function" on some classifiers). For :term:`decision_function` scores, values greater than or equal to zero should indicate the positive class. sample_weight : array-like of shape (n_samples,), default=None Sample weights. Returns ------- loss : float 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. References ---------- .. [1] Tsoumakas, G., Katakis, I., & Vlahavas, I. (2010). Mining multi-label data. In Data mining and knowledge discovery handbook (pp. 667-685). Springer US. Examples -------- >>> from sklearn.metrics import label_ranking_loss >>> y_true = [[1, 0, 0], [0, 0, 1]] >>> y_score = [[0.75, 0.5, 1], [1, 0.2, 0.1]] >>> label_ranking_loss(y_true, y_score) 0.75 """ y_true = check_array(y_true, ensure_2d=False, accept_sparse="csr") y_score = check_array(y_score, ensure_2d=False) check_consistent_length(y_true, y_score, sample_weight) y_type = type_of_target(y_true, input_name="y_true") if y_type not in ("multilabel-indicator",): raise ValueError("{0} format is not supported".format(y_type)) if y_true.shape != y_score.shape: raise ValueError("y_true and y_score have different shape") n_samples, n_labels = y_true.shape y_true = csr_matrix(y_true) loss = np.zeros(n_samples) for i, (start, stop) in enumerate(zip(y_true.indptr, y_true.indptr[1:])): # Sort and bin the label scores unique_scores, unique_inverse = np.unique(y_score[i], return_inverse=True) true_at_reversed_rank = np.bincount( unique_inverse[y_true.indices[start:stop]], minlength=len(unique_scores) ) all_at_reversed_rank = np.bincount(unique_inverse, minlength=len(unique_scores)) false_at_reversed_rank = all_at_reversed_rank - true_at_reversed_rank # if the scores are ordered, it's possible to count the number of # incorrectly ordered paires in linear time by cumulatively counting # how many false labels of a given score have a score higher than the # accumulated true labels with lower score. loss[i] = np.dot(true_at_reversed_rank.cumsum(), false_at_reversed_rank) n_positives = count_nonzero(y_true, axis=1) with np.errstate(divide="ignore", invalid="ignore"): loss /= (n_labels - n_positives) * n_positives # When there is no positive or no negative labels, those values should # be consider as correct, i.e. the ranking doesn't matter. loss[np.logical_or(n_positives == 0, n_positives == n_labels)] = 0.0 return float(np.average(loss, weights=sample_weight))
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 labels. The best performance is achieved with a ranking loss of zero. Read more in the :ref:`User Guide <label_ranking_loss>`. .. versionadded:: 0.17 A function *label_ranking_loss* Parameters ---------- y_true : {array-like, sparse matrix} of shape (n_samples, n_labels) True binary labels in binary indicator format. y_score : array-like of shape (n_samples, n_labels) Target scores, can either be probability estimates of the positive class, confidence values, or non-thresholded measure of decisions (as returned by "decision_function" on some classifiers). For :term:`decision_function` scores, values greater than or equal to zero should indicate the positive class. sample_weight : array-like of shape (n_samples,), default=None Sample weights. Returns ------- loss : float 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. References ---------- .. [1] Tsoumakas, G., Katakis, I., & Vlahavas, I. (2010). Mining multi-label data. In Data mining and knowledge discovery handbook (pp. 667-685). Springer US. Examples -------- >>> from sklearn.metrics import label_ranking_loss >>> y_true = [[1, 0, 0], [0, 0, 1]] >>> y_score = [[0.75, 0.5, 1], [1, 0.2, 0.1]] >>> label_ranking_loss(y_true, y_score) 0.75
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 by ``y_score``. Parameters ---------- y_true : ndarray of shape (n_samples, n_labels) True targets of multilabel classification, or true scores of entities to be ranked. y_score : ndarray of shape (n_samples, n_labels) Target scores, can either be probability estimates, confidence values, or non-thresholded measure of decisions (as returned by "decision_function" on some classifiers). k : int, default=None Only consider the highest k scores in the ranking. If `None`, use all outputs. log_base : float, default=2 Base of the logarithm used for the discount. A low value means a sharper discount (top results are more important). ignore_ties : bool, default=False Assume that there are no ties in y_score (which is likely to be the case if y_score is continuous) for efficiency gains. Returns ------- discounted_cumulative_gain : ndarray of shape (n_samples,) The DCG score for each sample. See Also -------- ndcg_score : The Discounted Cumulative Gain divided by the Ideal Discounted Cumulative Gain (the DCG obtained for a perfect ranking), in order to have a score between 0 and 1. """ discount = 1 / (np.log(np.arange(y_true.shape[1]) + 2) / np.log(log_base)) if k is not None: discount[k:] = 0 if ignore_ties: ranking = np.argsort(y_score)[:, ::-1] ranked = y_true[np.arange(ranking.shape[0])[:, np.newaxis], ranking] cumulative_gains = discount.dot(ranked.T) else: discount_cumsum = np.cumsum(discount) cumulative_gains = [ _tie_averaged_dcg(y_t, y_s, discount_cumsum) for y_t, y_s in zip(y_true, y_score) ] cumulative_gains = np.asarray(cumulative_gains) return cumulative_gains
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_samples, n_labels) True targets of multilabel classification, or true scores of entities to be ranked. y_score : ndarray of shape (n_samples, n_labels) Target scores, can either be probability estimates, confidence values, or non-thresholded measure of decisions (as returned by "decision_function" on some classifiers). k : int, default=None Only consider the highest k scores in the ranking. If `None`, use all outputs. log_base : float, default=2 Base of the logarithm used for the discount. A low value means a sharper discount (top results are more important). ignore_ties : bool, default=False Assume that there are no ties in y_score (which is likely to be the case if y_score is continuous) for efficiency gains. Returns ------- discounted_cumulative_gain : ndarray of shape (n_samples,) The DCG score for each sample. See Also -------- ndcg_score : The Discounted Cumulative Gain divided by the Ideal Discounted Cumulative Gain (the DCG obtained for a perfect ranking), in order to have a score between 0 and 1.
_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 group is then the average `y_true` within this group times the sum of discounts of the corresponding ranks. This amounts to averaging scores for all possible orderings of the tied groups. (note in the case of dcg@k the discount is 0 after index k) Parameters ---------- y_true : ndarray The true relevance scores. y_score : ndarray Predicted scores. discount_cumsum : ndarray Precomputed cumulative sum of the discounts. Returns ------- discounted_cumulative_gain : float The discounted cumulative gain. References ---------- McSherry, F., & Najork, M. (2008, March). Computing information retrieval performance measures efficiently in the presence of tied scores. In European conference on information retrieval (pp. 414-421). Springer, Berlin, Heidelberg. """ _, inv, counts = np.unique(-y_score, return_inverse=True, return_counts=True) ranked = np.zeros(len(counts)) np.add.at(ranked, inv, y_true) ranked /= counts groups = np.cumsum(counts) - 1 discount_sums = np.empty(len(counts)) discount_sums[0] = discount_cumsum[groups[0]] discount_sums[1:] = np.diff(discount_cumsum[groups]) return (ranked * discount_sums).sum()
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 the sum of discounts of the corresponding ranks. This amounts to averaging scores for all possible orderings of the tied groups. (note in the case of dcg@k the discount is 0 after index k) Parameters ---------- y_true : ndarray The true relevance scores. y_score : ndarray Predicted scores. discount_cumsum : ndarray Precomputed cumulative sum of the discounts. Returns ------- discounted_cumulative_gain : float The discounted cumulative gain. References ---------- McSherry, F., & Najork, M. (2008, March). Computing information retrieval performance measures efficiently in the presence of tied scores. In European conference on information retrieval (pp. 414-421). Springer, Berlin, Heidelberg.
_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 labels are ranked high by ``y_score``. Usually the Normalized Discounted Cumulative Gain (NDCG, computed by ndcg_score) is preferred. Parameters ---------- y_true : array-like of shape (n_samples, n_labels) True targets of multilabel classification, or true scores of entities to be ranked. y_score : array-like of shape (n_samples, n_labels) Target scores, can either be probability estimates, confidence values, or non-thresholded measure of decisions (as returned by "decision_function" on some classifiers). k : int, default=None Only consider the highest k scores in the ranking. If None, use all outputs. log_base : float, default=2 Base of the logarithm used for the discount. A low value means a sharper discount (top results are more important). sample_weight : array-like of shape (n_samples,), default=None Sample weights. If `None`, all samples are given the same weight. ignore_ties : bool, default=False Assume that there are no ties in y_score (which is likely to be the case if y_score is continuous) for efficiency gains. Returns ------- discounted_cumulative_gain : float The averaged sample DCG scores. See Also -------- ndcg_score : The Discounted Cumulative Gain divided by the Ideal Discounted Cumulative Gain (the DCG obtained for a perfect ranking), in order to have a score between 0 and 1. References ---------- `Wikipedia entry for Discounted Cumulative Gain <https://en.wikipedia.org/wiki/Discounted_cumulative_gain>`_. Jarvelin, K., & Kekalainen, J. (2002). Cumulated gain-based evaluation of IR techniques. ACM Transactions on Information Systems (TOIS), 20(4), 422-446. Wang, Y., Wang, L., Li, Y., He, D., Chen, W., & Liu, T. Y. (2013, May). A theoretical analysis of NDCG ranking measures. In Proceedings of the 26th Annual Conference on Learning Theory (COLT 2013). McSherry, F., & Najork, M. (2008, March). Computing information retrieval performance measures efficiently in the presence of tied scores. In European conference on information retrieval (pp. 414-421). Springer, Berlin, Heidelberg. Examples -------- >>> import numpy as np >>> from sklearn.metrics import dcg_score >>> # we have ground-truth relevance of some answers to a query: >>> true_relevance = np.asarray([[10, 0, 0, 1, 5]]) >>> # we predict scores for the answers >>> scores = np.asarray([[.1, .2, .3, 4, 70]]) >>> dcg_score(true_relevance, scores) 9.49 >>> # we can set k to truncate the sum; only top k answers contribute >>> dcg_score(true_relevance, scores, k=2) 5.63 >>> # now we have some ties in our prediction >>> scores = np.asarray([[1, 0, 0, 0, 1]]) >>> # by default ties are averaged, so here we get the average true >>> # relevance of our top predictions: (10 + 5) / 2 = 7.5 >>> dcg_score(true_relevance, scores, k=1) 7.5 >>> # we can choose to ignore ties for faster results, but only >>> # if we know there aren't ties in our scores, otherwise we get >>> # wrong results: >>> dcg_score(true_relevance, ... scores, k=1, ignore_ties=True) 5.0 """ y_true = check_array(y_true, ensure_2d=False) y_score = check_array(y_score, ensure_2d=False) check_consistent_length(y_true, y_score, sample_weight) _check_dcg_target_type(y_true) return float( np.average( _dcg_sample_scores( y_true, y_score, k=k, log_base=log_base, ignore_ties=ignore_ties ), weights=sample_weight, ) )
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, computed by ndcg_score) is preferred. Parameters ---------- y_true : array-like of shape (n_samples, n_labels) True targets of multilabel classification, or true scores of entities to be ranked. y_score : array-like of shape (n_samples, n_labels) Target scores, can either be probability estimates, confidence values, or non-thresholded measure of decisions (as returned by "decision_function" on some classifiers). k : int, default=None Only consider the highest k scores in the ranking. If None, use all outputs. log_base : float, default=2 Base of the logarithm used for the discount. A low value means a sharper discount (top results are more important). sample_weight : array-like of shape (n_samples,), default=None Sample weights. If `None`, all samples are given the same weight. ignore_ties : bool, default=False Assume that there are no ties in y_score (which is likely to be the case if y_score is continuous) for efficiency gains. Returns ------- discounted_cumulative_gain : float The averaged sample DCG scores. See Also -------- ndcg_score : The Discounted Cumulative Gain divided by the Ideal Discounted Cumulative Gain (the DCG obtained for a perfect ranking), in order to have a score between 0 and 1. References ---------- `Wikipedia entry for Discounted Cumulative Gain <https://en.wikipedia.org/wiki/Discounted_cumulative_gain>`_. Jarvelin, K., & Kekalainen, J. (2002). Cumulated gain-based evaluation of IR techniques. ACM Transactions on Information Systems (TOIS), 20(4), 422-446. Wang, Y., Wang, L., Li, Y., He, D., Chen, W., & Liu, T. Y. (2013, May). A theoretical analysis of NDCG ranking measures. In Proceedings of the 26th Annual Conference on Learning Theory (COLT 2013). McSherry, F., & Najork, M. (2008, March). Computing information retrieval performance measures efficiently in the presence of tied scores. In European conference on information retrieval (pp. 414-421). Springer, Berlin, Heidelberg. Examples -------- >>> import numpy as np >>> from sklearn.metrics import dcg_score >>> # we have ground-truth relevance of some answers to a query: >>> true_relevance = np.asarray([[10, 0, 0, 1, 5]]) >>> # we predict scores for the answers >>> scores = np.asarray([[.1, .2, .3, 4, 70]]) >>> dcg_score(true_relevance, scores) 9.49 >>> # we can set k to truncate the sum; only top k answers contribute >>> dcg_score(true_relevance, scores, k=2) 5.63 >>> # now we have some ties in our prediction >>> scores = np.asarray([[1, 0, 0, 0, 1]]) >>> # by default ties are averaged, so here we get the average true >>> # relevance of our top predictions: (10 + 5) / 2 = 7.5 >>> dcg_score(true_relevance, scores, k=1) 7.5 >>> # we can choose to ignore ties for faster results, but only >>> # if we know there aren't ties in our scores, otherwise we get >>> # wrong results: >>> dcg_score(true_relevance, ... scores, k=1, ignore_ties=True) 5.0
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 perfect ranking) to obtain a score between 0 and 1. This ranking metric yields a high value if true labels are ranked high by ``y_score``. Parameters ---------- y_true : ndarray of shape (n_samples, n_labels) True targets of multilabel classification, or true scores of entities to be ranked. y_score : ndarray of shape (n_samples, n_labels) Target scores, can either be probability estimates, confidence values, or non-thresholded measure of decisions (as returned by "decision_function" on some classifiers). k : int, default=None Only consider the highest k scores in the ranking. If None, use all outputs. ignore_ties : bool, default=False Assume that there are no ties in y_score (which is likely to be the case if y_score is continuous) for efficiency gains. Returns ------- normalized_discounted_cumulative_gain : ndarray of shape (n_samples,) The NDCG score for each sample (float in [0., 1.]). See Also -------- dcg_score : Discounted Cumulative Gain (not normalized). """ gain = _dcg_sample_scores(y_true, y_score, k, ignore_ties=ignore_ties) # Here we use the order induced by y_true so we can ignore ties since # the gain associated to tied indices is the same (permuting ties doesn't # change the value of the re-ordered y_true) normalizing_gain = _dcg_sample_scores(y_true, y_true, k, ignore_ties=True) all_irrelevant = normalizing_gain == 0 gain[all_irrelevant] = 0 gain[~all_irrelevant] /= normalizing_gain[~all_irrelevant] return gain
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 yields a high value if true labels are ranked high by ``y_score``. Parameters ---------- y_true : ndarray of shape (n_samples, n_labels) True targets of multilabel classification, or true scores of entities to be ranked. y_score : ndarray of shape (n_samples, n_labels) Target scores, can either be probability estimates, confidence values, or non-thresholded measure of decisions (as returned by "decision_function" on some classifiers). k : int, default=None Only consider the highest k scores in the ranking. If None, use all outputs. ignore_ties : bool, default=False Assume that there are no ties in y_score (which is likely to be the case if y_score is continuous) for efficiency gains. Returns ------- normalized_discounted_cumulative_gain : ndarray of shape (n_samples,) The NDCG score for each sample (float in [0., 1.]). See Also -------- dcg_score : Discounted Cumulative Gain (not normalized).
_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, obtained for a perfect ranking) to obtain a score between 0 and 1. This ranking metric returns a high value if true labels are ranked high by ``y_score``. Parameters ---------- y_true : array-like of shape (n_samples, n_labels) True targets of multilabel classification, or true scores of entities to be ranked. Negative values in `y_true` may result in an output that is not between 0 and 1. y_score : array-like of shape (n_samples, n_labels) Target scores, can either be probability estimates, confidence values, or non-thresholded measure of decisions (as returned by "decision_function" on some classifiers). k : int, default=None Only consider the highest k scores in the ranking. If `None`, use all outputs. sample_weight : array-like of shape (n_samples,), default=None Sample weights. If `None`, all samples are given the same weight. ignore_ties : bool, default=False Assume that there are no ties in y_score (which is likely to be the case if y_score is continuous) for efficiency gains. Returns ------- normalized_discounted_cumulative_gain : float in [0., 1.] The averaged NDCG scores for all samples. See Also -------- dcg_score : Discounted Cumulative Gain (not normalized). References ---------- `Wikipedia entry for Discounted Cumulative Gain <https://en.wikipedia.org/wiki/Discounted_cumulative_gain>`_ Jarvelin, K., & Kekalainen, J. (2002). Cumulated gain-based evaluation of IR techniques. ACM Transactions on Information Systems (TOIS), 20(4), 422-446. Wang, Y., Wang, L., Li, Y., He, D., Chen, W., & Liu, T. Y. (2013, May). A theoretical analysis of NDCG ranking measures. In Proceedings of the 26th Annual Conference on Learning Theory (COLT 2013) McSherry, F., & Najork, M. (2008, March). Computing information retrieval performance measures efficiently in the presence of tied scores. In European conference on information retrieval (pp. 414-421). Springer, Berlin, Heidelberg. Examples -------- >>> import numpy as np >>> from sklearn.metrics import ndcg_score >>> # we have ground-truth relevance of some answers to a query: >>> true_relevance = np.asarray([[10, 0, 0, 1, 5]]) >>> # we predict some scores (relevance) for the answers >>> scores = np.asarray([[.1, .2, .3, 4, 70]]) >>> ndcg_score(true_relevance, scores) 0.69 >>> scores = np.asarray([[.05, 1.1, 1., .5, .0]]) >>> ndcg_score(true_relevance, scores) 0.49 >>> # we can set k to truncate the sum; only top k answers contribute. >>> ndcg_score(true_relevance, scores, k=4) 0.35 >>> # the normalization takes k into account so a perfect answer >>> # would still get 1.0 >>> ndcg_score(true_relevance, true_relevance, k=4) 1.0... >>> # now we have some ties in our prediction >>> scores = np.asarray([[1, 0, 0, 0, 1]]) >>> # by default ties are averaged, so here we get the average (normalized) >>> # true relevance of our top predictions: (10 / 10 + 5 / 10) / 2 = .75 >>> ndcg_score(true_relevance, scores, k=1) 0.75 >>> # we can choose to ignore ties for faster results, but only >>> # if we know there aren't ties in our scores, otherwise we get >>> # wrong results: >>> ndcg_score(true_relevance, ... scores, k=1, ignore_ties=True) 0.5... """ y_true = check_array(y_true, ensure_2d=False) y_score = check_array(y_score, ensure_2d=False) check_consistent_length(y_true, y_score, sample_weight) if y_true.min() < 0: raise ValueError("ndcg_score should not be used on negative y_true values.") if y_true.ndim > 1 and y_true.shape[1] <= 1: raise ValueError( "Computing NDCG is only meaningful when there is more than 1 document. " f"Got {y_true.shape[1]} instead." ) _check_dcg_target_type(y_true) gain = _ndcg_sample_scores(y_true, y_score, k=k, ignore_ties=ignore_ties) return float(np.average(gain, weights=sample_weight))
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 returns a high value if true labels are ranked high by ``y_score``. Parameters ---------- y_true : array-like of shape (n_samples, n_labels) True targets of multilabel classification, or true scores of entities to be ranked. Negative values in `y_true` may result in an output that is not between 0 and 1. y_score : array-like of shape (n_samples, n_labels) Target scores, can either be probability estimates, confidence values, or non-thresholded measure of decisions (as returned by "decision_function" on some classifiers). k : int, default=None Only consider the highest k scores in the ranking. If `None`, use all outputs. sample_weight : array-like of shape (n_samples,), default=None Sample weights. If `None`, all samples are given the same weight. ignore_ties : bool, default=False Assume that there are no ties in y_score (which is likely to be the case if y_score is continuous) for efficiency gains. Returns ------- normalized_discounted_cumulative_gain : float in [0., 1.] The averaged NDCG scores for all samples. See Also -------- dcg_score : Discounted Cumulative Gain (not normalized). References ---------- `Wikipedia entry for Discounted Cumulative Gain <https://en.wikipedia.org/wiki/Discounted_cumulative_gain>`_ Jarvelin, K., & Kekalainen, J. (2002). Cumulated gain-based evaluation of IR techniques. ACM Transactions on Information Systems (TOIS), 20(4), 422-446. Wang, Y., Wang, L., Li, Y., He, D., Chen, W., & Liu, T. Y. (2013, May). A theoretical analysis of NDCG ranking measures. In Proceedings of the 26th Annual Conference on Learning Theory (COLT 2013) McSherry, F., & Najork, M. (2008, March). Computing information retrieval performance measures efficiently in the presence of tied scores. In European conference on information retrieval (pp. 414-421). Springer, Berlin, Heidelberg. Examples -------- >>> import numpy as np >>> from sklearn.metrics import ndcg_score >>> # we have ground-truth relevance of some answers to a query: >>> true_relevance = np.asarray([[10, 0, 0, 1, 5]]) >>> # we predict some scores (relevance) for the answers >>> scores = np.asarray([[.1, .2, .3, 4, 70]]) >>> ndcg_score(true_relevance, scores) 0.69 >>> scores = np.asarray([[.05, 1.1, 1., .5, .0]]) >>> ndcg_score(true_relevance, scores) 0.49 >>> # we can set k to truncate the sum; only top k answers contribute. >>> ndcg_score(true_relevance, scores, k=4) 0.35 >>> # the normalization takes k into account so a perfect answer >>> # would still get 1.0 >>> ndcg_score(true_relevance, true_relevance, k=4) 1.0... >>> # now we have some ties in our prediction >>> scores = np.asarray([[1, 0, 0, 0, 1]]) >>> # by default ties are averaged, so here we get the average (normalized) >>> # true relevance of our top predictions: (10 / 10 + 5 / 10) / 2 = .75 >>> ndcg_score(true_relevance, scores, k=1) 0.75 >>> # we can choose to ignore ties for faster results, but only >>> # if we know there aren't ties in our scores, otherwise we get >>> # wrong results: >>> ndcg_score(true_relevance, ... scores, k=1, ignore_ties=True) 0.5...
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 case isn't covered here. Read more in the :ref:`User Guide <top_k_accuracy_score>` Parameters ---------- y_true : array-like of shape (n_samples,) True labels. y_score : array-like of shape (n_samples,) or (n_samples, n_classes) Target scores. These can be either probability estimates or non-thresholded decision values (as returned by :term:`decision_function` on some classifiers). The binary case expects scores with shape (n_samples,) while the multiclass case expects scores with shape (n_samples, n_classes). In the multiclass case, the order of the class scores must correspond to the order of ``labels``, if provided, or else to the numerical or lexicographical order of the labels in ``y_true``. If ``y_true`` does not contain all the labels, ``labels`` must be provided. k : int, default=2 Number of most likely outcomes considered to find the correct label. normalize : bool, default=True If `True`, return the fraction of correctly classified samples. Otherwise, return the number of correctly classified samples. sample_weight : array-like of shape (n_samples,), default=None Sample weights. If `None`, all samples are given the same weight. labels : array-like of shape (n_classes,), default=None Multiclass only. List of labels that index the classes in ``y_score``. If ``None``, the numerical or lexicographical order of the labels in ``y_true`` is used. If ``y_true`` does not contain all the labels, ``labels`` must be provided. Returns ------- score : float The top-k accuracy score. The best performance is 1 with `normalize == True` and the number of samples with `normalize == False`. See Also -------- accuracy_score : Compute the accuracy score. By default, the function will return the fraction of correct predictions divided by the total number of predictions. Notes ----- In cases where two or more labels are assigned equal predicted scores, the labels with the highest indices will be chosen first. This might impact the result if the correct label falls after the threshold because of that. Examples -------- >>> import numpy as np >>> from sklearn.metrics import top_k_accuracy_score >>> y_true = np.array([0, 1, 2, 2]) >>> y_score = np.array([[0.5, 0.2, 0.2], # 0 is in top 2 ... [0.3, 0.4, 0.2], # 1 is in top 2 ... [0.2, 0.4, 0.3], # 2 is in top 2 ... [0.7, 0.2, 0.1]]) # 2 isn't in top 2 >>> top_k_accuracy_score(y_true, y_score, k=2) 0.75 >>> # Not normalizing gives the number of "correctly" classified samples >>> top_k_accuracy_score(y_true, y_score, k=2, normalize=False) 3.0 """ y_true = check_array(y_true, ensure_2d=False, dtype=None) y_true = column_or_1d(y_true) y_type = type_of_target(y_true, input_name="y_true") if y_type == "binary" and labels is not None and len(labels) > 2: y_type = "multiclass" if y_type not in {"binary", "multiclass"}: raise ValueError( f"y type must be 'binary' or 'multiclass', got '{y_type}' instead." ) y_score = check_array(y_score, ensure_2d=False) if y_type == "binary": if y_score.ndim == 2 and y_score.shape[1] != 1: raise ValueError( "`y_true` is binary while y_score is 2d with" f" {y_score.shape[1]} classes. If `y_true` does not contain all the" " labels, `labels` must be provided." ) y_score = column_or_1d(y_score) check_consistent_length(y_true, y_score, sample_weight) y_score_n_classes = y_score.shape[1] if y_score.ndim == 2 else 2 if labels is None: classes = _unique(y_true) n_classes = len(classes) if n_classes != y_score_n_classes: raise ValueError( f"Number of classes in 'y_true' ({n_classes}) not equal " f"to the number of classes in 'y_score' ({y_score_n_classes})." "You can provide a list of all known classes by assigning it " "to the `labels` parameter." ) else: labels = column_or_1d(labels) classes = _unique(labels) n_labels = len(labels) n_classes = len(classes) if n_classes != n_labels: raise ValueError("Parameter 'labels' must be unique.") if not np.array_equal(classes, labels): raise ValueError("Parameter 'labels' must be ordered.") if n_classes != y_score_n_classes: raise ValueError( f"Number of given labels ({n_classes}) not equal to the " f"number of classes in 'y_score' ({y_score_n_classes})." ) if len(np.setdiff1d(y_true, classes)): raise ValueError("'y_true' contains labels not in parameter 'labels'.") if k >= n_classes: warnings.warn( ( f"'k' ({k}) greater than or equal to 'n_classes' ({n_classes}) " "will result in a perfect score and is therefore meaningless." ), UndefinedMetricWarning, ) y_true_encoded = _encode(y_true, uniques=classes) if y_type == "binary": if k == 1: threshold = 0.5 if y_score.min() >= 0 and y_score.max() <= 1 else 0 y_pred = (y_score > threshold).astype(np.int64) hits = y_pred == y_true_encoded else: hits = np.ones_like(y_score, dtype=np.bool_) elif y_type == "multiclass": sorted_pred = np.argsort(y_score, axis=1, kind="mergesort")[:, ::-1] hits = (y_true_encoded == sorted_pred[:, :k].T).any(axis=0) if normalize: return float(np.average(hits, weights=sample_weight)) elif sample_weight is None: return float(np.sum(hits)) else: return float(np.dot(hits, sample_weight))
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 ---------- y_true : array-like of shape (n_samples,) True labels. y_score : array-like of shape (n_samples,) or (n_samples, n_classes) Target scores. These can be either probability estimates or non-thresholded decision values (as returned by :term:`decision_function` on some classifiers). The binary case expects scores with shape (n_samples,) while the multiclass case expects scores with shape (n_samples, n_classes). In the multiclass case, the order of the class scores must correspond to the order of ``labels``, if provided, or else to the numerical or lexicographical order of the labels in ``y_true``. If ``y_true`` does not contain all the labels, ``labels`` must be provided. k : int, default=2 Number of most likely outcomes considered to find the correct label. normalize : bool, default=True If `True`, return the fraction of correctly classified samples. Otherwise, return the number of correctly classified samples. sample_weight : array-like of shape (n_samples,), default=None Sample weights. If `None`, all samples are given the same weight. labels : array-like of shape (n_classes,), default=None Multiclass only. List of labels that index the classes in ``y_score``. If ``None``, the numerical or lexicographical order of the labels in ``y_true`` is used. If ``y_true`` does not contain all the labels, ``labels`` must be provided. Returns ------- score : float The top-k accuracy score. The best performance is 1 with `normalize == True` and the number of samples with `normalize == False`. See Also -------- accuracy_score : Compute the accuracy score. By default, the function will return the fraction of correct predictions divided by the total number of predictions. Notes ----- In cases where two or more labels are assigned equal predicted scores, the labels with the highest indices will be chosen first. This might impact the result if the correct label falls after the threshold because of that. Examples -------- >>> import numpy as np >>> from sklearn.metrics import top_k_accuracy_score >>> y_true = np.array([0, 1, 2, 2]) >>> y_score = np.array([[0.5, 0.2, 0.2], # 0 is in top 2 ... [0.3, 0.4, 0.2], # 1 is in top 2 ... [0.2, 0.4, 0.3], # 2 is in top 2 ... [0.7, 0.2, 0.1]]) # 2 isn't in top 2 >>> top_k_accuracy_score(y_true, y_score, k=2) 0.75 >>> # Not normalizing gives the number of "correctly" classified samples >>> top_k_accuracy_score(y_true, y_score, k=2, normalize=False) 3.0
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` instead. 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) Estimated target values. sample_weight : array-like of shape (n_samples,) or None Sample weights. multioutput : array-like or string in ['raw_values', uniform_average', 'variance_weighted'] or None None is accepted due to backward compatibility of r2_score(). dtype : str or list, default="numeric" the dtype argument passed to check_array. xp : module, default=None Precomputed array namespace module. When passed, typically from a caller that has already performed inspection of its own inputs, skips array namespace inspection. Returns ------- type_true : one of {'continuous', continuous-multioutput'} The type of the true target data, as output by 'utils.multiclass.type_of_target'. y_true : array-like of shape (n_samples, n_outputs) Ground truth (correct) target values. y_pred : array-like of shape (n_samples, n_outputs) Estimated target values. sample_weight : array-like of shape (n_samples,) or None Sample weights. multioutput : array-like of shape (n_outputs) or string in ['raw_values', uniform_average', 'variance_weighted'] or None Custom output weights if ``multioutput`` is array-like or just the corresponding argument if ``multioutput`` is a correct keyword. """ xp, _ = get_namespace(y_true, y_pred, multioutput, xp=xp) check_consistent_length(y_true, y_pred, sample_weight) y_true = check_array(y_true, ensure_2d=False, dtype=dtype) y_pred = check_array(y_pred, ensure_2d=False, dtype=dtype) if sample_weight is not None: sample_weight = _check_sample_weight(sample_weight, y_true, dtype=dtype) if y_true.ndim == 1: y_true = xp.reshape(y_true, (-1, 1)) if y_pred.ndim == 1: y_pred = xp.reshape(y_pred, (-1, 1)) if y_true.shape[1] != y_pred.shape[1]: raise ValueError( "y_true and y_pred have different number of output ({0}!={1})".format( y_true.shape[1], y_pred.shape[1] ) ) n_outputs = y_true.shape[1] allowed_multioutput_str = ("raw_values", "uniform_average", "variance_weighted") if isinstance(multioutput, str): if multioutput not in allowed_multioutput_str: raise ValueError( "Allowed 'multioutput' string values are {}. " "You provided multioutput={!r}".format( allowed_multioutput_str, multioutput ) ) elif multioutput is not None: multioutput = check_array(multioutput, ensure_2d=False) if n_outputs == 1: raise ValueError("Custom weights are useful only in multi-output cases.") elif n_outputs != multioutput.shape[0]: raise ValueError( "There must be equally many custom weights " f"({multioutput.shape[0]}) as outputs ({n_outputs})." ) y_type = "continuous" if n_outputs == 1 else "continuous-multioutput" return y_type, y_true, y_pred, sample_weight, multioutput
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) Ground truth (correct) target values. y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) Estimated target values. sample_weight : array-like of shape (n_samples,) or None Sample weights. multioutput : array-like or string in ['raw_values', uniform_average', 'variance_weighted'] or None None is accepted due to backward compatibility of r2_score(). dtype : str or list, default="numeric" the dtype argument passed to check_array. xp : module, default=None Precomputed array namespace module. When passed, typically from a caller that has already performed inspection of its own inputs, skips array namespace inspection. Returns ------- type_true : one of {'continuous', continuous-multioutput'} The type of the true target data, as output by 'utils.multiclass.type_of_target'. y_true : array-like of shape (n_samples, n_outputs) Ground truth (correct) target values. y_pred : array-like of shape (n_samples, n_outputs) Estimated target values. sample_weight : array-like of shape (n_samples,) or None Sample weights. multioutput : array-like of shape (n_outputs) or string in ['raw_values', uniform_average', 'variance_weighted'] or None Custom output weights if ``multioutput`` is array-like or just the corresponding argument if ``multioutput`` is a correct keyword.
_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_matching_floating_dtype`. Use this private method only when converting inputs to array API-compatibles. 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) Estimated target values. sample_weight : array-like of shape (n_samples,) multioutput : array-like or string in ['raw_values', 'uniform_average', \ 'variance_weighted'] or None None is accepted due to backward compatibility of r2_score(). xp : module, default=None Precomputed array namespace module. When passed, typically from a caller that has already performed inspection of its own inputs, skips array namespace inspection. Returns ------- type_true : one of {'continuous', 'continuous-multioutput'} The type of the true target data, as output by 'utils.multiclass.type_of_target'. y_true : array-like of shape (n_samples, n_outputs) Ground truth (correct) target values. y_pred : array-like of shape (n_samples, n_outputs) Estimated target values. sample_weight : array-like of shape (n_samples,), default=None Sample weights. multioutput : array-like of shape (n_outputs) or string in ['raw_values', \ 'uniform_average', 'variance_weighted'] or None Custom output weights if ``multioutput`` is array-like or just the corresponding argument if ``multioutput`` is a correct keyword. """ dtype_name = _find_matching_floating_dtype(y_true, y_pred, sample_weight, xp=xp) y_type, y_true, y_pred, sample_weight, multioutput = _check_reg_targets( y_true, y_pred, sample_weight, multioutput, dtype=dtype_name, xp=xp ) return y_type, y_true, y_pred, sample_weight, multioutput
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. 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) Estimated target values. sample_weight : array-like of shape (n_samples,) multioutput : array-like or string in ['raw_values', 'uniform_average', 'variance_weighted'] or None None is accepted due to backward compatibility of r2_score(). xp : module, default=None Precomputed array namespace module. When passed, typically from a caller that has already performed inspection of its own inputs, skips array namespace inspection. Returns ------- type_true : one of {'continuous', 'continuous-multioutput'} The type of the true target data, as output by 'utils.multiclass.type_of_target'. y_true : array-like of shape (n_samples, n_outputs) Ground truth (correct) target values. y_pred : array-like of shape (n_samples, n_outputs) Estimated target values. sample_weight : array-like of shape (n_samples,), default=None Sample weights. multioutput : array-like of shape (n_outputs) or string in ['raw_values', 'uniform_average', 'variance_weighted'] or None Custom output weights if ``multioutput`` is array-like or just the corresponding argument if ``multioutput`` is a correct keyword.
_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 ---------- 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) Estimated target values. sample_weight : array-like of shape (n_samples,), default=None Sample weights. multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ (n_outputs,), default='uniform_average' Defines aggregating of multiple output values. Array-like value defines weights used to average errors. 'raw_values' : Returns a full set of errors in case of multioutput input. 'uniform_average' : Errors of all outputs are averaged with uniform weight. Returns ------- loss : float or array of floats If multioutput is 'raw_values', then mean absolute error is returned for each output separately. If multioutput is 'uniform_average' or an ndarray of weights, then the weighted average of all output errors is returned. MAE output is non-negative floating point. The best value is 0.0. Examples -------- >>> from sklearn.metrics import mean_absolute_error >>> y_true = [3, -0.5, 2, 7] >>> y_pred = [2.5, 0.0, 2, 8] >>> mean_absolute_error(y_true, y_pred) 0.5 >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] >>> y_pred = [[0, 2], [-1, 2], [8, -5]] >>> mean_absolute_error(y_true, y_pred) 0.75 >>> mean_absolute_error(y_true, y_pred, multioutput='raw_values') array([0.5, 1. ]) >>> mean_absolute_error(y_true, y_pred, multioutput=[0.3, 0.7]) 0.85... """ xp, _ = get_namespace(y_true, y_pred, sample_weight, multioutput) _, y_true, y_pred, sample_weight, multioutput = ( _check_reg_targets_with_floating_dtype( y_true, y_pred, sample_weight, multioutput, xp=xp ) ) output_errors = _average( xp.abs(y_pred - y_true), weights=sample_weight, axis=0, xp=xp ) if isinstance(multioutput, str): if multioutput == "raw_values": return output_errors elif multioutput == "uniform_average": # pass None as weights to _average: uniform mean multioutput = None # Average across the outputs (if needed). # The second call to `_average` should always return # a scalar array that we convert to a Python float to # consistently return the same eager evaluated value. # Therefore, `axis=None`. mean_absolute_error = _average(output_errors, weights=multioutput) return float(mean_absolute_error)
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 (correct) target values. y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) Estimated target values. sample_weight : array-like of shape (n_samples,), default=None Sample weights. multioutput : {'raw_values', 'uniform_average'} or array-like of shape (n_outputs,), default='uniform_average' Defines aggregating of multiple output values. Array-like value defines weights used to average errors. 'raw_values' : Returns a full set of errors in case of multioutput input. 'uniform_average' : Errors of all outputs are averaged with uniform weight. Returns ------- loss : float or array of floats If multioutput is 'raw_values', then mean absolute error is returned for each output separately. If multioutput is 'uniform_average' or an ndarray of weights, then the weighted average of all output errors is returned. MAE output is non-negative floating point. The best value is 0.0. Examples -------- >>> from sklearn.metrics import mean_absolute_error >>> y_true = [3, -0.5, 2, 7] >>> y_pred = [2.5, 0.0, 2, 8] >>> mean_absolute_error(y_true, y_pred) 0.5 >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] >>> y_pred = [[0, 2], [-1, 2], [8, -5]] >>> mean_absolute_error(y_true, y_pred) 0.75 >>> mean_absolute_error(y_true, y_pred, multioutput='raw_values') array([0.5, 1. ]) >>> mean_absolute_error(y_true, y_pred, multioutput=[0.3, 0.7]) 0.85...
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) Ground truth (correct) target values. y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) Estimated target values. sample_weight : array-like of shape (n_samples,), default=None Sample weights. alpha : float, slope of the pinball loss, default=0.5, This loss is equivalent to :ref:`mean_absolute_error` when `alpha=0.5`, `alpha=0.95` is minimized by estimators of the 95th percentile. multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ (n_outputs,), default='uniform_average' Defines aggregating of multiple output values. Array-like value defines weights used to average errors. 'raw_values' : Returns a full set of errors in case of multioutput input. 'uniform_average' : Errors of all outputs are averaged with uniform weight. Returns ------- loss : float or ndarray of floats If multioutput is 'raw_values', then mean absolute error is returned for each output separately. If multioutput is 'uniform_average' or an ndarray of weights, then the weighted average of all output errors is returned. The pinball loss output is a non-negative floating point. The best value is 0.0. Examples -------- >>> from sklearn.metrics import mean_pinball_loss >>> y_true = [1, 2, 3] >>> mean_pinball_loss(y_true, [0, 2, 3], alpha=0.1) 0.03... >>> mean_pinball_loss(y_true, [1, 2, 4], alpha=0.1) 0.3... >>> mean_pinball_loss(y_true, [0, 2, 3], alpha=0.9) 0.3... >>> mean_pinball_loss(y_true, [1, 2, 4], alpha=0.9) 0.03... >>> mean_pinball_loss(y_true, y_true, alpha=0.1) 0.0 >>> mean_pinball_loss(y_true, y_true, alpha=0.9) 0.0 """ xp, _ = get_namespace(y_true, y_pred, sample_weight, multioutput) _, y_true, y_pred, sample_weight, multioutput = ( _check_reg_targets_with_floating_dtype( y_true, y_pred, sample_weight, multioutput, xp=xp ) ) diff = y_true - y_pred sign = xp.astype(diff >= 0, diff.dtype) loss = alpha * sign * diff - (1 - alpha) * (1 - sign) * diff output_errors = _average(loss, weights=sample_weight, axis=0) if isinstance(multioutput, str) and multioutput == "raw_values": return output_errors if isinstance(multioutput, str) and multioutput == "uniform_average": # pass None as weights to _average: uniform mean multioutput = None # Average across the outputs (if needed). # The second call to `_average` should always return # a scalar array that we convert to a Python float to # consistently return the same eager evaluated value. # Therefore, `axis=None`. return float(_average(output_errors, weights=multioutput))
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) Estimated target values. sample_weight : array-like of shape (n_samples,), default=None Sample weights. alpha : float, slope of the pinball loss, default=0.5, This loss is equivalent to :ref:`mean_absolute_error` when `alpha=0.5`, `alpha=0.95` is minimized by estimators of the 95th percentile. multioutput : {'raw_values', 'uniform_average'} or array-like of shape (n_outputs,), default='uniform_average' Defines aggregating of multiple output values. Array-like value defines weights used to average errors. 'raw_values' : Returns a full set of errors in case of multioutput input. 'uniform_average' : Errors of all outputs are averaged with uniform weight. Returns ------- loss : float or ndarray of floats If multioutput is 'raw_values', then mean absolute error is returned for each output separately. If multioutput is 'uniform_average' or an ndarray of weights, then the weighted average of all output errors is returned. The pinball loss output is a non-negative floating point. The best value is 0.0. Examples -------- >>> from sklearn.metrics import mean_pinball_loss >>> y_true = [1, 2, 3] >>> mean_pinball_loss(y_true, [0, 2, 3], alpha=0.1) 0.03... >>> mean_pinball_loss(y_true, [1, 2, 4], alpha=0.1) 0.3... >>> mean_pinball_loss(y_true, [0, 2, 3], alpha=0.9) 0.3... >>> mean_pinball_loss(y_true, [1, 2, 4], alpha=0.9) 0.03... >>> mean_pinball_loss(y_true, y_true, alpha=0.1) 0.0 >>> mean_pinball_loss(y_true, y_true, alpha=0.9) 0.0
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 the range [0, 1] by dividing by 100. Thus, an error of 200% corresponds to a relative error of 2. Read more in the :ref:`User Guide <mean_absolute_percentage_error>`. .. versionadded:: 0.24 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) Estimated target values. sample_weight : array-like of shape (n_samples,), default=None Sample weights. multioutput : {'raw_values', 'uniform_average'} or array-like Defines aggregating of multiple output values. Array-like value defines weights used to average errors. If input is list then the shape must be (n_outputs,). 'raw_values' : Returns a full set of errors in case of multioutput input. 'uniform_average' : Errors of all outputs are averaged with uniform weight. Returns ------- loss : float or ndarray of floats If multioutput is 'raw_values', then mean absolute percentage error is returned for each output separately. If multioutput is 'uniform_average' or an ndarray of weights, then the weighted average of all output errors is returned. MAPE output is non-negative floating point. The best value is 0.0. But note that bad predictions can lead to arbitrarily large MAPE values, especially if some `y_true` values are very close to zero. Note that we return a large value instead of `inf` when `y_true` is zero. Examples -------- >>> from sklearn.metrics import mean_absolute_percentage_error >>> y_true = [3, -0.5, 2, 7] >>> y_pred = [2.5, 0.0, 2, 8] >>> mean_absolute_percentage_error(y_true, y_pred) 0.3273... >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] >>> y_pred = [[0, 2], [-1, 2], [8, -5]] >>> mean_absolute_percentage_error(y_true, y_pred) 0.5515... >>> mean_absolute_percentage_error(y_true, y_pred, multioutput=[0.3, 0.7]) 0.6198... >>> # the value when some element of the y_true is zero is arbitrarily high because >>> # of the division by epsilon >>> y_true = [1., 0., 2.4, 7.] >>> y_pred = [1.2, 0.1, 2.4, 8.] >>> mean_absolute_percentage_error(y_true, y_pred) 112589990684262.48 """ xp, _, device_ = get_namespace_and_device( y_true, y_pred, sample_weight, multioutput ) _, y_true, y_pred, sample_weight, multioutput = ( _check_reg_targets_with_floating_dtype( y_true, y_pred, sample_weight, multioutput, xp=xp ) ) epsilon = xp.asarray(xp.finfo(xp.float64).eps, dtype=y_true.dtype, device=device_) y_true_abs = xp.abs(y_true) mape = xp.abs(y_pred - y_true) / xp.maximum(y_true_abs, epsilon) output_errors = _average(mape, weights=sample_weight, axis=0) if isinstance(multioutput, str): if multioutput == "raw_values": return output_errors elif multioutput == "uniform_average": # pass None as weights to _average: uniform mean multioutput = None # Average across the outputs (if needed). # The second call to `_average` should always return # a scalar array that we convert to a Python float to # consistently return the same eager evaluated value. # Therefore, `axis=None`. mean_absolute_percentage_error = _average(output_errors, weights=multioutput) return float(mean_absolute_percentage_error)
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 the :ref:`User Guide <mean_absolute_percentage_error>`. .. versionadded:: 0.24 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) Estimated target values. sample_weight : array-like of shape (n_samples,), default=None Sample weights. multioutput : {'raw_values', 'uniform_average'} or array-like Defines aggregating of multiple output values. Array-like value defines weights used to average errors. If input is list then the shape must be (n_outputs,). 'raw_values' : Returns a full set of errors in case of multioutput input. 'uniform_average' : Errors of all outputs are averaged with uniform weight. Returns ------- loss : float or ndarray of floats If multioutput is 'raw_values', then mean absolute percentage error is returned for each output separately. If multioutput is 'uniform_average' or an ndarray of weights, then the weighted average of all output errors is returned. MAPE output is non-negative floating point. The best value is 0.0. But note that bad predictions can lead to arbitrarily large MAPE values, especially if some `y_true` values are very close to zero. Note that we return a large value instead of `inf` when `y_true` is zero. Examples -------- >>> from sklearn.metrics import mean_absolute_percentage_error >>> y_true = [3, -0.5, 2, 7] >>> y_pred = [2.5, 0.0, 2, 8] >>> mean_absolute_percentage_error(y_true, y_pred) 0.3273... >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] >>> y_pred = [[0, 2], [-1, 2], [8, -5]] >>> mean_absolute_percentage_error(y_true, y_pred) 0.5515... >>> mean_absolute_percentage_error(y_true, y_pred, multioutput=[0.3, 0.7]) 0.6198... >>> # the value when some element of the y_true is zero is arbitrarily high because >>> # of the division by epsilon >>> y_true = [1., 0., 2.4, 7.] >>> y_pred = [1.2, 0.1, 2.4, 8.] >>> mean_absolute_percentage_error(y_true, y_pred) 112589990684262.48
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_outputs) Ground truth (correct) target values. y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) Estimated target values. sample_weight : array-like of shape (n_samples,), default=None Sample weights. multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ (n_outputs,), default='uniform_average' Defines aggregating of multiple output values. Array-like value defines weights used to average errors. 'raw_values' : Returns a full set of errors in case of multioutput input. 'uniform_average' : Errors of all outputs are averaged with uniform weight. Returns ------- loss : float or array of floats A non-negative floating point value (the best value is 0.0), or an array of floating point values, one for each individual target. Examples -------- >>> from sklearn.metrics import mean_squared_error >>> y_true = [3, -0.5, 2, 7] >>> y_pred = [2.5, 0.0, 2, 8] >>> mean_squared_error(y_true, y_pred) 0.375 >>> y_true = [[0.5, 1],[-1, 1],[7, -6]] >>> y_pred = [[0, 2],[-1, 2],[8, -5]] >>> mean_squared_error(y_true, y_pred) 0.708... >>> mean_squared_error(y_true, y_pred, multioutput='raw_values') array([0.41666667, 1. ]) >>> mean_squared_error(y_true, y_pred, multioutput=[0.3, 0.7]) 0.825... """ xp, _ = get_namespace(y_true, y_pred, sample_weight, multioutput) _, y_true, y_pred, sample_weight, multioutput = ( _check_reg_targets_with_floating_dtype( y_true, y_pred, sample_weight, multioutput, xp=xp ) ) output_errors = _average((y_true - y_pred) ** 2, axis=0, weights=sample_weight) if isinstance(multioutput, str): if multioutput == "raw_values": return output_errors elif multioutput == "uniform_average": # pass None as weights to _average: uniform mean multioutput = None # Average across the outputs (if needed). # The second call to `_average` should always return # a scalar array that we convert to a Python float to # consistently return the same eager evaluated value. # Therefore, `axis=None`. mean_squared_error = _average(output_errors, weights=multioutput) return float(mean_squared_error)
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) Estimated target values. sample_weight : array-like of shape (n_samples,), default=None Sample weights. multioutput : {'raw_values', 'uniform_average'} or array-like of shape (n_outputs,), default='uniform_average' Defines aggregating of multiple output values. Array-like value defines weights used to average errors. 'raw_values' : Returns a full set of errors in case of multioutput input. 'uniform_average' : Errors of all outputs are averaged with uniform weight. Returns ------- loss : float or array of floats A non-negative floating point value (the best value is 0.0), or an array of floating point values, one for each individual target. Examples -------- >>> from sklearn.metrics import mean_squared_error >>> y_true = [3, -0.5, 2, 7] >>> y_pred = [2.5, 0.0, 2, 8] >>> mean_squared_error(y_true, y_pred) 0.375 >>> y_true = [[0.5, 1],[-1, 1],[7, -6]] >>> y_pred = [[0, 2],[-1, 2],[8, -5]] >>> mean_squared_error(y_true, y_pred) 0.708... >>> mean_squared_error(y_true, y_pred, multioutput='raw_values') array([0.41666667, 1. ]) >>> mean_squared_error(y_true, y_pred, multioutput=[0.3, 0.7]) 0.825...
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,) or (n_samples, n_outputs) Ground truth (correct) target values. y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) Estimated target values. sample_weight : array-like of shape (n_samples,), default=None Sample weights. multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ (n_outputs,), default='uniform_average' Defines aggregating of multiple output values. Array-like value defines weights used to average errors. 'raw_values' : Returns a full set of errors in case of multioutput input. 'uniform_average' : Errors of all outputs are averaged with uniform weight. Returns ------- loss : float or ndarray of floats A non-negative floating point value (the best value is 0.0), or an array of floating point values, one for each individual target. Examples -------- >>> from sklearn.metrics import root_mean_squared_error >>> y_true = [3, -0.5, 2, 7] >>> y_pred = [2.5, 0.0, 2, 8] >>> root_mean_squared_error(y_true, y_pred) 0.612... >>> y_true = [[0.5, 1],[-1, 1],[7, -6]] >>> y_pred = [[0, 2],[-1, 2],[8, -5]] >>> root_mean_squared_error(y_true, y_pred) 0.822... """ xp, _ = get_namespace(y_true, y_pred, sample_weight, multioutput) output_errors = xp.sqrt( mean_squared_error( y_true, y_pred, sample_weight=sample_weight, multioutput="raw_values" ) ) if isinstance(multioutput, str): if multioutput == "raw_values": return output_errors elif multioutput == "uniform_average": # pass None as weights to _average: uniform mean multioutput = None # Average across the outputs (if needed). # The second call to `_average` should always return # a scalar array that we convert to a Python float to # consistently return the same eager evaluated value. # Therefore, `axis=None`. root_mean_squared_error = _average(output_errors, weights=multioutput) return float(root_mean_squared_error)
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_samples,) or (n_samples, n_outputs) Estimated target values. sample_weight : array-like of shape (n_samples,), default=None Sample weights. multioutput : {'raw_values', 'uniform_average'} or array-like of shape (n_outputs,), default='uniform_average' Defines aggregating of multiple output values. Array-like value defines weights used to average errors. 'raw_values' : Returns a full set of errors in case of multioutput input. 'uniform_average' : Errors of all outputs are averaged with uniform weight. Returns ------- loss : float or ndarray of floats A non-negative floating point value (the best value is 0.0), or an array of floating point values, one for each individual target. Examples -------- >>> from sklearn.metrics import root_mean_squared_error >>> y_true = [3, -0.5, 2, 7] >>> y_pred = [2.5, 0.0, 2, 8] >>> root_mean_squared_error(y_true, y_pred) 0.612... >>> y_true = [[0.5, 1],[-1, 1],[7, -6]] >>> y_pred = [[0, 2],[-1, 2],[8, -5]] >>> root_mean_squared_error(y_true, y_pred) 0.822...
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,) or (n_samples, n_outputs) Ground truth (correct) target values. y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) Estimated target values. sample_weight : array-like of shape (n_samples,), default=None Sample weights. multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ (n_outputs,), default='uniform_average' Defines aggregating of multiple output values. Array-like value defines weights used to average errors. 'raw_values' : Returns a full set of errors when the input is of multioutput format. 'uniform_average' : Errors of all outputs are averaged with uniform weight. Returns ------- loss : float or ndarray of floats A non-negative floating point value (the best value is 0.0), or an array of floating point values, one for each individual target. Examples -------- >>> from sklearn.metrics import mean_squared_log_error >>> y_true = [3, 5, 2.5, 7] >>> y_pred = [2.5, 5, 4, 8] >>> mean_squared_log_error(y_true, y_pred) 0.039... >>> y_true = [[0.5, 1], [1, 2], [7, 6]] >>> y_pred = [[0.5, 2], [1, 2.5], [8, 8]] >>> mean_squared_log_error(y_true, y_pred) 0.044... >>> mean_squared_log_error(y_true, y_pred, multioutput='raw_values') array([0.00462428, 0.08377444]) >>> mean_squared_log_error(y_true, y_pred, multioutput=[0.3, 0.7]) 0.060... """ xp, _ = get_namespace(y_true, y_pred) _, y_true, y_pred, sample_weight, multioutput = ( _check_reg_targets_with_floating_dtype( y_true, y_pred, sample_weight, multioutput, xp=xp ) ) if xp.any(y_true <= -1) or xp.any(y_pred <= -1): raise ValueError( "Mean Squared Logarithmic Error cannot be used when " "targets contain values less than or equal to -1." ) return mean_squared_error( xp.log1p(y_true), xp.log1p(y_pred), sample_weight=sample_weight, multioutput=multioutput, )
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_samples, n_outputs) Estimated target values. sample_weight : array-like of shape (n_samples,), default=None Sample weights. multioutput : {'raw_values', 'uniform_average'} or array-like of shape (n_outputs,), default='uniform_average' Defines aggregating of multiple output values. Array-like value defines weights used to average errors. 'raw_values' : Returns a full set of errors when the input is of multioutput format. 'uniform_average' : Errors of all outputs are averaged with uniform weight. Returns ------- loss : float or ndarray of floats A non-negative floating point value (the best value is 0.0), or an array of floating point values, one for each individual target. Examples -------- >>> from sklearn.metrics import mean_squared_log_error >>> y_true = [3, 5, 2.5, 7] >>> y_pred = [2.5, 5, 4, 8] >>> mean_squared_log_error(y_true, y_pred) 0.039... >>> y_true = [[0.5, 1], [1, 2], [7, 6]] >>> y_pred = [[0.5, 2], [1, 2.5], [8, 8]] >>> mean_squared_log_error(y_true, y_pred) 0.044... >>> mean_squared_log_error(y_true, y_pred, multioutput='raw_values') array([0.00462428, 0.08377444]) >>> mean_squared_log_error(y_true, y_pred, multioutput=[0.3, 0.7]) 0.060...
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 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) Estimated target values. sample_weight : array-like of shape (n_samples,), default=None Sample weights. multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ (n_outputs,), default='uniform_average' Defines aggregating of multiple output values. Array-like value defines weights used to average errors. 'raw_values' : Returns a full set of errors when the input is of multioutput format. 'uniform_average' : Errors of all outputs are averaged with uniform weight. Returns ------- loss : float or ndarray of floats A non-negative floating point value (the best value is 0.0), or an array of floating point values, one for each individual target. Examples -------- >>> from sklearn.metrics import root_mean_squared_log_error >>> y_true = [3, 5, 2.5, 7] >>> y_pred = [2.5, 5, 4, 8] >>> root_mean_squared_log_error(y_true, y_pred) 0.199... """ xp, _ = get_namespace(y_true, y_pred) _, y_true, y_pred, sample_weight, multioutput = ( _check_reg_targets_with_floating_dtype( y_true, y_pred, sample_weight, multioutput, xp=xp ) ) if xp.any(y_true <= -1) or xp.any(y_pred <= -1): raise ValueError( "Root Mean Squared Logarithmic Error cannot be used when " "targets contain values less than or equal to -1." ) return root_mean_squared_error( xp.log1p(y_true), xp.log1p(y_pred), sample_weight=sample_weight, multioutput=multioutput, )
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 of shape (n_samples,) or (n_samples, n_outputs) Estimated target values. sample_weight : array-like of shape (n_samples,), default=None Sample weights. multioutput : {'raw_values', 'uniform_average'} or array-like of shape (n_outputs,), default='uniform_average' Defines aggregating of multiple output values. Array-like value defines weights used to average errors. 'raw_values' : Returns a full set of errors when the input is of multioutput format. 'uniform_average' : Errors of all outputs are averaged with uniform weight. Returns ------- loss : float or ndarray of floats A non-negative floating point value (the best value is 0.0), or an array of floating point values, one for each individual target. Examples -------- >>> from sklearn.metrics import root_mean_squared_log_error >>> y_true = [3, 5, 2.5, 7] >>> y_pred = [2.5, 5, 4, 8] >>> root_mean_squared_log_error(y_true, y_pred) 0.199...
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 ---------- 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) Estimated target values. multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ (n_outputs,), default='uniform_average' Defines aggregating of multiple output values. Array-like value defines weights used to average errors. 'raw_values' : Returns a full set of errors in case of multioutput input. 'uniform_average' : Errors of all outputs are averaged with uniform weight. sample_weight : array-like of shape (n_samples,), default=None Sample weights. .. versionadded:: 0.24 Returns ------- loss : float or ndarray of floats If multioutput is 'raw_values', then mean absolute error is returned for each output separately. If multioutput is 'uniform_average' or an ndarray of weights, then the weighted average of all output errors is returned. Examples -------- >>> from sklearn.metrics import median_absolute_error >>> y_true = [3, -0.5, 2, 7] >>> y_pred = [2.5, 0.0, 2, 8] >>> median_absolute_error(y_true, y_pred) 0.5 >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] >>> y_pred = [[0, 2], [-1, 2], [8, -5]] >>> median_absolute_error(y_true, y_pred) 0.75 >>> median_absolute_error(y_true, y_pred, multioutput='raw_values') array([0.5, 1. ]) >>> median_absolute_error(y_true, y_pred, multioutput=[0.3, 0.7]) 0.85 """ xp, _ = get_namespace(y_true, y_pred, multioutput, sample_weight) _, y_true, y_pred, sample_weight, multioutput = _check_reg_targets( y_true, y_pred, sample_weight, multioutput ) if sample_weight is None: output_errors = _median(xp.abs(y_pred - y_true), axis=0) else: output_errors = _weighted_percentile( xp.abs(y_pred - y_true), sample_weight=sample_weight ) if isinstance(multioutput, str): if multioutput == "raw_values": return output_errors elif multioutput == "uniform_average": # pass None as weights to np.average: uniform mean multioutput = None return float(_average(output_errors, weights=multioutput))
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 (correct) target values. y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) Estimated target values. multioutput : {'raw_values', 'uniform_average'} or array-like of shape (n_outputs,), default='uniform_average' Defines aggregating of multiple output values. Array-like value defines weights used to average errors. 'raw_values' : Returns a full set of errors in case of multioutput input. 'uniform_average' : Errors of all outputs are averaged with uniform weight. sample_weight : array-like of shape (n_samples,), default=None Sample weights. .. versionadded:: 0.24 Returns ------- loss : float or ndarray of floats If multioutput is 'raw_values', then mean absolute error is returned for each output separately. If multioutput is 'uniform_average' or an ndarray of weights, then the weighted average of all output errors is returned. Examples -------- >>> from sklearn.metrics import median_absolute_error >>> y_true = [3, -0.5, 2, 7] >>> y_pred = [2.5, 0.0, 2, 8] >>> median_absolute_error(y_true, y_pred) 0.5 >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] >>> y_pred = [[0, 2], [-1, 2], [8, -5]] >>> median_absolute_error(y_true, y_pred) 0.75 >>> median_absolute_error(y_true, y_pred, multioutput='raw_values') array([0.5, 1. ]) >>> median_absolute_error(y_true, y_pred, multioutput=[0.3, 0.7]) 0.85
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, that may lead to NaN or -Inf output_scores = 1 - (numerator / denominator) else: nonzero_numerator = numerator != 0 # Default = Zero Numerator = perfect predictions. Set to 1.0 # (note: even if denominator is zero, thus avoiding NaN scores) output_scores = xp.ones([n_outputs], device=device, dtype=dtype) # Non-zero Numerator and Non-zero Denominator: use the formula valid_score = nonzero_denominator & nonzero_numerator output_scores[valid_score] = 1 - ( numerator[valid_score] / denominator[valid_score] ) # Non-zero Numerator and Zero Denominator: # arbitrary set to 0.0 to avoid -inf scores output_scores[nonzero_numerator & ~nonzero_denominator] = 0.0 if isinstance(multioutput, str): if multioutput == "raw_values": # return scores individually return output_scores elif multioutput == "uniform_average": # pass None as weights to _average: uniform mean avg_weights = None elif multioutput == "variance_weighted": avg_weights = denominator if not xp.any(nonzero_denominator): # All weights are zero, _average would raise a ZeroDiv error. # This only happens when all y are constant (or 1-element long) # Since weights are all equal, fall back to uniform weights. avg_weights = None else: avg_weights = multioutput result = _average(output_scores, weights=avg_weights) if size(result) == 1: return float(result) return result
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 explained variance score is not finite: it is either ``NaN`` (perfect predictions) or ``-Inf`` (imperfect predictions). To prevent such non-finite numbers to pollute higher-level experiments such as a grid search cross-validation, by default these cases are replaced with 1.0 (perfect predictions) or 0.0 (imperfect predictions) respectively. If ``force_finite`` is set to ``False``, this score falls back on the original :math:`R^2` definition. .. note:: The Explained Variance score is similar to the :func:`R^2 score <r2_score>`, with the notable difference that it does not account for systematic offsets in the prediction. Most often the :func:`R^2 score <r2_score>` should be preferred. Read more in the :ref:`User Guide <explained_variance_score>`. 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) Estimated target values. sample_weight : array-like of shape (n_samples,), default=None Sample weights. multioutput : {'raw_values', 'uniform_average', 'variance_weighted'} or \ array-like of shape (n_outputs,), default='uniform_average' Defines aggregating of multiple output scores. Array-like value defines weights used to average scores. 'raw_values' : Returns a full set of scores in case of multioutput input. 'uniform_average' : Scores of all outputs are averaged with uniform weight. 'variance_weighted' : Scores of all outputs are averaged, weighted by the variances of each individual output. force_finite : bool, default=True Flag indicating if ``NaN`` and ``-Inf`` scores resulting from constant data should be replaced with real numbers (``1.0`` if prediction is perfect, ``0.0`` otherwise). Default is ``True``, a convenient setting for hyperparameters' search procedures (e.g. grid search cross-validation). .. versionadded:: 1.1 Returns ------- score : float or ndarray of floats The explained variance or ndarray if 'multioutput' is 'raw_values'. See Also -------- r2_score : Similar metric, but accounting for systematic offsets in prediction. Notes ----- This is not a symmetric function. Examples -------- >>> from sklearn.metrics import explained_variance_score >>> y_true = [3, -0.5, 2, 7] >>> y_pred = [2.5, 0.0, 2, 8] >>> explained_variance_score(y_true, y_pred) 0.957... >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] >>> y_pred = [[0, 2], [-1, 2], [8, -5]] >>> explained_variance_score(y_true, y_pred, multioutput='uniform_average') 0.983... >>> y_true = [-2, -2, -2] >>> y_pred = [-2, -2, -2] >>> explained_variance_score(y_true, y_pred) 1.0 >>> explained_variance_score(y_true, y_pred, force_finite=False) nan >>> y_true = [-2, -2, -2] >>> y_pred = [-2, -2, -2 + 1e-8] >>> explained_variance_score(y_true, y_pred) 0.0 >>> explained_variance_score(y_true, y_pred, force_finite=False) -inf """ xp, _, device = get_namespace_and_device(y_true, y_pred, sample_weight, multioutput) _, y_true, y_pred, sample_weight, multioutput = ( _check_reg_targets_with_floating_dtype( y_true, y_pred, sample_weight, multioutput, xp=xp ) ) y_diff_avg = _average(y_true - y_pred, weights=sample_weight, axis=0) numerator = _average( (y_true - y_pred - y_diff_avg) ** 2, weights=sample_weight, axis=0 ) y_true_avg = _average(y_true, weights=sample_weight, axis=0) denominator = _average((y_true - y_true_avg) ** 2, weights=sample_weight, axis=0) return _assemble_r2_explained_variance( numerator=numerator, denominator=denominator, n_outputs=y_true.shape[1], multioutput=multioutput, force_finite=force_finite, xp=xp, device=device, )
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 numbers to pollute higher-level experiments such as a grid search cross-validation, by default these cases are replaced with 1.0 (perfect predictions) or 0.0 (imperfect predictions) respectively. If ``force_finite`` is set to ``False``, this score falls back on the original :math:`R^2` definition. .. note:: The Explained Variance score is similar to the :func:`R^2 score <r2_score>`, with the notable difference that it does not account for systematic offsets in the prediction. Most often the :func:`R^2 score <r2_score>` should be preferred. Read more in the :ref:`User Guide <explained_variance_score>`. 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) Estimated target values. sample_weight : array-like of shape (n_samples,), default=None Sample weights. multioutput : {'raw_values', 'uniform_average', 'variance_weighted'} or array-like of shape (n_outputs,), default='uniform_average' Defines aggregating of multiple output scores. Array-like value defines weights used to average scores. 'raw_values' : Returns a full set of scores in case of multioutput input. 'uniform_average' : Scores of all outputs are averaged with uniform weight. 'variance_weighted' : Scores of all outputs are averaged, weighted by the variances of each individual output. force_finite : bool, default=True Flag indicating if ``NaN`` and ``-Inf`` scores resulting from constant data should be replaced with real numbers (``1.0`` if prediction is perfect, ``0.0`` otherwise). Default is ``True``, a convenient setting for hyperparameters' search procedures (e.g. grid search cross-validation). .. versionadded:: 1.1 Returns ------- score : float or ndarray of floats The explained variance or ndarray if 'multioutput' is 'raw_values'. See Also -------- r2_score : Similar metric, but accounting for systematic offsets in prediction. Notes ----- This is not a symmetric function. Examples -------- >>> from sklearn.metrics import explained_variance_score >>> y_true = [3, -0.5, 2, 7] >>> y_pred = [2.5, 0.0, 2, 8] >>> explained_variance_score(y_true, y_pred) 0.957... >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] >>> y_pred = [[0, 2], [-1, 2], [8, -5]] >>> explained_variance_score(y_true, y_pred, multioutput='uniform_average') 0.983... >>> y_true = [-2, -2, -2] >>> y_pred = [-2, -2, -2] >>> explained_variance_score(y_true, y_pred) 1.0 >>> explained_variance_score(y_true, y_pred, force_finite=False) nan >>> y_true = [-2, -2, -2] >>> y_pred = [-2, -2, -2 + 1e-8] >>> explained_variance_score(y_true, y_pred) 0.0 >>> explained_variance_score(y_true, y_pred, force_finite=False) -inf
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 general case when the true y is non-constant, a constant model that always predicts the average y disregarding the input features would get a :math:`R^2` score of 0.0. In the particular case when ``y_true`` is constant, the :math:`R^2` score is not finite: it is either ``NaN`` (perfect predictions) or ``-Inf`` (imperfect predictions). To prevent such non-finite numbers to pollute higher-level experiments such as a grid search cross-validation, by default these cases are replaced with 1.0 (perfect predictions) or 0.0 (imperfect predictions) respectively. You can set ``force_finite`` to ``False`` to prevent this fix from happening. Note: when the prediction residuals have zero mean, the :math:`R^2` score is identical to the :func:`Explained Variance score <explained_variance_score>`. Read more in the :ref:`User Guide <r2_score>`. 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) Estimated target values. sample_weight : array-like of shape (n_samples,), default=None Sample weights. multioutput : {'raw_values', 'uniform_average', 'variance_weighted'}, \ array-like of shape (n_outputs,) or None, default='uniform_average' Defines aggregating of multiple output scores. Array-like value defines weights used to average scores. Default is "uniform_average". 'raw_values' : Returns a full set of scores in case of multioutput input. 'uniform_average' : Scores of all outputs are averaged with uniform weight. 'variance_weighted' : Scores of all outputs are averaged, weighted by the variances of each individual output. .. versionchanged:: 0.19 Default value of multioutput is 'uniform_average'. force_finite : bool, default=True Flag indicating if ``NaN`` and ``-Inf`` scores resulting from constant data should be replaced with real numbers (``1.0`` if prediction is perfect, ``0.0`` otherwise). Default is ``True``, a convenient setting for hyperparameters' search procedures (e.g. grid search cross-validation). .. versionadded:: 1.1 Returns ------- z : float or ndarray of floats The :math:`R^2` score or ndarray of scores if 'multioutput' is 'raw_values'. Notes ----- This is not a symmetric function. Unlike most other scores, :math:`R^2` score may be negative (it need not actually be the square of a quantity R). This metric is not well-defined for single samples and will return a NaN value if n_samples is less than two. References ---------- .. [1] `Wikipedia entry on the Coefficient of determination <https://en.wikipedia.org/wiki/Coefficient_of_determination>`_ Examples -------- >>> from sklearn.metrics import r2_score >>> y_true = [3, -0.5, 2, 7] >>> y_pred = [2.5, 0.0, 2, 8] >>> r2_score(y_true, y_pred) 0.948... >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] >>> y_pred = [[0, 2], [-1, 2], [8, -5]] >>> r2_score(y_true, y_pred, ... multioutput='variance_weighted') 0.938... >>> y_true = [1, 2, 3] >>> y_pred = [1, 2, 3] >>> r2_score(y_true, y_pred) 1.0 >>> y_true = [1, 2, 3] >>> y_pred = [2, 2, 2] >>> r2_score(y_true, y_pred) 0.0 >>> y_true = [1, 2, 3] >>> y_pred = [3, 2, 1] >>> r2_score(y_true, y_pred) -3.0 >>> y_true = [-2, -2, -2] >>> y_pred = [-2, -2, -2] >>> r2_score(y_true, y_pred) 1.0 >>> r2_score(y_true, y_pred, force_finite=False) nan >>> y_true = [-2, -2, -2] >>> y_pred = [-2, -2, -2 + 1e-8] >>> r2_score(y_true, y_pred) 0.0 >>> r2_score(y_true, y_pred, force_finite=False) -inf """ xp, _, device_ = get_namespace_and_device( y_true, y_pred, sample_weight, multioutput ) _, y_true, y_pred, sample_weight, multioutput = ( _check_reg_targets_with_floating_dtype( y_true, y_pred, sample_weight, multioutput, xp=xp ) ) if _num_samples(y_pred) < 2: msg = "R^2 score is not well-defined with less than two samples." warnings.warn(msg, UndefinedMetricWarning) return float("nan") if sample_weight is not None: sample_weight = column_or_1d(sample_weight) weight = sample_weight[:, None] else: weight = 1.0 numerator = xp.sum(weight * (y_true - y_pred) ** 2, axis=0) denominator = xp.sum( weight * (y_true - _average(y_true, axis=0, weights=sample_weight, xp=xp)) ** 2, axis=0, ) return _assemble_r2_explained_variance( numerator=numerator, denominator=denominator, n_outputs=y_true.shape[1], multioutput=multioutput, force_finite=force_finite, xp=xp, device=device_, )
: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 would get a :math:`R^2` score of 0.0. In the particular case when ``y_true`` is constant, the :math:`R^2` score is not finite: it is either ``NaN`` (perfect predictions) or ``-Inf`` (imperfect predictions). To prevent such non-finite numbers to pollute higher-level experiments such as a grid search cross-validation, by default these cases are replaced with 1.0 (perfect predictions) or 0.0 (imperfect predictions) respectively. You can set ``force_finite`` to ``False`` to prevent this fix from happening. Note: when the prediction residuals have zero mean, the :math:`R^2` score is identical to the :func:`Explained Variance score <explained_variance_score>`. Read more in the :ref:`User Guide <r2_score>`. 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) Estimated target values. sample_weight : array-like of shape (n_samples,), default=None Sample weights. multioutput : {'raw_values', 'uniform_average', 'variance_weighted'}, array-like of shape (n_outputs,) or None, default='uniform_average' Defines aggregating of multiple output scores. Array-like value defines weights used to average scores. Default is "uniform_average". 'raw_values' : Returns a full set of scores in case of multioutput input. 'uniform_average' : Scores of all outputs are averaged with uniform weight. 'variance_weighted' : Scores of all outputs are averaged, weighted by the variances of each individual output. .. versionchanged:: 0.19 Default value of multioutput is 'uniform_average'. force_finite : bool, default=True Flag indicating if ``NaN`` and ``-Inf`` scores resulting from constant data should be replaced with real numbers (``1.0`` if prediction is perfect, ``0.0`` otherwise). Default is ``True``, a convenient setting for hyperparameters' search procedures (e.g. grid search cross-validation). .. versionadded:: 1.1 Returns ------- z : float or ndarray of floats The :math:`R^2` score or ndarray of scores if 'multioutput' is 'raw_values'. Notes ----- This is not a symmetric function. Unlike most other scores, :math:`R^2` score may be negative (it need not actually be the square of a quantity R). This metric is not well-defined for single samples and will return a NaN value if n_samples is less than two. References ---------- .. [1] `Wikipedia entry on the Coefficient of determination <https://en.wikipedia.org/wiki/Coefficient_of_determination>`_ Examples -------- >>> from sklearn.metrics import r2_score >>> y_true = [3, -0.5, 2, 7] >>> y_pred = [2.5, 0.0, 2, 8] >>> r2_score(y_true, y_pred) 0.948... >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] >>> y_pred = [[0, 2], [-1, 2], [8, -5]] >>> r2_score(y_true, y_pred, ... multioutput='variance_weighted') 0.938... >>> y_true = [1, 2, 3] >>> y_pred = [1, 2, 3] >>> r2_score(y_true, y_pred) 1.0 >>> y_true = [1, 2, 3] >>> y_pred = [2, 2, 2] >>> r2_score(y_true, y_pred) 0.0 >>> y_true = [1, 2, 3] >>> y_pred = [3, 2, 1] >>> r2_score(y_true, y_pred) -3.0 >>> y_true = [-2, -2, -2] >>> y_pred = [-2, -2, -2] >>> r2_score(y_true, y_pred) 1.0 >>> r2_score(y_true, y_pred, force_finite=False) nan >>> y_true = [-2, -2, -2] >>> y_pred = [-2, -2, -2 + 1e-8] >>> r2_score(y_true, y_pred) 0.0 >>> r2_score(y_true, y_pred, force_finite=False) -inf
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_samples,) Estimated target values. Returns ------- max_error : float A positive floating point value (the best value is 0.0). Examples -------- >>> from sklearn.metrics import max_error >>> y_true = [3, 2, 7, 1] >>> y_pred = [4, 2, 7, 1] >>> max_error(y_true, y_pred) 1.0 """ xp, _ = get_namespace(y_true, y_pred) y_type, y_true, y_pred, _, _ = _check_reg_targets( y_true, y_pred, sample_weight=None, multioutput=None, xp=xp ) if y_type == "continuous-multioutput": raise ValueError("Multioutput not supported in max_error") return float(xp.max(xp.abs(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_samples,) Estimated target values. Returns ------- max_error : float A positive floating point value (the best value is 0.0). Examples -------- >>> from sklearn.metrics import max_error >>> y_true = [3, 2, 7, 1] >>> y_pred = [4, 2, 7, 1] >>> max_error(y_true, y_pred) 1.0
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 : array-like of shape (n_samples,) Estimated target values. sample_weight : array-like of shape (n_samples,), default=None Sample weights. power : float, default=0 Tweedie power parameter. Either power <= 0 or power >= 1. The higher `p` the less weight is given to extreme deviations between true and predicted targets. - power < 0: Extreme stable distribution. Requires: y_pred > 0. - power = 0 : Normal distribution, output corresponds to mean_squared_error. y_true and y_pred can be any real numbers. - power = 1 : Poisson distribution. Requires: y_true >= 0 and y_pred > 0. - 1 < p < 2 : Compound Poisson distribution. Requires: y_true >= 0 and y_pred > 0. - power = 2 : Gamma distribution. Requires: y_true > 0 and y_pred > 0. - power = 3 : Inverse Gaussian distribution. Requires: y_true > 0 and y_pred > 0. - otherwise : Positive stable distribution. Requires: y_true > 0 and y_pred > 0. Returns ------- loss : float A non-negative floating point value (the best value is 0.0). Examples -------- >>> from sklearn.metrics import mean_tweedie_deviance >>> y_true = [2, 0, 1, 4] >>> y_pred = [0.5, 0.5, 2., 2.] >>> mean_tweedie_deviance(y_true, y_pred, power=1) 1.4260... """ xp, _ = get_namespace(y_true, y_pred) y_type, y_true, y_pred, sample_weight, _ = _check_reg_targets_with_floating_dtype( y_true, y_pred, sample_weight, multioutput=None, xp=xp ) if y_type == "continuous-multioutput": raise ValueError("Multioutput not supported in mean_tweedie_deviance") if sample_weight is not None: sample_weight = column_or_1d(sample_weight) sample_weight = sample_weight[:, np.newaxis] message = f"Mean Tweedie deviance error with power={power} can only be used on " if power < 0: # 'Extreme stable', y any real number, y_pred > 0 if xp.any(y_pred <= 0): raise ValueError(message + "strictly positive y_pred.") elif power == 0: # Normal, y and y_pred can be any real number pass elif 1 <= power < 2: # Poisson and compound Poisson distribution, y >= 0, y_pred > 0 if xp.any(y_true < 0) or xp.any(y_pred <= 0): raise ValueError(message + "non-negative y and strictly positive y_pred.") elif power >= 2: # Gamma and Extreme stable distribution, y and y_pred > 0 if xp.any(y_true <= 0) or xp.any(y_pred <= 0): raise ValueError(message + "strictly positive y and y_pred.") else: # pragma: nocover # Unreachable statement raise ValueError return _mean_tweedie_deviance( y_true, y_pred, sample_weight=sample_weight, power=power )
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_weight : array-like of shape (n_samples,), default=None Sample weights. power : float, default=0 Tweedie power parameter. Either power <= 0 or power >= 1. The higher `p` the less weight is given to extreme deviations between true and predicted targets. - power < 0: Extreme stable distribution. Requires: y_pred > 0. - power = 0 : Normal distribution, output corresponds to mean_squared_error. y_true and y_pred can be any real numbers. - power = 1 : Poisson distribution. Requires: y_true >= 0 and y_pred > 0. - 1 < p < 2 : Compound Poisson distribution. Requires: y_true >= 0 and y_pred > 0. - power = 2 : Gamma distribution. Requires: y_true > 0 and y_pred > 0. - power = 3 : Inverse Gaussian distribution. Requires: y_true > 0 and y_pred > 0. - otherwise : Positive stable distribution. Requires: y_true > 0 and y_pred > 0. Returns ------- loss : float A non-negative floating point value (the best value is 0.0). Examples -------- >>> from sklearn.metrics import mean_tweedie_deviance >>> y_true = [2, 0, 1, 4] >>> y_pred = [0.5, 0.5, 2., 2.] >>> mean_tweedie_deviance(y_true, y_pred, power=1) 1.4260...
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` as constant prediction, disregarding the input features, gets a D^2 score of 0.0. Read more in the :ref:`User Guide <d2_score>`. .. versionadded:: 1.0 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_weight : array-like of shape (n_samples,), default=None Sample weights. power : float, default=0 Tweedie power parameter. Either power <= 0 or power >= 1. The higher `p` the less weight is given to extreme deviations between true and predicted targets. - power < 0: Extreme stable distribution. Requires: y_pred > 0. - power = 0 : Normal distribution, output corresponds to r2_score. y_true and y_pred can be any real numbers. - power = 1 : Poisson distribution. Requires: y_true >= 0 and y_pred > 0. - 1 < p < 2 : Compound Poisson distribution. Requires: y_true >= 0 and y_pred > 0. - power = 2 : Gamma distribution. Requires: y_true > 0 and y_pred > 0. - power = 3 : Inverse Gaussian distribution. Requires: y_true > 0 and y_pred > 0. - otherwise : Positive stable distribution. Requires: y_true > 0 and y_pred > 0. Returns ------- z : float The D^2 score. Notes ----- This is not a symmetric function. Like R^2, D^2 score may be negative (it need not actually be the square of a quantity D). This metric is not well-defined for single samples and will return a NaN value if n_samples is less than two. References ---------- .. [1] Eq. (3.11) of Hastie, Trevor J., Robert Tibshirani and Martin J. Wainwright. "Statistical Learning with Sparsity: The Lasso and Generalizations." (2015). https://hastie.su.domains/StatLearnSparsity/ Examples -------- >>> from sklearn.metrics import d2_tweedie_score >>> y_true = [0.5, 1, 2.5, 7] >>> y_pred = [1, 1, 5, 3.5] >>> d2_tweedie_score(y_true, y_pred) 0.285... >>> d2_tweedie_score(y_true, y_pred, power=1) 0.487... >>> d2_tweedie_score(y_true, y_pred, power=2) 0.630... >>> d2_tweedie_score(y_true, y_true, power=2) 1.0 """ xp, _ = get_namespace(y_true, y_pred) y_type, y_true, y_pred, sample_weight, _ = _check_reg_targets_with_floating_dtype( y_true, y_pred, sample_weight, multioutput=None, xp=xp ) if y_type == "continuous-multioutput": raise ValueError("Multioutput not supported in d2_tweedie_score") if _num_samples(y_pred) < 2: msg = "D^2 score is not well-defined with less than two samples." warnings.warn(msg, UndefinedMetricWarning) return float("nan") y_true, y_pred = xp.squeeze(y_true, axis=1), xp.squeeze(y_pred, axis=1) numerator = mean_tweedie_deviance( y_true, y_pred, sample_weight=sample_weight, power=power ) y_avg = _average(y_true, weights=sample_weight, xp=xp) denominator = _mean_tweedie_deviance( y_true, y_avg, sample_weight=sample_weight, power=power ) return 1 - numerator / denominator
: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 score of 0.0. Read more in the :ref:`User Guide <d2_score>`. .. versionadded:: 1.0 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_weight : array-like of shape (n_samples,), default=None Sample weights. power : float, default=0 Tweedie power parameter. Either power <= 0 or power >= 1. The higher `p` the less weight is given to extreme deviations between true and predicted targets. - power < 0: Extreme stable distribution. Requires: y_pred > 0. - power = 0 : Normal distribution, output corresponds to r2_score. y_true and y_pred can be any real numbers. - power = 1 : Poisson distribution. Requires: y_true >= 0 and y_pred > 0. - 1 < p < 2 : Compound Poisson distribution. Requires: y_true >= 0 and y_pred > 0. - power = 2 : Gamma distribution. Requires: y_true > 0 and y_pred > 0. - power = 3 : Inverse Gaussian distribution. Requires: y_true > 0 and y_pred > 0. - otherwise : Positive stable distribution. Requires: y_true > 0 and y_pred > 0. Returns ------- z : float The D^2 score. Notes ----- This is not a symmetric function. Like R^2, D^2 score may be negative (it need not actually be the square of a quantity D). This metric is not well-defined for single samples and will return a NaN value if n_samples is less than two. References ---------- .. [1] Eq. (3.11) of Hastie, Trevor J., Robert Tibshirani and Martin J. Wainwright. "Statistical Learning with Sparsity: The Lasso and Generalizations." (2015). https://hastie.su.domains/StatLearnSparsity/ Examples -------- >>> from sklearn.metrics import d2_tweedie_score >>> y_true = [0.5, 1, 2.5, 7] >>> y_pred = [1, 1, 5, 3.5] >>> d2_tweedie_score(y_true, y_pred) 0.285... >>> d2_tweedie_score(y_true, y_pred, power=1) 0.487... >>> d2_tweedie_score(y_true, y_pred, power=2) 0.630... >>> d2_tweedie_score(y_true, y_true, power=2) 1.0
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 uses the empirical median of `y_true` as constant prediction, disregarding the input features, gets a :math:`D^2` score of 0.0. Read more in the :ref:`User Guide <d2_score>`. .. versionadded:: 1.1 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) Estimated target values. sample_weight : array-like of shape (n_samples,), default=None Sample weights. multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ (n_outputs,), default='uniform_average' Defines aggregating of multiple output values. Array-like value defines weights used to average scores. 'raw_values' : Returns a full set of errors in case of multioutput input. 'uniform_average' : Scores of all outputs are averaged with uniform weight. Returns ------- score : float or ndarray of floats The :math:`D^2` score with an absolute error deviance or ndarray of scores if 'multioutput' is 'raw_values'. Notes ----- Like :math:`R^2`, :math:`D^2` score may be negative (it need not actually be the square of a quantity D). This metric is not well-defined for single samples and will return a NaN value if n_samples is less than two. References ---------- .. [1] Eq. (3.11) of Hastie, Trevor J., Robert Tibshirani and Martin J. Wainwright. "Statistical Learning with Sparsity: The Lasso and Generalizations." (2015). https://hastie.su.domains/StatLearnSparsity/ Examples -------- >>> from sklearn.metrics import d2_absolute_error_score >>> y_true = [3, -0.5, 2, 7] >>> y_pred = [2.5, 0.0, 2, 8] >>> d2_absolute_error_score(y_true, y_pred) 0.764... >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] >>> y_pred = [[0, 2], [-1, 2], [8, -5]] >>> d2_absolute_error_score(y_true, y_pred, multioutput='uniform_average') 0.691... >>> d2_absolute_error_score(y_true, y_pred, multioutput='raw_values') array([0.8125 , 0.57142857]) >>> y_true = [1, 2, 3] >>> y_pred = [1, 2, 3] >>> d2_absolute_error_score(y_true, y_pred) 1.0 >>> y_true = [1, 2, 3] >>> y_pred = [2, 2, 2] >>> d2_absolute_error_score(y_true, y_pred) 0.0 >>> y_true = [1, 2, 3] >>> y_pred = [3, 2, 1] >>> d2_absolute_error_score(y_true, y_pred) -1.0 """ return d2_pinball_score( y_true, y_pred, sample_weight=sample_weight, alpha=0.5, multioutput=multioutput )
: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 :math:`D^2` score of 0.0. Read more in the :ref:`User Guide <d2_score>`. .. versionadded:: 1.1 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) Estimated target values. sample_weight : array-like of shape (n_samples,), default=None Sample weights. multioutput : {'raw_values', 'uniform_average'} or array-like of shape (n_outputs,), default='uniform_average' Defines aggregating of multiple output values. Array-like value defines weights used to average scores. 'raw_values' : Returns a full set of errors in case of multioutput input. 'uniform_average' : Scores of all outputs are averaged with uniform weight. Returns ------- score : float or ndarray of floats The :math:`D^2` score with an absolute error deviance or ndarray of scores if 'multioutput' is 'raw_values'. Notes ----- Like :math:`R^2`, :math:`D^2` score may be negative (it need not actually be the square of a quantity D). This metric is not well-defined for single samples and will return a NaN value if n_samples is less than two. References ---------- .. [1] Eq. (3.11) of Hastie, Trevor J., Robert Tibshirani and Martin J. Wainwright. "Statistical Learning with Sparsity: The Lasso and Generalizations." (2015). https://hastie.su.domains/StatLearnSparsity/ Examples -------- >>> from sklearn.metrics import d2_absolute_error_score >>> y_true = [3, -0.5, 2, 7] >>> y_pred = [2.5, 0.0, 2, 8] >>> d2_absolute_error_score(y_true, y_pred) 0.764... >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] >>> y_pred = [[0, 2], [-1, 2], [8, -5]] >>> d2_absolute_error_score(y_true, y_pred, multioutput='uniform_average') 0.691... >>> d2_absolute_error_score(y_true, y_pred, multioutput='raw_values') array([0.8125 , 0.57142857]) >>> y_true = [1, 2, 3] >>> y_pred = [1, 2, 3] >>> d2_absolute_error_score(y_true, y_pred) 1.0 >>> y_true = [1, 2, 3] >>> y_pred = [2, 2, 2] >>> d2_absolute_error_score(y_true, y_pred) 0.0 >>> y_true = [1, 2, 3] >>> y_pred = [3, 2, 1] >>> d2_absolute_error_score(y_true, y_pred) -1.0
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, **kwargs ) if cache is not None: cache[response_method] = result return result
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_method(estimator, scorer._response_method).__name__ for scorer in self._scorers.values() if isinstance(scorer, _BaseScorer) ] ) if any(val > 1 for val in counter.values()): # The exact same response method or iterable of response methods # will be called more than once. return True return False
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_routing.MetadataRouter` encapsulating routing information. """ return MetadataRouter(owner=self.__class__.__name__).add( **self._scorers, method_mapping=MethodMapping().add(caller="score", callee="score"), )
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 routing information.
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 that is used to compute the score. X : {array-like, sparse matrix} Test data that will be fed to estimator.predict. y_true : array-like Gold standard target values for X. sample_weight : array-like of shape (n_samples,), default=None Sample weights. **kwargs : dict Other parameters passed to the scorer. Refer to :func:`set_score_request` for more details. Only available if `enable_metadata_routing=True`. See the :ref:`User Guide <metadata_routing>`. .. versionadded:: 1.3 Returns ------- score : float Score function applied to prediction of estimator on X. """ # TODO (1.8): remove in 1.8 (scoring="max_error" has been deprecated in 1.6) if self._deprecation_msg is not None: warnings.warn( self._deprecation_msg, category=DeprecationWarning, stacklevel=2 ) _raise_for_params(kwargs, self, None) _kwargs = copy.deepcopy(kwargs) if sample_weight is not None: _kwargs["sample_weight"] = sample_weight return self._score(partial(_cached_call, None), estimator, X, y_true, **_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 that is used to compute the score. X : {array-like, sparse matrix} Test data that will be fed to estimator.predict. y_true : array-like Gold standard target values for X. sample_weight : array-like of shape (n_samples,), default=None Sample weights. **kwargs : dict Other parameters passed to the scorer. Refer to :func:`set_score_request` for more details. Only available if `enable_metadata_routing=True`. See the :ref:`User Guide <metadata_routing>`. .. versionadded:: 1.3 Returns ------- score : float Score function applied to prediction of estimator on X.
__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 set(self._kwargs.keys()) overlap = _kwargs.intersection(kwargs.keys()) if overlap: warnings.warn( f"{message} Overlapping parameters are: {overlap}", UserWarning )
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 the form ``param_name=alias``, and `alias` can be one of ``{True, False, None, str}``. """ if not _routing_enabled(): raise RuntimeError( "This method is only available when metadata routing is enabled." " You can enable it using" " sklearn.set_config(enable_metadata_routing=True)." ) self._warn_overlap( message=( "You are setting metadata request for parameters which are " "already set as kwargs for this metric. These set values will be " "overridden by passed metadata if provided. Please pass them either " "as metadata or kwargs to `make_scorer`." ), kwargs=kwargs, ) self._metadata_request = MetadataRequest(owner=self.__class__.__name__) for param, alias in kwargs.items(): self._metadata_request.score.add_request(param=param, alias=alias) return self
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` can be one of ``{True, False, None, str}``.
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, potentially caching results. estimator : object Trained estimator to use for scoring. X : {array-like, sparse matrix} Test data that will be fed to clf.decision_function or clf.predict_proba. y_true : array-like Gold standard target values for X. These must be class labels, not decision function values. **kwargs : dict Other parameters passed to the scorer. Refer to :func:`set_score_request` for more details. Returns ------- score : float Score function applied to prediction of estimator on X. """ self._warn_overlap( message=( "There is an overlap between set kwargs of this scorer instance and" " passed metadata. Please pass them either as kwargs to `make_scorer`" " or metadata, but not both." ), kwargs=kwargs, ) pos_label = None if is_regressor(estimator) else self._get_pos_label() response_method = _check_response_method(estimator, self._response_method) y_pred = method_caller( estimator, _get_response_method_name(response_method), X, pos_label=pos_label, ) scoring_kwargs = {**self._kwargs, **kwargs} return self._sign * self._score_func(y_true, y_pred, **scoring_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, potentially caching results. estimator : object Trained estimator to use for scoring. X : {array-like, sparse matrix} Test data that will be fed to clf.decision_function or clf.predict_proba. y_true : array-like Gold standard target values for X. These must be class labels, not decision function values. **kwargs : dict Other parameters passed to the scorer. Refer to :func:`set_score_request` for more details. Returns ------- score : float Score function applied to prediction of estimator on X.
_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 as string. If callable it is returned as is. If None, returns None. Returns ------- scorer : callable The scorer. Notes ----- When passed a string, this function always returns a copy of the scorer object. Calling `get_scorer` twice for the same scorer results in two separate scorer objects. Examples -------- >>> import numpy as np >>> from sklearn.dummy import DummyClassifier >>> from sklearn.metrics import get_scorer >>> X = np.reshape([0, 1, -1, -0.5, 2], (-1, 1)) >>> y = np.array([0, 1, 1, 0, 1]) >>> classifier = DummyClassifier(strategy="constant", constant=0).fit(X, y) >>> accuracy = get_scorer("accuracy") >>> accuracy(classifier, X, y) 0.4 """ if isinstance(scoring, str): try: if scoring == "max_error": # TODO (1.8): scoring="max_error" has been deprecated in 1.6, # remove in 1.8 scorer = max_error_scorer else: scorer = copy.deepcopy(_SCORERS[scoring]) except KeyError: raise ValueError( "%r is not a valid scoring value. " "Use sklearn.metrics.get_scorer_names() " "to get valid options." % scoring ) else: scorer = scoring return scorer
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 returned as is. If None, returns None. Returns ------- scorer : callable The scorer. Notes ----- When passed a string, this function always returns a copy of the scorer object. Calling `get_scorer` twice for the same scorer results in two separate scorer objects. Examples -------- >>> import numpy as np >>> from sklearn.dummy import DummyClassifier >>> from sklearn.metrics import get_scorer >>> X = np.reshape([0, 1, -1, -0.5, 2], (-1, 1)) >>> y = np.array([0, 1, 1, 0, 1]) >>> classifier = DummyClassifier(strategy="constant", constant=0).fit(X, y) >>> accuracy = get_scorer("accuracy") >>> accuracy(classifier, X, y) 0.4
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