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

python spark: narrowing down most relevant features using PCA

我在 python 中使用 spark 2.2。我正在使用来自 ml.feature 模块的 PCA。我正在使用 VectorAssembler 将我的特征提供给 PCA。为了澄清,假设我有一个包含三列 col1、col2 和 col3 的 table 然后我正在做:

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(= 我原始 table 中的列数)行和 2(= 我的 PCA 中的组件数)列。我的问题是这里的三行的顺序是否与我为上面的向量汇编器指定输入列的顺序相同?为了进一步澄清,上面的矩阵是否对应于:

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

请注意,此处的示例只是为了清楚起见。在我真正的问题中,我正在处理 ~1600 列和一堆选择。我在 spark 文档中找不到任何明确的答案。我想这样做是为了从我原来的 table 中选择最好的列/特征,以根据最主要的主要成分来训练我的模型。或者我应该查看 spark ML PCA 中的其他/更好的东西来推断出这样的结果?

或者我不能为此使用 PCA 而必须使用其他技术,如 spearman 排名等?

are the (...) rows here in the same order in which I had specified my input columns

是的,他们是。让我们追踪一下是怎么回事:

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"])

VectorAseembler 遵循列的顺序:

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

您可以在此处查看列的实际顺序

df.schema["features"].metadata["ml_attr"]["attrs"]

通常会有两个类,["binary] & ["numeric"]

pd.DataFrame(df.schema["features"].metadata["ml_attr"]["attrs"]["binary"]+df.schema["features"].metadata["ml_attr"]["attrs"]["numeric"]).sort_values("idx")

应该给出所有列的准确顺序。 您可以验证,输入和输出的顺序保持不变。