在Python中使用Spark DataFrame创建labeledPoints

时间:2015-09-14 01:29:26

标签: python pandas apache-spark apache-spark-mllib apache-spark-ml

我使用python中的.map()函数从spark数据帧创建一组labeledPoints?如果标签/结果不是第一列,但我可以参考其列名,状态'?

,该表示法是什么?

我用这个.map()函数创建Python数据帧:

def parsePoint(line):
    listmp = list(line.split('\t'))
    dataframe = pd.DataFrame(pd.get_dummies(listmp[1:]).sum()).transpose()
    dataframe.insert(0, 'status', dataframe['accepted'])
    if 'NULL' in dataframe.columns:
        dataframe = dataframe.drop('NULL', axis=1)  
    if '' in dataframe.columns:
        dataframe = dataframe.drop('', axis=1)  
    if 'rejected' in dataframe.columns:
        dataframe = dataframe.drop('rejected', axis=1)  
    if 'accepted' in dataframe.columns:
        dataframe = dataframe.drop('accepted', axis=1)  
    return dataframe 

在reduce函数重新组合了所有Pandas数据帧之后,我将其转换为Spark数据帧。

parsedData=sqlContext.createDataFrame(parsedData)

但是现在如何在Python中创建labledPoints?我假设它可能是另一个.map()函数?

1 个答案:

答案 0 :(得分:13)

如果您已经拥有数字要素且无需其他转换,则可以使用VectorAssembler组合包含自变量的列:

from pyspark.ml.feature import VectorAssembler

assembler = VectorAssembler(
    inputCols=["your", "independent", "variables"],
    outputCol="features")

transformed = assembler.transform(parsedData)

接下来你可以简单地映射:

from pyspark.mllib.regression import LabeledPoint
from pyspark.sql.functions import col

(transformed.select(col("outcome_column").alias("label"), col("features"))
  .rdd
  .map(lambda row: LabeledPoint(row.label, row.features)))

自Spark 2.0 mlmllib API不再兼容,后者即将弃用和删除。如果您仍然需要,则必须将ml.Vectors转换为mllib.Vectors

from pyspark.mllib import linalg as mllib_linalg
from pyspark.ml import linalg as ml_linalg

def as_old(v):
    if isinstance(v, ml_linalg.SparseVector):
        return mllib_linalg.SparseVector(v.size, v.indices, v.values)
    if isinstance(v, ml_linalg.DenseVector):
        return mllib_linalg.DenseVector(v.values)
    raise ValueError("Unsupported type {0}".format(type(v)))

和地图:

lambda row: LabeledPoint(row.label, as_old(row.features)))