本文是对随机森林的总结。random forest,gbdt,xgboost可谓kaggle比赛的三剑客,在保持优秀的bias的基础上,有效地降低了variance,表现十分优秀。随机森林属于集成学习方法,可用于分类与回归,通过训练众多决策树,输出多数类别(分类问题)或预测均值(回归问题)。随机森林纠正了单颗决策树易过拟合的缺点。
随机森林基于bagging建树,bagging就是有放回的采样。这样采样的结果产生了不同的训练集,进而使得训练的每颗树都存在差异性,从而降低了过拟合的风险。随机森林更进一步,对特征也进行采样,每次只使用部分特征。
有了这些知识,就可以实现一个简单的随机森林了,核心就是采样和建树。下面是采样的代码片段,用到了numpy.random.choice,实现有放回采样。完整实现代码地址lxmly/machine-learning
def _sampling(self, X, y, sub_n_features, bootstrap=True):
"""样本和特征采样
这里仿照scikit-learn的设计
The sub-sample size is always the same as the original input sample size
but the samples are drawn with replacement if bootstrap=True (default)
"""
#横向连接,方便切割
X_y = np.concatenate((X, y.reshape((1, len(y))).T), axis=1)
n_samples = X_y.shape[0]
n_features = X_y.shape[1]
sub_samples = n_samples
if not bootstrap:
sub_samples = sub_samples // 2
#样本采样 纵向
sample_index = np.random.choice(range(n_samples), size=sub_samples, replace=bootstrap)
#特征采样 横向
feature_index = np.random.choice(range(n_features), size=sub_n_features, replace=False)
X_y = X_y[sample_index]
return X_y[:, :-1], X_y[:,-1], feature_index