pythonimagenumpysvd

Error when calculating singular values of a matrix


I'm trying to calculate the singular values of a matrix using 2 methods. The matrix I'm using is the red channel of a sunflower image. Here's the image if you need it.

The first method is using SVD:

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np

A = mpimg.imread('sunflower.jpeg')
R = A[:,:,0]

U, S, V = np.linalg.svd(R)
print(S)

The second is using an alternate approach to calculating singular values, where you take the square root of the eigenvalues of R.T*R.

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np

A = mpimg.imread('sunflower.jpeg')
R = A[:,:,0]

rW = np.linalg.eigvals(np.dot(R.T, R))
singvals = np.sqrt(rW)
print(singvals)

Hypothetically they should yield the same result, but that's not what I'm getting. Any help would be appreciated!


Solution

  • When I run your code after casting R to be .astype(np.int64), and round the values to 6 decimal places, and compare the two return values as set, I get that they return the same values. I suspect that one or more of

    is the source of the difference between the two...

    import matplotlib.pyplot as plt
    import matplotlib.image as mpimg
    import numpy as np
    
    A = mpimg.imread('sunflower.jpeg')
    R = A[:,:,0].astype(np.int64)
    
    U, S, V = np.linalg.svd(R)
    
    rW = np.linalg.eigvals(np.dot(R.T, R))
    singvals = np.sqrt(rW)
    
    set(S.round(6)) == set(singvals.round(6))
    # True