Python_sklearn机器学习库学习笔记(四)decision_tree(决策树)

# 决策树

import pandas as pd
from sklearn.tree import DecisionTreeClassifier
from sklearn.cross_validation import train_test_split
from sklearn.metrics import classification_report
from sklearn.pipeline import Pipeline
from sklearn.grid_search import GridSearchCV
import zipfile
#压缩节省空间
z=zipfile.ZipFile(‘ad-dataset.zip‘)
# df=pd.read_csv(z.open(z.namelist()[0]),header=None,low_memory=False)
# df = pd.read_csv(z.open(z.namelist()[0]), header=None, low_memory=False)
df=pd.read_csv(‘.\\tree_data\\ad.data‘,header=None)
explanatory_variable_columns=set(df.columns.values)
response_variable_column=df[len(df.columns.values)-1]
#最后一列是代表的标签类型
explanatory_variable_columns.remove(len(df.columns)-1)
y=[1 if e ==‘ad.‘ else 0 for e in response_variable_column]
X=df.loc[:,list(explanatory_variable_columns)]
#匹配?字符,并把值转化为-1
X.replace(to_replace=‘ *\?‘, value=-1, regex=True, inplace=True)

X_train,X_test,y_train,y_test=train_test_split(X,y)
#用信息增益启发式算法建立决策树
pipeline=Pipeline([(‘clf‘,DecisionTreeClassifier(criterion=‘entropy‘))])
parameters = {
‘clf__max_depth‘: (150, 155, 160),
‘clf__min_samples_split‘: (1, 2, 3),
‘clf__min_samples_leaf‘: (1, 2, 3)
}
#f1查全率和查准率的调和平均
grid_search=GridSearchCV(pipeline,parameters,n_jobs=-1,
                         verbose=1,scoring=‘f1‘)
grid_search.fit(X_train,y_train)
print ‘最佳效果:%0.3f‘%grid_search.best_score_
print ‘最优参数‘
best_parameters=grid_search.best_estimator_.get_params()
best_parameters

输出结果:

Fitting 3 folds for each of 27 candidates, totalling 81 fits
[Parallel(n_jobs=-1)]: Done  46 tasks      | elapsed:   21.0s
[Parallel(n_jobs=-1)]: Done  81 out of  81 | elapsed:   34.7s finished
最佳效果:0.888
最优参数

Out[123]:

{‘clf‘: DecisionTreeClassifier(class_weight=None, criterion=‘entropy‘, max_depth=160,
             max_features=None, max_leaf_nodes=None, min_samples_leaf=1,
             min_samples_split=3, min_weight_fraction_leaf=0.0,
             presort=False, random_state=None, splitter=‘best‘),
 ‘clf__class_weight‘: None,
 ‘clf__criterion‘: ‘entropy‘,
 ‘clf__max_depth‘: 160,
 ‘clf__max_features‘: None,
 ‘clf__max_leaf_nodes‘: None,
 ‘clf__min_samples_leaf‘: 1,
 ‘clf__min_samples_split‘: 3,
 ‘clf__min_weight_fraction_leaf‘: 0.0,
 ‘clf__presort‘: False,
 ‘clf__random_state‘: None,
 ‘clf__splitter‘: ‘best‘,
 ‘steps‘: [(‘clf‘,
   DecisionTreeClassifier(class_weight=None, criterion=‘entropy‘, max_depth=160,
               max_features=None, max_leaf_nodes=None, min_samples_leaf=1,
               min_samples_split=3, min_weight_fraction_leaf=0.0,
               presort=False, random_state=None, splitter=‘best‘))]}
for param_name in sorted(parameters.keys()):
    print (‘\t%s:%r‘%(param_name,best_parameters[param_name]))
predictions=grid_search.predict(X_test)
print classification_report(y_test,predictions)

输出结果:

clf__max_depth:150
clf__min_samples_leaf:1
clf__min_samples_split:1
             precision    recall  f1-score   support

0       0.97      0.99      0.98       703
          1       0.91      0.84      0.87       117

avg / total       0.96      0.96      0.96       820

df.head()

输出结果;

  0 1 2 3 4 5 6 7 8 9 ... 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558
