0

Why the line3 raise valueError‘ matrix must be 2-dimensional’

import numpy as np
np.mat([[[1],[2]],[[10],[1,3]]])
np.mat([[[1],[2]],[[10],[1]]])

WindSekirun
  • 1,038
  • 11
  • 22
神木马
  • 1
  • 1
  • 1
  • 2
    Please don't use the `matrix` API. See: [Deprecation status of the NumPy matrix class](https://stackoverflow.com/questions/53254738/deprecation-status-of-the-numpy-matrix-class) – cs95 Apr 09 '19 at 07:50

1 Answers1

1

The reason why this code raises an error is because NumPy tries to determine the dimensionality of your input using nesting levels (nesting levels -> dimensions). If, at some level, some elements do not have the same length (i.e. they are incompatible), it will create the array using the deepest nesting it can, using the objects as the elements of the array.

For this reason:

np.mat([[[1],[2]],[[10],[1,3]]])

Will give you a matrix of objects (lists), while:

np.mat([[[1],[2]],[[10],[1]]])

would result in a 3D array of numbers which np.mat() does not want to squeeze into a matrix.

Also, please avoid using np.mat() in your code as it is deprecated. Use np.array() instead.

Incidentally, np.array() would work in both cases and it would give you a (2, 2, 1)-shaped array of int, which you could np.squeeze() into a matrix if you like. However, it would be better to start from nesting level of 2 if all you want is a matrix:

np.array([[1, 2], [10, 1]])
norok2
  • 25,683
  • 4
  • 73
  • 99