zoukankan      html  css  js  c++  java
  • 机器学习之路:python 集成分类器 随机森林分类RandomForestClassifier 梯度提升决策树分类GradientBoostingClassifier 预测泰坦尼克号幸存者

    python3 学习使用随机森林分类器 梯度提升决策树分类 的api,并将他们和单一决策树预测结果做出对比

    附上我的git,欢迎大家来参考我其他分类器的代码: https://github.com/linyi0604/MachineLearning

      1 import pandas as pd
      2 from sklearn.cross_validation import train_test_split
      3 from sklearn.feature_extraction import DictVectorizer
      4 from sklearn.tree import DecisionTreeClassifier
      5 from sklearn.metrics import classification_report
      6 from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
      7 
      8 '''
      9 集成分类器:
     10 综合考量多个分类器的预测结果做出考量。
     11 这种综合考量大体上分两种:
     12     1 搭建多个独立的分类模型,然后通过投票的方式 比如 随机森林分类器
     13         随机森林在训练数据上同时搭建多棵决策树,这些决策树在构建的时候会放弃唯一算法,随机选取特征
     14     2 按照一定次序搭建多个分类模型,
     15         他们之间存在依赖关系,每一个后续模型的加入都需要现有模型的综合性能贡献,
     16         从多个较弱的分类器搭建出一个较为强大的分类器,比如梯度提升决策树
     17         提督森林决策树在建立的时候尽可能降低成体在拟合数据上的误差。
     18         
     19 下面将对比 单一决策树 随机森林 梯度提升决策树 的预测情况
     20 
     21 '''
     22 
     23 '''
     24 1 准备数据
     25 '''
     26 # 读取泰坦尼克乘客数据,已经从互联网下载到本地
     27 titanic = pd.read_csv("./data/titanic/titanic.txt")
     28 # 观察数据发现有缺失现象
     29 # print(titanic.head())
     30 
     31 # 提取关键特征,sex, age, pclass都很有可能影响是否幸免
     32 x = titanic[['pclass', 'age', 'sex']]
     33 y = titanic['survived']
     34 # 查看当前选择的特征
     35 # print(x.info())
     36 '''
     37 <class 'pandas.core.frame.DataFrame'>
     38 RangeIndex: 1313 entries, 0 to 1312
     39 Data columns (total 3 columns):
     40 pclass    1313 non-null object
     41 age       633 non-null float64
     42 sex       1313 non-null object
     43 dtypes: float64(1), object(2)
     44 memory usage: 30.9+ KB
     45 None
     46 '''
     47 # age数据列 只有633个,对于空缺的 采用平均数或者中位数进行补充 希望对模型影响小
     48 x['age'].fillna(x['age'].mean(), inplace=True)
     49 
     50 '''
     51 2 数据分割
     52 '''
     53 x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25, random_state=33)
     54 # 使用特征转换器进行特征抽取
     55 vec = DictVectorizer()
     56 # 类别型的数据会抽离出来 数据型的会保持不变
     57 x_train = vec.fit_transform(x_train.to_dict(orient="record"))
     58 # print(vec.feature_names_)   # ['age', 'pclass=1st', 'pclass=2nd', 'pclass=3rd', 'sex=female', 'sex=male']
     59 x_test = vec.transform(x_test.to_dict(orient="record"))
     60 
     61 '''
     62 3.1 单一决策树 训练模型 进行预测
     63 '''
     64 # 初始化决策树分类器
     65 dtc = DecisionTreeClassifier()
     66 # 训练
     67 dtc.fit(x_train, y_train)
     68 # 预测 保存结果
     69 dtc_y_predict = dtc.predict(x_test)
     70 
     71 '''
     72 3.2 使用随机森林 训练模型 进行预测
     73 '''
     74 # 初始化随机森林分类器
     75 rfc = RandomForestClassifier()
     76 # 训练
     77 rfc.fit(x_train, y_train)
     78 # 预测
     79 rfc_y_predict = rfc.predict(x_test)
     80 
     81 '''
     82 3.3 使用梯度提升决策树进行模型训练和预测
     83 '''
     84 # 初始化分类器
     85 gbc = GradientBoostingClassifier()
     86 # 训练
     87 gbc.fit(x_train, y_train)
     88 # 预测
     89 gbc_y_predict = gbc.predict(x_test)
     90 
     91 
     92 '''
     93 4 模型评估
     94 '''
     95 print("单一决策树准确度:", dtc.score(x_test, y_test))
     96 print("其他指标:
    ", classification_report(dtc_y_predict, y_test, target_names=['died', 'survived']))
     97 
     98 print("随机森林准确度:", rfc.score(x_test, y_test))
     99 print("其他指标:
    ", classification_report(rfc_y_predict, y_test, target_names=['died', 'survived']))
    100 
    101 print("梯度提升决策树准确度:", gbc.score(x_test, y_test))
    102 print("其他指标:
    ", classification_report(gbc_y_predict, y_test, target_names=['died', 'survived']))
    103 
    104 '''
    105 单一决策树准确度: 0.7811550151975684
    106 其他指标:
    107               precision    recall  f1-score   support
    108 
    109        died       0.91      0.78      0.84       236
    110    survived       0.58      0.80      0.67        93
    111 
    112 avg / total       0.81      0.78      0.79       329
    113 
    114 随机森林准确度: 0.78419452887538
    115 其他指标:
    116               precision    recall  f1-score   support
    117 
    118        died       0.91      0.78      0.84       237
    119    survived       0.58      0.80      0.68        92
    120 
    121 avg / total       0.82      0.78      0.79       329
    122 
    123 梯度提升决策树准确度: 0.790273556231003
    124 其他指标:
    125               precision    recall  f1-score   support
    126 
    127        died       0.92      0.78      0.84       239
    128    survived       0.58      0.82      0.68        90
    129 
    130 avg / total       0.83      0.79      0.80       329
    131 
    132 '''
  • 相关阅读:
    分页SQL 和Oracle 存储过程
    什么是SilverLight
    opendpi 源码分析(一)
    Multiway arrays
    循环链表
    轮询算法 这是一个印度人写的,学习下。 来自 codeproject
    Friday the Thirteenth
    通过命令行指定监听的IP和端口
    pthread_key_t
    贝叶斯网络 未学习前数据结构
  • 原文地址:https://www.cnblogs.com/Lin-Yi/p/8971348.html
Copyright © 2011-2022 走看看