Skip to content

Instantly share code, notes, and snippets.

@rtkilian
Created July 9, 2022 23:40
Show Gist options
  • Save rtkilian/b86f707d04f186d01d8de480d9352601 to your computer and use it in GitHub Desktop.
Save rtkilian/b86f707d04f186d01d8de480d9352601 to your computer and use it in GitHub Desktop.
Linear regression forecaster with sktime
from sktime.forecasting.model_selection import temporal_train_test_split
from sktime.forecasting.base import ForecastingHorizon
from sktime.forecasting.compose import make_reduction
from sktime.utils.plotting import plot_series
from sktime.performance_metrics.forecasting import mean_absolute_percentage_error
from sklearn.linear_model import LinearRegression
# Split data
y_train, y_test = temporal_train_test_split(y, test_size=26) # Predict from 1st July 2019
# Forecasting horizon, same as test data
fh = ForecastingHorizon(y_test.index, is_relative=False)
# Linear regression forecaster
regressor = LinearRegression()
forecaster = make_reduction(regressor, window_length=52, strategy="recursive")
# Fit and predict
forecaster.fit(y_train)
y_pred = forecaster.predict(fh)
# Plot predictions with training and test data
plot_series(y_train['2018-07-01':], y_test, y_pred, labels=["y_train", "y_test", "y_pred"], x_label='Date', y_label='Count pedestrians');
# Evaluate
print('MAPE: %.4f' % mean_absolute_percentage_error(y_test, y_pred, symmetric=False))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment