from statsforecast import StatsForecast from statsforecast.models import AutoARIMA,…
- User
from statsforecast import StatsForecast from statsforecast.models import AutoARIMA, SimpleExponentialSmoothing, HistoricAverage, Naive, RandomWalkWithDrift, SeasonalNaive 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 = [ AutoARIMA(season_length=12), SimpleExponentialSmoothing(alpha=0.8), HistoricAverage(), Naive(), RandomWalkWithDrift(), SeasonalNaive(season_length=12) ]
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_filtered, h=2, step_size=1, n_windows=8, sort_df=True)
Calculate the ensemble mean
ensemble = crossvalidation_df[['AutoARIMA', 'SimpleExponentialSmoothing', 'HistoricAverage', 'Naive', 'RandomWalkWithDrift', 'SeasonalNaive']].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))
- Assistant
- User
- Assistant
- User
what are you talking about? it says Introduction to TFT A Temporal Fusion Transformer (TFT) is an attention-based Deep Neural Network, optimized for superior performance in multi-horizon time series forecasting while producing interpretable insights into temporal dynamics.
- Assistant
- User
- Assistant
It looks like the error you're encountering is due to a
SchemaErrorwhen you're trying to split the unique identifier back into its original columns. The error message indicates there might be an issue with how the operation is being handled by the Polars library. - User
- Assistant
The
SyntaxErrorat line 49 in the given code snippet is caused by a missing quote in therenamemethod call. Specifically, it's the quote after'SalesOrg. Here's the corrected line of code:# Corrected rename statement forecasts_df = ( forecasts_df .with_columns(pl.col('unique_id').str.split('_', expand=True)) .rename({'unique_id_0': 'MaterialID', 'unique_id_1': 'SalesOrg', 'unique_id_2': 'DistrChan', 'unique_id_3': 'CL4'}) # Fixed here .drop('unique_id') )After the
renamefunction, the same line was causing the syntax error due to a missing closing quote on'SalesOrg.To avoid such syntax errors, make sure you check for matching pairs of quotes whenever you're dealing with string literals in your code. It is common for such typos to occur, and they generally result in syntax errors that prevent the code from running. Fixing the typo should allow the code to execute correctly.
- User
so you dont think this could work with my dataset to improve accuracy to 60%? To integrate TFT into your existing forecasting process and ensemble, you would have to train a TFT model on your dataset. Deep learning models like TFT typically require a substantial amount of data for each time series to perform well and may not be the ideal choice for very short series with only a few data points.
If you decide to include the TFT model in your ensemble, you can follow these general steps:
- Data Preparation: Prepare your dataset in a format suitable for training the TFT model, including static and dynamic features as well as your target variable.
- Assistant
- User
how about this, read this article carefully, https://archive.is/zBlZq
- Assistant
- User
- Assistant
- User
is catboost the best learning model? I have seen other examles using randomforestregressor
- Assistant
- User
- Assistant
- User
my problem is univariate, just order quantity forecast at from materialID-salesorg-distrchan-cl4 level on weekly data, which one should I use for stacking model
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.