# 决策树

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

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

  1. Python_sklearn机器学习库学习笔记(一)_Feature Extraction and Preprocessing(特征提取与预处理)

    # Extracting features from categorical variables #Extracting features from categorical variables 独热编 ...

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

    一.感知器 感知器是Frank Rosenblatt在1957年就职于Cornell航空实验室时发明的,其灵感来自于对人脑的仿真,大脑是处理信息的神经元(neurons)细胞和链接神经元细胞进行信息传 ...

  3. Python_sklearn机器学习库学习笔记(一)_一元回归

    一.引入相关库 %matplotlib inline import matplotlib.pyplot as plt from matplotlib.font_manager import FontP ...

  4. Python_sklearn机器学习库学习笔记(三)logistic regression(逻辑回归)

    # 逻辑回归 ## 逻辑回归处理二元分类 %matplotlib inline import matplotlib.pyplot as plt #显示中文 from matplotlib.font_m ...

  5. Python_sklearn机器学习库学习笔记(五)k-means(聚类)

    # K的选择:肘部法则 如果问题中没有指定 的值,可以通过肘部法则这一技术来估计聚类数量.肘部法则会把不同 值的成本函数值画出来.随着 值的增大,平均畸变程度会减小:每个类包含的样本数会减少,于是样本 ...

  6. Python_sklearn机器学习库学习笔记(六) dimensionality-reduction-with-pca

    # 用PCA降维 #计算协方差矩阵 import numpy as np X=[[2,0,-1.4], [2.2,0.2,-1.5], [2.4,0.1,-1], [1.9,0,-1.2]] np.c ...

  7. muduo网络库学习笔记(四) 通过eventfd实现的事件通知机制

    目录 muduo网络库学习笔记(四) 通过eventfd实现的事件通知机制 eventfd的使用 eventfd系统函数 使用示例 EventLoop对eventfd的封装 工作时序 runInLoo ...

  8. thon_sklearn机器学习库学习笔记(四)decision_tree(决策树)

    # 决策树 import pandas as pd from sklearn.tree import DecisionTreeClassifier from sklearn.cross_validat ...

  9. 【机器学习实战学习笔记(2-2)】决策树python3.6实现及简单应用

    文章目录 1.ID3及C4.5算法基础 1.1 计算香农熵 1.2 按照给定特征划分数据集 1.3 选择最优特征 1.4 多数表决实现 2.基于ID3.C4.5生成算法创建决策树 3.使用决策树进行分 ...

随机推荐

  1. windows 端口映射

    netsh interface portproxy add v4tov4 listenport=8765 listenaddress=0.0.0.0 connectaddress=172.19.24. ...

  2. Linux zip命令详解

    zip常见命令参数 Usage: zip [-options] [-b path] [-t mmddyyyy] [-n suffixes] [zipfile list] [-xi list] The ...

  3. 基于php-fpm的配置详解

    php5.3自带php-fpm/usr/local/php/etc/php-fpm.confpid = run/php-fpm.pidpid设置,默认在安装目录中的var/run/php-fpm.pi ...

  4. VMware下 CentOS 连接外网问题(笔记)

    虚拟机连接外网有三种模式.桥接.Nat.Host-Only.三者的区别,详见 实例讲解虚拟机3种网络模式(桥接.nat.Host-only) 使用虚拟机连接外网时,一定要充分考虑本地的网络环境!!! ...

  5. 占位符 %s

    a = input("Name:")b = input("Age:")c = input("Job:")d = input("ho ...

  6. #002 Emmet完整API

    介绍 这里包含了,所有的Emmet API,非常的详细,但是有一点详细过头了,如果只想快速上手,那么推荐<#001 Emmet的API图片> Emmet (前身为 Zen Coding) ...

  7. html5 js 游戏的一篇博客 貌似不错

    http://blog.csdn.net/lufy_legend/article/details/8888787

  8. reactor模型框架图和流程图 libevent

    学习libevent有助于提升程序设计功力,除了网络程序设计方面外,libevent的代码里有很多有用的设计技巧和基础数据结构,比如信息隐藏.函数指针.c语言的多态支持.链表和堆等等,都有助于提升自身 ...

  9. SSH环境搭建,配置整合初步(一)

    1,新Webproject.并把编码设为utf-8(全部的都是uft8数据库也是,就不会乱码了)2.加入框架环境JunitStruts2Hibernate Spring3,整合SSHStruts2与S ...

  10. JavaScript-2.内置对象---简单脚本之弹出对话框显示当前时间 ---ShinePans

    <html> <head> <meta http-equiv="content-type" content="text/html; char ...