python实现svd分解降阶
时间: 2025-01-17 13:36:42 浏览: 117
### 使用 Python 实现 SVD 进行降维
为了通过奇异值分解(SVD)来降低矩阵的维度,可以利用 `numpy` 或者 `scipy` 库中的函数。下面展示了一个具体的例子,说明如何应用这些库来进行数据集上的降维操作。
#### 导入必要的包
```python
import numpy as np
from scipy import linalg
```
#### 创建示例矩阵并执行 SVD 分解
定义一个待处理的数据矩阵 \(A\) 并对其进行标准形式下的 SVD 分解:
\[ A_{M \times N} = U_{M \times M}\Sigma_{M \times N}(V^{H})_{N \times N} \]
其中,
- \(U\) 是左奇异向量组成的正交矩阵;
- \(\Sigma\) 表示由奇异值构成的对角阵;
- \(V^H\) (\(V\) 的共轭转置)代表右奇异向量形成的另一个正交矩阵[^2]。
```python
# 定义原始矩阵 A
A = np.array([[1, 2, 3],
[4, 5, 6]])
print("Original Matrix:\n", A)
# 执行 svd 分解
U, sigma_values, Vt = linalg.svd(A)
sigma_matrix = linalg.diagsvd(sigma_values, *A.shape[:2])
```
#### 构建降维后的表示
选择前 k 个最大的奇异值及其对应的左右奇异向量构建新的低秩近似矩阵。这里假设要保留两个主要成分作为简化版本:
\[
A_k = U_k\Sigma_k{V_k}^T
\]
其中 \(k < min(M,N)\),并且只取前面 k 列/行用于重构更紧凑的形式[^4]。
```python
def reduce_dimensions(U, sigmas, VT, num_components=2):
"""
减少给定矩阵的特征数量至指定数目
参数:
U (ndarray): 左奇异向量.
sigmas (list or ndarray): 奇异值列表.
VT (ndarray): 右奇异向量(已转置).
num_components (int): 要保持的主要分量数.
返回:
tuple: 包含降维后的 U 和 Sigma 矩阵元组.
"""
reduced_U = U[:, :num_components]
reduced_Sigma = np.diag(sigmas)[:num_components, :num_components]
return reduced_U @ reduced_Sigma
reduced_representation = reduce_dimensions(U, sigma_values, Vt, num_components=2)
print("\nReduced Representation using first two components:")
print(reduced_representation)
```
此过程有效地降低了输入矩阵的信息复杂度,同时尽可能多地保存了原有结构特性。对于实际应用场景而言,可以根据具体需求调整所选组件的数量以达到最佳效果[^3]。
阅读全文
相关推荐

















