例如我们有:
from sklearn.decomposition import PCAimport numpy as np xx = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])pca = PCA()pca.fit_transform(xx)
输出:
array([[ 1.38340578, 0.2935787 ], [ 2.22189802, -0.25133484], [ 3.6053038 , 0.04224385], [-1.38340578, -0.2935787 ], [-2.22189802, 0.25133484], [-3.6053038 , -0.04224385]])
在这种情况下,我没有减少数组的维度,但是数组发生了变化…为什么?
回答:
PCA对你的特征空间进行了一个线性(旋转)变换。在你的例子中,假设特征1沿x
轴,特征2沿y
轴,结果变换相当于将你的特征向量旋转了theta
角,大约2.565弧度。下面我定义了这样一个旋转矩阵,并展示了你会得到相同的结果:
import numpy as npdef rot_matrix(theta): # 返回通过角度theta的旋转矩阵 rotation_matrix = np.dot(np.array([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]]) return rotation_matrixtheta = 2.565rot = rot_matrix(theta)np.dot(rot, xx.T).T
结果(接近)PCA变换的输出:
array([[ 1.38349574, 0.29315446], [ 2.22182084, -0.25201619], [ 3.60531658, 0.04113827], [-1.38349574, -0.29315446], [-2.22182084, 0.25201619], [-3.60531658, -0.04113827]])