【发布时间】:2017-02-15 12:55:07
【问题描述】:
我想使用 PySpark (Spark 1.6.2) 对 Hive 表中存在的数值数据执行主成分分析 (PCA)。我能够将 Hive 表导入 Spark 数据框:
>>> from pyspark.sql import HiveContext
>>> hiveContext = HiveContext(sc)
>>> dataframe = hiveContext.sql("SELECT * FROM my_table")
>>> type(dataframe)
<class 'pyspark.sql.dataframe.DataFrame'>
>>> dataframe.columns
['par001', 'par002', 'par003', etc...]
>>> dataframe.collect()
[Row(par001=1.1, par002=5.5, par003=8.2, etc...), Row(par001=0.0, par002=5.7, par003=4.2, etc...), etc...]
有一篇很棒的 StackOverflow 帖子展示了如何在 PySpark 中执行 PCA:https://stackoverflow.com/a/33481471/2626491
在帖子的“测试”部分,@desertnaut 创建了一个只有一列的数据框(称为“功能”):
>>> from pyspark.ml.feature import *
>>> from pyspark.mllib.linalg import Vectors
>>> data = [(Vectors.dense([0.0, 1.0, 0.0, 7.0, 0.0]),),
... (Vectors.dense([2.0, 0.0, 3.0, 4.0, 5.0]),),
... (Vectors.dense([4.0, 0.0, 0.0, 6.0, 7.0]),)]
>>> df = sqlContext.createDataFrame(data,["features"])
>>> type(df)
<class 'pyspark.sql.dataframe.DataFrame'>
>>> df.columns
['features']
>>> df.collect()
[Row(features=DenseVector([0.0, 1.0, 0.0, 7.0, 0.0])), Row(features=DenseVector([2.0, 0.0, 3.0, 4.0, 5.0])), Row(features=DenseVector([4.0, 0.0, 0.0, 6.0, 7.0]))]
@desertnaut 的示例数据框中的每一行都包含一个 DenseVector 对象,然后由 pca 函数使用。
问)如何将 Hive 中的数据框转换为单列数据框(“特征”),其中每行包含一个 DenseVector,代表原始行中的所有值?
【问题讨论】:
标签: apache-spark pyspark apache-spark-mllib pca apache-spark-ml