keras-team/keras · error · ValueError
Invalid value for argument `num_regressors`. Expected a valu
Error message
Invalid value for argument `num_regressors`. Expected a value >= 0. Received: num_regressors={num_regressors} What it means
R2Score requires num_regressors (the predictor count used for adjusted R-squared) to be a non-negative integer or None. Passing a negative value raises this ValueError in __init__. Pass None to get plain, non-adjusted R-squared.
Source
Thrown at keras/src/metrics/regression_metrics.py:427
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
def _build(self, y_true_shape, y_pred_shape):
if len(y_pred_shape) != 2 or len(y_true_shape) != 2:
raise ValueError(
"R2Score expects 2D inputs with shape "
"(batch_size, output_dim). Received input "View on GitHub (pinned to 7a34a03db6)
Solutions
- Pass num_regressors=None if you do not need adjusted R-squared.
- Otherwise pass the actual input feature count, e.g. num_regressors=X.shape[1].
- Map config sentinels like -1 to None before constructing the metric.
Example fix
# before metric = keras.metrics.R2Score(num_regressors=-1) # after metric = keras.metrics.R2Score(num_regressors=X_train.shape[1]) # or keras.metrics.R2Score() for plain R2
Defensive patterns
Strategy: validation
Validate before calling
if num_regressors is not None:
assert isinstance(num_regressors, int) and num_regressors >= 0, 'num_regressors must be >= 0 or None' Type guard
def is_valid_num_regressors(v) -> bool:
return v is None or (isinstance(v, int) and v >= 0) Prevention
- Map config sentinels like -1 to None before constructing R2Score.
When it happens
Trigger: keras.metrics.R2Score(num_regressors=-1) or any negative number, often from a config default of -1 meaning 'unset'.
Common situations: Config systems that use -1 as a sentinel for 'not configured'; arithmetic computing num_regressors from dataset dimensions that underflows.
Related errors
- Invalid value for argument `class_aggregation`. Expected one
- R2Score expects 2D inputs with shape (batch_size, output_dim
- R2Score expects 2D inputs with shape (batch_size, output_dim
- Layer `add_metric()` method is deprecated. Add your metric i
- Argument `num_thresholds` must be an integer > 0. Received:
AI-assisted analysis of keras-team/keras@7a34a03db6 (2026-08-25).
Data as JSON: /api/errors/c5b11b328e178fc5.
Report an issue: GitHub.