gpt4 book ai didi

python - 如何访问 Spark RandomForest 中的单个预测?

转载 作者:太空狗 更新时间:2023-10-30 01:13:22 25 4
gpt4 key购买 nike

我希望使用 pyspark.mllib.tree.RandomForest 模块为我的观察获取邻近矩阵。

到目前为止,我的数据小到可以直接加载到内存中。因此,我使用 sklearn.ensemble.RandomForestClassifier 通过以下方式获取邻近矩阵:假设 X 是包含特征的矩阵,Y 是包含标签的向量。我训练了随机森林来区分标签为“0”和标签为“1”的对象。有了训练有素的随机森林,我想通过计算两个观测值具有相同最终节点(=叶)的决策树数量来衡量数据集中每对观测值之间的接近度。因此,对于 100 棵决策树,两个观察值之间的接近度度量范围可以从 0(从不落在同一个最终叶子中)到 100(落在所有决策树中的相同最终叶子中)。这个的 python 实现:

import numpy
from sklearn import ensemble

## data
print X.shape, Y.shape # X is a matrix that holds the 4281 features and contains 8562 observations and Y contains 8562 labels
>> (8562, 4281) (8562,)

## train the tree
n_trees = 100
rand_tree = sklearn.ensemble.RandomForestClassifier(n_estimators=n_tress)
rand_tree.fit(X, Y)

## get proximity matrix
apply_mat = rand_tree.apply(X)
obs_num = len(apply_mat)
sim_mat = numpy.eye(obs_num) * len(apply_mat[0]) # max values that they can be similar at = N estimators

for i in xrange(obs_num):
for j in xrange(i, obs_num):
vec_i = apply_mat[i]
vec_j = apply_mat[j]
sim_val = len(vec_i[vec_i==vec_j])
sim_mat[i][j] = sim_val
sim_mat[j][i] = sim_val

sim_mat_norm = sim_mat / len(apply_mat[0])
print sim_mat_norm.shape
>> (8562, 8562)

现在,我处理的数据太大而无法放入内存,因此我决定改用 Spark。我能够加载数据并对其进行拟合,但我没有找到将随机森林“应用”到数据以获得邻近矩阵的方法。有没有办法得到它?(我使用与 Spark 文档中相同的实现:https://spark.apache.org/docs/1.2.0/mllib-ensembles.html#classification):

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])

model = RandomForest.trainClassifier(trainingData, numClasses=2, categoricalFeaturesInfo={},
numTrees=3, featureSubsetStrategy="auto",
impurity='gini', maxDepth=4, maxBins=32)

我也很乐意听到可以解决我的问题的其他想法。谢谢!

最佳答案

PySpark MLlib 模型不提供访问此信息的直接方式。从理论上讲,您可以尝试直接提取模型并为每棵树单独预测:

from pyspark.mllib.tree import DecisionTreeMode

numTrees = 3
trees = [DecisionTreeModel(model._java_model.trees()[i])
for i in range(numTrees)]

predictions = [t.predict(testData) for t in trees]

但最好改用 ML 模型:

from pyspark.ml.feature import StringIndexer
from pyspark.ml.classification import RandomForestClassifier

df = sqlContext.read.format("libsvm").load("data/mllib/sample_libsvm_data.txt")

indexer = StringIndexer(inputCol="label", outputCol="indexed").fit(df)
df_indexed = indexer.transform(df)

model = RandomForestClassifier(
numTrees=3, maxDepth=2, labelCol="indexed", seed=42
).fit(df_indexed)

并使用rawPredictionprobability 列:

model.transform(df).select("rawPrediction", "probability").show(5, False)

## +---------------------------------------+-----------------------------------------+
## |rawPrediction |probability |
## +---------------------------------------+-----------------------------------------+
## |[0.0,3.0] |[0.0,1.0] |
## |[2.979591836734694,0.02040816326530612]|[0.9931972789115647,0.006802721088435374]|
## |[2.979591836734694,0.02040816326530612]|[0.9931972789115647,0.006802721088435374]|
## |[2.979591836734694,0.02040816326530612]|[0.9931972789115647,0.006802721088435374]|
## |[2.979591836734694,0.02040816326530612]|[0.9931972789115647,0.006802721088435374]|
## +---------------------------------------+-----------------------------------------+

注意:如果您认为您的数据需要 Spark,那么构建全距离/相似度矩阵不太可能是个好主意。只是说。

关于python - 如何访问 Spark RandomForest 中的单个预测?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35523065/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com