在scikit中结合随机森林模型学习

时间:2015-02-12 23:11:57

标签: python python-2.7 scikit-learn classification random-forest

我有两个RandomForestClassifier模型,我想将它们组合成一个元模型。他们都使用类似但不同的数据进行培训。我怎么能这样做?

rf1 #this is my first fitted RandomForestClassifier object, with 250 trees
rf2 #this is my second fitted RandomForestClassifier object, also with 250 trees

我想创建big_rf,将所有树组合成一个500树模型

2 个答案:

答案 0 :(得分:19)

我相信通过修改RandomForestClassifier对象上的estimators_n_estimators属性可以实现这一点。林中的每个树都存储为DecisionTreeClassifier对象,这些树的列表存储在estimators_属性中。为了确保没有不连续性,更改n_estimators中的估算器数量也是有意义的。

这种方法的优点是你可以在多台机器上并行构建一堆小型森林并将它们组合起来。

以下是使用虹膜数据集的示例:

from sklearn.ensemble import RandomForestClassifier
from sklearn.cross_validation import train_test_split
from sklearn.datasets import load_iris

def generate_rf(X_train, y_train, X_test, y_test):
    rf = RandomForestClassifier(n_estimators=5, min_samples_leaf=3)
    rf.fit(X_train, y_train)
    print "rf score ", rf.score(X_test, y_test)
    return rf

def combine_rfs(rf_a, rf_b):
    rf_a.estimators_ += rf_b.estimators_
    rf_a.n_estimators = len(rf_a.estimators_)
    return rf_a

iris = load_iris()
X, y = iris.data[:, [0,1,2]], iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.33)
# in the line below, we create 10 random forest classifier models
rfs = [generate_rf(X_train, y_train, X_test, y_test) for i in xrange(10)]
# in this step below, we combine the list of random forest models into one giant model
rf_combined = reduce(combine_rfs, rfs)
# the combined model scores better than *most* of the component models
print "rf combined score", rf_combined.score(X_test, y_test)

答案 1 :(得分:5)

除了@mgoldwasser解决方案之外,另一种方法是在训练森林时使用warm_start。在Scikit-Learn 0.16-dev中,您现在可以执行以下操作:

# First build 100 trees on X1, y1
clf = RandomForestClassifier(n_estimators=100, warm_start=True)
clf.fit(X1, y1)

# Build 100 additional trees on X2, y2
clf.set_params(n_estimators=200)
clf.fit(X2, y2)