You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: content/tutorial-svd.md
+13-12Lines changed: 13 additions & 12 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -74,8 +74,8 @@ import matplotlib.pyplot as plt
74
74
```
75
75
76
76
```{code-cell}
77
-
plt.imshow(img)
78
-
plt.show()
77
+
fig, ax = plt.subplots()
78
+
ax.imshow(img)
79
79
```
80
80
81
81
### Shape, axis and array properties
@@ -196,8 +196,8 @@ To see if this makes sense in our image, we should use a colormap from `matplotl
196
196
In our case, we are approximating the grayscale portion of the image, so we will use the colormap `gray`:
197
197
198
198
```{code-cell}
199
-
plt.imshow(img_gray, cmap="gray")
200
-
plt.show()
199
+
fig, ax = plt.subplots()
200
+
ax.imshow(img_gray, cmap="gray")
201
201
```
202
202
203
203
Now, applying the [linalg.svd](https://numpy.org/devdocs/reference/generated/numpy.linalg.svd.html#numpy.linalg.svd) function to this matrix, we obtain the following decomposition:
@@ -259,8 +259,8 @@ np.allclose(img_gray, U @ Sigma @ Vt)
259
259
To see if an approximation is reasonable, we can check the values in `s`:
260
260
261
261
```{code-cell}
262
-
plt.plot(s)
263
-
plt.show()
262
+
fig, ax = plt.subplots()
263
+
ax.plot(s)
264
264
```
265
265
266
266
In the graph, we can see that although we have 768 singular values in `s`, most of those (after the 150th entry or so) are pretty small. So it might make sense to use only the information related to the first (say, 50) *singular values* to build a more economical approximation to our image.
Note that we had to use only the first `k` rows of `Vt`, since all other rows would be multiplied by the zeros corresponding to the singular values we eliminated from this approximation.
283
283
284
284
```{code-cell}
285
-
plt.imshow(approx, cmap="gray")
286
-
plt.show()
285
+
fig, ax = plt.subplots()
286
+
ax.imshow(approx, cmap="gray")
287
287
```
288
288
289
289
Now, you can go ahead and repeat this experiment with other values of `k`, and each of your experiments should give you a slightly better (or worse) image depending on the value you choose.
@@ -362,8 +362,9 @@ Since `imshow` expects values in the range, we can use `clip` to excise the floa
which is not the right shape for showing the image. Finally, reordering the axes back to our original shape of `(768, 1024, 3)`, we can see our approximation:
Even though the image is not as sharp, using a small number of `k` singular values (compared to the original set of 768 values), we can recover many of the distinguishing features from this image.
0 commit comments