3535logger = logging .getLogger (__name__ )
3636
3737
38+ def _as_python_label (label : Any ) -> Any :
39+ """Return a hashable Python scalar for NumPy scalar labels."""
40+ return label .item () if hasattr (label , "item" ) else label
41+
42+
43+ def _encode_labels_for_probability_columns (
44+ y_true : np .ndarray ,
45+ n_classes : int ,
46+ class_labels : Optional [np .ndarray ],
47+ ) -> np .ndarray :
48+ """Encode semantic labels into the class-index order used by y_prob columns."""
49+ if class_labels is not None :
50+ class_labels_array = np .asarray (class_labels )
51+ if len (class_labels_array ) != n_classes :
52+ raise ValueError (
53+ "class_labels length "
54+ f"({ len (class_labels_array )} ) does not match probability column shape "
55+ f"({ n_classes } columns)."
56+ )
57+
58+ label_to_index = {
59+ _as_python_label (label ): idx for idx , label in enumerate (class_labels_array )
60+ }
61+ try :
62+ encoded_labels : np .ndarray = np .asarray (
63+ [_as_python_label (label_to_index [_as_python_label (label )]) for label in y_true ],
64+ dtype = int ,
65+ )
66+ return encoded_labels
67+ except KeyError as exc :
68+ raise ValueError ("y_true contains labels that are missing from class_labels." ) from exc
69+
70+ return y_true .astype (int )
71+
72+
3873def _run_analysis_pipeline (
3974 model : Any ,
4075 X : np .ndarray ,
@@ -47,6 +82,7 @@ def _run_analysis_pipeline(
4782 plugins : Optional [list [str ]] = None ,
4883 framework : Optional [str ] = None ,
4984 backend_metadata : Optional [dict [str , Any ]] = None ,
85+ class_labels : Optional [np .ndarray ] = None ,
5086 verbose : bool = True ,
5187) -> TrustReport :
5288 """
@@ -98,7 +134,10 @@ def _run_analysis_pipeline(
98134
99135 # Multiclass Brier Score: 1/N * sum(sum((p_ic - o_ic)^2))
100136 # We can compute this efficiently
101- y_true_one_hot = np .eye (n_classes )[y_true .astype (int )]
137+ y_true_indices = _encode_labels_for_probability_columns (
138+ y_true , n_classes , class_labels
139+ )
140+ y_true_one_hot = np .eye (n_classes )[y_true_indices ]
102141 mbrier = np .mean (np .sum ((y_prob - y_true_one_hot ) ** 2 , axis = 1 ))
103142
104143 results ["calibration" ] = {
0 commit comments