在将Countvectorizer应用于tweet的语料库后,我得到了一个带有两个同义“标签”和“稀疏向量”的spark数据框。
当尝试训练随机森林回归模型时,我发现它仅接受Type LabeledPoint。
有人知道如何将我的spark DataFrame转换为LabeledPoint
答案 0 :(得分:2)
您使用的哪个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)