目录
4交叉验证和网格搜索对k紧邻算法的调优
4.1交叉验证
所有数据n等分,然后选择不同分数的i/n为训练集,剩余的分数作验证集,
然后可以得到不同的准确率
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-RWDqyO0z-1655610877782)(C:\Users\Administrator\Desktop\QQ截图20220618121023.png)]
4.2网格搜索-超参数搜索
超参数:就是需要手动设置的参数。那么对于交叉验证来说,每组超参数都采用交叉验证呢个开进行评估的画,就可以最后选出做最优参数组合建立模型
API:sklrearn.model_selection.GridSearchCV
参数:
sklearn.model_selection.GridSearchCV(estimator, param_ grid=None,cv
=None)
-
对估计器的指定参数值进行详尽搜索
-
estimator: 估计器对象(就是指用的什么算法、模型)
-
param_ grid: 估计器参数(dict)“n_ neighbors”:[1,3,5]}
-
cv:指定几折交叉验证(一般用10)
-
fit: 输入训练数据
-
score:准确率
结果分析:
-
best_score_:在交叉验证中验证的最好结果
-
best_ estimator_ :最好的参数模型
-
cv_results_:每次交叉验证后的测试集准确率结果和训练集准确
率结果
6估计器分类算法-决策树-随机森林
1 决策树API
def decision():
"""
决策树对泰坦尼克号进行预测生死
:return: None
"""
# 获取数据
titan = pd.read_csv("http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt")
# 处理数据,找出特征值和目标值
x = titan[['pclass', 'age', 'sex']]
y = titan['survived']
print(x)
# 缺失值处理
x['age'].fillna(x['age'].mean(), inplace=True)
# 分割数据集到训练集合测试集
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25)
# 进行处理(特征工程)特征-》类别-》one_hot编码
dict = DictVectorizer(sparse=False)
x_train = dict.fit_transform(x_train.to_dict(orient="records"))
print(dict.get_feature_names())
x_test = dict.transform(x_test.to_dict(orient="records"))
# print(x_train)
# 用决策树进行预测
# dec = DecisionTreeClassifier()s
#
# dec.fit(x_train, y_train)
#
# # 预测准确率
# print("预测的准确率:", dec.score(x_test, y_test))
#
# # 导出决策树的结构
# export_graphviz(dec, out_file="./tree.dot", feature_names=['年龄', 'pclass=1st', 'pclass=2nd', 'pclass=3rd', '女性', '男性'])
# 随机森林进行预测 (超参数调优)
rf = RandomForestClassifier()
param = {"n_estimators": [120, 200, 300, 500, 800, 1200], "max_depth": [5, 8, 15, 25, 30]}
# 网格搜索与交叉验证
gc = GridSearchCV(rf, param_grid=param, cv=2)
gc.fit(x_train, y_train)
print("准确率:", gc.score(x_test, y_test))
print("查看选择的参数模型:", gc.best_params_)
return None
2 决策树结构的保存
1、sklearn.tree.export_ graphviz() 该函数能够导出DOT格式
tree.export_ graphviz(estimator,out_ file=‘tree.dot’,feature_ names=[",'l])
2、工具:(能够将dot文件转换为pdf、png)
安装graphviz
- ubuntu:sudo apt- get install graphviz
- Mac:brew install graphviz
3、运行命令
然后我们运行这个命令
$ dot -Tpng tree.dot -0 tree.png
3 决策树的优缺点
优点:
- 简单的理解和解释,树木可视化。
- 需要很少的数据准备,其他技术通常需要数据归一化
缺点:
- 决策树学习者可以创建不能很好地推广数据的过于复杂的树,
这被称为过拟合。
改进:
- 减枝cart算法(决策树API当中已经实现,随机森林参数调优有相关介绍)
随机森林
4 随机森林
建立多个树的过程:N个样本,M个特征
- 随机在N个样本中选择一个样本,重复n次
- 随机在M个特征中选出m个特征,建立决策树
- 采取bootstrap抽样
5随机森林的API
class sklearn.ensemble.RandomForestClassifier(
**n_ estimators= 10, **
criterion=‘gini’,
**max_ depth=None, **
bootstrap=True,
random_ _state=None)
随机森林分类器
n_ estimators: integer, optional (default= 10)森林里的树木数量
120,200,300,500,800,1200
criteria: string, 可选(default =“gini”) 分割特征的测量方法
max_ depth: integer或None, 可选(默认=无)树的最大深度
5,8,15,25,30
max_ _features=“auto”,每个决策树的最大特征数量
-
If “auto”, then max_ features= =sqrt(n_ features) .
-
If “sqrt”, then imax_ features= =sqrt(n_ features) “(same as “auto”).
-
If “log2”, then imax_ .features =log2(n_ features)".
-
If None, then i’max_ features=n_ features .
bootstrap: boolean, optional (default = True) 是否在构建树时使用放回抽样
6随机森林的优点
- 在当前所有算法中,具有极好的准确率
- 能够有效地运行 在大数据集上
- 能够处理具有高维特征的输入样本,而且不需要降维
- 能够评估各个特征在分类问题上的重要性