为什么在使用tigramite库生成时间序列时元组索引超出范围?

1 投票
1 回答
34 浏览
提问于 2025-04-14 17:16

我安装了一个叫做 tigramite 的包,用来做因果推断,并导入了以下库:

# Imports
import numpy as np
import matplotlib
from matplotlib import pyplot as plt
%matplotlib inline     
import sklearn

import tigramite
from tigramite import data_processing as pp
from tigramite.toymodels import structural_causal_processes as toys

from tigramite import plotting as tp
from tigramite.pcmci import PCMCI
from tigramite.lpcmci import LPCMCI

from tigramite.independence_tests.parcorr import ParCorr
from tigramite.independence_tests.robust_parcorr import RobustParCorr
from tigramite.independence_tests.parcorr_wls import ParCorrWLS 
from tigramite.independence_tests.gpdc import GPDC
from tigramite.independence_tests.cmiknn import CMIknn
from tigramite.independence_tests.cmisymb import CMIsymb
from tigramite.independence_tests.gsquared import Gsquared
from tigramite.independence_tests.regressionCI import RegressionCI

现在我找到了以下代码,用来生成和模拟时间序列:

np.random.seed(42)     # Fix random seed to make results reproducible
links_coeffs = {0: [((0, -1), 0.7), ((1, -1), -0.8)],
            1: [((1, -1), 0.8), ((3, -1), 0.8)],
            2: [((2, -1), 0.5), ((1, -2), 0.5), ((3, -3), 0.6)],
            3: [((3, -1), 0.4)],
            } #stores the coefficients of the SCM
 T = 1000     # time series length
 #generate the timeseries
 data, true_parents_neighbors = toys.structural_causal_process(links_coeffs, T=T) 
 T, N = data.shape

 # Initialize dataframe object, specify time axis and variable names
 var_names = [r'$X^0$', r'$X^1$', r'$X^2$', r'$X^3$']
 dataframe = pp.DataFrame(data, 
                     datatime = {0:np.arange(len(data))}, 
                     var_names=var_names)

但是我遇到了一个错误,提示 IndexError: tuple index out of range,这个错误可能是出现在生成时间序列的那一行代码上:data, true_parents_neighbors = toys.structural_causal_process(links_coeffs, T=T)

我该怎么解决这个问题呢?

1 个回答

1

这是因为你的 links_coeffs 的格式不对。

要使用 structural_causal_process,链接的格式必须是 {0:[((i, -tau), coeff, func),...], 1:[...], ...},而你提供的格式不符合这个要求。正确的链接格式应该像这样:

def fn(x):
    return x

links_coeffs = {
    0: [((0, -1), 0.3, fn), ((2, 0), 0.5, fn), ((3, -1), -0.5, fn)],  # X1
    1: [((1, -1), 0.3, fn)],  # X2
    2: [((2, -1), 0.3, fn), ((1, -2), 0.4, fn)],  # X3
    3: [((3, -1), 0.3, fn)],  # X4
}

如果你需要那种特定格式的链接,或许你可以考虑使用 var_process

data, true_parents_neighbors = toys.structural_causal_process(links_coeffs, T=T)
data, true_parents_neighbors = toys.var_process(links_coeffs, T=T)

在这里输入图片描述

撰写回答