用 numpy linalg python 解决 Ax=b raise LinAlgError('Incompatible dimensions')
Solving Ax=b with numpy linalg python raise LinAlgError('Incompatible dimensions')
我正在尝试为 x 求解 Ax = b。
A是稀疏矩阵; x未知,a b为anp.array。
print(type(matrix_a))
print(type(vector_c))
print("Matrix A Shape -- %s " %str(matrix_a.shape))
print("vector c shape -- %s " %len(vector_c))
#xx = np.array([1],dtype=np.float32)
vec_c = np.insert(vector_c,0,1)
print("Update Vector c shape -- %s "% len(vec_c))
new_matrix = matrix_a.todense()
new_matrix_T = new_matrix.transpose()
x = np.linalg.lstsq(new_matrix_T,vec_c)
产生以下输出。
Matrix A Shape -- (48002, 7651)
vector c shape -- 48001
Update Vector C shape -- 48002
回溯(最近调用最后):文件
"/Users/removed/PycharmProjects/hw2/main.py", line 139, in
main() File "/Users/removed/PycharmProjects/hw2/main.py", line 65, in main
b1 = st.fit_parameters(A1, c) File "/Users/removed/PycharmProjects/hw2/hw3_part1.py", line 191, in
fit_parameters
x = np.linalg.lstsq(new_matrix_T,vec_c) File "/Users/removed/.conda/envs/hw2/lib/python3.6/site-packages/numpy/linalg/linalg.py", line 1984, in lstsq
raise LinAlgError('Incompatible dimensions') numpy.linalg.linalg.LinAlgError: Incompatible dimensions
您正在将形状为 M, N = 48002, 7651
的矩阵 matrix_a
转置为形状 N, M = 7651, 48002
。但问题是您的矢量形状为 M = 48002,
,而 np.linalg.lstsq
的尺寸为 (a.shape=(M, N), b.shape=(M,)
。由于您的转置,您正在传递尺寸 (a.shape=(N, M), b.shape=(M,))
.
解决方案?不要转置 matrix_a
.
我正在尝试为 x 求解 Ax = b。
A是稀疏矩阵; x未知,a b为anp.array。
print(type(matrix_a))
print(type(vector_c))
print("Matrix A Shape -- %s " %str(matrix_a.shape))
print("vector c shape -- %s " %len(vector_c))
#xx = np.array([1],dtype=np.float32)
vec_c = np.insert(vector_c,0,1)
print("Update Vector c shape -- %s "% len(vec_c))
new_matrix = matrix_a.todense()
new_matrix_T = new_matrix.transpose()
x = np.linalg.lstsq(new_matrix_T,vec_c)
产生以下输出。
Matrix A Shape -- (48002, 7651)
vector c shape -- 48001
Update Vector C shape -- 48002
回溯(最近调用最后):文件
"/Users/removed/PycharmProjects/hw2/main.py", line 139, in main() File "/Users/removed/PycharmProjects/hw2/main.py", line 65, in main b1 = st.fit_parameters(A1, c) File "/Users/removed/PycharmProjects/hw2/hw3_part1.py", line 191, in fit_parameters x = np.linalg.lstsq(new_matrix_T,vec_c) File "/Users/removed/.conda/envs/hw2/lib/python3.6/site-packages/numpy/linalg/linalg.py", line 1984, in lstsq raise LinAlgError('Incompatible dimensions') numpy.linalg.linalg.LinAlgError: Incompatible dimensions
您正在将形状为 M, N = 48002, 7651
的矩阵 matrix_a
转置为形状 N, M = 7651, 48002
。但问题是您的矢量形状为 M = 48002,
,而 np.linalg.lstsq
的尺寸为 (a.shape=(M, N), b.shape=(M,)
。由于您的转置,您正在传递尺寸 (a.shape=(N, M), b.shape=(M,))
.
解决方案?不要转置 matrix_a
.