PCA 降维


import numpy as np
import pandas as pda
from sklearn.datasets import load_iris
import matplotlib.pyplot as plt
#加载数据
iris=load_iris()
# print(iris)
data=iris["data"]
labels=iris["target"]
# print(data,labels)
df=pda.DataFrame(data,columns=["sepal_len","sepal_width","petal_len","petal_width"])
df["Irsa-setosa"]=labels
#处理数据
df.ix[df["Irsa-setosa"]==0,"Irsa-setosa"]="Iris-Setosa"
df.ix[df["Irsa-setosa"]==1,"Irsa-setosa"]="Iris-Versicolor"
df.ix[df["Irsa-setosa"]==2,"Irsa-setosa"]="Iris-Virgnica"

# print(df)
# print(df.shape)
X=data
# print(X)
y=df["Irsa-setosa"].values

label_dict={1:"Iris-Setosa",
            2: "Iris-Versicolor",
            3: "Iris-Virgnica"}
feature_dict={0:"sepal  length(cm)",
              1:"sepal width(cm)",
              2:"petal length(cm)",
              3:"petal width(cm)"}

plt.figure(figsize=(14,8))
for i in range(4):
    plt.subplot(2,2,i+1)
    for lab in ("Iris-Setosa","Iris-Versicolor","Iris-Virgnica"):
        plt.hist(X[y==lab,i],bins=20,alpha=0.8,label=lab)
    plt.xlabel(feature_dict[i])
    plt.legend(loc="upper right",fancybox=True,fontsize=8)
plt.show()

#标准化,消除量纲
from sklearn.preprocessing import StandardScaler

X_std=StandardScaler().fit_transform(X)
# print(X_std)
mean_vec=np.mean(X_std,axis=0)
cov_mat=(X_std-mean_vec).T.dot((X_std-mean_vec))/(X_std.shape[0]-1)
# print("Covarinance matrix :\n",cov_mat)

eig_vals,eig_vecs=np.linalg.eig(cov_mat)
# print("Eigenvectors \n %s" %eig_vecs)  #特征向量
# print("\nEigenvalues \n %s" %eig_vals)   #特征值

eig_pairs=[(np.abs(eig_vals[i]),eig_vecs[:,i]) for i in range(len(eig_vals))]
print()
print(eig_pairs)

eig_pairs.sort(key= lambda x:x[0],reverse=True)  #按照键值进行排序

print("Eigenvalues in descending order:")
for i in eig_pairs:
    print(i[0])
print("==========================================")
tot=sum(eig_vals)
vars_exp=[(i/tot)*100 for i in sorted(eig_vals,reverse=True)]
print(vars_exp)
# [72.77045209380134, 23.030523267680636, 3.683831957627396, 0.5151926808906299]
#cumsum n等于(0,n-1)的和
cum_var_exp=np.cumsum(vars_exp)
print(cum_var_exp)
# [ 72.77045209  95.80097536  99.48480732 100.        ]

plt.figure(figsize=(10,8))
plt.bar(range(4),vars_exp,alpha=0.5,align="center",label="individual explained variance ")
plt.step(range(4),cum_var_exp,where="mid",label="cumulative explained variance ")
plt.xlabel("Principal components")
plt.ylabel("Explained variance ratio")
plt.legend(loc="best")
plt.tight_layout()
plt.show()


matrix_w=np.hstack((eig_pairs[0][1].reshape(4,1),eig_pairs[1][1].reshape(4,1)))
print("matrix_w",matrix_w)

Y=X_std.dot(matrix_w)
print("Y",Y)

plt.figure(figsize=(6, 4))
for lab, col in zip(('Iris-Setosa', 'Iris-Versicolor', 'Iris-Virgnica'),('blue', 'red', 'green')):
    plt.scatter(X[y==lab, 0],X[y==lab, 1],label=lab,c=col)
plt.xlabel('sepal_len')
plt.ylabel('sepal_wid')
plt.legend(loc='best')
plt.tight_layout()
plt.show()

plt.figure(figsize=(6, 4))
for lab, col in zip(('Iris-Setosa', 'Iris-Versicolor', 'Iris-Virgnica'),('blue', 'red', 'green')):
    plt.scatter(Y[y==lab, 0], Y[y==lab, 1],label=lab,c=col)
plt.xlabel('Principal Component 1')
plt.ylabel('Principal Component 2')
plt.legend(loc='lower center')
plt.tight_layout()
plt.show()
### 主成分分析(PCA的实现与应用 #### PCA的核心原理 主成分分析是一种常用的线性技术,其核心在于通过特征值分解协方差矩阵来提取数据的主要变化方向。这种方法能够将高度的数据映射到低度空间,同时尽可能保留原始数据的信息[^3]。 具体来说,PCA的目标是最小化投影误差或者最大化投影后的方差。这可以通过计算样本数据的协方差矩阵并求解该矩阵的最大特征值对应的特征向量来完成。最大特征值所对应的方向就是数据中方差最大的方向,也就是第一个主成分;次大特征值对应第二个主成分,依此类推[^1]。 #### MATLAB代码实现PCA 以下是基于MATLAB的一个简单PCA过程: ```matlab % 假设X是一个n×d的矩阵,其中每一行代表一个观测样本,每列代表不同的属性。 function [Y, mu, W] = pca(X, k) % 数据中心化处理 mu = mean(X); % 计算均值 X_centered = bsxfun(@minus, X, mu); % 协方差矩阵计算 C = cov(X_centered); % 进行特征值分解 [V, D] = eig(C); % 对特征值按大小排序,并选取前k个主要成分 [D_sorted, idx] = sort(diag(D), 'descend'); V_sorted = V(:, idx); % 取前k个特征向量作为变换基底W W = V_sorted(:, 1:k); % 将原数据投射到新的子空间上 Y = (X_centered * W); end ``` 上述函数实现了完整的PCA流程:数据中心化、协方差矩阵构建、特征值分解以及最终的数据投影操作[^2]。 #### 应用场景举例 PCA广泛应用于图像压缩、基因数据分析等领域。例如,在人脸识别领域中,可以利用PCA减少面部图片像素点的数量从而低存储需求的同时保持识别精度。另外,在金融时间序列预测方面也可以借助PCA去除噪声干扰项以提高模型准确性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值