1.什么是 bootstraps?
bootstraps中文名称为自助法,是一种有放回的采样方法。其具体采样操作为:在m个样本组成的样本集合内,每次只抽取一个样本,有放回地抽取m次,这样就得到了m个样本组成的采样集合。
引理:D 中的某个样本在自助法采样中不被采到的概率约是 36.8%. 也就是说, 在 D 中大约有 36.8% 的样本未出现在采样数据集 D 中。 证明:对其中任意一个样本,它每次采样都不被抽中的概率为
p
=
m
?
1
m
p=\frac{m-1}{m}
p=mm?1?,因此m次抽样它都不被抽中的概率为
(
1
?
1
m
)
m
(1-\frac{1}{m})^m
(1?m1?)m,取极限得
1
/
e
=
36.8
%
1/e=36.8\%
1/e=36.8%。
自助法在数据集较小, 难以划分训练/验证集时很有用, 训练集大小仍是m. 然而, 自助法产生的数据集 改变了初始数据集分布, 会引入估计偏差. 因此, 当初始数据量足够时, 交叉验证和留出法更常用.
2. bootstraps与 bagging的联系
bootstraps采样是bagging其中必不可少的步骤。
3.什么是 bagging?
Bagging 的基本思路:一种朴素地增加基分类器多样性的方案是用训练集 D 的不同子集训练不同的个体学习器. 但是, 我们同时希望个体学习器不能太差. 如果每个子集互不相交, 则每个集学习器只用到了一小 部分训练数据, 甚至不足以有效学习. 因此, Bagging(boostrap aggregating) 从训练集 D 采样相互有交叠的采样子集。
Bagging 的具体过程包括如下三步.
- 从训练集 D 中由自助法采样得到 T 个采样集
D
1
,
D_1,
D1?,
- 基于自助采样集
D
t
D_t
Dt? 训练基学习器
h
t
h_t
ht?.
- 使用相对多数投票 (分类任务) 或简单平均 (回归任务) 得到
H
H
H
4.随机森林与 bagging的联系与区别。
随机森林 (random forest)是在以决策树为集学习器构建 Bagging 集成 的基础上, 进一步在单变量决策树的训练过程中引入了随机属性选择. 具体地说, 经典单变量决策树是在选择划分属性时是在当前结点的属性集合 (假设有 d 个属性) 中选择一个属性, 而在随机森林中, 对基决策树的每个结点, 先从该结点的属性集合中随机选择一个包含
d
^
\hat{d}
d^ 个属性的子集, 然后再从这个子集中选择一个最优属性用于划分. 这里的参数
d
^
\hat{d}
d^ 控制了随机性的引入程度:若
d
^
=
d
\hat{d}= d
d^=d, 基决策树的构建和经典单变量决策树相同; 若
d
^
=
1
\hat{d} = 1
d^=1, 则是随机选一个属性用于划分. 一般情况下, 推荐值
d
^
=
l
g
d
\hat{d}= lg d
d^=lgd
5.使用偏差与方差理论阐述为什么 bagging能提升模型的预测精度
6.请尝试使用 bagging与基本分类模型或者回归模型做对比,观察 bagging是否相对于基础模型的精度有所提高?(必做)
7.假如让你来实现 bagging.你会使用 python+numpy+ sklearn的基础模型来实现 bagging吗?(拓展)
from random import seed
from random import randrange
from csv import reader
def load_csv(filename):
dataset = list()
with open(filename, 'r') as file:
csv_reader = reader(file)
for row in csv_reader:
if not row:
continue
dataset.append(row)
return dataset
def str_column_to_float(dataset, column):
for row in dataset:
row[column] = float(row[column].strip())
def str_column_to_int(dataset, column):
class_values = [row[column] for row in dataset]
unique = set(class_values)
lookup = dict()
for i, value in enumerate(unique):
lookup[value] = i
for row in dataset:
row[column] = lookup[row[column]]
return lookup
def cross_validation_split(dataset, n_folds):
dataset_split = list()
dataset_copy = list(dataset)
fold_size = int(len(dataset) / n_folds)
for i in range(n_folds):
fold = list()
while len(fold) < fold_size:
index = randrange(len(dataset_copy))
fold.append(dataset_copy.pop(index))
dataset_split.append(fold)
return dataset_split
def accuracy_metric(actual, predicted):
correct = 0
for i in range(len(actual)):
if actual[i] == predicted[i]:
correct += 1
return correct / float(len(actual)) * 100.0
def evaluate_algorithm(dataset, algorithm, n_folds, *args):
folds = cross_validation_split(dataset, n_folds)
scores = list()
for fold in folds:
train_set = list(folds)
train_set.remove(fold)
train_set = sum(train_set, [])
test_set = list()
for row in fold:
row_copy = list(row)
test_set.append(row_copy)
row_copy[-1] = None
predicted = algorithm(train_set, test_set, *args)
actual = [row[-1] for row in fold]
accuracy = accuracy_metric(actual, predicted)
scores.append(accuracy)
return scores
def test_split(index, value, dataset):
left, right = list(), list()
for row in dataset:
if row[index] < value:
left.append(row)
else:
right.append(row)
return left, right
def gini_index(groups, classes):
n_instances = float(sum([len(group) for group in groups]))
gini = 0.0
for group in groups:
size = float(len(group))
if size == 0:
continue
score = 0.0
for class_val in classes:
p = [row[-1] for row in group].count(class_val) / size
score += p * p
gini += (1.0 - score) * (size / n_instances)
return gini
def get_split(dataset):
class_values = list(set(row[-1] for row in dataset))
b_index, b_value, b_score, b_groups = 999, 999, 999, None
for index in range(len(dataset[0])-1):
for row in dataset:
groups = test_split(index, row[index], dataset)
gini = gini_index(groups, class_values)
if gini < b_score:
b_index, b_value, b_score, b_groups = index, row[index], gini, groups
return {'index':b_index, 'value':b_value, 'groups':b_groups}
def to_terminal(group):
outcomes = [row[-1] for row in group]
return max(set(outcomes), key=outcomes.count)
def split(node, max_depth, min_size, depth):
left, right = node['groups']
del(node['groups'])
if not left or not right:
node['left'] = node['right'] = to_terminal(left + right)
return
if depth >= max_depth:
node['left'], node['right'] = to_terminal(left), to_terminal(right)
return
if len(left) <= min_size:
node['left'] = to_terminal(left)
else:
node['left'] = get_split(left)
split(node['left'], max_depth, min_size, depth+1)
if len(right) <= min_size:
node['right'] = to_terminal(right)
else:
node['right'] = get_split(right)
split(node['right'], max_depth, min_size, depth+1)
def build_tree(train, max_depth, min_size):
root = get_split(train)
split(root, max_depth, min_size, 1)
return root
def predict(node, row):
if row[node['index']] < node['value']:
if isinstance(node['left'], dict):
return predict(node['left'], row)
else:
return node['left']
else:
if isinstance(node['right'], dict):
return predict(node['right'], row)
else:
return node['right']
def subsample(dataset, ratio):
sample = list()
n_sample = round(len(dataset) * ratio)
while len(sample) < n_sample:
index = randrange(len(dataset))
sample.append(dataset[index])
return sample
def bagging_predict(trees, row):
predictions = [predict(tree, row) for tree in trees]
return max(set(predictions), key=predictions.count)
def bagging(train, test, max_depth, min_size, sample_size, n_trees):
trees = list()
for i in range(n_trees):
sample = subsample(train, sample_size)
tree = build_tree(sample, max_depth, min_size)
trees.append(tree)
predictions = [bagging_predict(trees, row) for row in test]
return(predictions)
seed(1)
filename = 'sonar.all-data.csv'
dataset = load_csv(filename)
for i in range(len(dataset[0])-1):
str_column_to_float(dataset, i)
str_column_to_int(dataset, len(dataset[0])-1)
n_folds = 5
max_depth = 6
min_size = 2
sample_size = 0.50
for n_trees in [1, 5, 10, 50]:
scores = evaluate_algorithm(dataset, bagging, n_folds, max_depth, min_size, sample_size, n_trees)
print('Trees: %d' % n_trees)
print('Scores: %s' % scores)
print('Mean Accuracy: %.3f%%' % (sum(scores)/float(len(scores))))
|