### Notebook refinements

parent c382b71c
 ... ... @@ -26,13 +26,13 @@ import matplotlib.pyplot as plt import numpy as np plt.rcParams['figure.figsize'] = [8, 8] image_url = 'Helix_Nebula.png' image_path = 'Helix_Nebula.png' A = imread(image_url) A = imread(image_path) ``` %% Cell type:markdown id: tags: The image will be loaded as a 3-dimensional array. The first two dimensions simply represent the grid of pixel, while the third dimension contains the three color channels: Red, Green and Blue. ... ... @@ -129,22 +129,43 @@ We can truncate the 3 resulting matrices from the SVD and perform matrix multiplication with these 3 matrices. What we get is an approximated version of the original matrix. The truncation is performed by taking the first k columns of U, the first k elements of the diangonal matrix \$\Sigma\$ and the first k rows of \$V^T\$. It is proven that the k-rank approximation of the SVD is the best k-rank approximation possibile. If I want to make a rank-10 approximation of my matrix, I just have to make a matrix product between the 3 SVD matrices (U, s, VT) after trucating the such as: - Take only the first 10 columns of **U** - **s** is stored as a 1-d array containing the elements of the diagonal (the singular values). We just need to take the first 10 singular values and build a diagonal matrix from them - Take the first 10 rows of **VT** %% Cell type:code id: tags: ``` python k = 10 X_rank10 = U[:,:k] @ np.diag(s[:k]) @ VT[:k,:] plt.set_cmap('gray') plt.imshow(X_rank10) plt.axis('off') ``` %% Cell type:markdown id: tags: Now, let's visualize the best rank-\$k\$ matrices, for \$k\$ = 1, 5, 10, 50, 100, 500 %% Cell type:code id: tags: ``` python fig, axs = plt.subplots(nrows = 2, ncols = 3, figsize = (18,12)) axs = axs.flatten() idxs = [1, 5, 10, 50, 100, 500] idxs = [1, 5, 10, 100, 200, 500] plt.set_cmap('gray') for i,k in enumerate(idxs): X_k = U[:,:k] @ np.diag(s[:k]) @ VT[:k,:] for i in range(len(idxs)): plt.set_cmap('gray') k = idxs[i] X_k = np.matmul(U[:,:k], np.matmul(np.diag(s[:k]),VT[:k,:])) axs[i].imshow(X_k) axs[i].set_title('k = %d' % k) axs[i].axis('off') ``` ... ...
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment