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

Python 在scikit学习中结合随机森林模型,python,python-2.7,scikit-learn,classification,random-forest,Python,Python 2.7,Scikit Learn,Classification,Random Forest,我有两个分类器模型,我想把它们组合成一个元模型。他们都使用相似但不同的数据进行训练。我该怎么做 rf1 #this is my first fitted RandomForestClassifier object, with 250 trees rf2 #this is my second fitted RandomForestClassifier object, also with 250 trees 我想创建big\u rf,将所有树合并到一个500树模型中我相信通过修改RandomFor

我有两个分类器模型,我想把它们组合成一个元模型。他们都使用相似但不同的数据进行训练。我该怎么做

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

我想创建
big\u rf
,将所有树合并到一个500树模型中

我相信通过修改RandomForestClassifier对象上的
估计器
n\u估计器
属性,这是可能的。林中的每棵树都存储为DecisionTreeClassifier对象,这些树的列表存储在
estimators\uu
属性中。为了确保不存在不连续性,在
n_估计器
中更改估计器的数量也是有意义的

这种方法的优点是,您可以跨多台机器并行地构建一组小型林,并将它们组合起来

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

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)

除了@mgoldwaser解决方案外,另一种方法是在训练森林时使用
warm\u 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)

当两个数据集具有不同数量的标签时,warm_start似乎不起作用。例如,如果您有(x1,y1),其中y1可以使用3个标签,然后是(x2,y2),其中y2可以使用另一个标签,则使用warm_start进行训练失败。交换顺序仍然会导致错误。@user929404为了指出明显的问题,模型正在numpy数组中的无名列上进行训练。当你开始训练模型时,它会看
y1
来确定要训练多少个特征,而当你继续训练
y2
时,必须有相同数量的特征,因为它无法神奇地理解第一个矩阵的变量如何与第二个矩阵的变量对齐,除非假定它们是相同的。此方法是否会影响所用数据集的顺序?如果有3个数据集,如果他们每次都以不同的顺序接受训练,会有什么区别吗?有没有一种方法可以推广到使用其他模型——逻辑回归、Guasian NB、,SVM@mgoldwasser嗨,我刚读了你们的答案,我有一个更一般的问题。我可以使用长度不同的功能吗?例如,一个可以有300个样品,另一个可以有200个?很抱歉偏离主题,但阅读您的答案,我正在考虑为每个功能构建一个林。rf_a.n_estimators=len(rf_a.estimators)。。犯错误这不应该是,;rf_a.n_估计器+=len(rf_a.n_估计器)?@软件机械代码正确
rf_a.估计器
在前一行中更新,其长度是我们想要的
n_估计器