%load_ext autoreload
%autoreload 2预测回调
获取每个预测时间段内的输入特征和预测结果。
如果您想在预测之前对输入进行某些操作,或者在输出在被用来更新目标(进而更新依赖于滞后的下一个特征)之前进行某些操作,您可以传递一个函数在这些时刻运行。
以下是一些示例:
import copy
import lightgbm as lgb
import numpy as np
from IPython.display import display
from mlforecast import MLForecast
from mlforecast.utils import generate_daily_seriesseries = generate_daily_series(1)预测之前
检查输入
我们可以定义一个函数,在预测之前显示我们的输入数据框。
def inspect_input(new_x):
"""显示模型输入以检查它们"""
display(new_x)
return new_x现在我们可以将这个函数传递给 MLForecast.predict 的 before_predict_callback 参数。
fcst = MLForecast(lgb.LGBMRegressor(verbosity=-1), freq='D', lags=[1, 2])
fcst.fit(series, static_features=['unique_id'])
preds = fcst.predict(2, before_predict_callback=inspect_input)
preds| unique_id | lag1 | lag2 | |
|---|---|---|---|
| 0 | id_0 | 4.15593 | 3.000028 |
| unique_id | lag1 | lag2 | |
|---|---|---|---|
| 0 | id_0 | 5.250205 | 4.15593 |
| unique_id | ds | LGBMRegressor | |
|---|---|---|---|
| 0 | id_0 | 2000-08-10 | 5.250205 |
| 1 | id_0 | 2000-08-11 | 6.241739 |
保存输入特征
在每个时间戳保存发送到模型的特征是有帮助的,例如用于估计SHAP值。这可以通过SaveFeatures回调轻松实现。
from mlforecast.callbacks import SaveFeaturesfcst = MLForecast(lgb.LGBMRegressor(verbosity=-1), freq='D', lags=[1])
fcst.fit(series, static_features=['unique_id'])
save_features_cbk = SaveFeatures()
fcst.predict(2, before_predict_callback=save_features_cbk);一旦我们调用了预测,我们可以直接获取特征。
save_features_cbk.get_features()| unique_id | lag1 | |
|---|---|---|
| 0 | id_0 | 4.155930 |
| 1 | id_0 | 5.281643 |
预测之后
在使用递归策略(默认设置)进行预测时,每个时间戳的预测结果会用来更新目标值并重新计算特征。如果您希望在此之前对这些预测结果进行某些操作,可以使用 MLForecast.predict 的 after_predict_callback 参数。
增加预测值
假设我们知道我们的模型总是低估,并且我们想通过将预测提高10%来防止这种情况发生。我们可以通过以下方式实现这一目标:
def increase_predictions(predictions):
"""所有预测提升10%"""
return 1.1 * predictionsfcst = MLForecast(
{'model': lgb.LGBMRegressor(verbosity=-1)},
freq='D',
date_features=['dayofweek'],
)
fcst.fit(series)
original_preds = fcst.predict(2)
scaled_preds = fcst.predict(2, after_predict_callback=increase_predictions)
np.testing.assert_array_less(
original_preds['model'].values,
scaled_preds['model'].values,
)fcst.ts._uids = fcst.ts.uids
fcst.ts._idxs = None
fcst.ts._static_features = fcst.ts.static_features_
fcst.ts._ga = copy.copy(fcst.ts.ga)
fcst.ts._predict_setup()
for attr in ('head', 'tail'):
new_x = fcst.ts._get_features_for_next_step(None)
original_preds = fcst.models_['model'].predict(new_x)
expected = 1.1 * original_preds
actual = getattr(scaled_preds.groupby('unique_id')['model'], attr)(1).values
np.testing.assert_equal(expected, actual)
fcst.ts._update_y(actual)Give us a ⭐ on Github