votes up 1

Array `mean` must be two dimensional.

Package:
scipy
github stars 8546
Exception Class:
ValueError

Raise code

""" 
        """

        # Process mean
        if mean is not None:
            mean = np.asarray(mean, dtype=float)
            meanshape = mean.shape
            if len(meanshape) != 2:
                raise ValueError("Array `mean` must be two dimensional.")
            if np.any(meanshape == 0):
                raise ValueError("Array `mean` has invalid shape.")

        # Process among-row covariance
        rowcov = np.asarray(rowcov, dtype=float)
        if rowcov.ndim == 0:
            if mean is not None:

Ways to fix

votes up 2 votes down

This error is raised inside the function scipy.stats.matrix_normal.pdf. The parameter mean is expected to be a 2D array. However a single dimension is given this error is raised.

How to reproduce the error:

$ pipenv install scipy numpy

$ pipenv shell

from scipy.stats import matrix_normal
import numpy as np
M = np.arange(6)
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)

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-4-9d3ecaadffdc> 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 
/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)  950 meanshape = mean.shape  951 if len(meanshape) != 2: --> 952 raise ValueError("Array `mean` must be two dimensional.")  953 if np.any(meanshape == 0):  954 raise ValueError("Array `mean` has invalid shape.") 
ValueError: Array `mean` must be two dimensional.

Working(Fixed) version of the code:

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