集成方法
优点:
集成方法的目标是将多个基本估计器的预测与给定的学习算法相结合,从而提高对单个估计器的通用性(泛化能力)。
将多个估计器的预测与给定的学习算法相结合,从而提高对单个估计其的通用性。
- bagging 每个预测器使用算法相同,但是在不同的训练集上进行训练,采样时如果将样本不放回叫做bagging.
- 有放回的叫做pasting。
极端随机树
随机森林在分裂结点的时候,仅考虑到一个随机子集所包含的特征它的阈值是通过搜索得出的最佳阈值。而极端随机树采用的是每个特征采用随机阈值,那么可以来判断随机森林训练起来比常规随机森林要快很多。
算法比较:通常两种算法不好来确定谁好谁坏,一般是通过交叉验证进行比较。
下面例子展示了使用ExtraTrespassingClassifier模型对人脸识别任务中每个像素的相对重要性进行颜色编码:
print(__doc__)
from time import time
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_olivetti_faces
from sklearn.ensemble import ExtraTreesClassifier
# Number of cores to use to perform parallel fitting of the forest model
n_jobs = 1
# Load the faces dataset
data = fetch_olivetti_faces()
X = data.images.reshape((len(data.images), -1))
y = data.target
mask = y < 5 # Limit to 5 classes
X = X[mask]
y = y[mask]
# Build a forest and compute the pixel importances
print("Fitting ExtraTreesClassifier on faces data with %d cores..." % n_jobs)
t0 = time()
forest = ExtraTreesClassifier(n_estimators=1000,
max_features=128,
n_jobs=n_jobs,
random_state=0)
forest.fit(X, y)
print("done in %0.3fs" % (time() - t0))
importances = forest.feature_importances_
importances = importances.reshape(data.images[0].shape)
# Plot pixel importances
plt.matshow(importances, cmap=plt.cm.hot)
plt.title("Pixel importances with forests of trees")
plt.savefig(r'C:\Users\lenovo\Desktop\04.png', dpi=400, bbox_inches='tight')
plt.show()
%matplotlib inline
特征越重要的像素点越红。
DecisionTree+Bagging/Pasting−>RandomforestRandomforest+otherClassifiers−>VotingClassifier Decision Tree + Bagging/Pasting - > Randomforest \\ Randomforest + other Classifiers - > VotingClassifier DecisionTree+Bagging/Pasting−>RandomforestRandomforest+otherClassifiers−>VotingClassifier
BaggingClassifier
参数
- base_estimator : 适用于数据集的基本估计量(一般是放几个决策树),如果没有会默认为一个决策树。
- n_estimators 决策树的个数。
- max_samples 从X中抽取的样本数,用于训练每个基本估计值。
- bootstrap :是否放回抽样,默认选择为True放回抽样。
- oob_score:是否采用包外误差来估计误差。
- warm_sart: 是否保留上次操作后的数据。
属性 - class_ : 类的标签。
- n_class_ : 类的数量。
- oob_score: 使用包外估计获得的训练数据集的得分。
- estimators_: 拟合基估计的集合。
方法 - decision_function 决策函数的每个实例属于每个类别的概率(随机森林有很多的树,统计每个实例在同一个类到数量在除以总的树的数量)。
- predict_prob :预测X的类概率。
- score 返回给定测试数据和标签的平均准确度。
- obb_score_ 使用保外评估分数。
下图为分别用决策树,和随机深林做分裂图。
决策树:
随机森林:
Voting
思想概念为:将概念上不同的机器学习分类器组合起来,使用对数投票或平均预测概率来预测类标签, 这样的分类器对一组性能相同的模型是有用的,以便平衡它们各自的弱点。
根据投票多的选择类别(硬投票)
- voting = “hard”.
使用案例:
>>> from sklearn import datasets
>>> from sklearn.model_selection import cross_val_score
>>> from sklearn.linear_model import LogisticRegression
>>> from sklearn.naive_bayes import GaussianNB
>>> from sklearn.ensemble import RandomForestClassifier
>>> from sklearn.ensemble import VotingClassifier
>>> iris = datasets.load_iris()
>>> X, y = iris.data[:, 1:3], iris.target
>>> clf1 = LogisticRegression(solver='lbfgs', multi_class='multinomial',
... random_state=1)
>>> clf2 = RandomForestClassifier(n_estimators=50, random_state=1)
>>> clf3 = GaussianNB()
>>> eclf = VotingClassifier(estimators=[('lr', clf1), ('rf', clf2), ('gnb', clf3)], voting='hard')
>>> for clf, label in zip([clf1, clf2, clf3, eclf], ['Logistic Regression', 'Random Forest', 'naive Bayes', 'Ensemble']):
... scores = cross_val_score(clf, X, y, cv=5, scoring='accuracy')
... print("Accuracy: %0.2f (+/- %0.2f) [%s]" % (scores.mean(), scores.std(), label))
#Accuracy: 0.95 (+/- 0.04) [Logistic Regression]
#Accuracy: 0.94 (+/- 0.04) [Random Forest]
#Accuracy: 0.91 (+/- 0.04) [naive Bayes]
#Accuracy: 0.95 (+/- 0.04) [Ensemble]
参数分析:- estimators : list of tuples (string, estimator) :string的作用是用来调参数时可以通过self.setparams_ + ‘string’ .set_params()调参数。
上面用到的voting = ‘hard’。进行多数决定投票,否则如果‘软’则根据概率和的argmax预测类标签,这是推荐用于校准良好的分类器集成。
- weight
加权序列,对预测类标记签出现的概率进行加权,如果没有,则使用同一的权重,可用列表实现。
由于下面的参数介绍的比较抽象,引入新的实例:
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble import RandomForestClassifier, VotingClassifier
clf1 = LogisticRegression(solver='lbfgs', multi_class='multinomial',
random_state=1)
clf2 = RandomForestClassifier(n_estimators=50, random_state=1)
clf3 = GaussianNB()
X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
y = np.array([1, 1, 1, 2, 2, 2])
eclf1 = VotingClassifier(estimators=[
('lr', clf1), ('rf', clf2), ('gnb', clf3)], voting='hard')
eclf1 = eclf1.fit(X, y)
print(eclf1.predict(X))
#[1 1 1 2 2 2]
np.array_equal(eclf1.named_estimators_.lr.predict(X),
eclf1.named_estimators_['lr'].predict(X))
#True
可得Voting中的选择器相当于是Class Voting.named_estimators.string或则是named_estimators_[‘string’]
**Methods
- fit_trainsfrom(self, X, y=None, **fit_params)
Parameters: X: Training set
shape[n_samples, n_features]
y:Target values shape[n_samples]
软投票
classifier | class1 | class2 | class3 |
---|---|---|---|
classifier 1 | w1*0.2 | w2*0.5 | w1*0.3 |
classifier 2 | w2*0.6 | w2*0.3 | w2*0.3 |
classifier 3 | w3*0.3 | w3*0.4 | w3*0.3 |
weighted average | 0.37 | 0.4 | 0.23 |
给的权重占比是相同的。
w1 = w2 = w3 = 1 .
使用的时一些细节:
iris = datasets.load_iris()
X = iris.data[:, [0, 2]]
y = iris.target
# Training classifiers
clf1 = DecisionTreeClassifier(max_depth=4)
clf2 = KNeighborsClassifier(n_neighbors=7)
clf3 = SVC(gamma='scale', kernel='rbf', probability=True)
eclf = VotingClassifier(estimators=[('dt', clf1), ('knn', clf2), ('svc', clf3)],voting='soft', weights=[2, 1, 2])
clf1 = clf1.fit(X, y)
clf2 = clf2.fit(X, y)
clf3 = clf3.fit(X, y)
eclf = eclf.fit(X, y)
SVC原本是没有概率,这里我们要加入probability部分让他有概率输出。
f, axarr = plt.subplots(2, 2, sharex='col', sharey='row', figsize=(10, 8))
for idx, clf, tt in zip(product([0, 1], [0, 1]),//product会产生一个笛卡尔元组,(0, 0), (0, 1), (1, 0), (1, 1)
[clf1, clf2, clf3, eclf],
['Decision Tree (depth=4)', 'KNN (k=7)',
'Kernel SVM', 'Soft Voting']):
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
axarr[idx[0], idx[1]].contourf(xx, yy, Z, alpha=0.4)
axarr[idx[0], idx[1]].scatter(X[:, 0], X[:, 1], c=y,
s=20, edgecolor='k')
axarr[idx[0], idx[1]].set_title(tt)
== Attation:当使用软投票时:每个评价函数都应该有predict-prob方法,因为软投票估计的概率==