1

我正在使用Databricks,并希望在Spark中使用Python中的MLlib包。当我以前使用Scikit-learn时,我将获得一个功能列表,以及另一个功能标签列表。我只是简单地使用决策树分类器来预测。如何从两个列表创建一个PySpark数据框?

望着文档,我就怎么做类似的事情上PySpark有点失落:https://docs.databricks.com/spark/latest/mllib/binary-classification-mllib-pipelines.html

我相信为了使用MLlib,我需要从一个数据帧中提取的列的功能和标签使用。因此,在这样做时,我想知道如何创建一个新的空白数据框,然后将两列添加到该列表中,其中一列是功能列表,另一列是标签列表。我的功能列表(例如:[2,0,0,1])被称为'ml_list',我的标签列表(例如:[1]或[0])被称为'标签'。

这是我的代码到目前为止,不知道我是否在正确的道路上。我的功能以及我的标签都是二进制的,所以我选择了IntegerType():

field = [StructField(“ml_list”,IntegerType(), 
True),StructField(“Labels”, IntegerType(), True)] 

schema = StructType(field) 
df_date = sqlContext.createDataFrame(sc.emptyRDD(), schema) 

任何帮助都会很棒,因为我对Spark很新。

回答

1

或者:

from pyspark.ml.linalg import Vectors 

dd = [(labels[i][0], Vectors.dense(features[i])) for i in range(len(labels))] 
df = spark.createDataFrame(sc.parallelize(dd),schema=["label", "features"]) 
2

如果您有:

labels = [[0], [1], [0]] 

features = [[2, 0, 0, 1], [0, 0, 0, 1], [0, 2, 0, 1]] 

,您可以:

from pyspark.ml.linalg import Vectors 

sc.parallelize(zip(labels, features)).map(lambda lp: (float(lp[0][0]), Vectors.dense(lp[1]))).toDF(["label", "features"]) 
相关问题