我正在使用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