我在使用sklearn在Python中训练一个随机森林分类器,用于图像数据语料库。由于我在进行图像分割,我需要存储每个像素的数据,这最终会变成一个巨大的矩阵,比如一个包含1亿个数据点的长矩阵。因此,当我在这个矩阵上运行RF分类器时,我的电脑会出现内存溢出错误,并且运行时间非常长。
我有一个想法,就是在数据集的顺序小批量上训练分类器,这样最终可以训练整个数据集,但每次都能改进分类器的拟合。这种方法可行吗?每次运行时,拟合会覆盖上一次的拟合吗?
回答:
你可以使用warm_start
来预计算树:
# 首先在X1, y1上构建100棵树clf = RandomForestClassifier(n_estimators=100, warm_start=True)clf.fit(X1, y1)# 在X2, y2上构建额外的100棵树clf.set_params(n_estimators=200)clf.fit(X2, y2)
或者
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 rfdef combine_rfs(rf_a, rf_b): rf_a.estimators_ += rf_b.estimators_ rf_a.n_estimators = len(rf_a.estimators_) return rf_aX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.33)# 创建'n'个随机森林分类器rf_clf = [generate_rf(X_train, y_train, X_test, y_test) for i in range(n)]# 合并分类器rf_clf_combined = reduce(combine_rfs, rfs)