votes up 1

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

Package:
scipy
github stars 8546
Exception Class:
ValueError

Raise code

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

        # Process among-column covariance

Ways to fix

votes up 2 votes down

rowcov should be either scalar or 2D array. Any other value causes an error.

How to reproduce the error:

$ pipenv install scipy numpy

from scipy.stats import matrix_normal
import numpy as np
M = np.arange(6).reshape(3,2)
U = np.diag([1,2,3]).reshape(3,3,1)
V = 0.3*np.identity(2)
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-12-3de3b30720ce> in <module>()  5 V = 0.3*np.identity(2)  6 X = M + 0.1 ----> 7 res = matrix_normal.pdf(X, mean=M, rowcov=U, colcov=V)  8 print(res) 
/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)  965 rowshape = rowcov.shape  966 if len(rowshape) != 2: --> 967 raise ValueError("`rowcov` must be a scalar or a 2D array.")  968 if rowshape[0] != rowshape[1]:  969 raise ValueError("Array `rowcov` must be square.") 
ValueError: `rowcov` must be a scalar or a 2D array.

Fixed:

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