我如何始终如一地展平 numpy 数组?

How do I consistently flatten a numpy array?

from numpy import array, eye, matrix

x = array([1, 0])
A = eye(2)
print(A.dot(x))

打印 [1. 0.]

另一方面,

B = matrix([[1, 0], [0, 1]])
print(B.dot(x))

打印 [[1 0]] 这是一个 1×2 数组。此外,

print(B.dot(x).flatten())

还打印 [[1 0]].

这很烦人。为什么展平在这里失败,我还能如何将它变成一维形状?

停止使用 matrixnumpy.matrix.flatten returns a 1-row matrix, because that's as flat as matrix instances get. If for some reason you are dead set on using matrix, convert to ndarray with matrix.A 展平前:

flat = whatever_matrix.A.flatten()

或者直接使用A1得到一个扁平的ndarray:

flat = whatever_matrix.A1