如何稳定展平NumPy数组?为何matrix的flatten方法失效?
flatten() fail on a numpy matrix result, and how to convert it to a 1D array? Let's break down what's happening here and how to fix it.
First, let's recap your test code to make sure we're aligned:
from numpy import array, eye, matrix x = array([1, 0]) # Using numpy's matrix class B = matrix([[1, 0], [0, 1]]) print(B.dot(x)) # Output: [[1 0]] (a 1×2 matrix object) print(B.dot(x).flatten()) # Output still: [[1 0]] — no shift to 1D
Why flatten() isn't working
The root issue is that numpy's matrix class is strictly a 2-dimensional structure. Every method on a matrix (including flatten()) returns another matrix instance, not a 1D ndarray. When you call flatten() on a 1×2 matrix, it just returns the same 1×2 matrix (since it's already "flat" within the 2D context) — it never drops down to a 1D array.
How to convert it to a 1D array
Here are a few straightforward solutions:
1. Convert the matrix to an ndarray first
You can either use np.array() explicitly, or use the .A shortcut attribute that all matrix objects have (it returns the equivalent ndarray):
result_matrix = B.dot(x) # Option 1a: Explicit conversion with np.array() result_1d = np.array(result_matrix).flatten() print(result_1d) # Output: [1 0] # Option 1b: Use the .A attribute result_1d = result_matrix.A.flatten() print(result_1d) # Output: [1 0]
2. Use numpy's top-level ravel() function
Instead of calling the matrix's own flatten() method, use np.ravel() directly. This function works on both matrices and arrays, and will return a 1D ndarray:
print(np.ravel(B.dot(x))) # Output: [1 0]
3. Stop using matrix entirely (recommended)
Numpy's matrix class is legacy — the official docs now recommend using regular ndarray for all array/matrix operations. ndarray doesn't have the strict 2D constraint, so your original workflow will work as expected:
from numpy import array, eye x = array([1, 0]) B = array([[1, 0], [0, 1]]) # Use array instead of matrix print(B.dot(x)) # Output: [1 0] (already a 1D array) print(B.dot(x).flatten()) # Still outputs [1 0] if you need explicit flattening
内容的提问来源于stack exchange,提问作者Sebastian Oberhoff

