我在 Apache Spark ML(版本 2.1.0)中使用 NaiveBayes 多项式分类器来预测一些文本类别。
问题是如何在没有训练数据框的情况下将预测标签(0.0, 1.0, 2.0)转换为字符串。
我知道可以使用 IndexToString,但这只有在训练和预测同时进行时才有帮助。但在我的情况下,这是独立的任务。
代码看起来像这样:
1) TrainingModel.scala:训练模型并将模型保存到文件中。
2) CategoryPrediction.scala:从文件加载训练模型并对测试数据进行预测。
请提供解决方案:
TrainingModel.scala
val trainData: Dataset[LabeledRecord] = spark.read.option("inferSchema", "false") .schema(schema).csv("trainingdata1.csv").as[LabeledRecord]val labelIndexer = new StringIndexer().setInputCol("category").setOutputCol("label").fit(trainData).setHandleInvalid("skip")val tokenizer = new RegexTokenizer().setInputCol("text").setOutputCol("words")val hashingTF = new HashingTF() .setInputCol("words") .setOutputCol("features") .setNumFeatures(1000)val rf = new NaiveBayes().setLabelCol("label").setFeaturesCol("features").setModelType("multinomial")val pipeline = new Pipeline().setStages(Array(tokenizer, hashingTF, labelIndexer, rf))val model = pipeline.fit(trainData)model.write.overwrite().save("naivebayesmodel");
CategoryPrediction.scala
val testData: Dataset[PredictLabeledRecord] = spark.read.option("inferSchema", "false") .schema(predictSchema).csv("testingdata.csv").as[PredictLabeledRecord]val model = PipelineModel.load("naivebayesmodel")val predictions = model.transform(testData)// val labelConverter = new IndexToString()// .setInputCol("prediction")// .setOutputCol("predictedLabelString")// .setLabels(trainDataFrameIndexer.labels) predictions.select("prediction", "text").show(false)
trainingdata1.csv
category,textDrama,"a b c d e spark"Action,"b d"Horror,"spark f g h"Thriller,"hadoop mapreduce"
testingdata.csv
text"a b c d e spark""spark f g h"
回答:
在你的管道中添加一个转换器,将预测类别转换回你的标签,类似这样:
val categoryConverter = new IndexToString() .setInputCol("prediction") .setOutputCol("category") .setLabels(labelIndexer.labels)val pipeline = new Pipeline().setStages(Array(tokenizer, hashingTF, labelIndexer, rf, categoryConverter))
这将使用你的 labelIndexer 将预测转换回标签。