数据来自 UCI 数据集 匹马印第安人糖尿病数据集

载入数据

  1. # -*- coding: utf-8 -*-
  2. import pandas as pd
  3. import matplotlib
  4. matplotlib.rcParams['font.sans-serif']=[u'simHei']
  5. matplotlib.rcParams['axes.unicode_minus']=False
  6. from sklearn.tree import DecisionTreeClassifier
  7. from sklearn.model_selection import train_test_split
  8. from sklearn.metrics import classification_report
  9. from sklearn.pipeline import Pipeline
  10. from sklearn.model_selection import GridSearchCV
  11.  
  12. from sklearn.datasets import load_breast_cancer
  13.  
  14. data_set = pd.read_csv('pima-indians-diabetes.csv')
  15. data = data_set.values[:,:]
  16.  
  17. y = data[:,8]
  18. X = data[:,:8]
  19. X_train,X_test,y_train,y_test = train_test_split(X,y)

建立决策树,网格搜索微调模型

  1. # In[1] 网格搜索微调模型
  2. pipeline = Pipeline([
  3. ('clf',DecisionTreeClassifier(criterion='entropy'))
  4. ])
  5. parameters={
  6. 'clf__max_depth':(3,5,10,15,20,25,30,35,40),
  7. 'clf__min_samples_split':(2,3),
  8. 'clf__min_samples_leaf':(1,2,3)
  9. }
  10. #GridSearchCV 用于系统地遍历多种参数组合,通过交叉验证确定最佳效果参数。
  11. grid_search = GridSearchCV(pipeline,parameters,n_jobs=-1,verbose=-1,scoring='f1')
  12. grid_search.fit(X_train,y_train)
  13.  
  14. # 获取搜索到的最优参数
  15. best_parameters = grid_search.best_estimator_.get_params()
  16. print("最好的F1值为:",grid_search.best_score_)
  17. print('最好的参数为:')
  18. for param_name in sorted(parameters.keys()):
  19. print('t%s: %r' % (param_name,best_parameters[param_name]))
  20.  
  21. # In[2] 输出预测结果并评价
  22. predictions = grid_search.predict(X_test)
  23. print(classification_report(y_test,predictions))
  1. 最好的F1值为: 0.5573515325670498
  2. 最好的参数为:
  3. tclf__max_depth: 5
  4. tclf__min_samples_leaf: 1
  5. tclf__min_samples_split: 2

评价模型

  1. # In[2] 输出预测结果并评价
  2. predictions = grid_search.predict(X_test)
  3. print(classification_report(y_test,predictions))
  1. precision recall f1-score support
  2.  
  3. 0.0 0.74 0.89 0.81 124
  4. 1.0 0.67 0.43 0.52 68

画出决策树

  1. # In[3]打印树
  2. from sklearn import tree
  3. feature_name=data_set.columns.values.tolist()[:-1] # 列名称
  4. DT = tree.DecisionTreeClassifier(criterion='entropy',max_depth=5,min_samples_split=2,min_samples_leaf=5)
  5. DT.fit(X_train,y_train)
  6.  
  7. '''
  8. # 法一
  9. import pydotplus
  10. from sklearn.externals.six import StringIO
  11. dot_data = StringIO()
  12. tree.export_graphviz(DT,out_file = dot_data,feature_names=feature_name,
  13. class_names=["有糖尿病","无病"],filled=True,rounded=True,
  14. special_characters=True)
  15. graph = pydotplus.graph_from_dot_data(dot_data.getvalue())
  16. graph.write_pdf("Tree.pdf")
  17. print('Visible tree plot saved as pdf.')
  18. '''
  19.  
  20. # 法二
  21. import graphviz
  22. #ID3为决策树分类器fit之后得到的模型,注意这里必须在fit后执行,在predict之后运行会报错
  23. dot_data = tree.export_graphviz(DT, out_file=None,feature_names=feature_name,class_names=["有糖尿病","无病"]) # doctest: +SKIP
  24. graph = graphviz.Source(dot_data) # doctest: +SKIP
  25. #在同级目录下生成tree.pdf文件
  26. graph.render("tree2") # doctest: +SKIP

随机森林

  1. # -*- coding: utf-8 -*-
  2. import pandas as pd
  3. import matplotlib
  4. matplotlib.rcParams['font.sans-serif']=[u'simHei']
  5. matplotlib.rcParams['axes.unicode_minus']=False
  6. from sklearn.tree import DecisionTreeClassifier
  7. from sklearn.model_selection import train_test_split
  8. from sklearn.metrics import classification_report
  9. from sklearn.pipeline import Pipeline
  10. from sklearn.model_selection import GridSearchCV
  11. from sklearn.ensemble import RandomForestClassifier
  12.  
  13. from sklearn.datasets import load_breast_cancer
  14.  
  15. data_set = pd.read_csv('pima-indians-diabetes.csv')
  16. data = data_set.values[:,:]
  17.  
  18. y = data[:,8]
  19. X = data[:,:8]
  20. X_train,X_test,y_train,y_test = train_test_split(X,y)
  21.  
  22. RF = RandomForestClassifier(n_estimators=10,random_state=11)
  23. RF.fit(X_train,y_train)
  24. predictions = RF.predict(X_test)
  25. print(classification_report(y_test,predictions))
  1. precision recall f1-score support
  2.  
  3. 0.0 0.82 0.91 0.86 126
  4. 1.0 0.78 0.61 0.68 66
  5.  
  6. micro avg 0.81 0.81 0.81 192
  7. macro avg 0.80 0.76 0.77 192
  8. weighted avg 0.80 0.81 0.80 192

