Here’s a complete implementation of time series cross-validation for TSMixer using the Darts library, following your requirements:
- Training data: First 130 points
- Test data: Last 26 points (out-of-sample)
- Cross-validation:
- Start forecasting from point 91 with a horizon of 26.
- Move forward with a stride of 4.
- Perform 4 cross-validation passes.
Step 1: Install Required Libraries
pip install darts tsmixer pandas numpy scikit-learn
Step 2: Full Implementation
import numpy as np
import pandas as pd
from darts import TimeSeries
from darts.models import TSMixerModel
from darts.metrics import mae
from darts.dataprocessing.transformers import Scaler
# --- Generate or load your time series data ---
# Example: Create a synthetic time series (replace with your data)
np.random.seed(42)
time = pd.date_range(start="2020-01-01", periods=156, freq="D")
values = np.sin(np.arange(156) * 0.1) + np.random.normal(0, 0.1, 156)
series = TimeSeries.from_dataframe(
pd.DataFrame({"time": time, "value": values}),
time_col="time",
value_cols="value",
)
# --- Split into train (130) and test (26) ---
train, test = series.split_before(0.833) # 130 train, 26 test
# --- Scale the data (optional but recommended) ---
scaler = Scaler()
train_scaled = scaler.fit_transform(train)
test_scaled = scaler.transform(test)
# --- Cross-validation parameters ---
initial_train_size = 91 # Start forecasting from point 91
forecast_horizon = 26 # Predict next 26 points
stride = 4 # Move forward by 4 points each time
n_splits = 4 # Number of CV passes
# --- Initialize TSMixer model ---
model = TSMixerModel(
input_chunk_length=initial_train_size, # Lookback window
output_chunk_length=forecast_horizon, # Forecast horizon
random_state=42,
)
# --- Perform cross-validation ---
mae_scores = []
for i in range(n_splits):
# Define the current training window
train_start = 0
train_end = initial_train_size + (i * stride)
current_train = train_scaled[:train_end]
# Fit the model on the current window
model.fit(current_train)
# Forecast the next 26 points
pred = model.predict(n=forecast_horizon)
# Get the actual values for the forecast period
actual_start = train_end
actual_end = train_end + forecast_horizon
actual = train_scaled[actual_start:actual_end]
# Compute MAE (inverse scaling if needed)
current_mae = mae(actual, pred)
mae_scores.append(current_mae)
print(f"Split {i+1}: MAE = {current_mae:.4f}")
print(f"Average MAE across CV splits: {np.mean(mae_scores):.4f}")
# --- Final evaluation on the test set ---
# Fit on the full training data
model.fit(train_scaled)
# Forecast the next 26 points (test set)
final_pred = model.predict(n=forecast_horizon)
# Compute MAE on the test set
test_mae = mae(test_scaled, final_pred)
print(f"Test MAE: {test_mae:.4f}")