0 125 125 1.0 1 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 ad.
1 57 468 8.2105 1 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 ad.
2 33 230 6.9696 1 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 ad.
3 60 468 7.8 1 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 ad.
4 60 468 7.8 1 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 ad.

 # 决策树集成

#coding:utf-8
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.cross_validation import train_test_split
from sklearn.metrics import classification_report
from sklearn.pipeline import Pipeline
from sklearn.grid_search import GridSearchCV

df=pd.read_csv(‘.\\tree_data\\ad.data‘,header=None,low_memory=False)
explanatory_variable_columns=set(df.columns.values)
response_variable_column=df[len(df.columns.values)-1]

df.head()
  0 1 2 3 4 5 6 7 8 9 ... 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558
0 125 125 1.0 1 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 ad.
1 57 468 8.2105 1 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 ad.
2 33 230 6.9696 1 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 ad.
3 60 468 7.8 1 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 ad.
4 60 468 7.8 1 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 ad.

#The last column describes the targets(去掉最后一列)
explanatory_variable_columns.remove(len(df.columns.values)-1)
y=[1 if e==‘ad.‘ else 0 for e in response_variable_column]
X=df.loc[:,list(explanatory_variable_columns)]
#置换有?的为-1
X.replace(to_replace=‘ *\?‘, value=-1, regex=True, inplace=True)
X_train,X_test,y_train,y_test=train_test_split(X,y)
pipeline=Pipeline([(‘clf‘,RandomForestClassifier(criterion=‘entropy‘))])
parameters = {
‘clf__n_estimators‘: (5, 10, 20, 50),
‘clf__max_depth‘: (50, 150, 250),
‘clf__min_samples_split‘: (1, 2, 3),
‘clf__min_samples_leaf‘: (1, 2, 3)
}
grid_search = GridSearchCV(pipeline,parameters,n_jobs=-1,verbose=1,scoring=‘f1‘)
grid_search.fit(X_train,y_train)

print(u‘最佳效果:%0.3f‘%grid_search.best_score_)
print u‘最优的参数:‘
best_parameters=grid_search.best_estimator_.get_params()
for param_name in sorted(parameters.keys()):
    print(‘\t%s:%r‘%(param_name,best_parameters[param_name]))

输出结果:

最佳效果:0.929 最优的参数: clf__max_depth:250 clf__min_samples_leaf:1 clf__min_samples_split:3 clf__n_estimators:50

predictions=grid_search.predict(X_test)
print classification_report(y_test,predictions)

输出结果:

precision    recall  f1-score   support

0       0.98      1.00      0.99       705
          1       0.97      0.90      0.93       115

avg / total       0.98      0.98      0.98       820

时间: 2024-08-26 21:34:04

Python_sklearn机器学习库学习笔记(四)decision_tree(决策树)的相关文章

Python_sklearn机器学习库学习笔记(七)the perceptron(感知器)

一.感知器 感知器是Frank Rosenblatt在1957年就职于Cornell航空实验室时发明的,其灵感来自于对人脑的仿真,大脑是处理信息的神经元(neurons)细胞和链接神经元细胞进行信息传递的突触(synapses)构成. 一个神经元可以看做将一个或者多个输入处理成一个输出的计算单元.一个感知器函数类似于一个神经元:它接受一个或多个输入,处理 他们然后返回一个输出.神经元可以实时,错误驱动的学习,神经元可以通过一个训练样本不断的更新参数,而非一次使用整套的数据.实时学习可能有效的处理

代码管理工具 --- git的学习笔记四《重新整理git(1)》

1.创建版本库 mkdir  创建目录 cd  地址,到该地址下 pwd 显示当前目录 1.创建目录 $ mkdir startGit $ cd startGit $ pwd 显示当前目录 或者cd到桌面,然后再创建目录 2.初始化版本库 $ git init 初始化仓库 提示信息:Initialized empty Git repository in /Users/xingzai/Desktop/startGit/.git/ 建立一个空的git仓库在/Users/xingzai/Desktop

机器学习实战学习笔记(一)

