Start learning free

LESSON 113 OF 165 · MACHINE LEARNING: TIME SERIES

A Model on Lags in Python

Practice

The two baselines guess each week with a fixed rule. A model on lags learns its own rule from the past. It reads last week's revenue (lag_1) and the revenue of 4 weeks back (lag_4), and it learns how much each one should count.

LinearRegression() makes an empty model. model.fit(X, y) learns one weight per column of X, plus a start value, so that its guesses come close to y. model.predict(X) gives back an array with one guess per row of X. After fitting, model.coef_ holds the weights, in the order of the columns, and model.intercept_ holds the start value. Here is the same idea on daily visitors, with one lag:

days = pd.DataFrame({"visitors": [120, 135, 128, 150, 160, 158]})
days["yesterday"] = days["visitors"].shift(1)
days = days.dropna()
m = LinearRegression()
m.fit(days[["yesterday"]], days["visitors"])
print(m.coef_, m.intercept_)

Fit only on train, the weeks before the last 8, and score on test, the last 8. That way the model never sees the weeks it is scored on. Score it with the same mean_absolute_error as the baselines, so the three numbers compare. Your script must print:

Last week MAE: 460.8
Average of 4 MAE: 350.0
Model MAE: 286.8
Weights: [0.62 0.32] start: 196.8

Your task: the starting code builds table, splits it into train and test and prints the two baselines. Below them, fit a LinearRegression on lag_1 and lag_4 of the train weeks, print its MAE on the test weeks, then print its weights and its start value.


Assignment
Follow the Coding Tutorial to fit a linear model on the two lag columns, score it on the test weeks and print what it learned.


Hint
Fit with train[features] and train["revenue"], predict with test[features]. coef_ is a numpy array, so round it with .round(2); intercept_ is one number, so use round(…, 1).


STEP 1 OF 6
    Ctrl + Enter to check

    Ts Forecast in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free