值错误:形状 (7,200) 和 (1,1) 未对齐:200(暗淡 1)!= 1(暗淡 0)



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

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

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

最新更新