如何将 ML 模型转换为 MLlib 模型?

How to convert ML model to MLlib model?

我已经使用基于 API(mllib 包)1.5.2 的 Spark RDD 训练了机器学习模型,比如 "Mymodel123",

org.apache.spark.mllib.tree.model.RandomForestModel Mymodel123 = ....;
Mymodel123.save("sparkcontext","path");

现在我正在使用基于 API(ml 包)2.2.0 的 Spark 数据集。有什么方法可以使用基于数据集的 API?

加载模型 (Mymodel123)
org.apache.spark.ml.classification.RandomForestClassificationModel newModel =  org.apache.spark.ml.classification.RandomForestClassificationModel.load("sparkcontext","path");

没有 public API 可以做到这一点,但是你 RandomForestModels 包装旧的 mllib API 和 provide private methods 可以用于将 mllib 模型转换为 ml 模型:

/** Convert a model from the old API */
private[ml] def fromOld(
    oldModel: OldRandomForestModel,
    parent: RandomForestClassifier,
    categoricalFeatures: Map[Int, Int],
    numClasses: Int,
    numFeatures: Int = -1): RandomForestClassificationModel = {
  require(oldModel.algo == OldAlgo.Classification, "Cannot convert RandomForestModel" +
    s" with algo=${oldModel.algo} (old API) to RandomForestClassificationModel (new API).")
  val newTrees = oldModel.trees.map { tree =>
    // parent for each tree is null since there is no good way to set this.
    DecisionTreeClassificationModel.fromOld(tree, null, categoricalFeatures)
  }
  val uid = if (parent != null) parent.uid else Identifiable.randomUID("rfc")
  new RandomForestClassificationModel(uid, newTrees, numFeatures, numClasses)
}

所以也不是不可能。在 Java 中,您可以直接使用它(Java 不考虑包私有修饰符),在 Scala 中,您必须将适配器代码放在 org.apache.spark.ml 包中。