Skip to content

r2_score: Coefficient of Determination (R²) Metric

The r2_score function computes the coefficient of determination (R²) for regression tasks. This metric measures the proportion of variance in the target variable that is explained by the model.


Overview

R² is a standard metric for evaluating regression models: - R² = 1 indicates perfect prediction. - R² = 0 indicates the model does no better than the mean. - R² < 0 indicates the model performs worse than the mean.


Parameters

Parameter Type Description Default
y_true array-like True values (targets). Required
y_pred array-like Predicted values. Required
verbose bool If True, enables detailed logging for debugging. False

Returns

  • float
    Proportion of variance explained (1 is perfect prediction).

Raises

  • TypeError
    If inputs are not array-like.
  • ValueError
    If shapes do not match or inputs are empty.

Example Usage

import numpy as np
from machinegnostics.metrics import r2_score

y_true = [3, -0.5, 2, 7]
y_pred = [2.5, 0.0, 2, 8]
score = r2_score(y_true, y_pred)
print(score)

adjusted_r2_score: Adjusted R² Metric

The adjusted_r2_score function computes the adjusted R² score, which accounts for the number of predictors in the model. This metric penalizes the addition of unnecessary features.


Overview

Adjusted R² is useful for comparing models with different numbers of predictors: - Adjusted R² increases only if the new predictor improves the model more than would be expected by chance.


Parameters

Parameter Type Description Default
y_true array-like True values (targets). Required
y_pred array-like Predicted values. Required
n_features int Number of features (independent variables) in the model. Required
verbose bool If True, enables detailed logging for debugging. False

Returns

  • float
    Adjusted R² accounting for number of predictors.

Raises

  • TypeError
    If inputs are not array-like or n_features is not a non-negative integer.
  • ValueError
    If shapes do not match, inputs are empty, or n_features is invalid.

Example Usage

import numpy as np
from machinegnostics.metrics import adjusted_r2_score

y_true = [3, -0.5, 2, 7]
y_pred = [2.5, 0.0, 2, 8]
n_features = 2
score_adj = adjusted_r2_score(y_true, y_pred, n_features)
print(score_adj)

Notes

  • Both functions support input as lists, numpy arrays, or pandas Series.
  • Inputs must be 1D, have the same shape, and must not be empty or contain NaN/Inf.
  • Adjusted R² is undefined if the number of samples is less than or equal to the number of features plus one.

Author: Nirmal Parmar
Date: 2025-09-24