gpt4 book ai didi

python - 无法使用新观察更新 StatsModels SARIMAX (ValueError)

转载 作者:行者123 更新时间:2023-12-05 03:40:08 28 4
gpt4 key购买 nike

我正在尝试使用 SciKitLearn 的 TimeSeriesSplit() 对时间序列数据集运行样本外验证,以创建训练/测试折叠。

想法是在训练折叠上训练 Statsmodel 的 SARIMAX,然后在不重新拟合模型的情况下在测试折叠上进行验证。为此,我们必须在预测之前,一次一个地迭代地将来自测试折叠的新观察结果附加到模型中。

但是,我在该追加步骤中收到 ValueError:ValueError:给定的 endog 没有扩展模型索引的索引。

这对我来说毫无意义。如果我为每个折叠打印出 print(max(train_fold.index), min(test_fold.index)) ,显然火车折叠的最后一个索引低于测试折叠的第一个索引。就我而言:

1983-05 1983-06
1984-05 1984-06
1985-05 1985-06
1986-05 1986-06
1987-05 1987-06

这是目前的完整代码。我确定我在做一些愚蠢的事情,但我被卡住了:

# Create a generator that yields the indices of our train and test folds
split = TimeSeriesSplit(n_splits=5).split(train_series)

# Loop through each fold
for train_idcs, test_idcs in split:

# Create an empty prediction list to append to
predictions = []

# Create the folds
train_fold = train_series[train_idcs]
test_fold = train_series[test_idcs]

# Fit the model on the training fold
model_instance = sm.tsa.statespace.SARIMAX(
train_fold,
order=(1, 0, 0),
seasonal_order=(1, 0, 0, 12),
simple_differencing=True,
enforce_stationarity=False,
enforce_invertibility=False,
)
model_fitted = model_instance.fit(disp=False)

# Create the initial prediction
pred = model_fitted.forecast(steps=1)[
0
] # Slice so we just get the forecast value only
predictions.append(pred)

# Now loop through the test set, adding observations individually,
# and getting the next prediction
for i in range(len(test_fold)):

# Get the next row
next_row = test_fold.iloc[
i : i + 1
] # Returns single row but in series form (which statsmodels expects)

# Append the row to the model
model_fitted.append(next_row, refit=False)

# Get the new prediction
pred = model_fitted.forecast(steps=1)[
0
] # Slice so we just get the forecast value only
predictions.append(pred)

print(predictions)

model_fitted.append(next_row, refit=False) 是失败点。有任何想法吗?谢谢!

最佳答案

明白了!这很愚蠢。

SARIMAX 模型的 .append() 方法返回模型本身,而不是更改模型中存储的数据。

所以正确的代码很简单:model_fitted = model_fitted.append(next_row, refit=False)

关于python - 无法使用新观察更新 StatsModels SARIMAX (ValueError),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68274569/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com