大多数机器学习库都使用 numpy 数组,即使您提供 Dataframe,最终也会被转换为 numpy 数组。通过向这些模型提供数组,我们可以加快处理速度,因为转换只发生一次。

数据设置

from mlforecast.utils import generate_daily_series
series = generate_daily_series(5)

fit 和 cross_validation 方法

import numpy as np
from lightgbm import LGBMRegressor
from sklearn.linear_model import LinearRegression

from mlforecast import MLForecast
fcst = MLForecast(
    models={'lr': LinearRegression(), 'lgbm': LGBMRegressor(verbosity=-1)},
    freq='D',
    lags=[7, 14],
    date_features=['dayofweek'],
)

如果您正在使用 MLForecast 的 fit/cross_validation 方法,要使用 numpy 数组进行训练,您只需提供 as_numpy 参数,该参数会在将特征传递给模型之前把它们转换为数组。

fcst.fit(series, as_numpy=True)
MLForecast(models=[lr, lgbm], freq=<Day>, lag_features=['lag7', 'lag14'], date_features=['dayofweek'], num_threads=1)

预测时,新特征也将被转换为数组,因此速度也会更快。

fcst.predict(1)
unique_iddslrlgbm
0id_02000-08-105.2687876.322262
1id_12000-04-074.4373165.213255
2id_22000-06-163.2465184.373904
3id_32000-08-300.1448601.285219
4id_42001-01-082.2113183.236700

对于 cross_validation,我们也只需指定 as_numpy=True

cv_res = fcst.cross_validation(series, n_windows=2, h=2, as_numpy=True)

preprocess 方法

将特征存储为 numpy 数组在某些情况下也很有帮助,例如当您有分类列而库不支持它们时,例如 LightGBM 与 polars。为了在 LightGBM 和 polars 中使用分类特征,我们必须将它们转换为整数表示,并告诉 LightGBM 将这些特征视为分类特征,这可以通过以下方式实现

series_pl = generate_daily_series(5, n_static_features=1, engine='polars')
series_pl.head(2)
unique_iddsystatic_0
catdatetime[ns]f64cat
”id_0”2000-01-01 00:00:0036.462689”84"
"id_0”2000-01-02 00:00:00121.008199”84”
fcst = MLForecast(
    models=[],
    freq='1d',
    lags=[7, 14],
    date_features=['weekday'],
)

为了通过 preprocess 方法将特征获取为数组,我们还需要请求 X, y 元组。

X, y = fcst.preprocess(series_pl, return_X_y=True, as_numpy=True)
X[:2]
array([[  0.        ,  20.30076749,  36.46268875,   6.        ],
       [  0.        , 119.51717097, 121.0081989 ,   7.        ]])

特征名称可在 fcst.ts.features_order_ 中获取

fcst.ts.features_order_
['static_0', 'lag7', 'lag14', 'weekday']

现在我们可以训练一个 LightGBM 模型,指定特征名称以及哪些特征应被视为分类特征。

model = LGBMRegressor(verbosity=-1)
model.fit(
    X=X,
    y=y,
    feature_name=fcst.ts.features_order_,
    categorical_feature=['static_0', 'weekday'],
);

现在我们可以将此模型添加到我们的 models 字典中,如自定义训练指南中所述。

fcst.models_ = {'lgbm': model}

并使用它进行预测。

fcst.predict(1)
unique_iddslgbm
catdatetime[ns]f64
”id_0”2000-08-10 00:00:00448.796188
”id_1”2000-04-07 00:00:0081.058211
”id_2”2000-06-16 00:00:004.450549
”id_3”2000-08-30 00:00:0014.219603
”id_4”2001-01-08 00:00:0087.361881