如何在scala中保存RandomForestClassifier Spark模型?

Yae*_*778 5 scala apache-spark apache-spark-mllib

我使用以下代码构建了一个随机森林模型:

import org.apache.spark.ml.classification.RandomForestClassificationModel
import org.apache.spark.ml.classification.RandomForestClassifier
val rf = new RandomForestClassifier().setLabelCol("indexedLabel").setFeaturesCol("features")
val labelConverter = new    IndexToString().setInputCol("prediction").setOutputCol("predictedLabel").setLabels(labelIndexer.labels)
val training = labelIndexer.transform(df)
val model = rf.fit(training)
Run Code Online (Sandbox Code Playgroud)

现在我想保存模型,以便以后使用以下代码进行预测:

val predictions: DataFrame = model.transform(testData)
Run Code Online (Sandbox Code Playgroud)

我在这里查看了Spark文档,但没有找到任何选项.任何的想法?我花了几个小时来构建模型,如果Spark破碎我将无法恢复它.

jav*_*dba 1

它位于界面中- 通过模型上的属性MLWriter进行访问:writer

model.asInstanceOf[MLWritable].write.save(path)
Run Code Online (Sandbox Code Playgroud)

这是界面:

abstract class MLWriter extends BaseReadWrite with Logging {

  protected var shouldOverwrite: Boolean = false

  /**
   * Saves the ML instances to the input path.
   */
  @Since("1.6.0")
  @throws[IOException]("If the input path already exists but overwrite is not enabled.")
  def save(path: String): Unit = {
Run Code Online (Sandbox Code Playgroud)

mllib这是对早期版本/的重构spark.ml

更新 看来模型不可写:

线程“main”中出现异常 java.lang.UnsupportedOperationException:管道写入将在此管道上失败,因为它包含一个未实现 Writable 的阶段。不可写阶段:类型为 org.apache.spark.ml.classification.RandomForestClassificationModel 的 rfc_4e467607406f

因此,可能没有一个简单的解决方案。