Python矩阵对齐问题:移除transpose后维度不匹配报错求解
Let's break down what's happening here and fix that shape mismatch error.
Your Code Context
Here's the relevant code snippet you shared:
import numpy as np from numpy.linalg import norm # ... (assumed setup for arr and new_arr) for i in range(len(new_arr)): new_arr[i] = new_arr[i].transpose() n = len(arr) u = [0 * n for i in range(n)] e = [0 * n for i in range(n)] print(e) print("Q") Q = [] for i in range(len(arr)): u[i] = new_arr[i] - ((np.dot(new_arr[i],e[i-1])*e[i-1])) e[i] = u[i] / norm(u[i])#Cari gapake norm e[i] = e[i].transpose() # Removing this line causes the error print(u[i]) print(e[i])
When you remove e[i] = e[i].transpose(), you get the error:
shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0)
Why This Happens
The core issue is how NumPy's np.dot() works with 2D arrays:
- For matrix multiplication (which
dotperforms on 2D arrays), the number of columns in the first array must equal the number of rows in the second array. - When you skip the transpose,
e[i]ends up as a row vector with shape(1,3). When you computenp.dot(new_arr[i], e[i-1]), ifnew_arr[i]is also a(1,3)row vector, you're trying to multiply(1,3) · (1,3)—which fails because 3 columns (from the first array) don't match 1 row (from the second).
In your original code, the transpose converts e[i] to a column vector ((3,1)), which makes new_arr[i] (a (1,3) row vector) and e[i-1] compatible for matrix multiplication: (1,3) · (3,1) produces a scalar, which works with your subtraction logic.
Fixes You Can Use
You have a few options depending on whether you want to keep using transpose or not:
1. Keep the Transpose (Simplest Fix)
The original transpose is doing exactly what you need—converting the row vector to a column vector to make the dot product valid. If this works for your overall logic, there's no need to remove it.
2. Use Element-Wise Inner Product Instead of Matrix Multiplication
If you want to avoid transpose, you can use np.inner() (which computes the inner product regardless of row/column orientation for 2D arrays) or flatten the arrays to 1D first for np.dot():
Option A: Use np.inner()
# Replace the u[i] calculation line with this: u[i] = new_arr[i] - (np.inner(new_arr[i], e[i-1]) * e[i-1])
Option B: Flatten arrays to 1D
# Flatten both arrays to 1D before the dot product dot_product = np.dot(new_arr[i].flatten(), e[i-1].flatten()) u[i] = new_arr[i] - (dot_product * e[i-1])
3. Initialize e as Column Vectors From the Start
Instead of transposing later, you can reshape e[i] to a column vector when you compute it:
# Replace the e[i] lines with this: e[i] = (u[i] / norm(u[i])).reshape(-1, 1) # Reshapes to (3,1) column vector
All these fixes ensure the dot product operation uses compatible shapes, so you won't get the alignment error anymore.
内容的提问来源于stack exchange,提问作者Hensel

