Source code for scalerqec.Stratified.fitting

import numpy as np

[docs] def r_squared(y_true, y_pred, clip=False): """ Compute the coefficient of determination (R²). Parameters ---------- y_true : array-like Observed data. y_pred : array-like Model-predicted data (same length as y_true). clip : bool, default False If True, negative R² values are clipped to 0 so the score lies strictly in the interval [0, 1]. Returns ------- float The R² statistic. """ y_true = np.asarray(y_true, dtype=float) y_pred = np.asarray(y_pred, dtype=float) if y_true.shape != y_pred.shape: raise ValueError("y_true and y_pred must have the same shape") ss_res = np.sum((y_true - y_pred) ** 2) # residual sum of squares ss_tot = np.sum((y_true - y_true.mean()) ** 2) # total sum of squares # Handle the degenerate case where variance is zero if ss_tot == 0.0: return 1.0 if ss_res == 0.0 else 0.0 r2 = 1.0 - ss_res / ss_tot return max(0.0, r2) if clip else r2