so do you know observations in the first fold? would it be 3 observations coming from 32 / 10? or is it 22 or how do you know
Assistant
User
okay so it's 32 - 10 and first fold is 22, what's weird is that I didn't start to get this error until sereies 2375
Assistant
It's possible that the error arose with series 2375 due to differences in the length of the time series for different unique_ids or a data issue specific to that series. Keep in mind that not all unique_id series may start at the same time or have the same number of observations. If series 2375 has just the minimum length required to not be filtered out by the length > 31 condition, it could face issues in the cross-validation process.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
for row in forecasts_df.to_dicts():
forecasts_list.append(row)
Print the list
for forecast in forecasts_list:
print(forecast) RemoteTraceback Traceback (most recent call last)
RemoteTraceback:
"""
Traceback (most recent call last):
File "/Users/tungnguyen/anaconda3/lib/python3.10/multiprocessing/pool.py", line 125, in worker
result = (True, func(*args, **kwds))
File "/Users/tungnguyen/anaconda3/lib/python3.10/site-packages/statsforecast/core.py", line 322, in cross_validation
raise error
File "/Users/tungnguyen/anaconda3/lib/python3.10/site-packages/statsforecast/core.py", line 319, in cross_validation
res_i = model.forecast(**forecast_kwargs)
File "/Users/tungnguyen/anaconda3/lib/python3.10/site-packages/statsforecast/models.py", line 1292, in forecast
mod = auto_theta(
File "/Users/tungnguyen/anaconda3/lib/python3.10/site-packages/statsforecast/theta.py", line 633, in auto_theta
y_decompose = seasonal_decompose(y, model=decomposition_type, period=m).seasonal
File "/Users/tungnguyen/anaconda3/lib/python3.10/site-packages/statsmodels/tsa/seasonal.py", line 171, in seasonal_decompose
raise ValueError(
ValueError: x must have 2 complete cycles requires 26 observations. x only has 22 observation(s)
"""
The above exception was the direct cause of the following exception:
ValueError Traceback (most recent call last)
Cell In[11], line 21
18 sf = StatsForecast(models=models, freq='1w', n_jobs=-1)
20 # Perform cross-validation with a step size of 1 to mimic an expanding window
---> 21 crossvalidation_df = sf.cross_validation(df=y_cl4_over_31, h=15, step_size=1, n_windows=10, sort_df=True)
23 # Calculate the ensemble mean
24 ensemble = crossvalidation_df[['AutoARIMA', 'AutoETS', 'DynamicOptimizedTheta']].mean(axis=1)
File ~/anaconda3/lib/python3.10/site-packages/statsforecast/core.py:1248, in _StatsForecast._cross_validation_parallel(self, h, test_size, step_size, input_size, fitted, level, refit, target_col)
1232 future = executor.apply_async(
1233 ga.cross_validation,
1234 (
(...)
1245 ),
1246 )
1247 futures.append(future)
-> 1248 out = [f.get() for f in futures]
1249 fcsts = [d["forecasts"] for d in out]
1250 fcsts = np.vstack(fcsts)
File ~/anaconda3/lib/python3.10/site-packages/statsforecast/core.py:1248, in (.0)
1232 future = executor.apply_async(
1233 ga.cross_validation,
1234 (
(...)
1245 ),
1246 )
1247 futures.append(future)
-> 1248 out = [f.get() for f in futures]
1249 fcsts = [d["forecasts"] for d in out]
1250 fcsts = np.vstack(fcsts)
ValueError: x must have 2 complete cycles requires 26 observations. x only has 22 observation(s) you could see that the y_cl4_over_31 has at least 32 observations. but when it is processed in n_windows = 10 which is 10 folds cross validation, it has error only 22 observations, how would you resolve this issue? reduce the folds? increase the number of observations in y_cl4_over_31?
The error you encountered is due to the seasonality requirement for the DynamicOptimizedTheta model, which expects at least 2 complete cycles in the data. In this case, with season_length=13, the model expects at least 2 * season_length, which is 26 observations.
When you perform cross-validation with 10 windows (n_windows=10), the first window has fewer than the required observations for the DynamicOptimizedTheta model because it is using an expanding window approach. Even if y_cl4_over_31 has at least 32 observations, those observations are split across folds, and the starting folds may not have enough data to satisfy the model's requirements.
Here are a few ways you could resolve this issue:
Reduce the number of folds (n_windows): By decreasing the number of windows, you increase the number of observations in each training set. If you reduce n_windows enough, each window should contain more than 26 observations, satisfying the model's requirement.
Increase the number of observations for each model run by adjusting input_size: You may ensure that every training set has enough observations by setting input_size to the appropriate value. input_size determines the minimum number of observations to consider while training the model at each step, so you could set it to be at least 26 or higher.
Skip the DynamicOptimizedTheta model during cross-validation and re-include it for the final forecasting: If adjusting the folds is not possible or if it results in too few validation points, you might perform cross-validation with the other models that don't have strict data requirements and re-introduce the DynamicOptimizedTheta model later when you have enough data for fitting.
Increase the training data (y_cl4_over_31): If possible, extend the dataset to have more historical observations, which would allow you to maintain the number of folds and still meet the seasonality requirements.
Use customized logic for early folds: Implement custom logic in cross-validation to use only the other models when there's not enough data and start including the DynamicOptimizedTheta model once enough data becomes available in the expanding window.
Before making these changes, verify the length of the shortest series in y_cl4_over_31 to ensure that it meets the seasonality requirement. You could use a filter to exclude series that do not have the minimum required length. Applying these solutions will depend on the specifics of your dataset and objectives, so you'll need to assess which method best aligns with your analysis goals.
In time series cross-validation, particularly with an expanding window approach, the number of observations in each fold can vary. The number of folds does not directly determine the number of observations in each fold.
Let's clarify how the expanding window works in cross-validation:
Test size (h): This is the number of periods to forecast for each fold.
Step size: This is the number of periods to step forward after each fold. If unspecified, it's often equal to the forecast horizon h.
Number of windows (n_windows): This is the number of validation (test) windows you want to have.
The first training window starts with the earliest data available and expands by the step size with each subsequent fold. The forecast is then made for the subsequent h periods. The process repeats until n_windows folds are created.
Because you start with the minimum amount of data in the first window and expand incrementally, the early windows will have fewer observations than later ones.
Let's break down the sizing:
The very first training data will end right before the very first test set. If there are n total observations, the test set has h observations, and n_windows is the number of folds, then the final training set will have at most n - h observations since it needs to leave out h observations for the final test set.
The training data for the first window will be the smallest. If _ represents a test observation and X represents a training observation, the pattern looks like this:
First fold: [XXX]_______
Second fold: [XXXXX]_______
...
Nth fold: [XXXXXXXXXXXXXXXXXXXX]___
As n_windows increases, the first few training sets will have fewer observations, potentially becoming smaller than your season length requirements. In the error message you saw, it mentioned that only 22 observations were available for the first fold, which is below the required 26.
To find out the exact number of observations in each fold, you would typically:
Start with the number of observations available in y_cl4_over_31.
Subtract the number of observations needed for the test sets (n_windows * h).
What remains would be included in the expanding training set. This number should be the same or larger as you progress through each fold.
Since y_cl4_over_31 has at least 32 observations and you have 10 folds, the maximum number of observations allotted to the test sets would be 10 * h where h is the forecast horizon. The actual train size can be determined starting from the beginning and expanding by step_size each time while keeping enough observations for the last test set. If the step_size is different from h, you would need to account for that in your calculations as well.
Given that early folds won't meet the requirement for the DynamicOptimizedTheta model, you would need to use one of the strategies mentioned earlier to address the issue—or adapt the step size to ensure sufficient observations for the Theta model and still retain meaningful cross-validation results.
Here is a likely scenario:
Your overall dataset y_cl4_over_31 may contain multiple time series identified by their unique_id.
These time series vary in length but all have more than 31 observations, meeting your threshold criterion.
When you run the cross-validation process, series with significantly more than 31 observations can accommodate the expanding window nature of the cross-validation without issue.
However, series that have barely over 31 observations (like series 2375) might encounter problems once you remove 10 * h observations for the test sets, as the remaining length for training in the initial folds may fail to meet the model's seasonal requirements.
You should always ensure that you have enough data for both the training and testing sets. A series with exactly 32 observations would encounter issues if you remove 10 * h observations (assuming h > 2) since the remaining data might not support the seasonal decomposition required by some models such as DynamicOptimizedTheta.
To diagnose the issue:
Check the length of each time series in the dataset to ensure that they all meet the seasonal requirement after setting aside the test data.
Double-check that the step_size and h parameters in your cross-validation are appropriately chosen given the lengths of your time series.
If you find that series 2375 or any other series does not have enough observations for the cross-validation process to be viable, you may need to exclude them from this part of the analysis or adjust your cross-validation parameters so that they fit within the length of the shortest series in your dataset.