```model = LinearRegression() model.fit(np.log(np....
# mlforecast
m
Copy code
model = LinearRegression()
model.fit(np.log(np.array(range(1,len(df)+1)).reshape(-1, 1)), np.log(df['Values'].values+1))

timestamps = pd.date_range(datetime.strptime(t['Timestamp'].values[-1],'%m-%d-%Y'), periods=forecast_horizon+1, freq='MS')
timestamps = timestamps[1:]

temp = pd.DataFrame()
temp['Timestamp'] = timestamps
forecasts = model.predict(np.log(np.array(range(len(df), len(df) + forecast_horizon)).reshape(-1, 1)))
forecast_values = np.exp(forecasts)-1
df['Power'] = np.exp(model.predict(np.log(np.array(range(1,len(df)+1)).reshape(-1, 1))))-1
j
So this is for a single serie and you want to use mlforecast to do this for every serie?
m
for all series i want to do this, using nixtla framework.
j
mlforecast trains a single model on all series, is that what you want or do you want one model per serie?
m
I want to do one model for all series. Also I am not able find Logarithmic and Power Model in nixtla
j
Copy code
import numpy as np
from mlforecast import MLForecast
from mlforecast.target_transforms import GlobalSklearnTransformer
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import FunctionTransformer
from utilsforecast.data import generate_series
from utilsforecast.feature_engineering import trend

# sample data
data = generate_series(2)
h = 5

# generate features
train, future = trend(data, freq='D', h=h)
train['trend'] = np.log(train['trend'])
future['trend'] = np.log(future['trend'])

# training
log1p = FunctionTransformer(func=np.log1p, inverse_func=np.expm1)
fcst = MLForecast(
    models=LinearRegression(),
    freq='D',
    target_transforms=[GlobalSklearnTransformer(log1p)],
)
fcst.fit(train, static_features=[])

# predicting
fcst.predict(h=h, X_df=future)
m
@José Morales Thanks Jose, this is quite good. Can i pass a list of models = [Linear, Logarithmic, Simple moving Average] ? Or i need to create different function for all models?
j
You can provide different models but they'll use the same features. I believe you want different features (linear trend, log trend), right?
m
yes that is correct.
j
In that case you need one instance for each model
m
understood. Thanks this is awesome
Copy code
============================Model Def=============================


import pandas as pd
import numpy as np
from mlforecast import MLForecast
from mlforecast.target_transforms import GlobalSklearnTransformer
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import FunctionTransformer
from utilsforecast.data import generate_series
from utilsforecast.feature_engineering import trend

def prepare_data(path, col_names):
    df = pd.read_csv(path, names=col_names, header=0)
    df[col_names[1]] = pd.to_datetime(df[col_names[1]], format="%Y-%m-%d")#.dt.strftime("%m-%d-%Y")
    # df[col_names[1]] = pd.to_datetime(df[col_names[1]], format="%d/%m/%Y")#.dt.strftime("%m-%d-%Y")
    return df

# sample data
path = "./data/purple_temp_forecast_source_data.csv"
# path = "./data/Sample_Air_pass.csv"
cNames = ["unique_id","ds", "y"]
data = prepare_data(path, col_names=cNames)
h = 60

# generate features
train, future = trend(data, freq='MS', h=h)
train['trend'] = np.log(train['trend'])
future['trend'] = np.log(future['trend'])

models ={
    'power': LinearRegression()
}

# training
log1p = FunctionTransformer(func=np.log1p, inverse_func=np.expm1)

fcst = MLForecast(
    models=models,
    freq='MS',
    target_transforms=[GlobalSklearnTransformer(log1p)],
)
fcst.fit(train, static_features=[])

# predicting
fcst.predict(h=h, X_df=future)

======================================Model Eval=============================

from utilsforecast.losses import mae, mape, rmse, smape
from utilsforecast.evaluation import evaluate

crossvalidation_df = fcst.cross_validation(
    df=train,
    h=60,
    n_windows=1,
    refit=False,
)
crossvalidation_df.head()

# Metrics to be used for evaluation
metrics = [
    mae,
    rmse,
    mape,
    smape
]


# Function to evaluate the crossvalidation
def evaluate_crossvalidation(crossvalidation_df, metrics, models):
    evaluations = []
    for c in crossvalidation_df['cutoff'].unique():
        df_cv = crossvalidation_df.query('cutoff == @c')
        evaluation = evaluate(
            df = df_cv,
            metrics=metrics,
            models=list(models.keys())
            )
        evaluations.append(evaluation)
    evaluations = pd.concat(evaluations, ignore_index=True).drop(columns='unique_id')
    evaluations = evaluations.groupby('metric').mean()
    return evaluations.style.background_gradient(cmap='RdYlGn_r', axis=1)


evaluate_crossvalidation(crossvalidation_df, metrics, models)
@José Morales Hope this is the right way to evaluate my power Model, based on the example your provided