Hi again, In MLForecast it is convienient to write...
# general
m
Hi again, In MLForecast it is convienient to write own lag functions, but if I needed to create an interaction term between lag and another exogenous feature would I have a way to do this? lag_transforms passes only the target variable and I guess I cant access the other features that way? Would then one model per step be the solution or is there some other way too? Have a great weekend!
j
Hey. The easiest way to do this is with a scikit-learn transformer and a pipeline. Here's an example:
Copy code
from mlforecast import MLForecast
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import make_pipeline
from utilsforecast.data import generate_series
from utilsforecast.feature_engineering import fourier

class FeatureInteraction(BaseEstimator, TransformerMixin):
    def __init__(self, lag, exog):
        self.lag = lag
        self.exog = exog

    def fit(self, X, y):
        return self

    def transform(self, X):
        X = X.copy(deep=False)
        X['my_interaction'] = X[self.lag] * X[self.exog]
        return X

freq = 'D'
h = 5
series = generate_series(2, freq=freq)
train, future = fourier(series, freq=freq, season_length=7, k=2, h=h)
model = make_pipeline(
    FeatureInteraction(lag='lag1', exog='sin1_7'),
    LinearRegression(),
)
mlf = MLForecast(
    models=[model],
    freq=freq,
    lags=[1, 2, 3],
)
You can then see what that looks like with preprocess + fit_transform
Copy code
X, y = mlf.preprocess(train, static_features=[], return_X_y=True)
model[:1].fit_transform(X, y)
And once you're comfortable you can just use fit + predict
Copy code
mlf.fit(train, static_features=[])
mlf.predict(h=h, X_df=future)
🔥 1
m
Thanks so much for the quick reply, I need to experiment this. So if I have recursive forecast horizon 21 days ahead with some lags, this would apply the interaction transformation to every lag and not only when the .fit() is called in beginning of the forecasting process?
j
The fit doesn't do anything, so what that'll do is it will generate the feature on every step before passing it to the model to make the prediction
m
Ok got it now, that's really nice thanks a lot!