更新 7.集成方法

This commit is contained in:
jiangzhonglian
2017-08-23 20:33:35 +08:00
parent b0c57257ca
commit 6e6b1bb96f

View File

@@ -93,15 +93,15 @@
#### 开发流程
```
收集数据:提供的文本文件
准备数据:转换样本集
分析数据:手工检查数据
训练算法:在数据上,利用 random_forest() 函数进行优化评估,返回模型的综合分类结果
测试算法:在采用自定义 n_folds 份随机重抽样 进行测试评估,得出综合的预测评分
使用算法:本例没有完成此步骤,若你感兴趣可以构建完整的应用程序,从案例进行封装,可以构造一个实际运行的类似系统
收集数据:提供的文本文件
准备数据:转换样本集
分析数据:手工检查数据
训练算法:在数据上,利用 random_forest() 函数进行优化评估,返回模型的综合分类结果
测试算法:在采用自定义 n_folds 份随机重抽样 进行测试评估,得出综合的预测评分
使用算法:若你感兴趣可以构建完整的应用程序,从案例进行封装,可以参考我们的代码
```
> 收集数据:提供的文本文件
> 收集数据:提供的文本文件
样本数据sonar-all-data.txt
@@ -139,17 +139,17 @@ def loadDataSet(filename):
> 训练算法:在数据上,利用 random_forest() 函数进行优化评估,返回模型的综合分类结果
* 数据随机
* 样本数据随机无放回抽样-用于交叉验证
```python
def cross_validation_split(dataset, n_folds):
"""cross_validation_split(将数据集进行抽重抽样 n_folds 份,数据可以重复重复抽取每一次list的元素是无重复的)
"""cross_validation_split(将数据集进行抽重抽样 n_folds 份,数据可以重复重复抽取)
Args:
dataset 原始数据集
n_folds 数据集dataset分成n_flods份
Returns:
dataset_split list集合存放的是将数据集进行抽重抽样 n_folds 份,数据可以重复重复抽取每一次list的元素是无重复的
dataset_split list集合存放的是将数据集进行抽重抽样 n_folds 份,数据可以重复重复抽取
"""
dataset_split = list()
dataset_copy = list(dataset) # 复制一份 dataset,防止 dataset 的内容改变
@@ -161,13 +161,38 @@ def cross_validation_split(dataset, n_folds):
index = randrange(len(dataset_copy))
# 将对应索引 index 的内容从 dataset_copy 中导出,并将该内容从 dataset_copy 中删除。
# pop() 函数用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。
# fold.append(dataset_copy.pop(index)) # 无放回的方式
fold.append(dataset_copy[index]) # 有放回的方式
fold.append(dataset_copy.pop(index)) # 无放回的方式
# fold.append(dataset_copy[index]) # 有放回的方式
dataset_split.append(fold)
# 由dataset分割出的n_folds个数据构成的列表为了用于交叉验证
return dataset_split
```
* 训练数据集随机化
```python
# Create a random subsample from the dataset with replacement
def subsample(dataset, ratio): # 创建数据集的随机子样本
"""random_forest(评估算法性能,返回模型得分)
Args:
dataset 训练数据集
ratio 训练数据集的样本比例
Returns:
sample 随机抽样的训练样本
"""
sample = list()
# 训练样本的按比例抽样。
# round() 方法返回浮点数x的四舍五入值。
n_sample = round(len(dataset) * ratio)
while len(sample) < n_sample:
# 有放回的随机采样,有一些样本被重复采样,从而在训练集中多次出现,有的则从未在训练集中出现,此则自助采样法。从而保证每棵决策树训练集的差异性
index = randrange(len(dataset))
sample.append(dataset[index])
return sample
```
* 特征随机化
```python
@@ -242,7 +267,7 @@ def evaluate_algorithm(dataset, algorithm, n_folds, *args):
scores 模型得分
"""
# 将数据集进行抽重抽样 n_folds 份,数据可以重复重复抽取,每一次 list 的元素是无重复的
# 将数据集进行随机抽样,分成 n_folds 份,数据重复抽取
folds = cross_validation_split(dataset, n_folds)
scores = list()
# 每次循环从 folds 从取出一个 fold 作为测试集,其余作为训练集,遍历整个 folds ,实现交叉验证
@@ -277,7 +302,7 @@ def evaluate_algorithm(dataset, algorithm, n_folds, *args):
return scores
```
> 使用算法:本例没有完成此步骤,若你感兴趣可以构建完整的应用程序,从案例进行封装,可以构造一个实际运行的类似系统
> 使用算法:若你感兴趣可以构建完整的应用程序,从案例进行封装,可以参考我们的代码
[完整代码地址](https://github.com/apachecn/MachineLearning/blob/master/src/python/7.RandomForest/randomForest.py): <https://github.com/apachecn/MachineLearning/blob/master/src/python/7.RandomForest/randomForest.py>