使用Prophet做时间序列预测效果差,如何优化模型?
如何优化Prophet时间序列预测模型?
我用Prophet做时间序列预测,但效果极差,MAE和R-squared指标都很低。已经试过调整季节性设置和模式,没明显改善。
数据集概览

我的代码
# pandas import pandas as pd # prophet from prophet import Prophet # metrics from sklearn.metrics import r2_score, mean_absolute_error # holoviews import holoviews as hv from holoviews import opts # Create a new column to identify if the date is a weekday or weekend df_prophet['day_type'] = df_prophet['ds'].apply(lambda x: 'Weekend' if x.weekday() >= 5 else 'Weekday') df_prophet threshold_date = pd.to_datetime('2023-10-01') mask = df_prophet['ds'] < threshold_date # Split the data and select `ds` and `y` columns. df_train = df_prophet[mask][['ds', 'y']] df_test = df_prophet[~ mask][['ds', 'y']] def build_model(): """Define forecasting model.""" model = Prophet( yearly_seasonality=True, weekly_seasonality=True, # daily_seasonality=True, # holidays = holidays, interval_width=0.95, mcmc_samples = 1000, # seasonality_mode = 'multiplicative', seasonality_mode = 'additive', growth= 'linear' ) # model.add_seasonality( # name='daily', # period=5, # fourier_order=5 # ) return model model = build_model() model.fit(df_train) # Extend dates and features. horizon = df_test.shape[0] future = model.make_future_dataframe(periods=horizon, freq='D') # daily days predictions # Generate predictions. forecast = model.predict(df=future) forecast.loc[:, 'yhat'] = forecast['yhat'].clip(lower=0) forecast.loc[:, 'yhat_lower'] = forecast['yhat_lower'].clip(lower=0) print('r2 train: {}'.format(r2_score(y_true=df_train['y'], y_pred=forecast_train['yhat']))) print('r2 test: {}'.format(r2_score(y_true=df_test['y'], y_pred=forecast_test['yhat']))) print('---'*10) print('mae train: {}'.format(mean_absolute_error(y_true=df_train['y'], y_pred=forecast_train['yhat']))) print('mae test: {}'.format(mean_absolute_error(y_true=df_test['y'], y_pred=forecast_test['yhat'])))
预测结果

优化建议
1. 用上已构造的day_type特征
你已经生成了day_type列,但训练时没传入模型。Prophet支持添加额外回归因子,在model.fit()前加上:
model.add_regressor('day_type')
同时,生成future dataframe后,要把day_type列合并进去,否则预测时会缺失特征:
future = future.merge(df_prophet[['ds', 'day_type']], on='ds', how='left')
2. 修正代码变量错误
打印指标时用到的forecast_train和forecast_test未定义,需要拆分forecast:
forecast_train = forecast[forecast['ds'] < threshold_date] forecast_test = forecast[forecast['ds'] >= threshold_date]
否则无法正确计算指标,甚至会报错。
3. 匹配数据特征调整模型增长模式
从数据集图看,数据存在明显突变点,默认线性增长可能不适用:
- 调大
changepoint_prior_scale让模型更敏感捕捉突变:model = Prophet(growth='linear', changepoint_prior_scale=0.1) - 手动指定突变点日期(根据数据实际突变情况调整):
model = Prophet(changepoints=['2023-05-01', '2023-08-01'])
4. 优化季节性设置
- 如果数据波动幅度随数值增大而变大,切换到
seasonality_mode='multiplicative'替代加法模式。 - 自定义季节性规则,比如针对工作日/周末设置不同的周季节性:
model.add_seasonality(name='weekly_working', period=7, fourier_order=3, condition_name='day_type') - 调整
fourier_order值:增大该值可让模型捕捉更复杂的季节性,但注意避免过拟合。
5. 关闭不必要的MCMC采样
mcmc_samples=1000会大幅增加训练时间,非特殊场景(如需要精确不确定性估计)建议去掉该参数,用默认MAP估计即可。
6. 加入节假日影响
如果业务有固定节假日影响数据,收集节假日列表传入模型:
holidays = pd.DataFrame({ 'holiday': 'festival', 'ds': pd.to_datetime(['2023-01-01', '2023-05-01']), # 替换为实际节假日日期 'lower_window': 0, 'upper_window': 1, }) model = Prophet(holidays=holidays)
内容的提问来源于stack exchange,提问作者AndCh
相关产品推荐
相关产品推荐

