r2#
- openstef_beam.metrics.r2(y_true: NDArray[floating], y_pred: NDArray[floating], *, sample_weights: NDArray[floating] | None = None) float[source]#
Calculate the R² (coefficient of determination) score.
R² represents the proportion of variance in the dependent variable that is predictable from the independent variable(s). It provides a measure of how well observed outcomes are replicated by the model, based on the proportion of total variation of outcomes explained by the model.
Structurally invalid inputs, such as incompatible shapes or unsupported dimensions, raise ValueError. Statistically unusable data, such as fewer than two samples or non-finite values, returns NaN.
- Parameters:
- Returns:
The R² score as a float. The best possible score is 1.0, and the score can be negative because a model can perform arbitrarily worse than a constant mean predictor. Fewer than two samples or non-finite data returns NaN.
For a constant target, this function follows scikit-learn’s default finite behavior: a perfect prediction returns 1.0 and an imperfect prediction returns 0.0.
- Raises:
ValueError – If the inputs are not one-dimensional, if y_true and y_pred have different shapes, or if sample_weights does not have the same one-dimensional shape as y_true.
- Return type:
Example
Basic usage with energy load data
>>> import numpy as np >>> y_true = np.array([100, 120, 110, 130, 105]) >>> y_pred = np.array([98, 122, 108, 135, 107]) >>> score = r2(y_true, y_pred) >>> round(score, 3) 0.929
Perfect predictions give R² = 1.0
>>> perfect_pred = np.array([100, 120, 110, 130, 105]) >>> r2(y_true, perfect_pred) 1.0
With sample weights
>>> weights = np.array([1, 2, 1, 2, 1]) >>> score = r2(y_true, y_pred, sample_weights=weights) >>> isinstance(score, float) True