O.r*_*rka 2 machine-learning pca dimensionality-reduction scikit-learn principal-components
我的 PCA 使用sklearn. 为什么我的转换不会像文档所说的那样产生相同尺寸的数组?
fit_transform(X, y=None)
Fit the model with X and apply the dimensionality reduction on X.
Parameters:
X : array-like, shape (n_samples, n_features)
Training data, where n_samples is the number of samples and n_features is the number of features.
Returns:
X_new : array-like, shape (n_samples, n_components)
Run Code Online (Sandbox Code Playgroud)
用 iris 数据集检查一下(150, 4),我正在制作 4 台 PC:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.preprocessing import StandardScaler
from sklearn import decomposition
import seaborn as sns; sns.set_style("whitegrid", {'axes.grid' : False})
%matplotlib inline
np.random.seed(0)
# Iris dataset
DF_data = pd.DataFrame(load_iris().data,
index = ["iris_%d" % i for i in range(load_iris().data.shape[0])],
columns = load_iris().feature_names)
Se_targets = pd.Series(load_iris().target,
index = ["iris_%d" % i for i in range(load_iris().data.shape[0])],
name = "Species")
# Scaling mean = 0, var = 1
DF_standard = pd.DataFrame(StandardScaler().fit_transform(DF_data),
index = DF_data.index,
columns = DF_data.columns)
# Sklearn for Principal Componenet Analysis
# Dims
m = DF_standard.shape[1]
K = m
# PCA (How I tend to set it up)
M_PCA = decomposition.PCA()
A_components = M_PCA.fit_transform(DF_standard)
#DF_standard.shape, A_components.shape
#((150, 4), (150, 4))
Run Code Online (Sandbox Code Playgroud)
但后来当我使用完全相同的方法对我的实际数据集(76, 1989)在76 samples和1989 attributes/dimensions我得到一个(76, 76)数组,而不是(76, 1989)
DF_centered = normalize(DF_mydata, method="center", axis=0)
m = DF_centered.shape[1]
# print(m)
# 1989
M_PCA = decomposition.PCA(n_components=m)
A_components = M_PCA.fit_transform(DF_centered)
DF_centered.shape, A_components.shape
# ((76, 1989), (76, 76))
Run Code Online (Sandbox Code Playgroud)
normalize只是我制作的一个包装器,它mean从每个维度中减去。
(注意:这个答案改编自我在此处交叉验证的答案:如果维数大于或等于 n,为什么 n 个数据点只有 n?1 个主成分?)
PCA(最常见的运行方式)通过以下方式创建新坐标系:
(有关更多详细信息,请参阅此优秀的 CV 主题:了解主成分分析、特征向量和特征值。)但是,第3步以非常特定的方式旋转您的轴。您的新 X1(现在称为“PC1”,即第一个主成分)面向您的数据的最大变化方向。第二个主成分的方向是与第一个主成分正交的下一个最大变化量的方向。其余的主成分同样形成。
考虑到这一点,让我们研究一个简单的例子(@amoeba 在评论中提出的建议)。这是一个在三维空间中有两个点的数据矩阵:
X = [ 1 1 1
2 2 2 ]
Run Code Online (Sandbox Code Playgroud)
让我们在(伪)三维散点图中查看这些点:
因此,让我们按照上面列出的步骤进行操作。(1) 新坐标系的原点将位于(1.5,1.5,1.5)。(2) 轴已经相等。(3) 第一个主成分将从原来的 (0,0,0) 斜向变化到原来的 (3,3,3),这是这些数据变化最大的方向。现在,第二个主成分必须与第一个正交,并且应该朝着剩余最大变化的方向发展。但那是什么方向?是从 (0,0,3) 到 (3,3,0),还是从 (0,3,0) 到 (3,0,3),还是别的什么?没有剩余的变异,所以不可能有更多的主成分。
使用 N=2 数据,我们可以拟合(最多)N?1=1 个主成分。