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

载入数据

# -*- coding: utf-8 -*-
import pandas as pd
import matplotlib
matplotlib.rcParams['font.sans-serif']=[u'simHei']
matplotlib.rcParams['axes.unicode_minus']=False
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV from sklearn.datasets import load_breast_cancer data_set = pd.read_csv('pima-indians-diabetes.csv')
data = data_set.values[:,:] y = data[:,8]
X = data[:,:8]
X_train,X_test,y_train,y_test = train_test_split(X,y)

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

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

评价模型

# In[2] 输出预测结果并评价
predictions = grid_search.predict(X_test)
print(classification_report(y_test,predictions))
              precision    recall  f1-score   support

         0.0       0.74      0.89      0.81       124
1.0 0.67 0.43 0.52 68

画出决策树

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

随机森林

# -*- coding: utf-8 -*-
import pandas as pd
import matplotlib
matplotlib.rcParams['font.sans-serif']=[u'simHei']
matplotlib.rcParams['axes.unicode_minus']=False
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV
from sklearn.ensemble import RandomForestClassifier from sklearn.datasets import load_breast_cancer data_set = pd.read_csv('pima-indians-diabetes.csv')
data = data_set.values[:,:] y = data[:,8]
X = data[:,:8]
X_train,X_test,y_train,y_test = train_test_split(X,y) RF = RandomForestClassifier(n_estimators=10,random_state=11)
RF.fit(X_train,y_train)
predictions = RF.predict(X_test)
print(classification_report(y_test,predictions))
              precision    recall  f1-score   support

         0.0       0.82      0.91      0.86       126
1.0 0.78 0.61 0.68 66 micro avg 0.81 0.81 0.81 192
macro avg 0.80 0.76 0.77 192
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. mongodb的基本操作之数据创建索引

    在数据量较少时,不使用索引,查询是很快的,但是在数据量较大时,查询将会变得非常缓慢,在mongodb中 查看索引 > db.test_collection.getIndexes() [ { &q ...

  2. HDU 6735 结论网络流 机器人不重叠路径

    我们可以得到一个结论:没有两个机器人走过的路会重叠 所以题目就转变为了能不能让机器人的路径不重叠且每个机器人能到达终点 直接一个点朝他四连通方向的四个点连容量为1的边即可 #include<bi ...

  3. windows下对socket的send和recv的超时设置,并附一个简洁明了的socket简单demo

    设置方法 int nNetTimeout=10000;//10秒,    //设置发送超时    setsockopt(m_socket,SOL_SOCKET,SO_SNDTIMEO,(char *) ...

  4. WPF绑定属性

    1.创建model类 model类要继承接口INotifyPropertyChanged,用于通知客户端属性值已更改 public class StudentModel : INotifyProper ...

  5. linux目录太长怎么办?分享一点小技巧

    在linux使用cd的时候,可能会遇到目录比较深的时候,这个时候总是cd一个很长的目录会很麻烦,那有没有什么比较方便的方法呢? 若是在两个目录中来回切换,这个时候可以使用cd - 这个命令,可以完成在 ...

  6. Selenium(一)自动化测试简介

    1.软件开发流程 产品分析需求--架构师确认系统包含哪些模块--开发编码--开发和测试一起做单元测试--测试开展版本(集成)测试(使用手工测试,测试通过后,才开始设计脚本)--测试开展系统测试--最后 ...

  7. Python+request+ smtplib 测试结果html报告邮件发送(下)《六》

    目录结构如下: 1.cfg.ini的配置信息写法如下: [email] ;--------------------------使用腾讯企业邮箱作为发件人的操作如下------------------- ...

  8. 如果简化stm32中printf函数的使用——首先重定向

    STM32单片机极简方法 使用宏定义 代替复杂的重定向printf()函数,实现串口打印.(HAL库例程)https://blog.csdn.net/wu10188/article/details/9 ...

  9. python2和python3编程差异杂谈(-)

    python2 默认编码ascii 在使用中文时要显示的声明   #-*-encoding:utf-8-*- python3 默认编码utf-8,良好的支持了中文输入 python2: print函数 ...

  10. [Google Guava] 1.3-常见Object方法

    原文链接 译者: 沈义扬 equals 当一个对象中的字段可以为null时,实现Object.equals方法会很痛苦,因为不得不分别对它们进行null检查.使用Objects.equal帮助你执行n ...