1.k-近邻算法 算法原理: 存在一个样本数据集(训练样本集),并且我们知道样本集中的每个数据与其所属分类的对应关系.输入未知类别的数据后将新数据的每个特征与样本集中数据对应的特征进行比较,然后算法提取样本集中特征最相似(最近邻)的k组数据.然后将k组数据中出现次数最多的分类,来作为新数据的分类. 算法步骤: 计算已知类别数据集中的每一个点与当前点之前的距离.(相似度度量) 按照距离递增次序排序 选取与当前点距离最小的k个点 确定k个点所在类别的出现频率 返回频率最高的类别作为当前点的分类 py

【Unity 3D】学习笔记四十六:输入与控制——键盘事件

在游戏中,玩家控制主角移动,按键攻击,选择行走.都需要在程序中监听玩家的输入.unity为开发者提供了input库,来支持键盘事件,鼠标事件以及触摸事件.本文主要回顾键盘事件,以后会逐文复习鼠标以及触摸事件. 键盘事件 一般的PC键盘有104个不同的按键,在程序中通过监听这些按键事件,从而进一步执行逻辑操作.如:射击游戏中,W表示前进,S表示后退,A表示左移,D表示右移. 按下事件 在脚本中,用input.GetKeyDown( )方法将按键值作为参数,监听此按键是否被按下.按下返回true,否

Caliburn.Micro学习笔记(四)----IHandle<T>实现多语言功能

Caliburn.Micro学习笔记(四)----IHandle<T>实现多语言功能 说一下IHandle<T>实现多语言功能 因为Caliburn.Micro是基于MvvM的UI与codebehind分离, binding可以是双向的所以我们想动态的实现多语言切换很是方便今天我做一个小demo给大家提供一个思路 先看一下效果 点击英文  变成英文状态点chinese就会变成中文                          源码的下载地址在文章的最下边 多语言用的是资源文件建

Linux学习笔记四:Linux的文件搜索命令

1.文件搜索命令  which 语法:which [命令名称] 范例:$which ls  列出ls命令所在目录 [[email protected] ~]$ which ls alias ls='ls --color=auto' /bin/ls 另外一个命令:whereis [名称名称],也可以列出命令所在目录. [[email protected] ~]$ whereis ls ls: /bin/ls /usr/share/man/man1/ls.1.gz /usr/share/man/ma

小猪的数据结构学习笔记(四)

小猪的数据结构学习笔记(四) 线性表之静态链表 --转载请注明出处:coder-pig 本章引言: 在二,三中中我们分别学习了顺序表中的线性表与单链表,线性表有点类似于 我们前面所学的数组,而单链表使用的最多的是指针,这里问个简单的问题, 如果是在以前没有指针的话,前辈先人们怎么实现单链表呢?大家思考下! 没有指针,那么用什么来代替呢?前辈先人们非常机智,想出了使用下标+游标的方式 来实现单链表的效果!也就是今天要讲的--静态链表! 当然你也可以直接跳过本章,因为有了单链表就没有必要用静态链表了

Swift学习笔记四:数组和字典

最近一个月都在专心做unity3d的斗地主游戏,从早到晚,最后总算是搞出来了,其中的心酸只有自己知道.最近才有功夫闲下来,还是学习学习之前的老本行--asp.net,现在用.net做项目流行MVC,而不是之前的三层,既然技术在更新,只能不断学习,以适应新的技术潮流! 创建MVC工程 1.打开Visual studio2012,新建MVC4工程 2.选择工程属性,创建MVC工程 3.生成工程的目录 App_Start:启动文件的配置信息,包括很重要的RouteConfig路由注册信息 Conten

《机器学习》学习笔记(一)

今天看了两集Stanford 的Machine Learning,先说说感受,在看的过程中,脑海里冒出来一个念头:在中国的大学里,教授们都是好像在做研究,而学生们都是好像在上课,到头来不知道学到了什么,我在屏幕的这边都能感受到他们和我们的不一样. 其实对于机器学习,我是真心不懂,也不知道为什么忽然就想学习一下了,然后看了第一集就觉得实在是太牛X了,他们做的那个爬越障碍物的狗和快速避障的小车,都不是我们能搞出来的,说来也奇怪,我们不是也有他们一样的课程体系吗?照理说在大学里能做出来的东西,我们也应