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

使用Skforecast拟合的ForecasterSarimax预测时触发TypeError错误

使用ForecasterSarimax预测时触发TypeError的解决方法

问题描述

拟合ForecasterSarimax对象后执行预测,出现如下错误:

TypeError: Expected index of type <class 'pandas.core.indexes.datetimes.DatetimeIndex'> for `last_window`. Got <class 'pandas.core.indexes.range.RangeIndex'>.

可复现代码

# 导入库
import pandas as pd
import numpy as np
from skforecast.Sarimax import Sarimax
from skforecast.ForecasterSarimax import ForecasterSarimax

# 生成数据集
start_date = '2023-01-01'
end_date = '2024-01-01'

date_range = pd.date_range(start=start_date, end=end_date, freq='D')
qty = np.random.randint(low=10, high=100, size=len(date_range))
data = pd.DataFrame({'date': date_range, 'qty': qty})
data.set_index('date', inplace=True)

end_train = '2023-11-01'

# 存在变量名错误:实际数据集变量为data,此处误用df
data_train = df.loc[:end_train]
data_test  = df.loc[end_train:]

# 转换为skforecast所需的Series格式
data_train_series = pd.Series(data_train['qty'].values, index=data_train.index, name='qty')
data_test_series  = pd.Series(data_test['qty'].values, index=data_test.index, name='qty')

# 初始化Sarimax预测器
forecaster = ForecasterSarimax(
                 regressor=Sarimax(order=(1, 1, 1), seasonal_order=(1, 1, 1, 12))
            )

forecaster.fit(y=data_train_series, suppress_warnings=True)

# 执行预测
predictions = forecaster.predict(steps=len(data_test_series))

完整错误日志

TypeError                                 Traceback (most recent call last)
File ~/Desktop/School/2024_projects/time_series_feature_engineering/practice/01_bakery_skforecast_quickstart.py:1
----> 1 predictions = forecaster.predict(steps=len(data_test_series))

File ~/Desktop/School/2024_projects/time_series_feature_engineering/.venv/lib/python3.9/site-packages/skforecast/ForecasterSarimax/ForecasterSarimax.py:363, in ForecasterSarimax.predict(self, steps, last_window, last_window_exog, exog)
    359 # Needs to be a new variable to avoid arima_res_.append when using 
    360 # self.last_window. It already has it stored.
    361 last_window_check = last_window if last_window is not None else self.last_window
--> 363 check_predict_input(
    364     forecaster_name  = type(self).__name__,
    365     steps            = steps,
    366     fitted           = self.fitted,
    367     included_exog    = self.included_exog,
    368     index_type       = self.index_type,
    369     index_freq       = self.index_freq,
    370     window_size      = self.window_size,
    371     last_window      = last_window_check,
    372     last_window_exog = last_window_exog,
    373     exog             = exog,
    374     exog_type        = self.exog_type,
    375     exog_col_names   = self.exog_col_names,
    376     interval         = None,
    377     alpha            = None,
    378     max_steps        = None,
    379     levels           = None,
    380     series_col_names = None
    381 )
    383 # If not last_window is provided, last_window needs to be None
    384 if last_window is not None:

File ~/Desktop/School/2024_projects/time_series_feature_engineering/.venv/lib/python3.9/site-packages/skforecast/utils/utils.py:643, in check_predict_input(forecaster_name, steps, fitted, included_exog, index_type, index_freq, window_size, last_window, last_window_exog, exog, exog_type, exog_col_names, interval, alpha, max_steps, levels, series_col_names)
    638 _, last_window_index = preprocess_last_window(
    639                            last_window   = last_window.iloc[:0],
    640                            return_values = False
    641                        ) 
    642 if not isinstance(last_window_index, index_type):
--> 643     raise TypeError(
    644         (f"Expected index of type {index_type} for `last_window`. "
    645          f"Got {type(last_window_index)}.")
    646     )
    647 if isinstance(last_window_index, pd.DatetimeIndex):
    648     if not last_window_index.freqstr == index_freq:

TypeError: Expected index of type <class 'pandas.core.indexes.datetimes.DatetimeIndex'> for `last_window`. Got <class 'pandas.core.indexes.range.RangeIndex'>.

问题原因

  1. 变量名误用:代码中错误使用未定义的df变量引用数据集,若环境中存在其他df且其索引为RangeIndex,会导致训练集索引类型异常。
  2. Series构造方式不当:通过pd.Series(data_train['qty'].values, ...)构造Series时,可能丢失原DatetimeIndex的频率属性,导致forecaster内部索引校验失败。

解决方案

修正后的代码

# 导入库
import pandas as pd
import numpy as np
from skforecast.Sarimax import Sarimax
from skforecast.ForecasterSarimax import ForecasterSarimax

# 生成数据集
start_date = '2023-01-01'
end_date = '2024-01-01'

date_range = pd.date_range(start=start_date, end=end_date, freq='D')
qty = np.random.randint(low=10, high=100, size=len(date_range))
data = pd.DataFrame({'date': date_range, 'qty': qty})
data.set_index('date', inplace=True)

end_train = '2023-11-01'

# 修正变量名:使用正确的data变量
data_train = data.loc[:end_train]
data_test  = data.loc[end_train:]

# 直接提取DataFrame列作为Series,保留原索引属性
data_train_series = data_train['qty']
data_test_series  = data_test['qty']

# 初始化Sarimax预测器
forecaster = ForecasterSarimax(
                 regressor=Sarimax(order=(1, 1, 1), seasonal_order=(1, 1, 1, 12))
            )

forecaster.fit(y=data_train_series, suppress_warnings=True)

# 执行预测
predictions = forecaster.predict(steps=len(data_test_series))

小时级数据集适配

若使用小时级数据,只需调整日期频率和季节性周期:

# 生成小时级日期范围
date_range = pd.date_range(start=start_date, end=end_date, freq='H')
# 调整季节性周期为24(每日24小时)
forecaster = ForecasterSarimax(
                 regressor=Sarimax(order=(1, 1, 1), seasonal_order=(1, 1, 1, 24))
            )

内容的提问来源于stack exchange,提问作者The Rookie

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 19:47:08