votes up 1

`colcov` must be a scalar or a 2D array.

Package:
scipy
github stars 8546
Exception Class:
ValueError

Raise code

                colcov = colcov * np.identity(meanshape[1])
            else:
                colcov = colcov * np.identity(1)
        elif colcov.ndim == 1:
            colcov = np.diag(colcov)
        colshape = colcov.shape
        if len(colshape) != 2:
            raise ValueError("`colcov` must be a scalar or a 2D array.")
        if colshape[0] != colshape[1]:
            raise ValueError("Array `colcov` must be square.")
        if colshape[0] == 0:
            raise ValueError("Array `colcov` has invalid shape.")
        numcols = colshape[0]

        # Ensure mean and covariances compatible

Ways to fix

votes up 2 votes down

The parameter colcov should be scalar or 2D shape.

Reproducing the error:

$ pipenv install scipy numpy

$ pipenv shell

from scipy.stats import matrix_normal
import numpy as np
M = np.arange(6).reshape(3,2)
U = np.diag([1,2,3])
V = 0.3*np.identity(2).reshape(2,2,1)
X = M + 0.1
res = matrix_normal.pdf(X, mean=M, rowcov=U, colcov=V)
print(res)

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-5-f4b739474959> in <module>()  5 V = 0.3*np.identity(2).reshape(2,2,1)  6 X = M + 0.1 ----> 7 res = matrix_normal.pdf(X, mean=M, rowcov=U, colcov=V)  8 print(res) 

Fixed version of the code:

/usr/local/lib/python3.7/dist-packages/scipy/stats/_multivariate.py in pdf(self, X, mean, rowcov, colcov)  1105   1106 """ -> 1107 return np.exp(self.logpdf(X, mean, rowcov, colcov))  1108   1109 def rvs(self, mean=None, rowcov=1, colcov=1, size=1, random_state=None): 
/usr/local/lib/python3.7/dist-packages/scipy/stats/_multivariate.py in logpdf(self, X, mean, rowcov, colcov)  1077 """  1078 dims, mean, rowcov, colcov = self._process_parameters(mean, rowcov, -> 1079 colcov)  1080 X = self._process_quantiles(X, dims)  1081 rowpsd = _PSD(rowcov, allow_singular=False) 
/usr/local/lib/python3.7/dist-packages/scipy/stats/_multivariate.py in _process_parameters(self, mean, rowcov, colcov)  983 colshape = colcov.shape  984 if len(colshape) != 2: --> 985 raise ValueError("`colcov` must be a scalar or a 2D array.")  986 if colshape[0] != colshape[1]:  987 raise ValueError("Array `colcov` must be square.") 
ValueError: `colcov` must be a scalar or a 2D array.

Fixed version of the book:

from scipy.stats import matrix_normal
import numpy as np
M = np.arange(6).reshape(3,2)
U = np.diag([1,2,3])
V = 0.3*np.identity(2)
X = M + 0.1
res = matrix_normal.pdf(X, mean=M, rowcov=U, colcov=V)
print(res)

0.023410202050005054

Oct 14, 2021 kellemnegasi answer
kellemnegasi 13.5k

Add a possible fix

Please authorize to post fix