Skip to content

LinAlg Error when trying to select order VAR #3240

Closed

Description

@cstich

I was trying to determine the optimal lag for a VAR model of mine but I encountered into a linear algebra error.

When I try to run this

var = VAR(data)
var.select_order()

I get this error trace

LinAlgError                               Traceback (most recent call last)
<ipython-input-36-410366a3da75> in <module>()
      2 data = np.column_stack((mobility_diff, np.asarray(inter_floats)))
      3 var = VAR(data)
----> 4 var.select_order()
      5 results = var.fit(7)
      6 results.plot()

/home/christoph/anaconda3/envs/time-series/lib/python3.5/site-packages/statsmodels/tsa/vector_ar/var_model.py in select_order(self, maxlags, verbose)
    503             result = self._estimate_var(p, offset=maxlags-p)
    504 
--> 505             for k, v in iteritems(result.info_criteria):
    506                 ics[k].append(v)
    507 

/home/christoph/anaconda3/envs/time-series/lib/python3.5/site-packages/statsmodels/base/wrapper.py in __getattribute__(self, attr)
     33             pass
     34 
---> 35         obj = getattr(results, attr)
     36         data = results.model.data
     37         how = self._wrap_attrs.get(attr)

/home/christoph/anaconda3/envs/time-series/lib/python3.5/site-packages/statsmodels/tools/decorators.py in __get__(self, obj, type)
     92         if _cachedval is None:
     93             # Call the "fget" function
---> 94             _cachedval = self.fget(obj)
     95             # Set the attribute in obj
     96 #            print("Setting %s in cache to %s" % (name, _cachedval))

/home/christoph/anaconda3/envs/time-series/lib/python3.5/site-packages/statsmodels/tsa/vector_ar/var_model.py in info_criteria(self)
   1466         free_params = lag_order * neqs ** 2 + neqs * self.k_trend
   1467 
-> 1468         ld = logdet_symm(self.sigma_u_mle)
   1469 
   1470         # See Lutkepohl pp. 146-150

/home/christoph/anaconda3/envs/time-series/lib/python3.5/site-packages/statsmodels/tools/linalg.py in logdet_symm(m, check_symm)
    211         if not np.all(m == m.T):  # would be nice to short-circuit check
    212             raise ValueError("m is not symmetric.")
--> 213     c, _ = linalg.cho_factor(m, lower=True)
    214     return 2*np.sum(np.log(c.diagonal()))
    215 

