决策树及集成模型 python实现

该博客介绍了如何使用决策树和集成模型预测泰坦尼克号乘客的生存情况。首先,通过pandas加载泰坦尼克数据,处理缺失值并选择关键特征如年龄、性别和船舱等级。接着,使用决策树模型进行训练和预测,评估模型性能。然后,引入随机森林和梯度提升决策树作为集成模型,比较它们与单一决策树的预测效果,结果显示集成模型在预测准确性和F1分数上略有提升。
摘要由CSDN通过智能技术生成

(三)、 决策树及集成模型

1、决策树

step1:泰坦尼克号乘客数据库
# 导入pandas用于数据分析。
import pandas as pd
# 利用pandas的read_csv模块直接从互联网收集泰坦尼克号乘客数据。
titanic = pd.read_csv('http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt')

# 观察一下前几行数据,可以发现,数据种类各异,数值型、类别型,甚至还有缺失数据。
titanic.head()

row.namespclasssurvivednameageembarkedhome.destroomticketboatsex
011st1Allen, Miss Elisabeth Walton29.0000SouthamptonSt Louis, MOB-524160 L2212female
121st0Allison, Miss Helen Loraine2.0000SouthamptonMontreal, PQ / Chesterville, ONC26NaNNaNfemale
231st0Allison, Mr Hudson Joshua Creighton30.0000SouthamptonMontreal, PQ / Chesterville, ONC26NaN(135)male
341st0Allison, Mrs Hudson J.C. (Bessie Waldo Daniels)25.0000SouthamptonMontreal, PQ / Chesterville, ONC26NaNNaNfemale
451st1Allison, Master Hudson Trevor0.9167SouthamptonMontreal, PQ / Chesterville, ONC22NaN11male
# 使用pandas,数据都转入pandas独有的dataframe格式(二维数据表格),直接使用info(),
#查看数据的统计特性。
titanic.info()

<class 'pandas.core.frame.DataFrame'>
Int64Index: 1313 entries, 0 to 1312
Data columns (total 11 columns):
row.names    1313 non-null int64
pclass       1313 non-null object
survived     1313 non-null int64
name         1313 non-null object
age          633 non-null float64
embarked     821 non-null object
home.dest    754 non-null object
room         77 non-null object
ticket       69 non-null object
boat         347 non-null object
sex          1313 non-null object
dtypes: float64(1), int64(2), object(8)
memory usage: 123.1+ KB
step2:使用决策树模型预测泰坦尼克号乘客的生还情况
# 机器学习有一个不太被初学者重视,并且耗时,但是十分重要的一环,特征的选择,
#这个需要基于一些背景知识。根据我们对这场事故的了解,sex, age, pclass这些都
#很有可能是决定幸免与否的关键因素。

X = titanic[['pclass', 'age', 'sex']]
y = titanic['survived']

# 对当前选择的特征进行探查。
X.info()

<class 'pandas.core.frame.DataFrame'>
Int64Index: 1313 entries, 0 to 1312
Data columns (total 3 columns):
pclass    1313 non-null object
age       633 non-null float64
sex       1313 non-null object
dtypes: float64(1), object(2)
memory usage: 41.0+ KB
# 借由上面的输出,我们设计如下几个数据处理的任务:
# 1) age这个数据列,只有633个,需要补完。
# 2) sex 与 pclass两个数据列的值都是类别型的,需要转化为数值特征,用0/1代替。

# 首先我们补充age里的数据,使用平均数或者中位数都是对模型偏离造成最小影响的策略。
X['age'].fillna(X['age'].mean(), inplace=True)

C:\Anaconda2\lib\site-packages\pandas\core\generic.py:2862: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  self._update_inplace(new_data)
# 对补完的数据重新探查。
X.info()

<class 'pandas.core.frame.DataFrame'>
Int64Index: 1313 entries, 0 to 1312
Data columns (total 3 columns):
pclass    1313 non-null object
age       1313 non-null float64
sex       1313 non-null object
dtypes: float64(1), object(2)
memory usage: 41.0+ KB
# 由此得知,age特征得到了补完。

# 数据分割。
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state = 33)

# 我们使用scikit-learn.feature_extraction中的特征转换器,详见3.1.1.1特征抽取。
from sklearn.feature_extraction import DictVectorizer
vec = DictVectorizer(sparse=False)

# 转换特征后,我们发现凡是类别型的特征都单独剥离出来,独成一列特征,数值型的则保持不变。
X_train = vec.fit_transform(X_train.to_dict(orient='record'))
print vec.feature_names_
['age', 'pclass=1st', 'pclass=2nd', 'pclass=3rd', 'sex=female', 'sex=male']
# 同样需要对测试数据的特征进行转换。
X_test = vec.transform(X_test.to_dict(orient='record'))

