keras-team/keras · error · ValueError

Invalid value for argument `class_aggregation`. Expected one

Error message

Invalid value for argument `class_aggregation`. Expected one of {valid_class_aggregation_values}. Received: class_aggregation={class_aggregation}

What it means

R2Score's class_aggregation argument controls how per-output R-squared values are combined and only accepts None, 'uniform_average' or 'variance_weighted_average'. Any other string (e.g. 'mean' or 'average') raises this ValueError at construction time.

Source

Thrown at keras/src/metrics/regression_metrics.py:421

    def __init__(
        self,
        class_aggregation="uniform_average",
        num_regressors=0,
        name="r2_score",
        dtype=None,
    ):
        super().__init__(name=name, dtype=dtype)
        # Metric should be maximized during optimization.
        self._direction = "up"

        valid_class_aggregation_values = (
            None,
            "uniform_average",
            "variance_weighted_average",
        )
        if class_aggregation not in valid_class_aggregation_values:
            raise ValueError(
                "Invalid value for argument `class_aggregation`. Expected "
                f"one of {valid_class_aggregation_values}. "
                f"Received: class_aggregation={class_aggregation}"
            )
        if num_regressors < 0:
            raise ValueError(
                "Invalid value for argument `num_regressors`. "
                "Expected a value >= 0. "
                f"Received: num_regressors={num_regressors}"
            )
        self.class_aggregation = class_aggregation
        self.num_regressors = num_regressors
        self.num_samples = self.add_variable(
            shape=(),
            initializer=initializers.Zeros(),
            name="num_samples",
        )
        self._built = False

View on GitHub (pinned to 7a34a03db6)

Solutions

  1. Use 'uniform_average' for a plain mean of per-output scores.
  2. Use 'variance_weighted_average' for variance-weighted aggregation, or None to get per-output values.

Example fix

# before
metric = keras.metrics.R2Score(class_aggregation='mean')

# after
metric = keras.metrics.R2Score(class_aggregation='uniform_average')
Defensive patterns

Strategy: validation

Validate before calling

VALID = (None, 'uniform_average', 'variance_weighted_average')
assert class_aggregation in VALID, f'class_aggregation must be in {VALID}'

Type guard

def is_valid_class_agg(v) -> bool:
    return v in (None, 'uniform_average', 'variance_weighted_average')

Prevention

When it happens

Trigger: keras.metrics.R2Score(class_aggregation='mean') or any value not in (None, 'uniform_average', 'variance_weighted_average').

Common situations: Assuming sklearn R2Score-style naming ('raw_values', 'mean') transfers to Keras; typo'd config values.

Understand the failure class

Background: Invalid enum value errors: "Unknown type", "Invalid scope", "must be one of" — when a string is not on the library's allowed list — this error's family across 23 libraries.

Related errors


AI-assisted analysis of keras-team/keras@7a34a03db6 (2026-08-25). Data as JSON: /api/errors/86ac2810a89fa08b. Report an issue: GitHub.