/home/christoph/anaconda3/envs/time-series/lib/python3.5/site-packages/scipy/linalg/decomp_cholesky.py in cho_factor(a, lower, overwrite_a, check_finite)
    130     """
    131     c, lower = _cholesky(a, lower=lower, overwrite_a=overwrite_a, clean=False,
--> 132                             check_finite=check_finite)
    133     return c, lower
    134 

/home/christoph/anaconda3/envs/time-series/lib/python3.5/site-packages/scipy/linalg/decomp_cholesky.py in _cholesky(a, lower, overwrite_a, clean, check_finite)
     28     c, info = potrf(a1, lower=lower, overwrite_a=overwrite_a, clean=clean)
     29     if info > 0:
---> 30         raise LinAlgError("%d-th leading minor not positive definite" % info)
     31     if info < 0:
     32         raise ValueError('illegal value in %d-th argument of internal potrf'

LinAlgError: 2-th leading minor not positive definite

I am on statsmodels 0.6.1 and and Python 3.5.2. I also attached the time series as a csv file as well as numpy pickle to this issue:
data.tar.gz

Activity

  1. josef-pkt commented on Oct 18, 2016

    @josef-pkt
    Member

    Hi,
    Did you do some basic checks on the data?
    Check the eigenvalues of sigma sigma_u or sigma_u_mle in the results instance. (I don't remember which is which and what exactly the name is).

    My guess based on the traceback would be that there is an eigenvalue around zero, which I guess would require some collinear data.

  2. josef-pkt commented on Oct 18, 2016

    @josef-pkt
    Member

    Can you copy your code here instead of the pickle? I'm not sure how to use it, and it would be version dependent.

    based on the data in the csv: try rescaling the variables so they are in the scale of 1 instead of 1e6 and similar.

    cross-link to sanity checks #1908
    but I'm not sure yet what would help here given that I have never seen this problem before

  3. josef-pkt commented on Oct 18, 2016

    @josef-pkt
    Member

    another possible related issue #1131 (scaling is my prime suspect, variance should be huge)

  4. cstich commented on Oct 18, 2016

    @cstich
    Author

    Just to be clear you mean the results of VAR.fit()? sigma_u as well as sigma_u_mle are both all clearly positive.

    So I z-transformed both variables but I am still able to reproduce this.
    All the code I need to reproduce this is:

    import pandas as pd
    from statsmodels.tsa.api import VAR
    df = pd.read_csv('data.txt', header=None)
    var = VAR(df.values)
    var.select_order()
    

    Whereas data.txt is this file here with the rescaled values:
    data.txt

  5. josef-pkt commented on Oct 18, 2016

    @josef-pkt
    Member

    Yes, I meant to get the results for soma fit. You could try to fit with different lags and see if summary() produces all the results.

    Also try to limit the number of lags for select_order, for example var.select_order(5)

    I just ran your example (Windows 64 with MKL linalg libraries, and approximately statsmodels master) and didn't have any problems, except trying again I get it also.

    Initially, I got the IC up to lag 9, which might have been numerical noise.
    Using some rescaled data, select_order works up to lag 8, but raises that exception at lag 9.

    I think we are estimating too many parameters, sigma_u_mle is singular.

    var = VAR(df.values / df.values.std(0))
    >>> res = var.fit(9)
    >>> res.params.shape
    (19, 2)
    >>> res.sigma_u_mle
    array([[ 0.00044912, -0.0013509 ],
           [-0.0013509 ,  0.00406341]])
    >>> np.linalg.eigvals(res.sigma_u_mle)
    array([ 0.        ,  0.00451253])
    

    Can you try different maxlags in select_order to see when it breaks for you?

    In either case, this is a bug now. We need to limit maxlags for shorter sample, or large systems., and try protect the lag search for numerical failures. (ARMA and similar add nans in case of convergence failures. Here the solution is explicit and just linear algebra.)

  6. added this to the 0.9 milestone on Oct 18, 2016
  7. josef-pkt commented on Oct 18, 2016

    @josef-pkt
    Member

    select_order maxlags does not take into account how many parameters we need, i.e. at least k_endog * maxlags per equations. I think we should limit it at least to have nobs >= 2 * number_parameters

    if maxlags is None:
                maxlags = int(round(12*(len(self.endog)/100.)**(1/4.)))
    

    something like
    maxlags = min((maxlags, nobs // (2 * k_endog)))
    which does not take constant and trend into account, nor exog in future, better is k_params per equation (if we have it).

  8. cstich commented on Oct 18, 2016

    @cstich
    Author

    I can confirm that it is the number of lags that break it. 9 lags breaks both fit as well as select_order for me. All lower lags work just fine.

  9. anbhimi commented on Feb 7, 2020

    @anbhimi

    Hi,

    I have the same error - LinAlgError in the same case. I tried changing the maxlags parameter from 0 to 30 and it did not work for any of them. My training data size is (10903, 21).

    results = model.fit(maxlags = 2)
    results.params.shape
    
    (43, 21)
    
  10. self-assigned this
    on Jul 8, 2020
  11. bashtage commented on Jul 9, 2020

    @bashtage
    Member

    Closed by cdad7de

  12. advaitk13 commented on Jul 18, 2020

    @advaitk13

    Is there a way to fix this?

  13. bashtage commented on Jul 18, 2020

    @bashtage
    Member

    Limit the maximum lag length

  14. advaitk13 commented on Jul 18, 2020

    @advaitk13

    Limit the maximum lag length

    It fails for max_lag=1, though. Tried to fix the data and now the johansen test is starting to fail, saying the Matrix is not positive definite.

  15. bashtage commented on Jul 18, 2020

    @bashtage
    Member

    Can you post the data?

  16. modified the milestones: 0.9, 0.12 on Jul 27, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions