You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AutoTS多变量时序预测优化:选Top3模型预测未来4季度

问题

使用AutoTS开展多变量时间序列预测,当前流程为:

  1. 划分训练集与验证集(取最后2个季度作为验证集)
  2. 拟合forecast_length=2的AutoTS模型,获取各列MAE指标
  3. 筛选Top3模型后,用其预测未来4个季度
    当前方案耗时较长,希望得到更优实现方法,同时寻求与其他单变量时间序列模型对比各列MAE的更佳方式。

一、AutoTS流程优化方案

核心优化点

  • 精简模型与预处理范围:当前model_list包含计算成本高的模型(如NeuralForecast),如果非必需,优先保留轻量多变量模型(如MAR、MultivariateRegression);同时将transformer_list设为superfast,降低预处理开销。
  • 复用已训练模型,避免重复拟合:原代码中筛选Top3后重新拟合forecast_length=4的模型是耗时核心,完全可以直接修改已训练模型的forecast_length后预测,无需重新拟合。
  • 简化验证策略:用validation_method="single"替代backwards,减少验证阶段的计算量(若对精度要求不高);num_validations=1已是最小验证次数,无需调整。

优化后代码示例

import pandas as pd
from autots import AutoTS

# 1. 数据划分:拆分训练集与验证集(最后2个季度为验证集)
full_df['year-quarter-date'] = pd.to_datetime(full_df['year-quarter-date'])
last_date = full_df['year-quarter-date'].max()
validation_cutoff = last_date - pd.DateOffset(months=6)
train_df = full_df[full_df['year-quarter-date'] <= validation_cutoff]
val_df = full_df[full_df['year-quarter-date'] > validation_cutoff]

# 2. 初始化并拟合AutoTS模型,优先选择轻量配置
model = AutoTS(
    forecast_length=2,
    frequency='Q',  # 直接指定季度频率,省去自动推断的开销
    model_list=['MAR','MultivariateRegression','NVAR'],  # 移除计算重的NeuralForecast
    transformer_list="superfast",
    transformer_max_depth=1,  # 降低transformer复杂度
    max_generations=1,
    num_validations=1,
    validation_method='single',  # 单验证集模式加快速度
    no_negatives=True,
    remove_leading_zeroes=True,
    metric='MAE'  # 明确指定MAE作为评分指标
)

model = model.fit(
    train_df,
    date_col='year-quarter-date',
    value_col='value',
    id_col='vial_size'
)

# 3. 获取Top3模型,直接复用已训练好的模型实例
top_3_results = model.results().sort_values(by='Score').head(3)
trained_top_models = [
    model.get_model(model_name=row['Model'], model_parameters=row['ModelParameters']) 
    for _, row in top_3_results.iterrows()
]

# 4. 修改forecast_length为4,直接预测未来4个季度(无需重新拟合)
for trained_model in trained_top_models:
    trained_model.forecast_length = 4
    prediction = trained_model.predict()
    forecast = prediction.forecast
    print(f"模型{trained_model.model_name}的未来4季度预测结果:\n{forecast}\n")

# 计算各列(vial_size)的MAE指标(基于验证集)
val_predictions = model.predict(future_data=val_df)
mae_df = val_predictions.forecast.merge(
    val_df, 
    on=['year-quarter-date', 'vial_size'], 
    suffixes=('_pred', '_true')
)
mae_df['MAE'] = abs(mae_df['value_pred'] - mae_df['value_true'])
mae_summary = mae_df.groupby('vial_size')['MAE'].mean().reset_index()
print("各列MAE汇总:\n", mae_summary)

二、与单变量模型对比MAE的方案

实现思路

针对每个vial_size列单独训练单变量模型(如Prophet、ARIMA),使用与AutoTS完全一致的训练/验证集划分,统一计算MAE后合并对比。

对比代码示例

from prophet import Prophet
import statsmodels.api as sm

# 定义单变量模型MAE计算函数
def calculate_univariate_mae(full_df, validation_cutoff, model_type='prophet'):
    mae_dict = {}
    for vial in full_df['vial_size'].unique():
        # 提取单变量时间序列数据
        subset = full_df[full_df['vial_size'] == vial].rename(columns={
            'year-quarter-date': 'ds', 
            'value': 'y'
        })
        train_sub = subset[subset['ds'] <= validation_cutoff]
        val_sub = subset[subset['ds'] > validation_cutoff]
        
        if model_type == 'prophet':
            m = Prophet(seasonality_mode='multiplicative')
            m.fit(train_sub)
            forecast = m.predict(val_sub[['ds']])
            mae = abs(forecast['yhat'] - val_sub['y']).mean()
        elif model_type == 'arima':
            # 简单ARIMA(1,1,1)配置,可根据需求调整参数
            model = sm.tsa.ARIMA(train_sub['y'], order=(1,1,1))
            results = model.fit()
            forecast = results.predict(
                start=len(train_sub), 
                end=len(train_sub)+len(val_sub)-1
            )
            mae = abs(forecast - val_sub['y']).mean()
        
        mae_dict[vial] = mae
    return pd.DataFrame.from_dict(
        mae_dict, 
        orient='index', 
        columns=[f'{model_type}_MAE']
    )

# 计算各单变量模型的MAE
prophet_mae = calculate_univariate_mae(full_df, validation_cutoff, 'prophet')
arima_mae = calculate_univariate_mae(full_df, validation_cutoff, 'arima')

# 合并AutoTS的MAE结果,生成对比表
mae_comparison = mae_summary.merge(
    prophet_mae, 
    left_on='vial_size', 
    right_index=True
).merge(
    arima_mae, 
    left_on='vial_size', 
    right_index=True
)
print("MAE对比结果:\n", mae_comparison)

内容的提问来源于stack exchange,提问作者sai akhil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 09:52:05