gpt4 book ai didi

python - Python 中带有 pandas + statsmodels 的 VAR 模型

转载 作者:太空狗 更新时间:2023-10-30 01:16:09 30 4
gpt4 key购买 nike

我是 R 的狂热用户,但最近由于一些不同的原因转而使用 Python。但是,我在 Python 中从 statsmodels 运行矢量 AR 模型时遇到了一些困难。

问题#1。运行此程序时出现错误,我怀疑它与我的向量类型有关。

    import numpy as np
import statsmodels.tsa.api
from statsmodels import datasets
import datetime as dt
import pandas as pd
from pandas import Series
from pandas import DataFrame
import os

df = pd.read_csv('myfile.csv')
speedonly = DataFrame(df['speed'])
results = statsmodels.tsa.api.VAR(speedonly)

Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
results = statsmodels.tsa.api.VAR(speedonly)
File "C:\Python27\lib\site-packages\statsmodels\tsa\vector_ar\var_model.py", line 336, in __init__
super(VAR, self).__init__(endog, None, dates, freq)
File "C:\Python27\lib\site-packages\statsmodels\tsa\base\tsa_model.py", line 40, in __init__
self._init_dates(dates, freq)
File "C:\Python27\lib\site-packages\statsmodels\tsa\base\tsa_model.py", line 54, in _init_dates
raise ValueError("dates must be of type datetime")
ValueError: dates must be of type datetime

现在,有趣的是,当我从这里运行 VAR 示例时 https://github.com/statsmodels/statsmodels/blob/master/docs/source/vector_ar.rst#id5 , 它工作正常。

我尝试使用来自 Wes McKinney 的“用于数据分析的 Python”第 293 页的第三个更短的向量 ts 的 VAR 模型,但它不起作用。

好吧,现在我认为这是因为向量的类型不同:

    >>> speedonly.head()
speed
0 559.984
1 559.984
2 559.984
3 559.984
4 559.984
>>> type(speedonly)
<class 'pandas.core.frame.DataFrame'> #DOESN'T WORK

>>> type(data)
<type 'numpy.ndarray'> #WORKS

>>> ts
2011-01-02 -0.682317
2011-01-05 1.121983
2011-01-07 0.507047
2011-01-08 -0.038240
2011-01-10 -0.890730
2011-01-12 -0.388685
>>> type(ts)
<class 'pandas.core.series.TimeSeries'> #DOESN'T WORK

所以我将 speedonly 转换为 ndarray... 但它仍然不起作用。但是这次我得到了另一个错误:

   >>> nda_speedonly = np.array(speedonly)
>>> results = statsmodels.tsa.api.VAR(nda_speedonly)

Traceback (most recent call last):
File "<pyshell#47>", line 1, in <module>
results = statsmodels.tsa.api.VAR(nda_speedonly)
File "C:\Python27\lib\site-packages\statsmodels\tsa\vector_ar\var_model.py", line 345, in __init__
self.neqs = self.endog.shape[1]
IndexError: tuple index out of range

有什么建议吗?

问题#2。我的数据集中有似乎对预测有用的外生特征变量。以上来自 statsmodels 的模型是不是最好用的模型?

最佳答案

当您将 pandas 对象提供给时间序列模型时,它期望索引是日期。错误信息在当前源中得到改进(即将发布)。

ValueError: Given a pandas object and the index does not contain dates

在第二种情况下,您将单个 1d 系列提供给 VAR。当您有多个系列时,将使用 VAR。这就是为什么你有形状错误的原因,因为它期望你的数组中有第二个维度。我们或许可以改进此处的错误消息。对于具有外生变量的单系列 AR 模型,您可能希望使用 sm.tsa.ARMA。请注意,有一个 known bug在 ARMA.predict 中,具有外生变量的模型很快就会修复。如果您能为此提供一个测试用例,那将会很有帮助。

关于python - Python 中带有 pandas + statsmodels 的 VAR 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15778753/

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