|
2 | 2 | # SPDX-FileCopyrightText: Copyright (c) 2020-2026, NVIDIA CORPORATION. |
3 | 3 | # SPDX-License-Identifier: Apache-2.0 |
4 | 4 | # |
| 5 | +import warnings |
| 6 | + |
5 | 7 | import cudf |
6 | 8 | import cupy as cp |
| 9 | +import cupyx |
7 | 10 | import numpy as np |
| 11 | +from sklearn.exceptions import UndefinedMetricWarning |
8 | 12 |
|
9 | 13 | from cuml.internals.validation import ( |
10 | 14 | check_array, |
@@ -108,6 +112,311 @@ def accuracy_score(y_true, y_pred, *, sample_weight=None, normalize=True): |
108 | 112 | return float(cp.count_nonzero(correct)) |
109 | 113 |
|
110 | 114 |
|
| 115 | +def precision_score( |
| 116 | + y_true, |
| 117 | + y_pred, |
| 118 | + *, |
| 119 | + labels=None, |
| 120 | + pos_label=1, |
| 121 | + average="binary", |
| 122 | + sample_weight=None, |
| 123 | + zero_division="warn", |
| 124 | +): |
| 125 | + """ |
| 126 | + Compute the precision. |
| 127 | +
|
| 128 | + The precision is the ratio ``tp / (tp + fp)`` where ``tp`` is the number |
| 129 | + of true positives and ``fp`` the number of false positives. The precision |
| 130 | + is intuitively the ability of the classifier not to label as positive a |
| 131 | + sample that is negative. |
| 132 | +
|
| 133 | + The best value is 1 and the worst value is 0. |
| 134 | +
|
| 135 | + Parameters |
| 136 | + ---------- |
| 137 | + y_true : array-like (device or host) of shape (n_samples,) |
| 138 | + Ground truth (correct) target values. |
| 139 | + y_pred : array-like (device or host) of shape (n_samples,) |
| 140 | + Estimated target values as returned by a classifier. |
| 141 | + labels : array-like (device or host), default=None |
| 142 | + The set of labels to include when ``average != 'binary'``, and their |
| 143 | + order if ``average is None``. Labels present in the data can be |
| 144 | + excluded, and labels not present in the data will receive the score |
| 145 | + given by ``zero_division``. Ignored when ``average == 'binary'``. |
| 146 | + pos_label : int, float, bool or str, default=1 |
| 147 | + The class to report if ``average='binary'`` and the data is binary, |
| 148 | + otherwise this parameter is ignored. |
| 149 | + average : {'micro', 'macro', 'weighted', 'binary'} or None, \ |
| 150 | + default='binary' |
| 151 | + This parameter is required for multiclass targets. |
| 152 | + ``'micro'``: |
| 153 | + Calculate metrics globally by counting the total true positives |
| 154 | + and false positives. |
| 155 | + ``'macro'``: |
| 156 | + Calculate metrics for each label, and find their unweighted mean. |
| 157 | + ``'weighted'``: |
| 158 | + Calculate metrics for each label, and find their average weighted |
| 159 | + by support (the number of true instances for each label). |
| 160 | + ``'binary'``: |
| 161 | + Only report results for the class specified by ``pos_label``. |
| 162 | + Only applicable to binary targets. |
| 163 | + If ``None``, the scores for each label are returned individually. |
| 164 | + sample_weight : array-like (device or host) of shape (n_samples,), \ |
| 165 | + default=None |
| 166 | + Sample weights. |
| 167 | + zero_division : {"warn", 0.0, 1.0}, default="warn" |
| 168 | + Sets the value to return when there is a zero division. If set to |
| 169 | + ``"warn"``, this acts like 0, but a warning is also raised. |
| 170 | +
|
| 171 | + Returns |
| 172 | + ------- |
| 173 | + score : float or numpy.ndarray of float |
| 174 | + Precision of the positive class in binary classification or the |
| 175 | + averaged precision of each class for the multiclass task. A NumPy |
| 176 | + array with one score per label, ordered following ``labels`` (or the |
| 177 | + sorted union of the observed labels when ``labels is None``), is |
| 178 | + returned when ``average is None``. |
| 179 | +
|
| 180 | + See Also |
| 181 | + -------- |
| 182 | + accuracy_score : Accuracy classification score. |
| 183 | + confusion_matrix : Compute confusion matrix to evaluate the accuracy of a |
| 184 | + classification. |
| 185 | +
|
| 186 | + Notes |
| 187 | + ----- |
| 188 | + Numeric labels (integer, float and bool dtypes) are counted on the GPU. |
| 189 | + String, object and categorical labels are supported through a device-side |
| 190 | + encoding against the sorted union of the observed labels, which matches |
| 191 | + scikit-learn's label ordering. Null values are not supported. The |
| 192 | + ``'samples'`` averaging strategy, multilabel indicator input and |
| 193 | + ``zero_division=np.nan`` accepted by scikit-learn are not supported. |
| 194 | +
|
| 195 | + Examples |
| 196 | + -------- |
| 197 | + .. code-block:: python |
| 198 | +
|
| 199 | + >>> import cupy as cp |
| 200 | + >>> from cuml.metrics import precision_score |
| 201 | + >>> y_true = cp.array([0, 1, 2, 0, 1, 2]) |
| 202 | + >>> y_pred = cp.array([0, 2, 1, 0, 0, 1]) |
| 203 | + >>> precision_score(y_true, y_pred, average='macro') |
| 204 | + 0.2222222222222222 |
| 205 | + >>> precision_score(y_true, y_pred, average='micro') |
| 206 | + 0.3333333333333333 |
| 207 | + >>> precision_score(y_true, y_pred, average=None) |
| 208 | + array([0.66666667, 0. , 0. ]) |
| 209 | + """ |
| 210 | + |
| 211 | + average_options = (None, "micro", "macro", "weighted", "binary") |
| 212 | + if average not in average_options: |
| 213 | + raise ValueError(f"average has to be one of {average_options}") |
| 214 | + |
| 215 | + if isinstance(zero_division, str) and zero_division == "warn": |
| 216 | + zero_division_value = 0.0 |
| 217 | + elif isinstance(zero_division, (int, float)) and zero_division in (0, 1): |
| 218 | + zero_division_value = float(zero_division) |
| 219 | + else: |
| 220 | + raise ValueError( |
| 221 | + 'zero_division must be one of {"warn", 0, 1}, got ' |
| 222 | + f"{zero_division!r}" |
| 223 | + ) |
| 224 | + |
| 225 | + y_true = _input_to_cupy_or_cudf_series(y_true) |
| 226 | + y_pred = _input_to_cupy_or_cudf_series(y_pred) |
| 227 | + |
| 228 | + check_consistent_length(y_true, y_pred) |
| 229 | + |
| 230 | + if len(y_true) == 0 or len(y_pred) == 0: |
| 231 | + raise ValueError( |
| 232 | + "Found empty input array (e.g., `y_true` or `y_pred`) while a " |
| 233 | + "minimum of 1 sample is required." |
| 234 | + ) |
| 235 | + |
| 236 | + for name, y in (("y_true", y_true), ("y_pred", y_pred)): |
| 237 | + if isinstance(y, cudf.Series) and y.isna().any(): |
| 238 | + raise ValueError( |
| 239 | + f"precision_score does not support null values in {name}" |
| 240 | + ) |
| 241 | + |
| 242 | + if ( |
| 243 | + sample_weight := check_sample_weight(sample_weight, dtype=np.float64) |
| 244 | + ) is not None: |
| 245 | + check_consistent_length(y_true, sample_weight) |
| 246 | + |
| 247 | + numeric = all( |
| 248 | + not isinstance(y, cudf.Series) or y.dtype.kind in "iufb" |
| 249 | + for y in (y_true, y_pred) |
| 250 | + ) |
| 251 | + |
| 252 | + if numeric: |
| 253 | + y_true_t = ( |
| 254 | + y_true.to_cupy() if isinstance(y_true, cudf.Series) else y_true |
| 255 | + ) |
| 256 | + y_pred_t = ( |
| 257 | + y_pred.to_cupy() if isinstance(y_pred, cudf.Series) else y_pred |
| 258 | + ) |
| 259 | + present = cp.unique( |
| 260 | + cp.concatenate([cp.unique(y_true_t), cp.unique(y_pred_t)]) |
| 261 | + ) |
| 262 | + present_labels = cp.asnumpy(present).tolist() |
| 263 | + for name, arr in (("y_true", y_true_t), ("y_pred", y_pred_t)): |
| 264 | + if arr.dtype.kind == "f": |
| 265 | + if bool(cp.isnan(arr).any()): |
| 266 | + raise ValueError(f"Input {name} contains NaN.") |
| 267 | + if bool(cp.isinf(arr).any()): |
| 268 | + raise ValueError( |
| 269 | + f"Input {name} contains infinity or a value too " |
| 270 | + "large for dtype('float64')." |
| 271 | + ) |
| 272 | + if bool((arr != cp.floor(arr)).any()): |
| 273 | + raise ValueError(f"'{name}' can only have integer values") |
| 274 | + else: |
| 275 | + y_true = ( |
| 276 | + y_true if isinstance(y_true, cudf.Series) else cudf.Series(y_true) |
| 277 | + ) |
| 278 | + y_pred = ( |
| 279 | + y_pred if isinstance(y_pred, cudf.Series) else cudf.Series(y_pred) |
| 280 | + ) |
| 281 | + try: |
| 282 | + present_labels = sorted( |
| 283 | + set().union( |
| 284 | + *[ |
| 285 | + set(y.unique().dropna().to_pandas().tolist()) |
| 286 | + for y in (y_true, y_pred) |
| 287 | + ] |
| 288 | + ) |
| 289 | + ) |
| 290 | + except TypeError: |
| 291 | + raise ValueError( |
| 292 | + "Mix of label input types (string and number)" |
| 293 | + ) from None |
| 294 | + |
| 295 | + if average == "binary": |
| 296 | + if len(present_labels) > 2: |
| 297 | + raise ValueError( |
| 298 | + "Target is multiclass but average='binary'. Please choose " |
| 299 | + "another average setting, one of [None, 'micro', 'macro', " |
| 300 | + "'weighted']." |
| 301 | + ) |
| 302 | + if len(present_labels) >= 2 and pos_label not in present_labels: |
| 303 | + raise ValueError( |
| 304 | + f"pos_label={pos_label} is not a valid label. It should be " |
| 305 | + f"one of {present_labels}" |
| 306 | + ) |
| 307 | + out_labels = [pos_label] if not numeric else cp.array([pos_label]) |
| 308 | + else: |
| 309 | + if pos_label not in (None, 1): |
| 310 | + warnings.warn( |
| 311 | + "Note that pos_label (set to " |
| 312 | + f"{pos_label!r}) is ignored when average != 'binary' " |
| 313 | + f"(got {average!r}). You may use labels=[pos_label] to " |
| 314 | + "specify a single positive class.", |
| 315 | + UserWarning, |
| 316 | + stacklevel=2, |
| 317 | + ) |
| 318 | + if labels is not None: |
| 319 | + out_labels = _labels_as_device_or_host(labels, numeric) |
| 320 | + else: |
| 321 | + out_labels = present if numeric else present_labels |
| 322 | + |
| 323 | + if numeric: |
| 324 | + table = cp.unique(cp.concatenate([present, out_labels])) |
| 325 | + pos = cp.searchsorted(table, out_labels) |
| 326 | + true_idx = cp.searchsorted(table, y_true_t) |
| 327 | + pred_idx = cp.searchsorted(table, y_pred_t) |
| 328 | + n_labels_total = table.shape[0] |
| 329 | + else: |
| 330 | + table = sorted(set(present_labels) | set(out_labels)) |
| 331 | + cat_dtype = cudf.CategoricalDtype(categories=table) |
| 332 | + true_idx = ( |
| 333 | + y_true.astype(cat_dtype).cat.codes.to_cupy().astype(np.int64) |
| 334 | + ) |
| 335 | + pred_idx = ( |
| 336 | + y_pred.astype(cat_dtype).cat.codes.to_cupy().astype(np.int64) |
| 337 | + ) |
| 338 | + pos = cp.array( |
| 339 | + [table.index(label) for label in out_labels], dtype=np.int64 |
| 340 | + ) |
| 341 | + n_labels_total = len(table) |
| 342 | + |
| 343 | + weights = ( |
| 344 | + cp.ones(y_true.shape[0], dtype=cp.float64) |
| 345 | + if sample_weight is None |
| 346 | + else sample_weight.astype(cp.float64, copy=False) |
| 347 | + ) |
| 348 | + |
| 349 | + cm = cupyx.scipy.sparse.coo_matrix( |
| 350 | + (weights, (true_idx, pred_idx)), |
| 351 | + shape=(n_labels_total, n_labels_total), |
| 352 | + ).toarray() |
| 353 | + |
| 354 | + tp_sum = cm[pos, pos] |
| 355 | + pred_sum = cm[:, pos].sum(axis=0) |
| 356 | + true_sum = cm[pos, :].sum(axis=1) |
| 357 | + |
| 358 | + empty = pred_sum == 0 |
| 359 | + per_class = cp.where( |
| 360 | + empty, zero_division_value, tp_sum / cp.where(empty, 1.0, pred_sum) |
| 361 | + ) |
| 362 | + n_out = per_class.shape[0] |
| 363 | + |
| 364 | + if average is None: |
| 365 | + if zero_division == "warn" and empty.any(): |
| 366 | + _warn_precision_undefined(n_out) |
| 367 | + return cp.asnumpy(per_class) |
| 368 | + |
| 369 | + if average == "binary": |
| 370 | + if zero_division == "warn" and pred_sum[0] == 0: |
| 371 | + _warn_precision_undefined(1) |
| 372 | + return float(per_class[0]) |
| 373 | + |
| 374 | + if average == "micro": |
| 375 | + pred_total = pred_sum.sum() |
| 376 | + if pred_total == 0: |
| 377 | + if zero_division == "warn": |
| 378 | + _warn_precision_undefined(1) |
| 379 | + return zero_division_value |
| 380 | + return float(tp_sum.sum() / pred_total) |
| 381 | + |
| 382 | + if zero_division == "warn" and empty.any(): |
| 383 | + _warn_precision_undefined(n_out) |
| 384 | + |
| 385 | + if average == "macro": |
| 386 | + return float(per_class.mean()) |
| 387 | + |
| 388 | + per_class = cp.asnumpy(per_class) |
| 389 | + try: |
| 390 | + return float(np.average(per_class, weights=cp.asnumpy(true_sum))) |
| 391 | + except ZeroDivisionError: |
| 392 | + # all-zero support: scikit-learn ignores the weights entirely |
| 393 | + return float(np.average(per_class)) |
| 394 | + |
| 395 | + |
| 396 | +def _labels_as_device_or_host(labels, numeric): |
| 397 | + if numeric: |
| 398 | + labels = _input_to_cupy_or_cudf_series(labels) |
| 399 | + if isinstance(labels, cudf.Series): |
| 400 | + labels = labels.to_cupy() |
| 401 | + return cp.reshape(labels, (-1,)) |
| 402 | + if isinstance(labels, cudf.Series): |
| 403 | + return labels.to_pandas().tolist() |
| 404 | + if hasattr(labels, "tolist"): |
| 405 | + return labels.tolist() |
| 406 | + return list(labels) |
| 407 | + |
| 408 | + |
| 409 | +def _warn_precision_undefined(n_labels): |
| 410 | + due_to = "due to" if n_labels == 1 else "in labels with" |
| 411 | + warnings.warn( |
| 412 | + "Precision is ill-defined and being set to 0.0 " |
| 413 | + f"{due_to} no predicted samples. Use `zero_division` parameter " |
| 414 | + "to control this behavior.", |
| 415 | + UndefinedMetricWarning, |
| 416 | + stacklevel=3, |
| 417 | + ) |
| 418 | + |
| 419 | + |
111 | 420 | def log_loss( |
112 | 421 | y_true, y_pred, eps=1e-15, normalize=True, sample_weight=None |
113 | 422 | ) -> float: |
|
0 commit comments