[英]How to make binary classication in Spark ML without StringIndexer
我尝试在不带StringIndexer的管道中使用Spark ML DecisionTreeClassifier,因为我的功能已经被索引为(0.0; 1.0)。 DecisionTreeClassifier作为标签需要双精度值,因此此代码应该可以工作:
def trainDecisionTreeModel(training: RDD[LabeledPoint], sqlc: SQLContext): Unit = {
import sqlc.implicits._
val trainingDF = training.toDF()
//format of this dataframe: [label: double, features: vector]
val featureIndexer = new VectorIndexer()
.setInputCol("features")
.setOutputCol("indexedFeatures")
.setMaxCategories(4)
.fit(trainingDF)
val dt = new DecisionTreeClassifier()
.setLabelCol("label")
.setFeaturesCol("indexedFeatures")
val pipeline = new Pipeline()
.setStages(Array(featureIndexer, dt))
pipeline.fit(trainingDF)
}
但实际上我得到
java.lang.IllegalArgumentException:
DecisionTreeClassifier was given input with invalid label column label,
without the number of classes specified. See StringIndexer.
当然,我可以只放StringIndexer并让他使它适用于我的双重“标签”字段,但是我想使用DecisionTreeClassifier的输出rawPrediction列来为每一行获得0.0和1.0的概率,例如...
val predictions = model.transform(singletonDF)
val zeroProbability = predictions.select("rawPrediction").asInstanceOf[Vector](0)
val oneProbability = predictions.select("rawPrediction").asInstanceOf[Vector](1)
如果将StringIndexer放置在Pipeline中-我将不知道rawPrediction矢量中输入标签“ 0.0”和“ 1.0”的索引,因为String indexer将按值的频率进行索引,该频率可能会有所不同。
请在不使用StringIndexer的情况下帮助为DecisionTreeClassifier准备数据,或者建议采用其他方法来获取每行原始标签的概率(0.0; 1.0)。
您始终可以手动设置所需的元数据:
import sqlContext.implicits._
import org.apache.spark.ml.attribute.NominalAttribute
val meta = NominalAttribute
.defaultAttr
.withName("label")
.withValues("0.0", "1.0")
.toMetadata
val dfWithMeta = df.withColumn("label", $"label".as("label", meta))
pipeline.fit(dfWithMeta)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.