决策树
决策树是一种基本的分类方法,当然也可以用于回归。我们一般只讨论用于分类的决策树。决策树模型呈树形结构。在分类问题中,表示基于特征对实例进行分类的过程,它可以认为是if-then规则的集合。在决策树的结构中,每一个实例都被一条路径或者一条规则所覆盖。通常决策树学习包括三个步骤:特征选择、决策树的生成和决策树的修剪
优点:计算复杂度不高,输出结果易于理解,对中间值的缺失不敏感,可以处理逻辑回归等不能解决的非线性特征数据
缺点:可能产生过度匹配问题
适用数据类型:数值型和标称型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.feature_extraction import DictVectorizer from sklearn.ensemble import RandomForestClassifier from sklearn.tree import DecisionTreeClassifier, export_graphviz import pandas as pd 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() param = { "max_depth" : [ 5 , 8 , 15 , 25 , 30 ]} # 网格搜索与交叉验证 gc = GridSearchCV(dec, param_grid = param, cv = 2 ) gc.fit(x_train, y_train) print ( "准确率:" , gc.score(x_test, y_test)) print ( "查看选择的参数模型:" , gc.best_params_) # 导出决策树的结构 export_graphviz(dec, out_file = "./tree.dot" , feature_names = [ '年龄' , 'pclass=1st' , 'pclass=2nd' , 'pclass=3rd' , '女性' , '男性' ]) return None if __name__ = = "__main__" : decision() |
随机森林
在机器学习中,随机森林是一个包含多个决策树的分类器,并且其输出的类别是由个别树输出的类别的众数而定。利用相同的训练数搭建多个独立的分类模型,然后通过投票的方式,以少数服从多数的原则作出最终的分类决策。例如, 如果你训练了5个树, 其中有4个树的结果是True, 1个数的结果是False, 那么最终结果会是True.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.feature_extraction import DictVectorizer from sklearn.ensemble import RandomForestClassifier from sklearn.tree import DecisionTreeClassifier, export_graphviz import pandas as pd 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) # 随机森林进行预测 (超参数调优) 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 if __name__ = = "__main__" : decision() |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)