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

使用statsmodels拟合SVAR模型时遇ValueError错误求助

解决statsmodels拟合SVAR模型时的ValueError问题

问题场景

使用statsmodels库拟合Structural Vector Autoregression (SVAR)模型时,触发如下错误:

ValueError: zero-size array to reduction operation maximum which has no identity

原代码如下:

import pandas as pd
import numpy as np
from statsmodels.tsa.vector_ar.svar_model import SVAR

df_sample = pd.DataFrame(
    {
    'Product_1': np.random.rand(240) * 10000,
    'Product_2': np.random.rand(240) * 10000,
    'Product_3': np.random.rand(240) * 10000
    }, 
    index=pd.date_range(start='2019-11-16', periods=240, freq='W-SAT'))

A = np.array([
    [1, 0, 0],
    [np.nan, 1, 0],
    [np.nan, np.nan, 1]
], dtype='U')

# Fit SVAR
model = SVAR(df_sample, svar_type='A', A=A)
res = model.fit(maxlags=4)

错误原因

核心问题在于约束矩阵A被设置为字符串类型(dtype='U'):

  • statsmodels的SVAR模型要求约束矩阵必须是数值类型(如float),字符串类型的矩阵会导致模型在参数估计阶段无法正确解析待估计的参数(np.nan被转为字符串"nan"),进而引发数组维度相关的计算错误。

修正方案

移除A矩阵的dtype='U'参数,让numpy自动推断为数值类型(float),确保np.nan作为数值缺失值被模型识别为待估计的自由参数。

修正后的完整代码

import pandas as pd
import numpy as np
from statsmodels.tsa.vector_ar.svar_model import SVAR

df_sample = pd.DataFrame(
    {
    'Product_1': np.random.rand(240) * 10000,
    'Product_2': np.random.rand(240) * 10000,
    'Product_3': np.random.rand(240) * 10000
    }, 
    index=pd.date_range(start='2019-11-16', periods=240, freq='W-SAT'))

# 移除dtype='U',使用默认数值类型
A = np.array([
    [1, 0, 0],
    [np.nan, 1, 0],
    [np.nan, np.nan, 1]
])

# 拟合SVAR模型
model = SVAR(df_sample, svar_type='A', A=A)
res = model.fit(maxlags=4)

# 查看估计结果
print(res.summary())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 23:02:42