aloha
aloha

Reputation: 23

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)

Upvotes: 0

Views: 9299

Answers (2)

Chris
Chris

Reputation: 1668

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.

Upvotes: 1

Kais Ben Daamech
Kais Ben Daamech

Reputation: 122

You are trying to make a dot product between two incompatible matrices. The number of the columns of u (it has the shape of (4x4)) isn't equal to the number of rows of np.dot(np.diag(s), vt) (it has the shape of (3x3))

Upvotes: 0

Related Questions