from statsforecast import StatsForecast from statsforecast.models import HoltWinters…
- User
from statsforecast import StatsForecast from statsforecast.models import HoltWinters from statsforecast.utils import ConformalIntervals import numpy as np import polars as pl
Polars option to display all rows
pl.Config.set_tbl_rows(None)
Initialize the models
models = [ HoltWinters(season_length=4) ]
Initialize the StatsForecast model
sf = StatsForecast(models=models, freq='1w', n_jobs=-1)
Perform cross-validation with a step size of 1 to mimic an expanding window
crossvalidation_df = sf.cross_validation(df=y_cl4_over_19, h=4, step_size=1, n_windows=5, sort_df=True)
Calculate the ensemble mean
ensemble = crossvalidation_df[['HoltWinters']].mean(axis=1)
Create a Series for the ensemble mean
ensemble_series = pl.Series('Ensemble', ensemble)
Add the ensemble mean as a new column to the DataFrame
crossvalidation_df = crossvalidation_df.with_columns(ensemble_series)
def wmape(y_true, y_pred): return np.abs(y_true - y_pred).sum() / np.abs(y_true).sum()
Calculate the WMAPE for the ensemble model
wmape_value = wmape(crossvalidation_df['y'], crossvalidation_df['Ensemble']) print('Average WMAPE for Ensemble: ', round(wmape_value, 4))
Calculate the errors for the ensemble model
errors = crossvalidation_df['y'] - crossvalidation_df['Ensemble']
For an individual forecast
individual_accuracy = 1 - (abs(crossvalidation_df['y'] - crossvalidation_df['Ensemble']) / crossvalidation_df['y']) individual_bias = (crossvalidation_df['Ensemble'] / crossvalidation_df['y']) - 1
Add these calculations as new columns to DataFrame
crossvalidation_df = crossvalidation_df.with_columns([ individual_accuracy.alias("individual_accuracy"), individual_bias.alias("individual_bias") ])
Print the individual accuracy and bias for each week
for row in crossvalidation_df.to_dicts(): id = row['unique_id'] date = row['ds'] accuracy = row['individual_accuracy'] bias = row['individual_bias'] print(f"{id}, {date}, Individual Accuracy: {accuracy:.4f}, Individual Bias: {bias:.4f}")
For groups of forecasts
group_accuracy = 1 - (errors.abs().sum() / crossvalidation_df['y'].sum()) group_bias = (crossvalidation_df['Ensemble'].sum() / crossvalidation_df['y'].sum()) - 1
Print the average group accuracy and group bias over all folds for the ensemble model
print('Average Group Accuracy: ', round(group_accuracy, 4)) print('Average Group Bias: ', round(group_bias, 4)) 12519007_US01_8_1108349, 2023-11-13 00:00:00, Individual Accuracy: -0.4972, Individual Bias: 1.4972 12519007_US01_8_1108349, 2023-11-20 00:00:00, Individual Accuracy: 0.4678, Individual Bias: -0.5322 12519007_US01_8_1108349, 2023-11-06 00:00:00, Individual Accuracy: 0.9100, Individual Bias: -0.0900 12519007_US01_8_1108349, 2023-11-13 00:00:00, Individual Accuracy: -1.7148, Individual Bias: 2.7148 12519007_US01_8_1108349, 2023-11-20 00:00:00, Individual Accuracy: 0.6192, Individual Bias: -0.3808 12519007_US01_8_1108349, 2023-11-27 00:00:00, Individual Accuracy: -5.4835, Individual Bias: 6.4835 12519007_US01_8_5338737, 2023-07-31 00:00:00, Individual Accuracy: -97.3718, Individual Bias: 98.3718 12519007_US01_8_5338737, 2023-08-14 00:00:00, Individual Accuracy: -8.2802, Individual Bias: 9.2802 12519007_US01_8_5338737, 2023-08-28 00:00:00, Individual Accuracy: -14.6154, Individual Bias: 15.6154 12519007_US01_8_5338737, 2023-09-04 00:00:00, Individual Accuracy: 0.3744, Individual Bias: -0.6256 12519007_US01_8_5338737, 2023-08-14 00:00:00, Individual Accuracy: -4.6083, Individual Bias: 5.6083 12519007_US01_8_5338737, 2023-08-28 00:00:00, Individual Accuracy: -10.1394, Individual Bias: 11.1394 there are negative values in here leading to big spread on inidividual accuracy and bias calculations, is there a way to put a constraint on group accuracy and bias calculation to ignore individual accurray and individual bias with values greater than -15 or 15? , only at the group level # For groups of forecasts group_accuracy = 1 - (errors.abs().sum() / crossvalidation_df['y'].sum()) group_bias = (crossvalidation_df['Ensemble'].sum() / crossvalidation_df['y'].sum()) - 1
- Assistant
Yes, you can apply a constraint to ignore individual accuracies and biases with values greater than 15 or less than -15 at the group level by first filtering the
crossvalidation_dfDataFrame to only include rows where the individual accuracies and biases are within the specified range. Then, you can recalculate the group accuracy and bias based on this filtered DataFrame. Here's how you can do it:# Filter the DataFrame to include only rows with individual accuracy and bias within the specified range constraint_df = crossvalidation_df.filter((pl.col('individual_accuracy') <= 15) & (pl.col('individual_accuracy') >= -15) & (pl.col('individual_bias') <= 15) & (pl.col('individual_bias') >= -15)) # Recalculate the errors for the constrained ensemble model errors_constrained = constraint_df['y'] - constraint_df['Ensemble'] # For groups of forecasts with constraints group_accuracy_constrained = 1 - (errors_constrained.abs().sum() / constraint_df['y'].sum()) group_bias_constrained = (constraint_df['Ensemble'].sum() / constraint_df['y'].sum()) - 1 # Print the constrained average group accuracy and group bias over all folds for the ensemble model print('Constrained Average Group Accuracy: ', round(group_accuracy_constrained, 4)) print('Constrained Average Group Bias: ', round(group_bias_constrained, 4)) - User
wait, I didn't say less than -15, I mean greater than 15 or greater than -15
- Assistant
I see, if you're looking to exclude individual accuracies and biases that have absolute values greater than 15, you're essentially focusing on a narrower range of values (-15 to 15). The goal is to filter out outliers from the group accuracy and bias calculations. Let's correct the approach based on your clarification:
The key here is focusing on filtering out individual accuracies and biases with absolute values greater than 15. In other words, we keep only those observations where both the absolute individual accuracy and the absolute individual bias are less than or equal to 15.
# Filter the DataFrame to include only rows with absolute individual accuracy and bias <= 15 filtered_df = crossvalidation_df.filter((pl.col('individual_accuracy').abs() <= 15) & (pl.col('individual_bias').abs() <= 15)) # Recalculate the errors for the filtered ensemble model errors_filtered = filtered_df['y'] - filtered_df['Ensemble'] # For groups of forecasts with the updated condition group_accuracy_filtered = 1 - (errors_filtered.abs().sum() / filtered_df['y'].abs().sum()) group_bias_filtered = (filtered_df['Ensemble'].sum() / filtered_df['y'].sum()) - 1 # Print the filtered average group accuracy and group bias over all folds for the ensemble model print('Filtered Average Group Accuracy: ', round(group_accuracy_filtered, 4)) print('Filtered Average Group Bias: ', round(group_bias_filtered, 4)) - User
is this correct # Filter the DataFrame to include only rows with absolute individual accuracy and bias <= 15 filtered_df = crossvalidation_df.filter((pl.col('individual_accuracy').abs() <= 15) & (pl.col('individual_bias').abs() <= 15))
Recalculate the errors for the filtered ensemble model
errors_filtered = filtered_df['y'] - filtered_df['Ensemble']
For groups of forecasts with the updated condition
group_accuracy = 1 - (errors_filtered.abs().sum() / filtered_df['y'].abs().sum()) group_bias = (filtered_df['Ensemble'].sum() / filtered_df['y'].sum()) - 1
Print the average group accuracy and group bias over all folds for the ensemble model
print('Average Group Accuracy: ', round(group_accuracy, 4)) print('Average Group Bias: ', round(group_bias, 4))
- Assistant
The approach you've outlined has the right intent and is almost correct, but there could be a minor misunderstanding around the calculation for the group accuracy. Specifically, the adjustment to calculate accuracy using absolute values for the sum in the group accuracy calculation may not reflect a typical accuracy measure as closely as intended. Generally, accuracy metrics don't involve taking the absolute of the actual values sum ( should be used directly unless there's a specific reason for using the absolute).
- User
how about now # Filter the DataFrame to include only rows with absolute individual accuracy and bias <= 15 filtered_df = crossvalidation_df.filter((pl.col('individual_accuracy').abs() <= 15) & (pl.col('individual_bias').abs() <= 15))
Recalculate the errors for the filtered ensemble model
errors_filtered = filtered_df['y'] - filtered_df['Ensemble']
For groups of forecasts with the updated condition
group_accuracy = 1 - (errors_filtered.abs().sum() / filtered_df['y'].sum()) group_bias = (filtered_df['Ensemble'].sum() / filtered_df['y'].sum()) - 1
Print the average group accuracy and group bias over all folds for the ensemble model
print('Average Group Accuracy: ', round(group_accuracy, 4)) print('Average Group Bias: ', round(group_bias, 4))
- Assistant
- User
Convert 'WeekDate' to datetime format
dataset_lowvolume = dataset_lowvolume.with_columns( pl.col("WeekDate").str.strptime(pl.Datetime, "%Y-%m-%d") )
Group by ‘MaterialID’, ‘SalesOrg’, ‘DistrChan’, 'CL4' and 'WeekDate', then sum 'OrderQuantity'
y_cl4 = dataset_lowvolume.groupby(['MaterialID', 'SalesOrg', 'DistrChan', 'CL4', 'WeekDate']).agg( pl.sum("OrderQuantity").alias("OrderQuantity") )
Sort by 'WeekDate'
- Assistant
When you convert a
polarsDataFrame to a pandas DataFrame using.to_pandas(), the order of the rows is preserved from thepolarsDataFrame. Given that you have already sorted they_cl4_over_19DataFrame by'ds'(which corresponds to 'WeekDate') using the.sort('ds')operation in Polars, there should be no need to perform an additional sort immediately after converting it to pandas for the purpose of maintaining the order by date. - User
y_cl4_over_19 ds y unique_id 0 2020-11-30 3.0 12158538_US01_8_5339008 1 2020-11-30 150.0 12495546_US01_8_6684463 2 2020-11-30 780.0 12039064_US05_5_4472194 crossvalidation_df unique_id ds cutoff NBEATS-median NBEATS-lo-90 NBEATS-lo-80 NBEATS-hi-80 NBEATS-hi-90 y Ensemble str datetime[ms] datetime[ms] f32 f32 f32 f32 f32 f64 f32 "10000012_US03_… 2023-09-10 00:00:00 2023-09-03 00:00:00 51.205292 -1.873669 6.763798 136.216843 176.697311 null 51.205292 "10000012_US03_… 2023-09-17 00:00:00 2023-09-03 00:00:00 42.527237 -3.223297 4.508997 136.884048 177.853592 null 42.527237 "10000012_US03_… 2023-09-24 00:00:00 2023-09-03 00:00:00 47.484734 -2.504555 0.242155 138.733902 185.736206 null 47.484734 why is y turned into null after cross validation?
- Assistant
- User
- Assistant
The error you're encountering suggests that there's an issue with how the
NeuralForecastlibrary is trying to process your DataFrame. Specifically, the error messageAttributeError: 'DataFrame' object has no attribute 'index'indicates that the library expects a pandas DataFrame (or at least an object with an attribute), but it's likely receiving a polars DataFrame instead. - User
no polars only, no pandas it says polars in the documentation right NeuralForecast.cross_validation (df:Union[pandas.core.frame.DataFrame,pol ars.dataframe.frame.DataFrame,NoneType]= None, static_df:Union[pandas.core.frame. DataFrame,polars.dataframe.frame.DataFra me,NoneType]=None, n_windows:int=1, step_size:int=1,
- Assistant
- User
how about these appraocches, 1. Hybrid Modeling: In this approach, you would decompose the time series into different components and use NBEATS and Holt-Winters to model different aspects of the data:
Step 1: Fit the Holt-Winters model to the original time series data to capture the trend and seasonal components. Step 2: Obtain the residuals (irregular components) by subtracting the Holt-Winters fitted values from the original time series. Step 3: Train the NBEATS model on the residuals to capture the non-linear and irregular patterns. Step 4: For forecasting, use the Holt-Winters model to forecast the trend and seasonal components, and use the NBEATS model to forecast the residuals (irregular components). Step 5: Combine the Holt-Winters forecast and the NBEATS forecast of residuals by adding them together to obtain the final hybrid forecast.
This approach leverages the strengths of both models: Holt-Winters for capturing trend and seasonality, and NBEATS for capturing non-linear and irregular patterns that remain after removing the trend and seasonal components.
- Assistant
- User
- Assistant
- User
which stat models could I do this instead with holt winter? I mean holt winter + another stat model instead of n beats
- Assistant
- User
y_cl4.head() ds y unique_id datetime[μs] f64 str 2020-11-30 00:00:00 44.0 "12255887_US03_… 2020-11-30 00:00:00 14.0 "12495540_US01_… 2020-11-30 00:00:00 56.0 "12486024_US01_… 2020-11-30 00:00:00 900.0 "12036337_US01_… 2020-11-30 00:00:00 17.0 "12420916_US01_… from utilsforecast.feature_engineering import fourier
transformed_df, future_df = fourier(y_cl4, freq='1w', season_length=4, k=2, h=4) transformed_df --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) /Users/tungnguyen/Downloads/Nestle/Experiment Polars CL4 AECD Low Volume Ensemble.ipynb Cell 33 line 3 1 from utilsforecast.feature_engineering import fourier ----> 3 transformed_df, future_df = fourier(y_cl4, freq='1w', season_length=4, k=2, h=4) 4 transformed_df
File ~/anaconda3/lib/python3.10/site-packages/utilsforecast/feature_engineering.py:83, in fourier(df, freq, season_length, k, h, id_col, time_col) 81 if sort_idxs is not None: 82 restore_idxs = np.empty_like(sort_idxs) ---> 83 restore_idxs[sort_idxs] = np.arange(sort_idxs.size) 84 vals = vals[restore_idxs] 85 times = ufp.take_rows(times, sort_idxs)
AttributeError: 'Series' object has no attribute 'size'
- Assistant
- User
how do I convert back to polars
- Assistant
Converting a pandas DataFrame back to a polars DataFrame is straightforward using the
from_pandasmethod provided by polars. Here's how you can do it:import polars as pl # Assuming you have a pandas DataFrame named `transformed_df_pandas` transformed_df_polars = pl.from_pandas(transformed_df_pandas) # If you also converted `future_df` to pandas and need to convert it back to polars future_df_polars = pl.from_pandas(future_df_pandas)This method allows you to seamlessly transition between pandas and polars DataFrame objects, making it easier to work with libraries or functions that require a specific DataFrame type.
Please make sure that you have both pandas and polars libraries installed in your environment. If you're working within a Jupyter notebook or another interactive Python environment, these transformations can help you integrate functionality from libraries that are specifically designed for one DataFrame implementation or the other.
Quick Recap:
- Use
df.to_pandas()to convert a polars DataFrame to pandas. - Use
pl.from_pandas(df_pandas)to convert a pandas DataFrame back to polars.
- Use