将Prophet的预测后果作为特色输出到 LightGBM 模型中进行时序的预测

咱们以前的对于应用机器学习进行工夫序列预测的文章中,都是专一于解释如何应用基于机器学习的办法进行工夫序列预测并获得良好后果。

然而在这篇文章将应用更高级的技术来预测工夫序列,本文将应用 Prophet 来提取新的有意义的特色,例如季节性、置信区间、趋势等。

工夫序列预测

个别状况下 LightGBM 模型都会应用一些lag的特色来预测将来的后果,这样做个别状况下可能获得很好的成果。本文介绍一种新的思路:应用 Prophet 从工夫序列中提取新特色,而后应用LightGBM 进行训练,能够失去更好的成果。Prophet 模型的理论预测、置信区间的下限和上限、每日和每周的季节性和趋势等都能够作为咱们的新特色。对于其余类型的问题,Prophet 还能够帮忙咱们提取形容假日成果。

原始数据

咱们的数据如下所示:

应用 Prophet 提取特色

咱们特色工程的第一步非常简单。咱们只须要应用Prophet 模型进行预测:

def prophet_features(df, horizon=24*7):    temp_df = df.reset_index()    temp_df = temp_df[['datetime', 'count']]    temp_df.rename(columns={'datetime': 'ds', 'count': 'y'}, inplace=True)        #take last week of the dataset for validation    train, test = temp_df.iloc[:-horizon,:], temp_df.iloc[-horizon:,:]        #define prophet model    m = Prophet(                growth='linear',                seasonality_mode='additive',                interval_width=0.95,                daily_seasonality=True,                weekly_seasonality=True,                yearly_seasonality=False            )    #train prophet model    m.fit(train)        #extract features from data using prophet to predict train set    predictions_train = m.predict(train.drop('y', axis=1))    #extract features from data using prophet to predict test set    predictions_test = m.predict(test.drop('y', axis=1))    #merge train and test predictions    predictions = pd.concat([predictions_train, predictions_test], axis=0)    return predictions

下面的函数将返回一个给咱们的 LightGBM 模型筹备的新特色的DF:

应用 Prophet 特色训练 Autorregressive LightGBM

咱们应用 Prophet 提取了新特色,下一步就是进行特色的合并和应用 LightGBM 进行预测:

def train_time_series_with_folds_autoreg_prophet_features(df, horizon=24*7, lags=[1, 2, 3, 4, 5]):    #create a dataframe with all the new features created with Prophet    new_prophet_features = prophet_features(df, horizon=horizon)    df.reset_index(inplace=True)        #merge the Prophet features dataframe with the our first dataframe    df = pd.merge(df, new_prophet_features, left_on=['datetime'], right_on=['ds'], how='inner')    df.drop('ds', axis=1, inplace=True)    df.set_index('datetime', inplace=True)        #create some lag variables using Prophet predictions (yhat column)    for lag in lags:        df[f'yhat_lag_{lag}'] = df['yhat'].shift(lag)    df.dropna(axis=0, how='any')        X = df.drop('count', axis=1)    y = df['count']        #take last week of the dataset for validation    X_train, X_test = X.iloc[:-horizon,:], X.iloc[-horizon:,:]    y_train, y_test = y.iloc[:-horizon], y.iloc[-horizon:]        #define LightGBM model, train it and make predictions    model = LGBMRegressor(random_state=42)    model.fit(X_train, y_train)    predictions = model.predict(X_test)        #calculate MAE    mae = np.round(mean_absolute_error(y_test, predictions), 3)            #plot reality vs prediction for the last week of the dataset    fig = plt.figure(figsize=(16,6))    plt.title(f'Real vs Prediction - MAE {mae}', fontsize=20)    plt.plot(y_test, color='red')    plt.plot(pd.Series(predictions, index=y_test.index), color='green')    plt.xlabel('Hour', fontsize=16)    plt.ylabel('Number of Shared Bikes', fontsize=16)    plt.legend(labels=['Real', 'Prediction'], fontsize=16)    plt.grid()    plt.show()

执行上述代码后,咱们将合并特色df,创立滞后的lag值,训练 LightGBM 模型,而后用咱们训练的模型进行预测,将咱们的预测与理论后果进行比拟。输入将如下所示:

如果咱们仔细观察后果咱们的 MAE 为 28.665。这要比个别特色工程后果有很大的进步。

总结

将监督机器学习办法与 Prophet 等统计办法相结合,能够帮忙咱们获得令人印象粗浅的后果。依据我在事实世界我的项目中的教训,很难在需求预测问题中取得比这些更好的后果。

https://www.overfit.cn/post/4f12535a96ac41fb98e8b7820a0cda5f

作者:Unai López Ansoleaga