使用 Pyspark 从 Spark DataFrame 创建 labeledPoints
Create labeledPoints from a Spark DataFrame using Pyspark
我有一个 spark Dataframe,其中包含两个列 "label" 和 "sparse Vector",这是在将 Countvectorizer 应用于推文语料库后获得的。
在尝试训练随机森林回归模型时,我发现它只接受 Type LabeledPoint。
有谁知道如何将我的 spark DataFrame 转换为 LabeledPoint
您使用的是哪个spark版本。 Spark 使用 spark ml 而不是 mllib。
from pyspark.ml.feature import CountVectorizer
from pyspark.ml.classification import RandomForestClassifier
from pyspark.sql import functions as F
# Input data: Each row is a bag of words with a ID.
df = sqlContext.createDataFrame([
(0, "a b c".split(" ")),
(1, "a b b c a".split(" "))
], ["id", "words"])
# fit a CountVectorizerModel from the corpus.
cv = CountVectorizer(inputCol="words", outputCol="features", vocabSize=3, minDF=2.0)
model = cv.fit(df)
result = model.transform(df).withColumn('label', F.lit(0))
rf = RandomForestClassifier(labelCol="label", featuresCol="features", numTrees=10)
rf.fit(result)
如果您坚持使用 mllib:
from pyspark.mllib.regression import LabeledPoint
from pyspark.mllib.tree import RandomForest
rdd = result \
.rdd \
.map(lambda row: LabeledPoint(row['label'], row['features'].toArray()))
RandomForest.trainClassifier(rdd, 2, {}, 3)
我有一个 spark Dataframe,其中包含两个列 "label" 和 "sparse Vector",这是在将 Countvectorizer 应用于推文语料库后获得的。
在尝试训练随机森林回归模型时,我发现它只接受 Type LabeledPoint。
有谁知道如何将我的 spark DataFrame 转换为 LabeledPoint
您使用的是哪个spark版本。 Spark 使用 spark ml 而不是 mllib。
from pyspark.ml.feature import CountVectorizer
from pyspark.ml.classification import RandomForestClassifier
from pyspark.sql import functions as F
# Input data: Each row is a bag of words with a ID.
df = sqlContext.createDataFrame([
(0, "a b c".split(" ")),
(1, "a b b c a".split(" "))
], ["id", "words"])
# fit a CountVectorizerModel from the corpus.
cv = CountVectorizer(inputCol="words", outputCol="features", vocabSize=3, minDF=2.0)
model = cv.fit(df)
result = model.transform(df).withColumn('label', F.lit(0))
rf = RandomForestClassifier(labelCol="label", featuresCol="features", numTrees=10)
rf.fit(result)
如果您坚持使用 mllib:
from pyspark.mllib.regression import LabeledPoint
from pyspark.mllib.tree import RandomForest
rdd = result \
.rdd \
.map(lambda row: LabeledPoint(row['label'], row['features'].toArray()))
RandomForest.trainClassifier(rdd, 2, {}, 3)