%load_ext autoreload
%autoreload 2使用numpy数组进行训练
将你的数据框转换为数组,以减少内存使用并加快训练速度
大多数机器学习库使用numpy数组,即使您提供的是数据框,它最终也会被转换为numpy数组。通过向这些模型提供数组,我们可以加快过程,因为转换只会发生一次。
数据设置
from mlforecast.utils import generate_daily_seriesseries = generate_daily_series(5)拟合和交叉验证方法
import numpy as np
from lightgbm import LGBMRegressor
from sklearn.linear_model import LinearRegression
from mlforecast import MLForecastfcst = MLForecast(
models={'lr': LinearRegression(), 'lgbm': LGBMRegressor(verbosity=-1)},
freq='D',
lags=[7, 14],
date_features=['dayofweek'],
)如果您使用MLForecast中的fit/cross_validation方法,您需要做的就是提供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_id | ds | lr | lgbm | |
|---|---|---|---|---|
| 0 | id_0 | 2000-08-10 | 5.268787 | 6.322262 |
| 1 | id_1 | 2000-04-07 | 4.437316 | 5.213255 |
| 2 | id_2 | 2000-06-16 | 3.246518 | 4.373904 |
| 3 | id_3 | 2000-08-30 | 0.144860 | 1.285219 |
| 4 | id_4 | 2001-01-08 | 2.211318 | 3.236700 |
对于交叉验证,我们只需指定 as_numpy=True。
cv_res = fcst.cross_validation(series, n_windows=2, h=2, as_numpy=True)预处理方法
将特征作为numpy数组处理在某些情况下也很有帮助,例如当你有类别列而库不支持它们时,例如LightGBM与polars。为了在LightGBM和polars中使用类别特征,我们必须将它们转换为整数表示,并告诉LightGBM将这些特征视为类别特征,我们可以通过以下方式实现:
series_pl = generate_daily_series(5, n_static_features=1, engine='polars')
series_pl.head(2)
shape: (2, 4)
| unique_id | ds | y | static_0 |
|---|---|---|---|
| cat | datetime[ns] | f64 | cat |
| "id_0" | 2000-01-01 00:00:00 | 36.462689 | "84" |
| "id_0" | 2000-01-02 00:00:00 | 121.008199 | "84" |
fcst = MLForecast(
models=[],
freq='1d',
lags=[7, 14],
date_features=['weekday'],
)为了使用预处理方法获取特征数组,我们还必须请求 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'],
);我们现在可以将这个模型添加到我们的模型字典中,如自定义训练指南中所述。
fcst.models_ = {'lgbm': model}并用它进行预测。
fcst.predict(1)
shape: (5, 3)
| unique_id | ds | lgbm |
|---|---|---|
| cat | datetime[ns] | f64 |
| "id_0" | 2000-08-10 00:00:00 | 448.796188 |
| "id_1" | 2000-04-07 00:00:00 | 81.058211 |
| "id_2" | 2000-06-16 00:00:00 | 4.450549 |
| "id_3" | 2000-08-30 00:00:00 | 14.219603 |
| "id_4" | 2001-01-08 00:00:00 | 87.361881 |
Give us a ⭐ on Github