votes up 1

Array 'cov' must be at most two-dimensional, but cov.ndim = %d

Package:
scipy
github stars 8546
Exception Class:
ValueError

Raise code

           " but cov.shape = %s." % str(shape.shape))
            else:
                msg = ("Dimension mismatch: array 'cov' is of shape %s,"
                       " but 'loc' is a vector of length %d.")
                msg = msg % (str(shape.shape), len(loc))
            raise ValueError(msg)
        elif shape.ndim > 2:
            raise ValueError("Array 'cov' must be at most two-dimensional,"
                             " but cov.ndim = %d" % shape.ndim)

        # Process degrees of freedom.
        if df is None:
            df = 1
        elif df <= 0:
            raise ValueError("'df' must be greater than zero.")
        elif

Ways to fix

votes up 1 votes down

This happens when the shape argument is not 2D or less. If a 3D array is given this exception can be reproduced as follows.

from scipy.stats import multivariate_t
x = [0.45]
loc = [01]
shape = [[[10.1], [0.11]]]
df = 7
multivariate_t.rvs(loc, shape, df)

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-2-88076911866f> in <module>()  4 shape = [[[1, 0.1], [0.1, 1]]]  5 df = 7 ----> 6 multivariate_t.rvs(loc, shape, df) 
/usr/local/lib/python3.7/dist-packages/scipy/stats/_multivariate.py in rvs(self, loc, shape, df, size, random_state)  4070 # http://rjournal.github.io/archive/2013-2/hofert.pdf  4071 # -> 4072 dim, loc, shape, df = self._process_parameters(loc, shape, df)  4073 if random_state is not None:  4074 rng = check_random_state(random_state) 
/usr/local/lib/python3.7/dist-packages/scipy/stats/_multivariate.py in _process_parameters(self, loc, shape, df)  4148 elif shape.ndim > 2:  4149 raise ValueError("Array 'cov' must be at most two-dimensional," -> 4150 " but cov.ndim = %d" % shape.ndim)  4151   4152 # Process degrees of freedom. 
ValueError: Array 'cov' must be at most two-dimensional, but cov.ndim = 3


Fixed version of the code:

Make sure the shape array is not 3D or greater. In our case we are using 2D array.

from scipy.stats import multivariate_t
x = [0.45]
loc = [01]
shape = [[10.1], [0.11]]
df = 7
multivariate_t.rvs(loc, shape, df)

array([0.7739751 , 0.27750071])
Nov 25, 2021 kellemnegasi answer
kellemnegasi 18.3k

Add a possible fix

Please authorize to post fix