我正在尝试提取我使用PySpark训练的随机森林对象的要素重要性 . 但是,我没有看到在文档中的任何地方执行此操作的示例,也不是RandomForestModel的方法 .
如何从PySpark中的 RandomForestModel
回归量或分类器中提取要素重要性?
以下是文档中提供的示例代码,以帮助我们开始;但是,没有提到其中的特征重要性 .
from pyspark.mllib.tree import RandomForest
from pyspark.mllib.util import MLUtils
# Load and parse the data file into an RDD of LabeledPoint.
data = MLUtils.loadLibSVMFile(sc, 'data/mllib/sample_libsvm_data.txt')
# Split the data into training and test sets (30% held out for testing)
(trainingData, testData) = data.randomSplit([0.7, 0.3])
# Train a RandomForest model.
# Empty categoricalFeaturesInfo indicates all features are continuous.
# Note: Use larger numTrees in practice.
# Setting featureSubsetStrategy="auto" lets the algorithm choose.
model = RandomForest.trainClassifier(trainingData, numClasses=2, categoricalFeaturesInfo={},
numTrees=3, featureSubsetStrategy="auto",
impurity='gini', maxDepth=4, maxBins=32)
我没有看到 model.__featureImportances_
属性可用 - 我在哪里可以找到它?
5 回答
UPDATE for version > 2.0.0
从版本2.0.0开始,如您所见here,FeatureImportances可用于随机森林 .
事实上,你可以找到here:
如果要使用功能重要性值,则必须使用ml包,而不是mllib,并使用数据帧 .
下面是一个例子,你可以找到here:
我不得不让你失望,但是在MLFib实现的RandomForest中的特征重要性只是没有计算出来,所以你不能从任何地方获取它们,除非你自己实现它们的计算 .
以下是如何找到它:
你在这里调用函数
RandomForest.trainClassifier
deinfed https://github.com/apache/spark/blob/branch-1.3/python/pyspark/mllib/tree.py它调用
callMLlibFunc("trainRandomForestModel", ...)
,这是对Scala函数RandomForest.trainClassifier
或RandomForest.trainRegressor
(取决于算法)的调用,它返回RandomForestModel
对象 .此对象在https://github.com/apache/spark/blob/branch-1.3/mllib/src/main/scala/org/apache/spark/mllib/tree/model/treeEnsembleModels.scala中描述,并且在同一源文件中定义的
TreeEnsembleModel
扩展 . 不幸的是,这个类只存储算法(回归或分类),树本身,树的相对权重和组合策略(总和,平均,投票) . 遗憾的是,它不存储要素重要性,甚至不计算它们(有关计算算法,请参阅https://github.com/apache/spark/blob/branch-1.3/mllib/src/main/scala/org/apache/spark/mllib/tree/RandomForest.scala)功能重要性现在在Spark 1.5中实现 . See resolved JIRA issue.您可以通过以下方式获取要素重要性向量:
我相信这现在有效 . 你可以打电话:
在RandomForestClassifier上运行拟合会返回一个RandomForestClassificationModel,它具有所需的featureImportances计算结果 . 我希望这个对你有用 : )
如上所述,未实现特征重要性 .
也许这对你有用:https://github.com/wxhC3SC6OPm8M1HXboMy/spark-ml/blob/master/FeatureSelection.scala