Rank-constrained matrix approximation
In this recipe, you will learn how to compute a rank-considerant matrix approximation. The problem is formulated as an optimization problem. Given an input matrix, the aim is to find its approximation where the fit is measured using the Frobenius norm and the rank of the output matrix should not be greater than the given value. This functionality, among other fields, is used in data compression and machine learning.
Getting ready
Before you proceed with this recipe, you need to install the OpenCV 3.0 (or greater) Python API package.
How to do it...
You need to complete the following steps:
- Import the modules:
import cv2 import numpy as np
- Generate a random matrix:
A = np.random.randn(10, 10)
- Compute the SVD:
w, u, v_t = cv2.SVDecomp(A)
- Compute the rank-constrained matrix approximation:
RANK = 5 w[RANK:,0] = 0 B = u @ np.diag(w[:,0]) @ v_t
- Check the results:
print('Rank before:', np.linalg.matrix_rank(A)) print('Rank after:', np.linalg.matrix_rank(B)) print('Norm...