首页 > 解决方案 > 将特征重要性向量压缩到列名数组时,Scala java.io toArray 错误

问题描述

当试图将特征重要性向量从 lightGBM 压缩getfeatureImportances到列名数组时,我遇到了以下错误:

import com.microsoft.ml.spark.LightGBMClassificationModel
import org.apache.spark.ml.classification.RandomForestClassificationModel

def getFeatureImportances(inputContainer: PipelineModelContainer): (String, String) = {
    val transformer = inputContainer.pipelineModel.stages.last

    val featureImportancesVector = inputContainer.params match {
        case RandomForestParameters(numTrees, treeDepth, featureTransformer) =>
            transformer.asInstanceOf[RandomForestClassificationModel].featureImportances
        case LightGBMParameters(treeDepth, numLeaves, iterations, featureTransformer) => 
            transformer.asInstanceOf[LightGBMClassificationModel].getFeatureImportances("split")
    }

    val colNames = inputContainer.featureColNames
    val sortedFeatures = (colNames zip featureImportancesVector.toArray).sortWith(_._2 > _._2).zipWithIndex
}

参考我的代码的最后一行,我收到此错误:

value toArray is not a member of java.io.Serializable

似乎轻 GBM 特征重要性不能转换为数组。如果它只是 randomForestClassifier 功能的重要性,则此代码可以正常工作。我还能做什么?

标签: javascalaapache-sparkjava-iolightgbm

解决方案


在该match块的两个分支中,一个返回Array[Double],另一个返回Vector

这两种类型的共同超类型是java.io.Serializable,因此 Scala 将变量的类型推断为该类型featureImportancesVectortoArray尽管该方法在这两种情况下都存在,但在该类型中不可用。

要解决这个问题很容易,正如评论中所建议的那样,将 移动.toArrayfeatureImportances,以便两个分支的类型以及变量的类型变为Array[Double]


推荐阅读