keras/src/metrics/regression_metrics.py/R2Score/result
class R2Score:    def result(self):
        mean = self.sum / self.count
        total = self.squared_sum - self.sum * mean
        raw_scores = 1 - (self.total_mse / total)
        raw_scores = ops.where(ops.isinf(raw_scores), 0.0, raw_scores)

        if self.class_aggregation == "uniform_average":
            r2_score = ops.mean(raw_scores)
        elif self.class_aggregation == "variance_weighted_average":
            weighted_sum = ops.sum(total * raw_scores)
            sum_of_weights = ops.sum(total)
            r2_score = weighted_sum / sum_of_weights
        else:
            r2_score = raw_scores

        if self.num_regressors != 0:
            if self.num_regressors > self.num_samples - 1:
                warnings.warn(
                    "More independent predictors than datapoints "
                    "in adjusted R2 score. Falling back to standard R2 score.",
                    stacklevel=2,
                )
            elif self.num_regressors == self.num_samples - 1:
                warnings.warn(
                    "Division by zero in Adjusted R2 score. "
                    "Falling back to standard R2 score.",
                    stacklevel=2,
                )
            else:
                n = ops.convert_to_tensor(self.num_samples, dtype="float32")
                p = ops.convert_to_tensor(self.num_regressors, dtype="float32")
                num = ops.multiply(
                    ops.subtract(1.0, r2_score), ops.subtract(n, 1.0)
                )
                den = ops.subtract(ops.subtract(n, p), 1.0)
                r2_score = ops.subtract(1.0, ops.divide(num, den))
        return r2_score