【问题标题】:Solving Ax=b with numpy linalg python raise LinAlgError('Incompatible dimensions')用 numpy linalg python raise LinAlgError('Incompatible dimensions') 解决 Ax=b
【发布时间】:2018-11-27 10:20:52
【问题描述】:

我正在尝试为 x 解决 Ax = b。

A 是一个稀疏矩阵; x 是未知的,a b 是一个 np.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)

产生以下输出。

矩阵 A 形 -- (48002, 7651)
矢量 c 形 -- 48001
更新向量 C 形状 -- 48002

Traceback(最近一次调用最后一次):文件

“/Users/已删除/PycharmProjects/hw2/main.py”,第 139 行,在 main() 文件“/Users/已删除/PycharmProjects/hw2/main.py”,第 65 行,在 main b1 = st.fit_parameters(A1, c) 文件“/Users/removed/PycharmProjects/hw2/hw3_part1.py”,第 191 行,在 拟合参数 x = np.linalg.lstsq(new_matrix_T,vec_c) 文件“/Users/已删除/.conda/envs/hw2/lib/python3.6/site-packages/numpy/linalg/linalg.py ",第 1984 行,在 lstsq raise LinAlgError('Incompatible dimensions') numpy.linalg.linalg.LinAlgError: Incompatible dimensions

【问题讨论】:

  • 你能贴出vec_c.shape(不是len)和vector_c.shape是什么吗?

标签: python numpy linear-algebra least-squares


【解决方案1】:

您将矩阵matrix_a(形状M, N = 48002, 7651)转换为形状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

【讨论】:

    猜你喜欢
    • 2014-03-03
    • 1970-01-01
    • 2017-12-19
    • 2014-08-15
    • 1970-01-01
    • 2018-08-06
    • 2017-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多