gpt4 book ai didi

python - 为什么我从 grangercausalitytests 得到 "LinAlgError: Singular matrix"?

转载 作者:太空狗 更新时间:2023-10-29 22:06:21 31 4
gpt4 key购买 nike

我正在尝试在两个时间序列上运行 grangercausalitytests:

import numpy as np
import pandas as pd

from statsmodels.tsa.stattools import grangercausalitytests

n = 1000
ls = np.linspace(0, 2*np.pi, n)

df1 = pd.DataFrame(np.sin(ls))
df2 = pd.DataFrame(2*np.sin(1+ls))

df = pd.concat([df1, df2], axis=1)

df.plot()

grangercausalitytests(df, maxlag=20)

但是,我得到了

Granger Causality
number of lags (no zero) 1
ssr based F test: F=272078066917221398041264652288.0000, p=0.0000 , df_denom=996, df_num=1
ssr based chi2 test: chi2=272897579166972095424217743360.0000, p=0.0000 , df=1
likelihood ratio test: chi2=60811.2671, p=0.0000 , df=1
parameter F test: F=272078066917220553616334520320.0000, p=0.0000 , df_denom=996, df_num=1

Granger Causality
number of lags (no zero) 2
ssr based F test: F=7296.6976, p=0.0000 , df_denom=995, df_num=2
ssr based chi2 test: chi2=14637.3954, p=0.0000 , df=2
likelihood ratio test: chi2=2746.0362, p=0.0000 , df=2
parameter F test: F=13296850090491009488285469769728.0000, p=0.0000 , df_denom=995, df_num=2
...
/usr/local/lib/python3.5/dist-packages/numpy/linalg/linalg.py in _raise_linalgerror_singular(err, flag)
88
89 def _raise_linalgerror_singular(err, flag):
---> 90 raise LinAlgError("Singular matrix")
91
92 def _raise_linalgerror_nonposdef(err, flag):

LinAlgError: Singular matrix

我不确定为什么会这样。

最佳答案

问题的出现是由于您数据中两个系列之间的完美相关性。从回溯中,您可以看到,内部使用 wald 检验来计算滞后时间序列参数的最大似然估计。为此,需要估计参数协方差矩阵(然后接近于零)及其逆矩阵(正如您在 invcov = np.linalg.inv(cov_p) 行中看到的那样)回溯)。对于某个最大滞后数 (>=5),这个接近零的矩阵现在是奇异的,因此测试崩溃了。如果您在数据中加入一点噪音,错误就会消失:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.tsa.stattools import grangercausalitytests

n = 1000
ls = np.linspace(0, 2*np.pi, n)
df1Clean = pd.DataFrame(np.sin(ls))
df2Clean = pd.DataFrame(2*np.sin(ls+1))
dfClean = pd.concat([df1Clean, df2Clean], axis=1)
dfDirty = dfClean+0.00001*np.random.rand(n, 2)

grangercausalitytests(dfClean, maxlag=20, verbose=False) # Raises LinAlgError
grangercausalitytests(dfDirty, maxlag=20, verbose=False) # Runs fine

关于python - 为什么我从 grangercausalitytests 得到 "LinAlgError: Singular matrix"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44305456/

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