Singular Value Decomposition (SVD) outputs a 1-D singular value array, instead of 2-D diagonal matrix [Python]
Asked Answered
E

2

6

I was posting a question on similar subject, and encountered another more important question.

When I apply SVD to a matrix 'A' (code below) the output I get is the expected 2-D eigenvector matrices ('U' and 'V') and an unexpected 1-D singular value array 'S'.

U,S,V=np.linalg.svd(A)

For context: The reason for it being unexpected is that Singular Value Decomposition should result in the product of three matrices. The middle matrix (in this case 1-D array) should be a diagonal matrix, holding non-negative singular values in decreasing order of magnitude.

Why does Python 'transform' the matrix into an array? Is there a way around it?

Thanks!

Eggshaped answered 10/4, 2020 at 16:17 Comment(0)
B
4

This is made quite clear in the docs, there you'll see that:

s : (…, K) array: Vector(s) with the singular values, within each vector sorted in descending order. The first a.ndim - 2 dimensions have the same size as those of the input a.

So basically S is just the diagonal of the matrix you mention, i.e the singular values. You can construct a diagonal matrix from it with:

np.diag(S)
Bulb answered 10/4, 2020 at 16:21 Comment(1)
I see. I thought there might be a way to intrinsecally change the svd function, but the approach proposed by you and ev-br seems a much more reasonable and simple. Thanks!Eggshaped
I
2

Use np.diag (https://docs.scipy.org/doc/numpy/reference/generated/numpy.diag.html)

>>> np.diag([0, 4, 8])
array([[0, 0, 0],
       [0, 4, 0],
       [0, 0, 8]])
Interdental answered 10/4, 2020 at 16:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.