Spark ML 将预测标签转换为字符串而不使用训练数据框

我在 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 将预测转换回标签。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注