Okay, let's complete the function evaluate_model_complete.
There are a few key points to address:
- The
append issue: The line d_eval[cur_model.__class__.__name__] = d_eval[cur_model.__class__.__name__].append(metrics) is incorrect because the .append() method modifies the list in-place and returns None. You should call append directly on the list.
- Storing metrics: The
evaluate_model function returns a DataFrame containing different metrics. You need to extract the specific values (MAE, MASE, SMAPE) for the current model and append those values, not the entire DataFrame.
- Calculating averages: You need to iterate through the collected metrics for each model and calculate the mean. Pandas Series are convenient for this.
- Typo: The code uses
df_ex inside the loop, but df_art is defined just before. Assuming df_ex is a typo and should be df_art (or potentially the original df if evaluate_model expects the entire dataset context, though passing df_art seems more logical if the evaluation is item-specific). Let's assume df_art is the intended DataFrame to pass as the main data context.
- Assumptions about
evaluate_model output: Based on your description ("one different metric per line and the column with the metric's value has the same name as the model used"), we assume the returned DataFrame metrics has an index like ['MAE', 'MASE', 'SMAPE'] and a single column named after the model being evaluated (e.g., 'CrostonClassic').
Here's the completed function:
import pandas as pd
# Assuming necessary imports like CrostonClassic, ADIDA, IMAPA, evaluate_model, get_zero_ratio are available
# from your_module import CrostonClassic, CrostonOptimized, ADIDA, IMAPA, evaluate_model, get_zero_ratio
# Placeholder definitions if not imported (replace with actual imports)
class CrostonClassic: pass
class CrostonOptimized: pass
class ADIDA: pass
class IMAPA: pass
def evaluate_model(cur_model, df, train_df, n_windows, horizon, step_size, season_length, freq):
# This is a placeholder for the actual evaluate_model function.
# It should return a DataFrame with metrics as described.
# Example structure:
# ModelName
# MAE 10.5
# MASE 1.2
# SMAPE 0.15
model_name = cur_model.__class__.__name__
metrics_data = {
'MAE': pd.np.random.rand() * 10,
'MASE': pd.np.random.rand() * 2,
'SMAPE': pd.np.random.rand() * 0.2
}
# Simulate returning a DataFrame with the model name as the column header
return pd.DataFrame(metrics_data, index=['MAE', 'MASE', 'SMAPE'], columns=[model_name])
def get_zero_ratio(df):
# Placeholder for the zero ratio calculation
# Example: return (df['y'] == 0).mean() if 'y' in df.columns else 0
return (df['y'] == 0).mean() if 'y' in df.columns else 0.0
def evaluate_model_complete(
df,
model_list=[CrostonClassic(),CrostonOptimized(),ADIDA(),IMAPA()],
season_length=1,
horizon=180,
step_size=180,
n_windows=18,
freq='D'
):
"""
Evaluates a list of models across multiple time series using a rolling forecast origin approach.
Args:
df (pd.DataFrame): DataFrame with time series data. Must contain columns
'unique_id', 'ds' (datetime), and 'y' (value).
model_list (list): List of instantiated forecasting model objects.
season_length (int): Seasonality length for models that use it.
horizon (int): Forecast horizon in terms of number of periods.
step_size (int): Step size for the rolling forecast origin.
n_windows (int): Number of windows to use for evaluation.
freq (str): Frequency of the time series (e.g., 'D' for daily, 'M' for monthly).
Returns:
dict: Dictionary where keys are model names and values are lists containing
the average MAE, MASE, and SMAPE across all evaluated series.
e.g., {'ModelName': [avg_mae, avg_mase, avg_smape]}
"""
# Initialize dictionary to store metrics lists for each model
# Structure: { 'ModelName': {'MAE': [m1_mae, m2_mae, ...], 'MASE': [...], 'SMAPE': [...] } }
d_eval = {m.__class__.__name__: {'MAE': [], 'MASE': [], 'SMAPE': []} for m in model_list}
# Get unique item identifiers
unique_ids = df['unique_id'].unique()
# Pour chaque article, faire évaluation
for art_id in unique_ids:
df_art = df[df['unique_id'] == art_id].sort_values('ds') # Ensure data is sorted by date
# Basic check: Skip if series is too short for evaluation
# This check might need refinement based on horizon and n_windows
if len(df_art) < n_windows * step_size:
print(f"Warning: Skipping item {art_id} due to insufficient data length.")
continue
# Skip series with too many zeros (using the provided helper function)
# NOTE: Ensure get_zero_ratio is correctly defined and handles potential errors
try:
if get_zero_ratio(df_art) > 0.2:
# print(f"Skipping item {art_id} due to high zero ratio.") # Optional logging
continue
except Exception as e:
print(f"Warning: Could not compute zero ratio for item {art_id}. Skipping. Error: {e}")
continue
# Define the training split point as per the original code
# Ensure 'ds' column is datetime type for comparison
df_art['ds'] = pd.to_datetime(df_art['ds'])
split_date = pd.to_datetime('2024-06-01')
train_df = df_art[df_art['ds'] <= split_date]
# Check if training set is sufficient
if len(train_df) == 0:
print(f"Warning: Skipping item {art_id} because training set is empty.")
continue
# Pour chaque modèle, évaluer
for cur_model in model_list:
model_name = cur_model.__class__.__name__
try:
# Call the evaluation function
# Assuming df_ex was a typo for df_art and evaluate_model uses df_art for context
metrics = evaluate_model(
cur_model,
df=df_art, # Pass the full df_art for context if needed by evaluate_model
train_df=train_df, # Pass the specific training split
n_windows=n_windows,
horizon=horizon,
step_size=step_size,
season_length=season_length,
freq=freq
)
# Extract metrics based on the assumed DataFrame structure
# Assumes index=['MAE', 'MASE', 'SMAPE'] and column=model_name
if model_name in metrics.columns:
mae = metrics.loc['MAE', model_name]
mase = metrics.loc['MASE', model_name]
smape = metrics.loc['SMAPE', model_name]
# Append the extracted metrics (Corrected approach)
d_eval[model_name]['MAE'].append(mae)
d_eval[model_name]['MASE'].append(mase)
d_eval[model_name]['SMAPE'].append(smape)
else:
print(f"Warning: Metric column '{model_name}' not found for item {art_id}.")
# Append NaN to keep list lengths consistent if needed
d_eval[model_name]['MAE'].append(pd.NA)
d_eval[model_name]['MASE'].append(pd.NA)
d_eval[model_name]['SMAPE'].append(pd.NA)
except KeyError as e:
print(f"Warning: Metric index '{e}' not found for model {model_name} on item {art_id}. Metrics DataFrame:\n{metrics}")
# Append NaN if expected metrics are missing
d_eval[model_name]['MAE'].append(pd.NA)
d_eval[model_name]['MASE'].append(pd.NA)
d_eval[model_name]['SMAPE'].append(pd.NA)
except Exception as e:
print(f"Error evaluating model {model_name} on item {art_id}: {e}")
# Append NaN in case of any other error during evaluation or extraction
d_eval[model_name]['MAE'].append(pd.NA)
d_eval[model_name]['MASE'].append(pd.NA)
d_eval[model_name]['SMAPE'].append(pd.NA)
# Calculer moyenne des métriques
res = {}
for m_name, metrics_lists in d_eval.items():
# Convert lists to pandas Series to easily calculate mean, handling potential NaNs
mae_list = pd.Series(metrics_lists['MAE'])
mase_list = pd.Series(metrics_lists['MASE'])
smape_list = pd.Series(metrics_lists['SMAPE'])
# Calculate mean, ignoring NaNs if any occurred
avg_mae = mae_list.mean()
avg_mase = mase_list.mean()
avg_smape = smape_list.mean()
# Store results, potentially as NaN if no valid metrics were computed
res[m_name] = [avg_mae, avg_mase, avg_smape]
# Optional: Print info about skipped series for this model
# num_valid = mae_list.count() # Counts non-NA values
# if num_valid < len(unique_ids):
# print(f"Info: Model {m_name} evaluated on {num_valid}/{len(unique_ids)} series.")
return res
# Example Usage (requires pandas and numpy)
# Assuming df is a pandas DataFrame properly loaded with 'unique_id', 'ds', 'y'
# For example:
# data = {
# 'unique_id': ['item1']*100 + ['item2']*100,
# 'ds': pd.to_datetime(pd.date_range(start='2020-01-01', periods=100).tolist() * 2),
# 'y': list(pd.np.random.rand(100) * 5 + 10) + list(pd.np.random.rand(50)*2 + pd.np.repeat([0,5], 25) + list(pd.np.random.rand(50)*2)) # item2 has zeros
# }
# df_example = pd.DataFrame(data)
# df_example['y'] = df_example['y'].round(1) # Some values for item2 might be 0
# results = evaluate_model_complete(df_example)
# print(results)