【问题标题】:ValueError: shapes (7,200) and (1,1) not aligned: 200 (dim 1) != 1 (dim 0)ValueError:形状(7,200)和(1,1)未对齐:200(dim 1)!= 1(dim 0)
【发布时间】:2019-09-29 00:05:58
【问题描述】:

我有两个 ndarray x,y x 的形状是 (7,200),y 的形状是 (200,1) 但是当我使用 matmul 我得到错误说 y 的形状是 (1,1)

我尝试使用矩阵而不是 ndarray,但得到相同的结果

def solve(X,Y):
    x = np.asmatrix(X)
    x = np.transpose(x)
    x = np.insert(x,0,1,axis=1)
    xt = x.T
    xtx = np.matmul(xt,x)
    y = np.asmatrix(Y)
    y = np.transpose(y)
    print('y',y.shape)
    pinv = np.linalg.pinv(xtx)
    print('pinv',pinv.shape)
    print('xt',xt.shape)
    z = np.matmul(pinv,xt)
    print('z',z.shape)
    B = np.matmul(z, y)
    print('B',B.shape)
    return B

('y', (200, 1))
('pinv', (8, 8))
('xt', (8, 200))
('z', (8, 200))
('B', (8, 1))


Traceback (most recent call last):

 File "project1.py", line 79, in <module>
    Z = X*B+resi
  File "/home/yiming/.local/lib/python2.7/site-packages/numpy/matrixlib/defmatrix.py", line 226, in __rmul__

return N.dot(other, self)

ValueError: shapes (7,200) and (1,1) not aligned: 200 (dim 1) != 1 (dim 0)

【问题讨论】:

  • 您能否添加将其转换为minimal reproducible example 的其余代码?
  • @Mike 'Pomax' Kamermans 我已经编辑了我的帖子并使用了 y 的矩阵版本,y 的形状变成了 (200,1),但是当我使用 matmul 时,我仍然得到同样的错误
  • 我很确定错误是因为np.matmul(pinv,xt) - xt 的形状是什么?
  • 您可能仍希望添加更多代码,以便人们可以看到出错的地方。如果 (7,200) 和 (200,1) 出错,那么 (1,2) 和 (2,1) 也应该出错,这对于硬编码作为输入来说是微不足道的,并且更容易print() at每一行,这样您就可以验证形状不会'/确实发生适当的变化。
  • @OverLordGoldDragon 我发现了问题,我用错误的方式调用了这个函数。我正在使用返回多个属性的 numpy.lstsq 。当我调用求解函数时,格式类似于 B = solve(x,y)[0] 导致此错误。感谢您的帮助

标签: python-3.x numpy numpy-ndarray


【解决方案1】:

通过在每一步打印形状更容易排除故障:

def solve(X,Y):
    x = np.asmatrix(X);          print(1, x.shape)
    x = np.transpose(x);         print(2, x.shape)
    x = np.insert(x,0,1,axis=1); print(3, x.shape)
    xt = x.T;                    print(4, xt.shape)
    xtx = np.matmul(xt,x);       print(5, xtx.shape)
    y = np.asmatrix(Y);          print(6, y.shape)
    y = np.transpose(y);         print(7, y.shape)
    pinv = np.linalg.pinv(xtx);  print(8, pinv.shape)
    pre_B = np.matmul(pinv,xt);  print(9, pre_B.shape, y.shape)
    B = np.matmul(pre_B, y)
    return B

## OUTPUT:
# 1 (7, 200)
# 2 (200, 7)
# 3 (200, 8)
# 4 (8, 200)
# 5 (8, 8)
# 6 (200, 1)
# 7 (1, 200)
# 8 (8, 8)
# 9 (8, 200) (1, 200)  <-- PROBLEM

解决方案:在最后一个matmul 之前转置y - 然后内部尺寸一致:(8, 200) x (200, 1) - 最终输出形状将为(8, 1)

B = np.matmul(np.matmul(pinv,xt), y.T)
return B

【讨论】:

  • 问题出在我的输出中,#7 是 (200,1),#9 是 (8,200) (200,1),但是在 np.matmul, (7,200) 和(1,1) 未对齐
猜你喜欢
  • 1970-01-01
  • 2019-03-21
  • 2019-05-28
  • 2021-04-25
  • 2021-05-09
  • 1970-01-01
  • 2020-07-26
  • 2019-04-25
  • 2019-04-01
相关资源
最近更新 更多