# 从sklearn.tree中导入决策树分类器。
from sklearn.tree import DecisionTreeClassifier
# 使用默认配置初始化决策树分类器。
dtc = DecisionTreeClassifier()
# 使用分割到的训练数据进行模型学习。
dtc.fit(X_train, y_train)
# 用训练好的决策树模型对测试特征数据进行预测。
y_predict = dtc.predict(X_test)

step3:决策树模型对泰塔尼克乘客是否生还的预测性能
# 从sklearn.metrics导入classification_report。
from sklearn.metrics import classification_report
# 输出预测准确性。
print dtc.score(X_test, y_test)
# 输出更加详细的分类性能。
print classification_report(y_predict, y_test, target_names = ['died', 'survived'])

0.781155015198
             precision    recall  f1-score   support

       died       0.91      0.78      0.84       236
   survived       0.58      0.80      0.67        93

avg / total       0.81      0.78      0.79       329
2、集成模型
step1:使用集成模型对泰坦尼克号乘客是否生还的预测
#导入pandas,并且重命名为pd
import pandas as pd

#通过互联网读取泰坦尼克乘客档案,并存储在变量titanic中
titanic = pd.read_csv('http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt')

# 人工选取pclass、age以及sex作为判别乘客是否能够生还的特征。
X = titanic[['pclass', 'age', 'sex']]
y = titanic['survived']

# 对于缺失的年龄信息,我们使用全体乘客的平均年龄代替,这样可以在保证顺利训练模型的同时,尽可能不影响预测任务。
X['age'].fillna(X['age'].mean(), inplace=True)

C:\Anaconda2\lib\site-packages\pandas\core\generic.py:2862: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable
/indexing.html#indexing-view-versus-copy
  self._update_inplace(new_data)
# 对原始数据进行分割,25%的乘客数据用于测试。
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state = 33)

# 对类别型特征进行转化,成为特征向量。
from sklearn.feature_extraction import DictVectorizer

vec = DictVectorizer(sparse=False)
X_train = vec.fit_transform(X_train.to_dict(orient='record'))
X_test = vec.transform(X_test.to_dict(orient='record'))

# 使用单一决策树进行模型训练以及预测分析。
from sklearn.tree import DecisionTreeClassifier

dtc = DecisionTreeClassifier()
dtc.fit(X_train, y_train)
dtc_y_pred = dtc.predict(X_test)

# 使用随机森林分类器进行集成模型的训练以及预测分析。
from sklearn.ensemble import RandomForestClassifier

rfc = RandomForestClassifier()
rfc.fit(X_train, y_train)
rfc_y_pred = rfc.predict(X_test)

# 使用梯度提升决策树进行集成模型的训练以及预测分析。
from sklearn.ensemble import GradientBoostingClassifier

gbc = GradientBoostingClassifier()
gbc.fit(X_train, y_train)
gbc_y_pred = gbc.predict(X_test)

对比单一决策树(Decision Tree)、随机森林分类器(Random Forest Classifier)、梯度提升决策树(Gradient Tree Boosting)的性能差异。

step2:集成模型对泰塔尼克乘客是否生还的预测性能
# 从sklearn.metrics导入classification_report。
from sklearn.metrics import classification_report

# 输出单一决策树在测试集上的分类准确性,以及更加详细的精确率、召回率、F1指标。
print 'The accuracy of decision tree is', dtc.score(X_test, y_test)
print classification_report(dtc_y_pred, y_test)

The accuracy of decision tree is 0.781155015198
             precision    recall  f1-score   support

          0       0.91      0.78      0.84       236
          1       0.58      0.80      0.67        93

avg / total       0.81      0.78      0.79       329
# 输出随机森林分类器在测试集上的分类准确性,以及更加详细的精确率、召回率、F1指标。
print 'The accuracy of random forest classifier is', rfc.score(X_test, y_test)
print classification_report(rfc_y_pred, y_test)

The accuracy of random forest classifier is 0.784194528875
             precision    recall  f1-score   support

          0       0.92      0.77      0.84       239
          1       0.57      0.81      0.67        90

avg / total       0.82      0.78      0.79       329
# 输出梯度提升决策树在测试集上的分类准确性,以及更加详细的精确率、召回率、F1指标。
print 'The accuracy of gradient tree boosting is', gbc.score(X_test, y_test)
print classification_report(gbc_y_pred, y_test)

The accuracy of gradient tree boosting is 0.790273556231
             precision    recall  f1-score   support

          0       0.92      0.78      0.84       239
          1       0.58      0.82      0.68        90

avg / total       0.83      0.79      0.80       329

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值