scikit-learn机器学习(四)使用决策树做分类,并画出决策树,随机森林对比的更多相关文章

  1. iris数据集 决策树实现分类并画出决策树

    # coding=utf-8 import pandas as pd from sklearn.model_selection import train_test_split from sklearn ...

  2. 机器学习-树模型理论(GDBT,xgboost,lightBoost,随机森林)

    tree based ensemble algorithms 主要介绍以下几种ensemble的分类器(tree based algorithms) xgboost lightGBM: 基于决策树算法 ...

  3. 机器学习相关知识整理系列之二:Bagging及随机森林

    1. Bagging的策略 从样本集中重采样(有放回)选出\(n\)个样本,定义子样本集为\(D\): 基于子样本集\(D\),所有属性上建立分类器,(ID3,C4.5,CART,SVM等): 重复以 ...

  4. kaggle 欺诈信用卡预测——不平衡训练样本的处理方法 综合结论就是:随机森林+过采样(直接复制或者smote后,黑白比例1:3 or 1:1)效果比较好!记得在smote前一定要先做标准化!!!其实随机森林对特征是否标准化无感,但是svm和LR就非常非常关键了

    先看数据: 特征如下: Time Number of seconds elapsed between each transaction (over two days) numeric V1 No de ...

  5. scikit-learn机器学习(四)使用决策树做分类

    我们使用决策树来创建一个能屏蔽网页横幅广告的软件. 已知图片的数据判断它属于广告还是文章内容. 数据来自 http://archive.ics.uci.edu/ml/datasets/Internet ...

  6. ROC曲线是通过样本点分类概率画出的 例如某一个sample预测为1概率为0.6 预测为0概率0.4这样画出来,此外如果曲线不是特别平滑的话,那么很可能存在过拟合的情况

    ROC和AUC介绍以及如何计算AUC from:http://alexkong.net/2013/06/introduction-to-auc-and-roc/ ROC(Receiver Operat ...

  7. 机器学习中的算法(1)-决策树模型组合之随机森林与GBDT

    版权声明: 本文由LeftNotEasy发布于http://leftnoteasy.cnblogs.com, 本文可以被全部的转载或者部分使用,但请注明出处,如果有问题,请联系wheeleast@gm ...

  8. 机器学习中的算法——决策树模型组合之随机森林与GBDT

    前言: 决策树这种算法有着很多良好的特性,比如说训练时间复杂度较低,预测的过程比较快速,模型容易展示(容易将得到的决策树做成图片展示出来)等.但是同时,单决策树又有一些不好的地方,比如说容易over- ...

  9. 机器学习中的算法-决策树模型组合之随机森林与GBDT

    机器学习中的算法(1)-决策树模型组合之随机森林与GBDT 版权声明: 本文由LeftNotEasy发布于http://leftnoteasy.cnblogs.com, 本文可以被全部的转载或者部分使 ...

随机推荐

  1. ubuntu python3虚拟环境

    mkvirtualenv flow_chart -p /usr/bin/python3.6 #  命令    环境名    -p   python所在路径 pip install -r request ...

  2. Juit

    Junit这种老技术,现在又拿出来说,不为别的,某种程度上来说,更是为了要说明它在项目中的重要性. 凭本人的感觉和经验来说,在项目中完全按标准都写Junit用例覆盖大部分业务代码的,应该不会超过一半. ...

  3. 最近公共祖先算法LCA笔记(树上倍增法)

    Update: 2019.7.15更新 万分感谢[宁信]大佬,认认真真地审核了本文章,指出了超过五处错误捂脸,太尴尬了. 万分感谢[宁信]大佬,认认真真地审核了本文章,指出了超过五处错误捂脸,太尴尬了 ...

  4. ndk学习之c++语言基础复习----C++容器、类型转换、异常与文件流操作

    继续来复习C++,比较枯燥,但是这是扎实掌握NDK开发的必经之路,不容小觑. 容器: 容器,就是用来存放东西的盒子. 常用的数据结构包括:数组array, 链表list, 树tree, 栈stack, ...

  5. 解析.conf配置文件

    解析.conf配置文件 解析.conf配置文件 解析.conf配置文件

  6. 原生JS实现简单富文本编辑器

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  7. 「数据结构与算法(Python)」(三)

    栈结构实现 栈可以用顺序表实现,也可以用链表实现. 栈的操作 Stack() 创建一个新的空栈 push(item) 添加一个新的元素item到栈顶 pop() 弹出栈顶元素 peek() 返回栈顶元 ...

  8. [Google Guava] 7-原生类型

    原文链接 译文链接 译者:沈义扬,校对:丁一 概述 Java的原生类型就是指基本类型:byte.short.int.long.float.double.char和boolean. 在从Guava查找原 ...

  9. 2、细节&Class对象

    2.细节&Class对象 class Class{ 提供获取字节码文件中的内容. 比如: 名称,字段,构造函数,一般函数 } 该类就可以获取字节码文件中的所有内容,那么反射就是依靠该类完成的. ...

  10. Java_hutool 发起请求

    //执行接口 String realUrl = "http://localhost:8091/SzeportCodeService/MSGService/encryptAES"; ...