Help with PyMC3 Model - Convergence Warning and Theano Error

Hi everyone,

I’m reaching out to the forum for some assistance with a PyMC3 model I’m building for a Time-Varying Parameter Vector Autoregression (TVP-PVAR) analysis. I’m encountering a convergence warning and a Theano compilation error, and I’d appreciate any insights or suggestions you might have.

Errors:

  • Convergence Warning: I’m getting a ConvergenceWarning related to the iterative imputation process used for handling missing values in my data. The warning suggests that the imputation might not have fully converged within the set maximum iterations.
[IterativeImputer] Early stopping criterion not reached.
  • Theano Compilation Error: Following the convergence warning, I encounter a Theano compilation error with a message about exceeding the maximum bracket nesting level.
Compilation failed (return status=1): /Users//.theano/compiledir_macOS-14.5-arm64-arm-64bit-arm-3.11.8-64/tmpenzneiyk/mod.cpp:72300:32: fatal error: bracket nesting level exceeded maximum of 256.

Code Snippet:

# code deleted at the request of the author/original poster

other code

System Information:

  • Python version: (mention your Python version)
  • PyMC3 version: 3.11.4(
  • Theano version: latest
    *Aesera version: latest
  • OS: macos

Questions:

  1. How can I effectively address the convergence warning and ensure the iterative imputation process converges adequately?
  2. Are there any strategies to handle the Theano compilation error related to the bracket nesting level, particularly if it’s caused by the model complexity?

I’ve searched online for solutions, but haven’t found a definitive fix for this specific combination of errors. Any guidance or recommendations from the community would be greatly appreciated.

Additional Information:

  • I’ve tried increasing the imputer_max_iter parameter in the fit_tvp_pvar function to allow more iterations for imputation.
  • I’m open to exploring alternative imputation methods like KNN imputation or more advanced techniques if necessary.

I eneded up with this code after trying to solve this error

anaconda3/lib/python3.11/site-packages/sklearn/impute/_iterative.py:801: ConvergenceWarning: [IterativeImputer] Early stopping criterion not reached.
warnings.warn(
Auto-assigning NUTS sampler…
Initializing NUTS using jitter+adapt_diag…

You can find the C code in this temporary file: /var/folders/p_/4shh5wgx7vn_sp4_77tp6c7m0000gn/T/theano_compilation_error_0s9f3yfr
Traceback (most recent call last):

File ~/anaconda3/lib/python3.11/site-packages/theano/tensor/basic.py:184 in as_tensor_variable
x = [extract_constants(i) for i in x]

File ~/anaconda3/lib/python3.11/site-packages/theano/tensor/basic.py:184 in
x = [extract_constants(i) for i in x]

File ~/anaconda3/lib/python3.11/site-packages/theano/tensor/basic.py:179 in extract_constants
raise TypeError

TypeError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):

Cell In[2], line 1
model.fit_tvp_pvar(num_iterations=50000, burn=20000, tune=10000, cores=4, imputation_method=‘iterative’, imputer_max_iter=1000)

Cell In[1], line 130 in fit_tvp_pvar
trace = pm.sample(num_iterations, tune=tune, cores=cores, return_inferencedata=True)

File ~/anaconda3/lib/python3.11/site-packages/pymc3/sampling.py:496 in sample
start_, step = init_nuts(

File ~/anaconda3/lib/python3.11/site-packages/pymc3/sampling.py:2187 in init_nuts
step = pm.NUTS(potential=potential, model=model, **kwargs)

File ~/anaconda3/lib/python3.11/site-packages/pymc3/step_methods/hmc/nuts.py:168 in init
super().init(vars, **kwargs)

File ~/anaconda3/lib/python3.11/site-packages/pymc3/step_methods/hmc/base_hmc.py:88 in init
super().init(vars, blocked=blocked, model=model, dtype=dtype, **theano_kwargs)

File ~/anaconda3/lib/python3.11/site-packages/pymc3/step_methods/arraystep.py:254 in init
func = model.logp_dlogp_function(vars, dtype=dtype, **theano_kwargs)

File ~/anaconda3/lib/python3.11/site-packages/pymc3/model.py:1001 in logp_dlogp_function
costs = [self.logpt]

File ~/anaconda3/lib/python3.11/site-packages/pymc3/model.py:1011 in logpt
logp = tt.sum([tt.sum(factor) for factor in factors])

File ~/anaconda3/lib/python3.11/site-packages/theano/tensor/basic.py:3221 in sum
out = elemwise.Sum(axis=axis, dtype=dtype, acc_dtype=acc_dtype)(input)

File ~/anaconda3/lib/python3.11/site-packages/theano/graph/op.py:250 in call
node = self.make_node(*inputs, **kwargs)

File ~/anaconda3/lib/python3.11/site-packages/theano/tensor/elemwise.py:1925 in make_node
input = as_tensor_variable(input)

File ~/anaconda3/lib/python3.11/site-packages/theano/tensor/basic.py:194 in as_tensor_variable
return theano.tensor.opt.MakeVector(dtype)(*x)

File ~/anaconda3/lib/python3.11/site-packages/theano/graph/op.py:253 in call
compute_test_value(node)

File ~/anaconda3/lib/python3.11/site-packages/theano/graph/op.py:126 in compute_test_value
thunk = node.op.make_thunk(node, storage_map, compute_map, no_recycling=)

File ~/anaconda3/lib/python3.11/site-packages/theano/graph/op.py:634 in make_thunk
return self.make_c_thunk(node, storage_map, compute_map, no_recycling)

File ~/anaconda3/lib/python3.11/site-packages/theano/graph/op.py:600 in make_c_thunk
outputs = cl.make_thunk(

File ~/anaconda3/lib/python3.11/site-packages/theano/link/c/basic.py:1203 in make_thunk
cthunk, module, in_storage, out_storage, error_storage = self.compile(

File ~/anaconda3/lib/python3.11/site-packages/theano/link/c/basic.py:1138 in compile
thunk, module = self.cthunk_factory(

File ~/anaconda3/lib/python3.11/site-packages/theano/link/c/basic.py:1634 in cthunk_factory
module = get_module_cache().module_from_key(key=key, lnk=self)

File ~/anaconda3/lib/python3.11/site-packages/theano/link/c/cmodule.py:1191 in module_from_key
module = lnk.compile_cmodule(location)

File ~/anaconda3/lib/python3.11/site-packages/theano/link/c/basic.py:1543 in compile_cmodule
module = c_compiler.compile_str(

File ~/anaconda3/lib/python3.11/site-packages/theano/link/c/cmodule.py:2546 in compile_str
raise Exception(

Exception: ('Compilation failed (return status=1): /Users/evangeloss/.theano/compiledir_macOS-14.5-arm64-arm-64bit-arm-3.11.8-64/tmpenzneiyk/mod.cpp:72300:32: fatal error: bracket nesting level exceeded maximum of 256. if (!PyErr_Occurred()) {. ^. /Users/evangeloss/.theano/compiledir_macOS-14.5-arm64-arm-64bit-arm-3.11.8-64/tmpenzneiyk/mod.cpp:72300:32: note: use -fbracket-depth=N to increase maximum nesting level. 1 error generated… ', "FunctionGraph(MakeVector{dtype=‘float64’}(<TensorType(float64, scalar)>, <TensorType(float64, scalar)>, <TensorType(float64, scalar)>, <TensorType(float64, scalar)>, <TensorType(float64, scalar)>, <TensorType(float64, scalar)>, <TensorType(float64, scalar)>, <TensorType(float64, scalar)>,

Thanks in advance for your time and help!

Best regards,

Dimitri

Welcome!

The first, strong suggestion would be to upgrade to a recent version of PyMC. 3.11.4 was released in 2021 and theano/aesara isn’t even used by the package anymore (and neither is actively maintained). Installation instructions can be found here.

3 Likes

Thank you so much for your kind reply.
I have tried to create a new environment, as on the official page of the module

conda create -c conda-forge -n pymc_env “pymc>=5”
conda activate pymc_env

Nonetheless, when I try to import the specific module in the new environment, I get

In [1]: import pymc3 as pm
/opt/anaconda3/lib/python3.11/site-packages/theano/scalar/basic.py:2412: FutureWarning: In the future np.bool will be defined as the corresponding NumPy scalar.
self.ctor = getattr(np, o_type.dtype)
Traceback (most recent call last):

Cell In[1], line 1
import pymc3 as pm

File /opt/anaconda3/lib/python3.11/site-packages/pymc3/init.py:23
import theano

File /opt/anaconda3/lib/python3.11/site-packages/theano/init.py:83
from theano import scalar, tensor

File /opt/anaconda3/lib/python3.11/site-packages/theano/scalar/init.py:1
from .basic import *

File /opt/anaconda3/lib/python3.11/site-packages/theano/scalar/basic.py:2460
convert_to_bool = Cast(bool, name=“convert_to_bool”)

File /opt/anaconda3/lib/python3.11/site-packages/theano/scalar/basic.py:2412 in init
self.ctor = getattr(np, o_type.dtype)

File /opt/anaconda3/lib/python3.11/site-packages/numpy/init.py:324 in getattr
raise AttributeError(former_attrs[attr])

AttributeError: module ‘numpy’ has no attribute ‘bool’.
np.bool was a deprecated alias for the builtin bool. To avoid this error in existing code, use bool by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use np.bool_ here.
The aliases was originally deprecated in NumPy 1.20; for more details and guidance see the original release note at:
NumPy 1.20.0 Release Notes — NumPy v2.1.dev0 Manual

I have no installations of theano or aesea in the new environment. Nor other modules, apart from those that were downloaded with the environment creation. I did not even touch the installation.

I am frustrated, but I cannot solve.
Thanks for any help

Dimitri

If you have followed the instructions I linked to, you should import pymc, not pymc3.

1 Like

Also, if you can first

conda activate pymc_env

and then

conda list

and share the output, that might help.

Here are the modulus installed from the environment

packages in environment at /opt/anaconda3/envs/pymc_env:

Name Version Build Channel

accelerate 0.31.0 pyhd8ed1ab_0 conda-forge
arviz 0.18.0 pyhd8ed1ab_0 conda-forge
atk-1.0 2.38.0 hd03087b_2 conda-forge
blas 2.122 openblas conda-forge
blas-devel 3.9.0 22_osxarm64_openblas conda-forge
brotli 1.1.0 hb547adb_1 conda-forge
brotli-bin 1.1.0 hb547adb_1 conda-forge
brotli-python 1.1.0 py312h9f69965_1 conda-forge
bzip2 1.0.8 h93a5062_5 conda-forge
c-ares 1.28.1 h93a5062_0 conda-forge
ca-certificates 2024.6.2 hf0a4a13_0 conda-forge
cached-property 1.5.2 hd8ed1ab_1 conda-forge
cached_property 1.5.2 pyha770c72_1 conda-forge
cachetools 5.3.3 pyhd8ed1ab_0 conda-forge
cairo 1.18.0 hd1e100b_0 conda-forge
cctools_osx-arm64 986 h62378fb_0 conda-forge
certifi 2024.6.2 pyhd8ed1ab_0 conda-forge
charset-normalizer 3.3.2 pyhd8ed1ab_0 conda-forge
clang 16.0.6 default_h095aff0_8 conda-forge
clang-16 16.0.6 default_hb63da90_8 conda-forge
clang_impl_osx-arm64 16.0.6 hc421ffc_16 conda-forge
clang_osx-arm64 16.0.6 h54d7cd3_16 conda-forge
clangxx 16.0.6 default_h095aff0_8 conda-forge
clangxx_impl_osx-arm64 16.0.6 hcd7bac0_16 conda-forge
clangxx_osx-arm64 16.0.6 h54d7cd3_16 conda-forge
cloudpickle 3.0.0 pyhd8ed1ab_0 conda-forge
colorama 0.4.6 pyhd8ed1ab_0 conda-forge
compiler-rt 16.0.6 h3808999_2 conda-forge
compiler-rt_osx-arm64 16.0.6 h3808999_2 conda-forge
cons 0.4.6 pyhd8ed1ab_0 conda-forge
contourpy 1.2.1 py312h0fef576_0 conda-forge
cycler 0.12.1 pyhd8ed1ab_0 conda-forge
dm-tree 0.1.8 py312h1a610f3_4 conda-forge
etuples 0.3.9 pyhd8ed1ab_0 conda-forge
expat 2.6.2 hebf3989_0 conda-forge
filelock 3.15.1 pyhd8ed1ab_0 conda-forge
font-ttf-dejavu-sans-mono 2.37 hab24e00_0 conda-forge
font-ttf-inconsolata 3.000 h77eed37_0 conda-forge
font-ttf-source-code-pro 2.038 h77eed37_0 conda-forge
font-ttf-ubuntu 0.83 h77eed37_2 conda-forge
fontconfig 2.14.2 h82840c6_0 conda-forge
fonts-conda-ecosystem 1 0 conda-forge
fonts-conda-forge 1 0 conda-forge
fonttools 4.53.0 py312h7e5086c_0 conda-forge
freetype 2.12.1 hadb7bae_2 conda-forge
fribidi 1.0.10 h27ca646_0 conda-forge
fsspec 2024.6.0 pyhff2d567_0 conda-forge
gdk-pixbuf 2.42.12 h7ddc832_0 conda-forge
gettext 0.22.5 h8fbad5d_2 conda-forge
gettext-tools 0.22.5 h8fbad5d_2 conda-forge
giflib 5.2.2 h93a5062_0 conda-forge
gmp 6.3.0 hebf3989_1 conda-forge
gmpy2 2.1.5 py312hfa9fade_1 conda-forge
graphite2 1.3.13 hebf3989_1003 conda-forge
graphviz 11.0.0 h9bb9bc9_0 conda-forge
gtk2 2.24.33 h7895bb2_4 conda-forge
gts 0.7.6 he42f4ea_4 conda-forge
h5netcdf 1.3.0 pyhd8ed1ab_0 conda-forge
h5py 3.11.0 nompi_py312h903599c_102 conda-forge
harfbuzz 8.5.0 h1836168_0 conda-forge
hdf5 1.14.3 nompi_hec07895_105 conda-forge
huggingface_hub 0.23.3 pyhd8ed1ab_0 conda-forge
icu 73.2 hc8870d7_0 conda-forge
idna 3.7 pyhd8ed1ab_0 conda-forge
jinja2 3.1.4 pyhd8ed1ab_0 conda-forge
kiwisolver 1.4.5 py312h389731b_1 conda-forge
krb5 1.21.2 h92f50d5_0 conda-forge
lcms2 2.16 ha0e7c42_0 conda-forge
ld64_osx-arm64 711 ha4bd21c_0 conda-forge
lerc 4.0.0 h9a09cb3_0 conda-forge
libabseil 20240116.2 cxx17_hebf3989_0 conda-forge
libaec 1.1.3 hebf3989_0 conda-forge
libasprintf 0.22.5 h8fbad5d_2 conda-forge
libasprintf-devel 0.22.5 h8fbad5d_2 conda-forge
libblas 3.9.0 22_osxarm64_openblas conda-forge
libbrotlicommon 1.1.0 hb547adb_1 conda-forge
libbrotlidec 1.1.0 hb547adb_1 conda-forge
libbrotlienc 1.1.0 hb547adb_1 conda-forge
libcblas 3.9.0 22_osxarm64_openblas conda-forge
libclang-cpp16 16.0.6 default_hb63da90_8 conda-forge
libcurl 8.8.0 h7b6f9a7_0 conda-forge
libcxx 17.0.6 h5f092b4_0 conda-forge
libdeflate 1.20 h93a5062_0 conda-forge
libedit 3.1.20191231 hc8eb9b7_2 conda-forge
libev 4.33 h93a5062_2 conda-forge
libexpat 2.6.2 hebf3989_0 conda-forge
libffi 3.4.2 h3422bc3_5 conda-forge
libgd 2.3.3 hfdf3952_9 conda-forge
libgettextpo 0.22.5 h8fbad5d_2 conda-forge
libgettextpo-devel 0.22.5 h8fbad5d_2 conda-forge
libgfortran 5.0.0 13_2_0_hd922786_3 conda-forge
libgfortran5 13.2.0 hf226fd6_3 conda-forge
libglib 2.80.2 h59d46d9_1 conda-forge
libiconv 1.17 h0d3ecfb_2 conda-forge
libintl 0.22.5 h8fbad5d_2 conda-forge
libintl-devel 0.22.5 h8fbad5d_2 conda-forge
libjpeg-turbo 3.0.0 hb547adb_1 conda-forge
liblapack 3.9.0 22_osxarm64_openblas conda-forge
liblapacke 3.9.0 22_osxarm64_openblas conda-forge
libllvm16 16.0.6 haab561b_3 conda-forge
libnghttp2 1.58.0 ha4dd798_1 conda-forge
libopenblas 0.3.27 openmp_h6c19121_0 conda-forge
libpng 1.6.43 h091b4b1_0 conda-forge
libprotobuf 4.25.3 hbfab5d5_0 conda-forge
librsvg 2.58.0 hb3d354b_1 conda-forge
libsqlite 3.46.0 hfb93653_0 conda-forge
libssh2 1.11.0 h7a5bd25_0 conda-forge
libtiff 4.6.0 h07db509_3 conda-forge
libtorch 2.3.0 cpu_generic_h95df8ed_1 conda-forge
libuv 1.48.0 h93a5062_0 conda-forge
libwebp 1.4.0 h54798ee_0 conda-forge
libwebp-base 1.4.0 h93a5062_0 conda-forge
libxcb 1.15 hf346824_0 conda-forge
libxml2 2.12.7 ha661575_1 conda-forge
libzlib 1.3.1 hfb2fe0b_1 conda-forge
llvm-openmp 18.1.7 hde57baf_0 conda-forge
llvm-tools 16.0.6 haab561b_3 conda-forge
logical-unification 0.4.6 pyhd8ed1ab_0 conda-forge
macosx_deployment_target_osx-arm64 11.0 h6553868_1 conda-forge
markdown-it-py 3.0.0 pyhd8ed1ab_0 conda-forge
markupsafe 2.1.5 py312he37b823_0 conda-forge
matplotlib-base 3.8.4 py312h4479663_2 conda-forge
mdurl 0.1.2 pyhd8ed1ab_0 conda-forge
minikanren 1.0.3 pyhd8ed1ab_0 conda-forge
mpc 1.3.1 h91ba8db_0 conda-forge
mpfr 4.2.1 h41d338b_1 conda-forge
mpmath 1.3.0 pyhd8ed1ab_0 conda-forge
multipledispatch 0.6.0 py_0 conda-forge
munkres 1.1.4 pyh9f0ad1d_0 conda-forge
ncurses 6.5 hb89a1cb_0 conda-forge
networkx 3.3 pyhd8ed1ab_1 conda-forge
nomkl 1.0 h5ca1d4c_0 conda-forge
numpy 1.26.4 py312h8442bc7_0 conda-forge
openblas 0.3.27 openmp_h55c453e_0 conda-forge
openjpeg 2.5.2 h9f1df11_0 conda-forge
openssl 3.3.1 hfb2fe0b_0 conda-forge
packaging 24.1 pyhd8ed1ab_0 conda-forge
pandas 2.2.2 py312h8ae5369_1 conda-forge
pango 1.54.0 h5cb9fbc_0 conda-forge
pcre2 10.44 h297a79d_0 conda-forge
pillow 10.3.0 py312h8a801b1_0 conda-forge
pip 24.0 pyhd8ed1ab_0 conda-forge
pixman 0.43.4 hebf3989_0 conda-forge
psutil 5.9.8 py312he37b823_0 conda-forge
pthread-stubs 0.4 h27ca646_1001 conda-forge
pygments 2.18.0 pyhd8ed1ab_0 conda-forge
pymc 5.15.1 hd8ed1ab_1 conda-forge
pymc-base 5.15.1 pyhd8ed1ab_1 conda-forge
pyparsing 3.1.2 pyhd8ed1ab_0 conda-forge
pysocks 1.7.1 pyha2e5f31_6 conda-forge
pytensor 2.22.1 py312h18108a9_0 conda-forge
pytensor-base 2.22.1 py312h2b2a681_0 conda-forge
python 3.12.3 h4a7b5fc_0_cpython conda-forge
python-dateutil 2.9.0 pyhd8ed1ab_0 conda-forge
python-graphviz 0.20.3 pyh717bed2_0 conda-forge
python-tzdata 2024.1 pyhd8ed1ab_0 conda-forge
python_abi 3.12 4_cp312 conda-forge
pytorch 2.3.0 cpu_generic_py312h2aa0b4f_1 conda-forge
pytz 2024.1 pyhd8ed1ab_0 conda-forge
pyyaml 6.0.1 py312h02f2b3b_1 conda-forge
readline 8.2 h92ec313_1 conda-forge
requests 2.32.3 pyhd8ed1ab_0 conda-forge
rich 13.7.1 pyhd8ed1ab_0 conda-forge
safetensors 0.4.3 py312h5280bc4_0 conda-forge
scipy 1.13.1 py312h14ffa8f_0 conda-forge
setuptools 70.0.0 pyhd8ed1ab_0 conda-forge
sigtool 0.1.3 h44b9a77_0 conda-forge
six 1.16.0 pyh6c4a22f_0 conda-forge
sleef 3.5.1 h156473d_2 conda-forge
sympy 1.12 pypyh9d50eac_103 conda-forge
tapi 1100.0.11 he4954df_0 conda-forge
threadpoolctl 3.5.0 pyhc1e730c_0 conda-forge
tk 8.6.13 h5083fa2_1 conda-forge
toolz 0.12.1 pyhd8ed1ab_0 conda-forge
tqdm 4.66.4 pyhd8ed1ab_0 conda-forge
typing-extensions 4.12.2 hd8ed1ab_0 conda-forge
typing_extensions 4.12.2 pyha770c72_0 conda-forge
tzdata 2024a h0c530f3_0 conda-forge
urllib3 2.2.1 pyhd8ed1ab_0 conda-forge
wheel 0.43.0 pyhd8ed1ab_1 conda-forge
xarray 2024.6.0 pyhd8ed1ab_1 conda-forge
xarray-einstats 0.7.0 pyhd8ed1ab_0 conda-forge
xorg-libxau 1.0.11 hb547adb_0 conda-forge
xorg-libxdmcp 1.1.3 h27ca646_0 conda-forge
xz 5.2.6 h57fd34a_0 conda-forge
yaml 0.2.5 h3422bc3_2 conda-forge
zlib 1.3.1 hfb2fe0b_1 conda-forge
zstd 1.5.6 hb46c0d2_0 conda-forge
(pymc_env)

Now

I have

import sys
import numpy as np
import pandas as pd
from sklearn.experimental import enable_iterative_imputer
from sklearn.impute import IterativeImputer, KNNImputer
from scipy.stats import multivariate_normal, invwishart
from scipy.linalg import cholesky
from statsmodels.stats.outliers_influence import variance_inflation_factor
from statsmodels.tsa.stattools import adfuller, kpss
import pymc
import pymc3 as pm
import arviz as az
import matplotlib.pyplot as plt
import time
from pykalman import KalmanFilter # Import KalmanFilter from pykalman
import dill
from sklearn.exceptions import ConvergenceWarning
import warnings

Increase maximum recursion limit

sys.setrecursionlimit(10000)

Set Aesara to use float64 precision by default (no longer needed with recent PyMC3)

pm.set_tt_rng(42)

np.random.seed(42)

class TVPPVARFitter:
def init(self, data, vars, p=1, seed=42):
self.data = data
self.vars = vars
self.p = p
self.n_vars = len(vars) # Initialize n_vars with the number of variables
self.n_obs, _ = data.shape
self.seed = seed
self.irf = None # Placeholder for IRFs
self.trace = None # Placeholder for posterior trace

OTHER CODE

def fit_tvp_pvar(self, num_iterations=1000, burn=500, tune=500, cores=6, delay=1, imputer_max_iter=100):
imputation_methods = [‘iterative’, ‘kalman’, ‘knn’]

    imputed = False
    for method in imputation_methods:
        try:
            if method == 'iterative':
                # Iterative Imputer
                imputer = IterativeImputer(max_iter=imputer_max_iter, random_state=self.seed)
                with warnings.catch_warnings():  # Handle potential ConvergenceWarning
                    warnings.filterwarnings("ignore", category=ConvergenceWarning)
                    data = imputer.fit_transform(self.data[self.vars].values)

            elif method == 'kalman':
                # Kalman Filter Imputation
                data = self.kalman_imputation(self.data[self.vars].values)

            elif method == 'knn':
                # KNN Imputer
                imputer = KNNImputer()
                data = imputer.fit_transform(self.data[self.vars].values)

            if not np.any(np.isnan(data)) and not np.any(np.isinf(data)):
                imputed = True
                print(f"Imputation successful with {method} method.")
                self.n_vars = data.shape[1]  # Update n_vars after successful imputation
                break
        except Exception as e:
            print(f"{method} imputation failed: {e}")
            print("Trying the next method...")

    if not imputed:
        raise ValueError("All imputation methods failed.")

    valid_mask = ~np.isnan(data) & ~np.isinf(data)  # Mask for valid values
    self.n_obs = data.shape[0]  # Update n_obs based on imputed data

    with pm.Model() as tvp_pvar_model:
        # Priors
        sd_dist = pm.HalfNormal.dist(sigma=1.0)
        log_sd_vals = pm.Normal('log_sd_vals', mu=0, sigma=1, shape=(self.n_vars,))
        log_sd_vals_flattened = pm.Deterministic('log_sd_vals_flattened', pm.reshape(log_sd_vals, (-1, 1)))
        exp_log_sd_vals_flattened = pm.Deterministic('exp_log_sd_vals_flattened', pm.math.exp(log_sd_vals_flattened))
        sd_vals = pm.Deterministic('sd_vals', pm.math.diag(exp_log_sd_vals_flattened))
        alphas = pm.Normal('alphas', mu=0, sigma=1, shape=(self.n_obs, self.n_vars))
        phis = self.horseshoe_prior('phis', shape=(self.n_obs - self.p, self.p, self.n_vars, self.n_vars))

        # Cholesky-factor covariance matrix
        cov_matrix_chol = pm.LKJCholeskyCov('cov_matrix_chol', n=self.n_vars, eta=2, sd_dist=sd_dist)
        diag_sd_vals = pm.Deterministic('diag_sd_vals', pm.math.diag(sd_vals))
        cov_matrix = pm.Deterministic('cov_matrix', diag_sd_vals.dot(cov_matrix_chol.dot(cov_matrix_chol.T)).dot(diag_sd_vals))
        chol_cov = pm.Deterministic('chol_cov', pm.math.slinalg.cholesky(cov_matrix))

        # Likelihood
        yt = pm.Normal('yt', mu=0, sd=1, shape=(self.n_obs, self.n_vars))
        for t in range(self.p, self.n_obs):
            mu_t = pm.math.dot(phis[t - self.p], alphas[t - self.p])
            yt[t] = pm.Normal.dist(mu=mu_t, sd=chol_cov).random()

        # Sampling
       
        trace = pm.sample(num_iterations, tune=tune, cores=cores, chains=2, return_inferencedata=False, discard_tuned_samples=False, delays=delay)

        # Calculate Impulse Response Functions (IRFs)
        self.calculate_irf(trace)

        # Store posterior trace for further analysis
        self.trace = trace

OTNER CODE

I get

Traceback (most recent call last):

Cell In[2], line 1
model.fit_tvp_pvar(num_iterations=50000, burn=20000, tune=10000, cores=6, delay=1,)

Cell In[1], line 106 in fit_tvp_pvar
log_sd_vals_flattened = pm.Deterministic(‘log_sd_vals_flattened’, pm.reshape(log_sd_vals, (-1, 1)))

AttributeError: module ‘pymc3’ has no attribute ‘reshape’

I guess it should not be using any theano nor aesera. I would much any help you can provide to help me solve this issue.

Thank you so so much in advance for yor time and any help

Best
Dimitri

I’m not sure I understand how your code is running in that environment. The line import pymc3 as pm should fail because you don’t have PyMC3 installed. Are you sure you are using the environment you describe here?

1 Like