树基模型适合用于集成,主要是因为他们对于训练数据中的变换特别灵敏,使用子控件抽样(subspace sampling)的树状模型会非常有效率,并且其模型更具备多样性,因为集成的每个模型只工作于子集,这样就减少了训练时间。在该集成中,每棵树都使用了特征的不同的随机子集,因此被称为随机森林(random forest)。
随机森林对对实例空间的分裂式森林中每棵树各自分裂的交集,这种方式要比任何一个树单独分裂要好。另外,随机森林也可以反向分裂成为一棵单独的树,因为每个交集都相当于两棵不同树分支的结合。随机森林本质上可以被认为是对树基模型的另一种训练算法。
在bagging集成中的线性分类器能够学习复杂的决策边界,而这对于单一的线性分类器则是不可能的。sklearn.ensemble模块有两种基于决策树的算法——随机森林和极端随机树。他们都是在其构造中引入随机性而创建出多样化的分类器。同时包含了分类和回归,下面我们来学习其中的极端随机树。
极端随机树:与随机森林一样,极端随机数(extra trees)方法使用了特征的随机子集但是并没有使用最有区分的阈值,而是使用了随机产生的阈值集合中的最优者。该方式以微小的增加偏差为代价减少了方差。
sklearn.ensenble模块有两个极端随机树的实现类——ExtraTreesClassifier类和ExtraTreesRegressior类。下面我们来看一个使用了随机森林分类器和极端随机树分类器的例子——该例子使用了VotingClassifier来组合不同的分类器。有助于平衡单个模型的弱点。对应的代码如下:
from sklearn.linear_model import LogisticRegression
import numpy as np
from sklearn import cross_validation
import matplotlib.pyplot as plt
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_breast_cancer
from sklearn.datasets import make_classification
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.ensemble import VotingClassifier
def voting_class(w1, w2, w3, w4):
x, y = make_classification(n_features=15, n_informative=4, n_samples=800,
n_clusters_per_class=5)
x_train, x_test, y_train, y_test = cross_validation.train_test_split(x, y, test_size=0.3)
clf1 = LogisticRegression(random_state=150)
clf2 = GaussianNB()
clf3 = RandomForestClassifier(n_estimators=15, bootstrap=True, random_state=150)
clf4 = ExtraTreesClassifier(n_estimators=15, bootstrap=True, random_state=150)
clfes = [clf1, clf2, clf3, clf4]
voting_clf = VotingClassifier(estimators=[('lr', clf1), ('gnb', clf2), ('rfc', clf3),
('extra', clf4)], voting = 'soft',
weights = [w1, w2, w3, w4])
for c in (clf1, clf2, clf3, clf4, voting_clf):
c.fit(x_train, y_train)
N=5
ind = np.arange(N)
width = 0.3
fig, ax = plt.subplots()
for i, clf in enumerate(clfes):
print(clf, i)
p1 = ax.bar(i+width, clfes[i].score(x_train, y_train,), width=width, color="black")
p2 = ax.bar(i+width, clfes[i].score(x_test, y_test,), width=width, color="gray")
#将各种分数可视化并打印出对应的测试分时和训练分数
print("极端随机树对应的训练分数为:{:.3f}".format(voting_clf.score(x_train, y_train,)))
ax.bar(len(clfes)+width, voting_clf.score(x_train, y_train,), width=width,
color="green")
print("极端随机树对应的测试分数为:{:.3f}".format(voting_clf.score(x_test, y_test,)))
ax.bar(len(clfes)+width*2, voting_clf.score(x_test, y_test,), width=width,
color="gray")
plt.axvline(3.8, color='k', line)
ax.set_xticks(ind + width)
ax.set_xticklabels(['LogisticRegression', 'GaussianNB', 'RandomForestClassifier',
'ExtraTrees', 'VotingClassifier'], rotation=40, ha='right')
plt.title('Training and test score for diffient classifiers')
plt.legend([p1[0], p2[0]], ['training', 'test'], loc='lower left')
plt.show()
voting_class(2, 4, 5, 8)
运行后对应的结果如下:
极端随机树对应的训练分数为:0.991
极端随机树对应的测试分数为:0.758
各种算法对应的测试和训练分数
这里,我们对函数传入了四个权重,这些权重决定了每个单独模型对整体结果的贡献,我们可以看到,这两个树状模型对训练数据集都过度拟合(训练的分很高,但是测试得分很低),但是对测试数据表现较好。另外,极端特征树在这里要稍逊于随机森林,而votingclassifier要优于以上几种情况的分类器。
依据特征所贡献的期望的样本比例,树状模型可用来对特征的相对排名进行评估。我们使用一种树状模型来估计每一种特征在分类任务中的重要性,特征在树中所出现的相对位置决定了其相对重要性。位于树顶端的特征对树的决策的贡献率更大。
我们在来看一个人脸识别的例子,该例子使用ExtraTreesClassifier来评估特征的重要性:
from sklearn.datasets import fetch_olivetti_faces
data = fetch_olivetti_faces()
def test_face_importance(n_estimators=800, max_features=150, n_jobs=-1, random_state=0):
x = data.images.reshape((len(data.images), -1))
y = data.target
extra_forest = ExtraTreesClassifier(n_estimators, max_features=max_features, n_jobs=n_jobs,
random_state=random_state)
extra_forest.fit(x, y)
dstring = "scores=%d..." %n_jobs + "features=%s..." %max_features + "estimators=%d..."%n_estimators + "random=%d" %random_state
print(dstring)
importances = extra_forest.feature_importances_
importances = importances.reshape(data.images[0].shape)
plt.matshow(importances, cmap=plt.cm.hot)
plt.title(dstring)
plt.show()
test_face_importance()
运行上述代码结果如下:
极端随机树用于在人脸识别中评估特征重要性
该代码使用的数据集由10幅图组成,每幅图中有40个人的头像,一共有400个头像,每个头像都有标识了其身份。每个橡树都表示一个特征,所以在输出的时候,亮度标识了特征的重要性(如果像素点月亮则表示特征越重要),所以我们可以看出,眼睛上面及额头部分对于这些图片来说,是很重要的特征(在这些照片中,说明这部分能够体现出每个人的不同细节)。
本文来自投稿,不代表本人立场,如若转载,请注明出处:http://www.sosokankan.com/article/1687340.html