随机森林是由Leo Breiman和 Adele Cutler发展的分类和回归算法,使用了大量的决策树模型,从而通过降低估计的偏差和方差来提高精确的预测。
作为开箱即用的算法,随机森林算法的执行步骤主要如下:
- 创建大量决策树,每棵树之间都不一样,基于观察点和变量的不同子集。
- 为每棵树用自助法(bootstrap)来采样观察数据集(用置换法从原始数据采样)。相同的观察点可以在相同的数据集出现多次
- 为每棵树随机选择并仅适用一部分变量。
- 适用由采样所排除的管擦点来估计每棵树的性能。
- 在全部数据被拟合和预测后,获取最终预测,即为回归估计的平均值或用于预测的最频繁类。
一、使用随机森林分类器
#使用bagging 模仿随机森林
#载入手写数字数据集
from sklearn.datasets import load_digits
digit = load_digits()
X, y = digit.data, digit.target
from sklearn.ensemble import RandomForestClassifier
from sklearn.cross_validation import cross_val_score
from sklearn.cross_validation import KFold
crossvalidation = KFold(n=X.shape[0], n_folds=5, shuffle=True, random_state=1)
RF_cls = RandomForestClassifier(n_estimators=300)
score = np.mean(cross_val_score(RF_cls, X, y, scoring='accuracy', cv=crossvalidation, n_jobs=1))
print ('Accuracy: %.3f' % score)
![]()
结果显示准确度相当高,n-estimators=300
如果想进一步提高模型精度,可画出精确度与评估器的曲线,选择合适的评估器个数
#求训练得分和测试得分
from sklearn.learning_curve import validation_curve
train_scores, test_scores = validation_curve(RF_cls, X, y,
'n_estimators', param_range=[10,50,100,200,300,500,800,1000,1500],
cv=crossvalidation, scoring='accuracy', n_jobs=1)
print ('mean cv accuracy %s' % np.mean(test_scores,axis=1))
#作图
import matplotlib.pyplot as plt
mean_test = np.mean(test_scores,axis=1)
#plt.plot([10,50,100,200,300,500,1000],mean_train,'ro--', label='Training')
plt.plot([10,50,100,200,300,500,800,1000,1500],mean_test,'bD-.', label='Cross-validation')
plt.grid()
plt.xlabel('Number of estimators') # adds label to x axis
plt.ylabel('accuracy') # adds label to y axis
plt.legend(loc='lower right', numpoints= 1)
plt.show()

可以看出500由于400/300和600,1000最优,优于1500.
二、使用随机森林回归器工作
from sklearn.datasets import load_digits
digit = load_digits()
X, y = boston.data, boston.target
from sklearn.ensemble import RandomForestRegressor
RF_rg = RandomForestRegressor (n_estimators=300, random_state=1)
crossvalidation = KFold(n=X.shape[0], n_folds=5, shuffle=True, random_state=1)
score = np.mean(cross_val_score(RF_rg, X, y, scoring='neg_mean_squared_error', cv=crossvalidation, n_jobs=1))
print ('Mean squared error: %.3f' % abs(score))
![]()
均方差为12.028,训练效果较好。
三、优化随机森林算法
from sklearn.ensemble import RandomForestClassifier
X, y = digit.data, digit.target
crossvalidation = KFold(n=X.shape[0], n_folds=5, shuffle=True, random_state=1)
RF_cls = RandomForestClassifier(n_estimators=300)
scorer = 'accuracy'
RF_cls.fit(X,y)
#X = RF_cls.fit_transform(X)
#print (X.shape)
#print (RF_cls.feature_importances_)
from sklearn import grid_search
search_grid = {'max_features': [21, 'sqrt', 'log2', 'auto'], 'min_samples_leaf': [1, 2, 10, 30]}
search_func = grid_search.GridSearchCV(estimator=RF_cls, param_grid=search_grid, scoring=scorer, n_jobs=1, cv=crossvalidation)
search_func.fit(X,y)
print ('Best parameters: %s' % search_func.best_params_)
print ('Best accuracy: %.3f' % search_func.best_score_)
![]()
结果显示:max_features=sqrt(也就是平方根),min_samples_leaf=1

2万+



被折叠的 条评论
为什么被折叠?



