from numpy import array, eye, matrix
x = array([1, 0])
A = eye(2)
print(A.dot(x))
prints [1. 0.]
.
On the other hand,
B = matrix([[1, 0], [0, 1]])
print(B.dot(x))
prints [[1 0]]
which is a 1-by-2 array. Furthermore,
print(B.dot(x).flatten())
also prints [[1 0]]
.
This is rather annoying. Why does flatten fail here and how else can I get this into the 1-d shape?
Stop using matrix
. numpy.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
before flattening:
flat = whatever_matrix.A.flatten()
or just use A1
to get a flat ndarray directly:
flat = whatever_matrix.A1
来源:https://stackoverflow.com/questions/50453626/how-do-i-consistently-flatten-a-numpy-array