# Custom training

Customize the training procedure for your models

mlforecast abstracts away most of the training details, which is useful for iterating quickly. However, sometimes you want more control over the fit parameters, the data that goes into the model, etc. This guide shows how you can train a model in a specific way and then giving it back to mlforecast to produce forecasts with it.

## Data setup

```
from mlforecast.utils import generate_daily_series
```

```
series = generate_daily_series(5)
```

## Creating forecast object

```
import numpy as np
from lightgbm import LGBMRegressor
from sklearn.linear_model import LinearRegression
from mlforecast import MLForecast
```

Suppose we want to train a linear regression with the default settings.

```
fcst = MLForecast(
models={'lr': LinearRegression()},
freq='D',
date_features=['dayofweek'],
)
```

## Generate training set

Use
`MLForecast.preprocess`

to generate the training data.

```
prep = fcst.preprocess(series)
prep.head()
```

unique_id | ds | y | dayofweek | |
---|---|---|---|---|

0 | id_0 | 2000-01-01 | 0.428973 | 5 |

1 | id_0 | 2000-01-02 | 1.423626 | 6 |

2 | id_0 | 2000-01-03 | 2.311782 | 0 |

3 | id_0 | 2000-01-04 | 3.192191 | 1 |

4 | id_0 | 2000-01-05 | 4.148767 | 2 |

```
X = prep.drop(columns=['unique_id', 'ds', 'y'])
y = prep['y']
```

## Regular training

Since we don’t want to do anything special in our training process for
the linear regression, we can just call
`MLForecast.fit_models`

```
fcst.fit_models(X, y)
```

```
MLForecast(models=[lr], freq=<Day>, lag_features=[], date_features=['dayofweek'], num_threads=1)
```

This has trained the linear regression model and is now available in the
`MLForecast.models_`

attribute.

```
fcst.models_
```

```
{'lr': LinearRegression()}
```

## Custom training

Now suppose you also want to train a LightGBM model on the same data, but specifying sample weights.

```
rng = np.random.RandomState(0)
weights = rng.rand(y.size)
```

We train the model as we normally would and provide the weights through
the `sample_weight`

argument.

```
model = LGBMRegressor(verbosity=-1).fit(X, y, sample_weight=weights)
```

## Computing forecasts

Now we just assign this model to the `MLForecast.models_`

dictionary.
Note that you can assign as many models as you want.

```
fcst.models_['lgbm'] = model
fcst.models_
```

```
{'lr': LinearRegression(), 'lgbm': LGBMRegressor(verbosity=-1)}
```

And now when calling
`MLForecast.predict`

,
mlforecast will use those models to compute the forecasts.

```
fcst.predict(1)
```

unique_id | ds | lr | lgbm | |
---|---|---|---|---|

0 | id_0 | 2000-08-10 | 3.247803 | 3.642456 |

1 | id_1 | 2000-04-07 | 3.182126 | 4.808618 |

2 | id_2 | 2000-06-16 | 3.182126 | 4.808618 |

3 | id_3 | 2000-08-30 | 3.313480 | 2.777129 |

4 | id_4 | 2001-01-08 | 3.444834 | 3.404631 |