【发布时间】:2016-06-02 01:47:19
【问题描述】:
我希望使用 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)
我也很高兴听到其他可以解决我问题的想法。 谢谢!
【问题讨论】:
标签: python apache-spark pyspark apache-spark-mllib random-forest