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
最优参数
{'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]))
输出结果:
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(决策树)的更多相关文章
- Python_sklearn机器学习库学习笔记(一)_Feature Extraction and Preprocessing(特征提取与预处理)
# Extracting features from categorical variables #Extracting features from categorical variables 独热编 ...
- Python_sklearn机器学习库学习笔记(七)the perceptron(感知器)
一.感知器 感知器是Frank Rosenblatt在1957年就职于Cornell航空实验室时发明的,其灵感来自于对人脑的仿真,大脑是处理信息的神经元(neurons)细胞和链接神经元细胞进行信息传 ...
- Python_sklearn机器学习库学习笔记(一)_一元回归
一.引入相关库 %matplotlib inline import matplotlib.pyplot as plt from matplotlib.font_manager import FontP ...
- Python_sklearn机器学习库学习笔记(三)logistic regression(逻辑回归)
# 逻辑回归 ## 逻辑回归处理二元分类 %matplotlib inline import matplotlib.pyplot as plt #显示中文 from matplotlib.font_m ...
- Python_sklearn机器学习库学习笔记(五)k-means(聚类)
# K的选择:肘部法则 如果问题中没有指定 的值,可以通过肘部法则这一技术来估计聚类数量.肘部法则会把不同 值的成本函数值画出来.随着 值的增大,平均畸变程度会减小:每个类包含的样本数会减少,于是样本 ...
- 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 ...
- muduo网络库学习笔记(四) 通过eventfd实现的事件通知机制
目录 muduo网络库学习笔记(四) 通过eventfd实现的事件通知机制 eventfd的使用 eventfd系统函数 使用示例 EventLoop对eventfd的封装 工作时序 runInLoo ...
- thon_sklearn机器学习库学习笔记(四)decision_tree(决策树)
# 决策树 import pandas as pd from sklearn.tree import DecisionTreeClassifier from sklearn.cross_validat ...
- 【机器学习实战学习笔记(2-2)】决策树python3.6实现及简单应用
文章目录 1.ID3及C4.5算法基础 1.1 计算香农熵 1.2 按照给定特征划分数据集 1.3 选择最优特征 1.4 多数表决实现 2.基于ID3.C4.5生成算法创建决策树 3.使用决策树进行分 ...
随机推荐
- 动画隐藏UITabBarController与UINavigationController
动画隐藏UITabBarController与UINavigationController 效果图: 源码: AppDelegate.m // // AppDelegate.m // HideTabb ...
- libcurl同时下载多个文件
#include <errno.h> #include <stdlib.h> #include <string.h> #ifndef WIN32 #include ...
- 【笔记】JS脚本为什么要放在body最后面以及async和defer的异同点
1.没有defer或async 浏览器遇到脚本的时候会暂停渲染并立即加载执行脚本(外部脚本),"立即"指的是在渲染该 script 标签之下的文档元素之前,也就是说不等待后续载入的 ...
- [装]JMX监控Hadoop
http://chenjc-it.iteye.com/blog/1539746 实验成功!
- Java并发:Executor与连接池
概述 首先来说一说java连接池中常用到的几个类:Executor,ExecutorService,ScheduledExecutorService Executor 执行已经提交的任务对象.此接口提 ...
- 1001. [BJOI2006]狼抓兔子【最小割】
Description 现在小朋友们最喜欢的"喜羊羊与灰太狼",话说灰太狼抓羊不到,但抓兔子还是比较在行的, 而且现在的兔子还比较笨,它们只有两个窝,现在你做为狼王,面对下面这样一 ...
- 【洛谷】【堆+结论】P4597 序列sequence
[题目背景:] 原题cf13c 数据加强版(就是说原来能用DP做现在不行了QwQ) [题目描述:] 给定一个序列,每次操作可以把某个数+1-1.要求把序列变成非降数列.而且要求修改后的数列只能出现修改 ...
- ES6新特性2:变量的解构赋值
本文摘自ECMAScript6入门,转载请注明出处. ES6允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构(Destructuring).不仅适用于var命令,也适用于let和c ...
- Jenkins + GitLab 通过 Webhook 自动触发构建爬坑记录
前言 在局域网搭建了一个Jenkins服务,用于自动构建和发布,在调通了构建程序之后,想使用内网的GitLab的Webhook功能触发代码推送事件,然后进行自动构建.后来发现在GitLab上做测试 ...
- centos 6.8安装java环境
1.rpm -qa |grep java 查看当前是否有java已经安装了,部分centos系统已经安装了的openjava环境,但是很多项目不熟要求的是要必须是sun的java环境 2.yum ...