Bry*_*yan 14 random-forest apache-spark pyspark apache-spark-mllib
我正在尝试提取我使用PySpark训练的随机森林对象的要素重要性.但是,我没有看到在文档中的任何地方执行此操作的示例,也不是RandomForestModel的方法.
如何从RandomForestModelPySpark中的回归器或分类器中提取要素重要性?
以下是文档中提供的示例代码,以帮助我们开始; 但是,没有提到其中的特征重要性.
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)
Run Code Online (Sandbox Code Playgroud)
我没有看到model.__featureImportances_可用的属性 - 我在哪里可以找到它?
tit*_*o89 14
更新版本> 2.0.0
从2.0.0版本,你可以看到这里,FeatureImportances可用于随机森林.
事实上,你可以在这里找到:
DataFrame API支持两种主要的树集合算法:随机森林和梯度提升树(GBT).两者都使用spark.ml决策树作为基础模型.
用户可以在MLlib Ensemble指南中找到有关集合算法的更多信息.在本节中,我们将演示用于集合的DataFrame API.
此API与原始MLlib合奏API之间的主要区别是:
- 支持DataFrames和ML Pipelines
- 分类与回归的分离
- 使用DataFrame元数据来区分连续和分类功能
- 随机森林的更多功能:特征重要性的估计,以及用于分类的每个类(也称为类条件概率)的预测概率.
如果要使用功能重要性值,则必须使用ml包,而不是mllib,并使用数据帧.
下面是一个例子,你可以在这里找到:
# IMPORT
>>> import numpy
>>> from numpy import allclose
>>> from pyspark.ml.linalg import Vectors
>>> from pyspark.ml.feature import StringIndexer
>>> from pyspark.ml.classification import RandomForestClassifier
# PREPARE DATA
>>> df = spark.createDataFrame([
... (1.0, Vectors.dense(1.0)),
... (0.0, Vectors.sparse(1, [], []))], ["label", "features"])
>>> stringIndexer = StringIndexer(inputCol="label", outputCol="indexed")
>>> si_model = stringIndexer.fit(df)
>>> td = si_model.transform(df)
# BUILD THE MODEL
>>> rf = RandomForestClassifier(numTrees=3, maxDepth=2, labelCol="indexed", seed=42)
>>> model = rf.fit(td)
# FEATURE IMPORTANCES
>>> model.featureImportances
SparseVector(1, {0: 1.0})
Run Code Online (Sandbox Code Playgroud)
我必须让您感到失望,但是没有计算RandomForest的MLlib实现中的功能重要性,因此您不能从任何地方获取它们,除非通过自己实现它们的计算。
找出方法如下:
您RandomForest.trainClassifier在此处调用定义的函数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计算算法)
| 归档时间: |
|
| 查看次数: |
17789 次 |
| 最近记录: |