jupyterPCA实验:对data.csv文件中的数据实现PCA操作并实现维度恢复1.数据读取及处理 2.特征归一化 3.计算协方差矩阵Sigma = □1/m∑_i=0^m▒(x^(i))(x^(i))^T 4.奇异值分解[U, S, V] = svd(Sigma) 5.Ureduce = U(:, 1:k) 6. z = Ureduceʼ * x7.绘图
时间: 2024-03-03 20:52:38 浏览: 89
好的,这是对数据集进行 PCA 操作的完整代码:
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# 1.数据读取及处理
data = pd.read_csv("data.csv", header=None)
X = data.values.T
m, n = X.shape
# 2.特征归一化
def feature_normalize(X):
mu = np.mean(X, axis=1)
sigma = np.std(X, axis=1, ddof=1)
X_norm = (X - mu.reshape(-1, 1)) / sigma.reshape(-1, 1)
return X_norm, mu, sigma
X_norm, mu, sigma = feature_normalize(X)
# 3.计算协方差矩阵 Sigma
Sigma = 1 / m * X_norm.dot(X_norm.T)
# 4.奇异值分解[U, S, V] = svd(Sigma)
U, S, V = np.linalg.svd(Sigma)
# 5.Ureduce = U(:, 1:k)
k = 1 # 恢复到1维
U_reduce = U[:, :k]
# 6. z = Ureduceʼ * x
Z = U_reduce.T.dot(X_norm)
# 维度恢复
X_approx = U_reduce.dot(Z)
# 绘图
fig, ax = plt.subplots(figsize=(12, 8))
ax.set_aspect('equal')
ax.scatter(X[0], X[1], c='b', marker='o')
ax.scatter(X_approx[0], X_approx[1], c='r', marker='o')
plt.xlabel('x1')
plt.ylabel('x2')
plt.title('Original Data Points vs. PCA Reduced Data Points')
plt.show()
```
请注意,我将 k 设置为 1,因此维度恢复到了 1 维。如果您想恢复到其他维度,请相应地更改 k 的值。
阅读全文