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

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

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