/ / Spark ML Converti etichetta Prediction in stringa senza formazione DataFrame - scala, apache-spark, machine-learning

Spark ML Converti etichetta Prediction in stringa senza formazione DataFrame - scala, apache-spark, machine-learning

Sto usando il classificatore multinomiale NaiveBayes in Apache Spark ML (versione 2.1.0) per prevedere alcune categorie di testo.

Il problema è come convertire l'etichetta di previsione (0.0, 1.0, 2.0) nella stringa senza DataFrame addestrato.

So che IndexToString può essere usato ma è utile solo se l'allenamento e la previsione sono entrambi allo stesso tempo. Ma, nel mio caso, il suo lavoro indipendente.

il codice sembra come
1) TrainingModel.scala: forma il modello e salva il modello nel file.
2) CategoryPrediction.scala: carica il modello addestrato dal file e fa la previsione sui dati di test.

Si prega di suggerire la soluzione:

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,text
Drama,"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"

risposte:

1 per risposta № 1

Aggiungi un convertitore che tradurrà le categorie di previsione nelle tue etichette nella tua pipeline, qualcosa del genere:

val categoryConverter = new IndexToString()
.setInputCol("prediction")
.setOutputCol("category")
.setLabels(labelIndexer.labels)

val pipeline = new Pipeline().setStages(Array(tokenizer, hashingTF, labelIndexer, rf, categoryConverter))

Questo prenderà la previsione e la riconvertirà in un'etichetta usando labelIndexer.