python spark: 使用PCA缩小最相关特征

我正在使用Python的Spark 2.2版本。我使用的是ml.feature模块中的PCA。我使用VectorAssembler将我的特征输入到PCA中。为了说明清楚,假设我有一个包含三列col1、col2和col3的表格,那么我做的操作是:

from pyspark.ml.feature import VectorAssembler
assembler = VectorAssembler(inputCols=table.columns, outputCol="features")
df = assembler.transform(table).select("features")
from pyspark.ml.feature import PCA
pca = PCA(k=2, inputCol="features", outputCol="pcaFeatures")
model = pca.fit(df)

此时,我已经运行了具有2个成分的PCA,并且可以查看其值如下:

m = model.pc.values.reshape(3, 2)

这对应于3行(等于我原始表格中的列数)和2列(等于我的PCA中的成分数)。我的问题是,这里的三行是否与我上面指定给向量组装器的输入列的顺序相同?为了进一步澄清,上述矩阵是否对应于:

          | PC1 | PC2 | 
---------|-----|-----|
    col1  |     |     | 
---------|-----|-----|
    col2  |     |     | 
---------|-----|-----|
    col3  |     |     | 
---------+-----+-----+

请注意,这里给出的示例仅用于说明。在我的实际问题中,我处理的是大约1600列和一系列选择。我在Spark文档中找不到任何明确的答案。我想这样做是为了根据最主要的成分从我的原始表格中选择最佳列/特征来训练我的模型。或者,在Spark ML PCA中是否有其他更好的方法来推导出这样的结果?

或者我不能使用PCA来做这件事,而必须使用其他技术,比如斯皮尔曼排名等?


回答:

这里的(…)行是否与我指定的输入列的顺序相同

是的,它们是相同的。让我们追踪一下发生了什么:

from pyspark.ml.feature import PCA, VectorAssembler
data = [    (0.0, 1.0, 0.0, 7.0, 0.0), (2.0, 0.0, 3.0, 4.0, 5.0),     (4.0, 0.0, 0.0, 6.0, 7.0)]
df = spark.createDataFrame(data, ["u", "v", "x", "y", "z"])

VectorAssembler遵循列的顺序:

assembler = VectorAssembler(inputCols=df.columns, outputCol="features")
vectors = assembler.transform(df).select("features")
vectors.schema[0].metadata
# {'ml_attr': {'attrs': {'numeric': [{'idx': 0, 'name': 'u'},
#     {'idx': 1, 'name': 'v'},
#     {'idx': 2, 'name': 'x'},
#     {'idx': 3, 'name': 'y'},
#     {'idx': 4, 'name': 'z'}]},
#   'num_attrs': 5}}

主成分也是如此

model = PCA(inputCol="features", outputCol="pc_features", k=3).fit(vectors)
model.pc
# Type:        property
# String form: <property object at 0x7feb5bdc1d68>
# Docstring:  
# Returns a principal components Matrix.
# Each column is one principal component.
# 
# .. versionadded:: 2.0.0

最后进行健全性检查:

import numpy as np
x = np.array(data)
y = model.pc.values.reshape(3, 5).transpose()
z = np.array(model.transform(vectors).rdd.map(lambda x: x.pc_features).collect())
np.linalg.norm(x.dot(y) - z)
# 8.881784197001252e-16

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注