|
| 1 | +from typing import Optional, Tuple, Union |
| 2 | + |
| 3 | +import cloudpickle |
| 4 | +import numpy.typing as npt |
| 5 | +from sklearn import metrics |
| 6 | + |
| 7 | +from snowflake import snowpark |
| 8 | +from snowflake.ml._internal import telemetry |
| 9 | +from snowflake.snowpark import functions as F |
| 10 | +from snowflake.snowpark._internal import utils as snowpark_utils |
| 11 | + |
| 12 | +_PROJECT = "ModelDevelopment" |
| 13 | +_SUBPROJECT = "Metrics" |
| 14 | + |
| 15 | + |
| 16 | +@telemetry.send_api_usage_telemetry(project=_PROJECT, subproject=_SUBPROJECT) |
| 17 | +def roc_curve( |
| 18 | + *, |
| 19 | + df: snowpark.DataFrame, |
| 20 | + y_true_col_name: str, |
| 21 | + y_score_col_name: str, |
| 22 | + pos_label: Optional[Union[str, int]] = None, |
| 23 | + sample_weight_col_name: Optional[str] = None, |
| 24 | + drop_intermediate: bool = True, |
| 25 | +) -> Tuple[npt.ArrayLike, npt.ArrayLike, npt.ArrayLike]: |
| 26 | + """ |
| 27 | + Compute Receiver operating characteristic (ROC). |
| 28 | +
|
| 29 | + Note: this implementation is restricted to the binary classification task. |
| 30 | +
|
| 31 | + Args: |
| 32 | + df: Input dataframe. |
| 33 | + y_true_col_name: Column name representing true binary labels. |
| 34 | + If labels are not either {-1, 1} or {0, 1}, then pos_label should be |
| 35 | + explicitly given. |
| 36 | + y_score_col_name: Column name representing target scores, can either |
| 37 | + be probability estimates of the positive class, confidence values, |
| 38 | + or non-thresholded measure of decisions (as returned by |
| 39 | + "decision_function" on some classifiers). |
| 40 | + pos_label: The label of the positive class. |
| 41 | + When ``pos_label=None``, if `y_true` is in {-1, 1} or {0, 1}, |
| 42 | + ``pos_label`` is set to 1, otherwise an error will be raised. |
| 43 | + sample_weight_col_name: Column name representing sample weights. |
| 44 | + drop_intermediate: Whether to drop some suboptimal thresholds which would |
| 45 | + not appear on a plotted ROC curve. This is useful in order to create |
| 46 | + lighter ROC curves. |
| 47 | +
|
| 48 | + Returns: |
| 49 | + fpr: ndarray of shape (>2,) |
| 50 | + Increasing false positive rates such that element i is the false |
| 51 | + positive rate of predictions with score >= `thresholds[i]`. |
| 52 | + tpr : ndarray of shape (>2,) |
| 53 | + Increasing true positive rates such that element `i` is the true |
| 54 | + positive rate of predictions with score >= `thresholds[i]`. |
| 55 | + thresholds : ndarray of shape = (n_thresholds,) |
| 56 | + Decreasing thresholds on the decision function used to compute |
| 57 | + fpr and tpr. `thresholds[0]` represents no instances being predicted |
| 58 | + and is arbitrarily set to `max(y_score) + 1`. |
| 59 | + """ |
| 60 | + session = df._session |
| 61 | + assert session is not None |
| 62 | + sproc_name = f"roc_curve_{snowpark_utils.generate_random_alphanumeric()}" |
| 63 | + statement_params = telemetry.get_statement_params(_PROJECT, _SUBPROJECT) |
| 64 | + |
| 65 | + cols = [y_true_col_name, y_score_col_name] |
| 66 | + if sample_weight_col_name: |
| 67 | + cols.append(sample_weight_col_name) |
| 68 | + query = df[cols].queries["queries"][-1] |
| 69 | + |
| 70 | + @F.sproc( # type: ignore[misc] |
| 71 | + session=session, |
| 72 | + name=sproc_name, |
| 73 | + replace=True, |
| 74 | + packages=["cloudpickle", "scikit-learn", "snowflake-snowpark-python"], |
| 75 | + statement_params=statement_params, |
| 76 | + ) |
| 77 | + def roc_curve_sproc(session: snowpark.Session) -> bytes: |
| 78 | + df = session.sql(query).to_pandas(statement_params=statement_params) |
| 79 | + y_true = df[y_true_col_name] |
| 80 | + y_score = df[y_score_col_name] |
| 81 | + sample_weight = df[sample_weight_col_name] if sample_weight_col_name else None |
| 82 | + fpr, tpr, thresholds = metrics.roc_curve( |
| 83 | + y_true, |
| 84 | + y_score, |
| 85 | + pos_label=pos_label, |
| 86 | + sample_weight=sample_weight, |
| 87 | + drop_intermediate=drop_intermediate, |
| 88 | + ) |
| 89 | + |
| 90 | + return cloudpickle.dumps((fpr, tpr, thresholds)) # type: ignore[no-any-return] |
| 91 | + |
| 92 | + loaded_data = cloudpickle.loads(session.call(sproc_name)) |
| 93 | + res: Tuple[npt.ArrayLike, npt.ArrayLike, npt.ArrayLike] = loaded_data |
| 94 | + return res |
0 commit comments