随机森林(random forest)是之前我们学习的决策树的集成,因此我们用森林来称呼。随机森林的思想也不复杂,但是表现却非常好。
通过这一课,您将会:
1、认识随机森林;
2、学会使用sklearn操作随机森林;
3、明白随机森林和神经网络的应用区别。
随机森林
如果说我们怕一棵决策树有“偏见”,那么就可以通过建造一个森林,这个森林是由一棵棵决策树组成的,然后我们给每颗决策树棵“随机”分配数据去训练。最后综合整个森林的结果来做判断,从而达到在决策树的基础上进一步提高算法表现的目的。
随机森林算法大致分为4个步骤:
通过自助法(bootstrap)构建大小为n的一个训练集,即重复抽样选择n个训练样例
对于刚才新得到的训练集,构建一棵决策树。在每个节点执行操作:通过不重复抽样选择d个特征;利用上面的d个特征,选择某种度量分割节点
重复步骤1和2,k次
对于每一个测试样例,对k颗决策树的预测结果进行投票。票数最多的结果就是随机森林的预测结果。
在训练时,随机森林中的每棵树都会从数据点的随机样本中学习。样本被有放回的抽样,称为自助抽样法(bootstrapping),这意味着一些样本将在一棵树中被多次使用。背后的想法是在不同样本上训练每棵树,尽管每棵树相对于特定训练数据集可能具有高方差,但总体而言,整个森林将具有较低的方差,同时不以增加偏差为代价。
在实际运用随机森林模型时,树的数目(k)需要好好调参。一般,k越大,随机森林的性能越好,当然计算成本也越高。
样本大小n能够控制bias-variance平衡,如果n很大,我们就减小了随机性因此随机森林就容易过拟合。另一方面,如果n很小,虽然不会过拟合,但模型的性能会降低。
随机森林的优点:
优秀的分类表现
扩展性
使用简单
代码实现
我们继续使用sklearn来实现随机森林:
from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt
import warnings
def versiontuple(v):
return tuple(map(int, (v.split("."))))
def plot_decision_regions(X, y, classifier, test_idx=None, resolution=0.02):
# setup marker generator and color map
markers = ('s', 'x', 'o', '^', 'v')
colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
cmap = ListedColormap(colors[:len(np.unique(y))])
# plot the decision surface
x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
np.arange(x2_min, x2_max, resolution))
Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
Z = Z.reshape(xx1.shape)
plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap)
plt.xlim(xx1.min(), xx1.max())
plt.ylim(xx2.min(), xx2.max())
for idx, cl in enumerate(np.unique(y)):
plt.scatter(x=X[y == cl, 0],
y=X[y == cl, 1],
alpha=0.6,
c=cmap(idx),
edgecolor='black',
marker=markers[idx],
label=cl)
# highlight test samples
if test_idx:
# plot all samples
if not versiontuple(np.__version__) >= versiontuple('1.9.0'):
X_test, y_test = X[list(test_idx), :], y[list(test_idx)]
warnings.warn('Please update to NumPy 1.9.0 or newer')
else:
X_test, y_test = X[test_idx, :], y[test_idx]
plt.scatter(X_test[:, 0],
X_test[:, 1],
c='',
alpha=1.0,
edgecolor='black',
linewidths=1,
marker='o',
s=55, label='test set')
from sklearn import datasets
import numpy as np
iris = datasets.load_iris()
X = iris.data[:, [2, 3]]
y = iris.target
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=0)
X_combined = np.vstack((X_train, X_test))
y_combined = np.hstack((y_train, y_test))
from sklearn.ensemble import RandomForestClassifier
forest = RandomForestClassifier(criterion='entropy',
n_estimators=10,
random_state=1,
n_jobs=2)
forest.fit(X_train, y_train)
plot_decision_regions(X_combined, y_combined,
classifier=forest, test_idx=range(105, 150))
plt.xlabel('petal length [cm]')
plt.ylabel('petal width [cm]')
plt.legend(loc='upper left')
plt.tight_layout()
# plt.savefig('./figures/random_forest.png', dpi=300)
plt.show()
运行结果:
对比随机森林和神经网络
python培训班:http://www.baizhiedu.com/python2019
注释:本文内容来自公众号Python与机器学习之路