gridsearch() returns a NaN-scored parameter combination as best when it comes first in the grid
darts/models/forecasting/forecasting_model.py:2033
errors: list[float] = _parallel_apply(
iterator, _evaluate_combination, n_jobs, {}, {}
)
min_error = min(errors)
best_param_combination = dict(
list(zip(parameters.keys(), params_cross_product[errors.index(min_error)]))
)With NaN in the list, Python's min() depends on order. x < nan is always False, so a NaN in position 0 is never replaced, while a NaN anywhere else is skipped: min([nan, 5.0, 0.3]) is nan but min([5.0, nan, 0.3]) is 0.3. The docstring (L1692) says "the model resulting in the smallest metric output will be chosen". In practice, whenever the first evaluated combination scores NaN, gridsearch returns that combination with min_error=nan, whatever the other scores are.
Since 0.47.0 (#3122) the default configuration produces NaN scores. The default metric=mape now uses zero_division="warn". A window where every actual is 0 and the forecast is not now returns NaN, where it used to raise. In expanding-window mode, gridsearch passes its default reduction=np.mean (L1674, L1975) to backtest, where it is applied at L1639. A single such window therefore makes the whole combination NaN. A model that emits NaN forecasts, for example after a diverged training run, also scores NaN under every aggregated metric. Scaled metrics (mase, etc.) can also return NaN on a zero in-sample scale since 0.44.0 (#3059).
The discussion on #3122 noted that, because mape is the default metric for backtest and gridsearch, the change "makes those surface NaN instead of raising on a zero actual". That discussion did not cover how gridsearch picks among NaN and finite scores. #1462 (a try/except around combinations that raise) is related but separate.
Measured
Method: lines 2029–2037 were executed verbatim. Each combination is scored with darts' mape, copied together with ape and _safe_divide (default zero_division="warn", component_reduction=np.nanmean), on a fixed forecast per combination. For expanding-window mode, the per-window scores go through backtest's errors_series = reduction(errors_series, axis=1) (L1639) with gridsearch's default reduction=np.mean.
| Mode | Actuals | Grid order (forecast) | Scores | Chosen | min_error |
Expected |
|---|---|---|---|---|---|---|
| split | [0,0,0] |
bad [4,4,4], perfect [0,0,0] |
[nan, 0.0] |
bad | nan | perfect, 0.0 |
| split | [0,0,0] |
perfect, bad | [0.0, nan] |
perfect | 0.0 | perfect, 0.0 |
| split | [10,20,30] |
diverged [nan,nan,nan], worse (+20%), better (+10%) |
[nan, 20.0, 10.0] |
diverged | nan | better, 10.0 |
| split | [10,20,30] |
worse, better, diverged | [20.0, 10.0, nan] |
better | 10.0 | better, 10.0 |
| split | [10,20,30] |
worse, better | [20.0, 10.0] |
better | 10.0 | better, 10.0 |
| expanding, h=1 | [5,0,3,4] |
lag1 [5.5,1,3.3,4.4], exact [5,0,3,4], awful [50,0,30,40] |
[nan, 0.0, 675.0] |
lag1 | nan | exact, 0.0 |
| expanding, h=1 | [5,0,3,4] |
awful, lag1, exact | [675.0, nan, 0.0] |
exact | 0.0 | exact, 0.0 |
| expanding, h=1 | [5,0,3,4] |
lag1, lag1 | [nan, nan] |
lag1 | nan | error or warning: nothing scorable |
The data and the scores are the same in every row; only the grid order changes which model is chosen. With n_random_samples, _sample_params uses random.sample (L2671, L2680), so the order, and with it the chosen model, is random.
Consequence
gridsearchreturns an untrained model, which callers usually fit right away. A configuration that could not be scored (NaN forecasts, or undefined under the metric) is fitted and used as the best one, even when the grid contains a perfect combination.- On intermittent series with the default metric in expanding-window mode and
forecast_horizon=1, any combination that forecasts a non-zero value at a zero actual scores NaN. The result then depends on whether the first grid entry is one of those combinations. - gridsearch itself does not warn that combinations were unscorable, or that the returned
min_erroris NaN. For zero actuals, the only signal is the metric's generic "denominator is zero" warning. For NaN forecasts there is no warning at all. No gridsearch test intest_backtesting.pycovers a NaN score.
Suggested fix
Treat a NaN score as "not scorable" when picking the minimum. This matches how NaN is already handled elsewhere: the metrics default to component_reduction=np.nanmean, mape averages over time with np.nanmean, and backtest defaults to reduction=np.nanmean (L1289).
errors_arr = np.asarray(errors, dtype=float)
nan_mask = np.isnan(errors_arr)
if nan_mask.all():
raise_log(
ValueError("All hyperparameter combinations resulted in a NaN `metric` score."),
logger,
)
if nan_mask.any():
logger.warning(
f"{int(nan_mask.sum())} of {len(errors)} hyperparameter combinations resulted in a "
"NaN `metric` score and were excluded from the selection."
)
best_idx = int(np.nanargmin(errors_arr))
min_error = errors[best_idx]
best_param_combination = dict(zip(parameters.keys(), params_cross_product[best_idx]))A test with a NaN-scoring combination at position 0 of the grid would pin this.
Source: unit8co/darts