# 决策树

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

最新文章

  1. 每日学习心得:UEditor样式被过滤无法显示问题
  2. Python多线程(1)——介绍
  3. 斗地主你什么时候才会托管?(.NET中的托管于非托管)
  4. mysql内核源代码深度解析 缓冲池 buffer pool 整体概述
  5. 滚动页面时DIV到达顶部时固定在顶部
  6. php5.5 + apache2.4 安装配置
  7. 多线程下不重复读取SQL Server 表的数据
  8. Java面试题:Java中怎么样实现多线程
  9. Java学习笔记——i++与++i问题
  10. 2018.09.29 Lua
  11. Mac电脑 阿里云ECS(ContentOS) Apache+vsftpd+nodejs+mongodb建站过程总结
  12. Android GUI之View测量
  13. python-flask-wtforms
  14. 深度学习原理与框架-卷积网络细节-三代物体检测算法 1.R-CNN 2.Fast R-CNN 3.Faster R-CNN
  15. 20155205 《Java程序设计》实验二(Java面向对象程序设计)实验报告
  16. iview给radio按钮组件加点击事件
  17. opencv之图像拼接
  18. Linux系统中/opt 和 /usr目录
  19. 苹果App Store提交app审核时EULA(终端用户软件使用条款)的注意事项等政策解读
  20. [android] AndroidManifest.xml - 【 manifest -> Application -> activity 】

热门文章

  1. android 绑定spinner键值对显示内存地址的问题
  2. JVM & Server & Connector & Context Relationship
  3. 使用PerfView诊断.Net GC的问题
  4. javaEE中关于dao层和services层的理解
  5. GMM的EM算法实现
  6. MacOS changed System Integrity Protection status
  7. TCP、UDP、IP 协议分析
  8. 头像上传,拖拽,裁切 (非HTML5)版本
  9. 柯朗数(Courant number)研究
  10. Nodejs学习(四)- express目录的分析