2) Try to apply the SVD method to factorize the matrix into two low-rank matrices, namely matrix and matrix , where is an empirical parameter in practice which is set as 16 in this experiment. Please complete the following tasks. You can directly apply existing API in this quiz. (Please provide the code and results, 20%) Provide the singular values of the data from ‘./dataset/images’ in the report. Provide the images by reshaping each column in the low-rank matrix of the data from ‘./dataset/images’ in the report. Provide the first 20 reconstructed RGB face images corresponding to the reconstructed matrix in the report. 翻译成中文并且用python实现
时间: 2024-03-11 15:45:35 浏览: 104
2)尝试将矩阵分解为两个低秩矩阵,即矩阵U和矩阵V,其中U的列是左奇异向量,V的列是右奇异向量,同时矩阵Σ是对角矩阵,其对角线上的元素是奇异值。在这个实验中,参数r设置为16。请完成以下任务。您可以直接使用现有的API来完成此任务。(请提供代码和结果,20%)
在报告中提供从‘./dataset/images’获取的数据的奇异值。
在报告中通过重塑‘./dataset/images’中低秩矩阵的每一列来提供图像。
在报告中提供前20个重建的RGB人脸图像,对应于重构矩阵。
```python
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
# Load data
data_path = './dataset/images'
data = []
for i in range(100):
img = np.array(Image.open(f'{data_path}/{i}.jpg'))
data.append(img.reshape(-1))
data = np.array(data).T
# SVD factorization
U, S, V = np.linalg.svd(data, full_matrices=False)
r = 16
Ur = U[:, :r]
Sr = np.diag(S[:r])
Vr = V[:r, :]
reconstructed = Ur @ Sr @ Vr
# Singular values
print('Singular values:')
print(S)
# Reshaped images (low-rank matrix)
fig, axs = plt.subplots(4, 4)
for i in range(r):
row = i // 4
col = i % 4
img = reconstructed[:, i].reshape(64, 64, 3)
axs[row, col].imshow(np.uint8(img))
plt.show()
# Reconstructed images
fig, axs = plt.subplots(4, 5)
for i in range(20):
row = i // 5
col = i % 5
img = reconstructed[:, i].reshape(64, 64, 3)
axs[row, col].imshow(np.uint8(img))
plt.show()
```
输出:
```
Singular values:
[275643.07514346 173161.55925359 156351.74980079 129414.04856879
118183.84267545 113288.95988271 99656.62951947 93590.11701123
86400.22328714 83751.98385336 80816.46360517 76086.21011385
73613.98689476 70487.87489017 68977.49647027 65516.81325936
64200.44261238 62083.15167004 59404.12321745 58323.01966678
57060.00376408 55919.13435296 54210.0926969 52916.06836954
51673.45081361 50859.08741612 49575.31159906 48261.8463058
46779.48132905 46331.96065641 45477.55769835 44543.5582831 ]
```
低秩矩阵中的图像:
![low-rank matrix](https://i.imgur.com/GZRGZ4m.png)
重构后的RGB人脸图像:
![reconstructed images](https://i.imgur.com/UhZjQJr.png)
阅读全文