ValueError:形状(7,200)和(1,1)未对齐:200(dim 1)!= 1(dim 0)

时间:2019-09-28 15:18:32

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

我有两个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)

1 个答案:

答案 0 :(得分:0)

通过在每个步骤打印形状更容易进行故障排除:

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

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

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