pythonnumpylsa

ValueError: shapes (4,4) and (3,) not aligned: 4 (dim 1) != 3 (dim 0)


import numpy as np
A = np.matrix([[1, 2, 3],
               [4, 5, 6],
               [7, 8, 9],
               [10, 11, 12]])
u, s, vt = np.linalg.svd(A)
print (np.dot(u, np.dot(np.diag(s), vt)))

I use numpy for creating the matrix and It shows script error below.

ValueError: shapes (4,4) and (3,) not aligned: 4 (dim 1) != 3 (dim 0)


Solution

  • If you add print(u.shape, s.shape, vt.shape) after the SVD, you'll see that u is a 4x4 matrix, whereas np.dot(np.diag(s), vt) returns a 3x3 matrix. Hence why the dot product with u cannot be computed. Setting the full_matrices option of np.linalg.svd to False will return a 4x3 matrix, and allow the dot product to be computed. I.e.

    import numpy as np
    A = np.matrix([[1, 2, 3], 
                   [4, 5, 6], 
                   [7, 8, 9],
                   [10, 11, 12]])
    u, s, vt = np.linalg.svd(A, full_matrices=False)
    print(np.dot(u, np.dot(np.diag(s), vt)))
    

    Whether that is the right thing to do for your specific problem is another matter.