Bagging的核心在于自助采样(bootstrap)这一概念,即有放回的从数据集中进行采样 Bagging是一种降低方差的技术:Var(x)=1/n*(方差),抽样的次数n越大,方差越小 测试误差中,方差越小,偏差越大,当方差的减小大于偏差的增大,可以满足测试误差减小。(通过不同的采样增加模型的差异性,所以偏差会增大) 随机森林和bagging的区别:随机森林不仅对样本进行采样,还要对特征进行采样。
from sklearn import datasets
import pandas as pd
import numpy as np
iris = datasets.load_iris()
X = iris.data
y = iris.target
feature = iris.feature_names
data = pd.DataFrame(X,columns=feature)
data['target'] = y
from sklearn.linear_model import LogisticRegression
log_iris = LogisticRegression()
log_iris.fit(X,y)
log_iris.score(X,y)
from numpy import mean
from numpy import std
from sklearn.datasets import make_classification
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import RepeatedStratifiedKFold
from sklearn.ensemble import BaggingClassifier
model = BaggingClassifier()
n_scores = cross_val_score(model, X, y, scoring='accuracy', cv=cv, n_jobs=-1, error_score='raise')
print('Accuracy: %.3f (%.3f)' % (mean(n_scores), std(n_scores)))
结果: 用鸢尾花数据:
log: 0.9733333333333334 bagging:0.949 (0.051)
用随机生成数据:
log: 0.849 bagging:0.857 (0.037)
和数据有关?不一定自主采样后的方差减小量一定大于偏差?
|