泰坦尼克号生还者预测案例分析

作者: 羽恒 | 来源:发表于2020-02-24 01:06 被阅读0次

    泰坦尼克号生还者预测

    1912年4月15日,在首次航行期间,泰坦尼克号撞上冰山后沉没,2224名乘客和机组人员中有1502人遇难。这场悲剧轰动了国际社会。沉船导致遇难的原因之一是没有足够的救生艇给乘客和船员。虽然在这场灾难中幸存下来有一些运气在里面,但一些人比其他人更有可能幸存,比如妇女,儿童和上层阶级。

    1.数据描述

    data.info()

    survival - 是否幸存(0=幸存,1=遇难)
    pclass - 船票类型(1=一等票,2=二等票,3=三等票)
    sex - 性别
    age - 年龄
    sibsp - 泰坦尼克号上该人员兄弟姐妹的数量
    parch - 泰坦尼克好上该人员父母或者子女的数量
    ticket - 船票编号
    fare - 乘客票价
    cabin - 客舱号码
    embarked - 起航运港(C = Cherbourg, Q = Queenstown, S = Southampton)
    boat - 救生艇的编号(如果幸存)
    body - 人体编号(如果遇难并且尸体被找到)
    home.dest - 出发地到目的地

    2.数据分析

    2.1 幸存率分析

    幸存率

    计算显示只有38%左右的乘客幸存下来,这次惨剧发生的原因是泰坦尼克号上并未携带足够的救生艇,只有20艘,这对于1317名乘客和885名机组人员来说还远远不够。

    2.1 阶级地位分析

    阶级地位分析

    我们可以看出来头等舱对乘客有62%的生还几率,相比之下三等舱对乘客只有25.5%的生还概率,此外客舱越豪华,乘客的年纪也就越大,同时一等票票价明显高于二三等票。

    2.2 阶级和性别分析

    阶级和性别分析

    从上面的分析中可以看出来,在惨剧发生的时候大家倾向于首先疏散妇女和儿童。在所有的阶层中,女性比男性更有可能生存下来。


    年龄分析

    由上图分析可以看出来,在惨剧发生的时候儿童存活的可能性相对来说还是极高的。

    3.数据处理

    在构建机器学习模型前我们需要删除填充缺失值并且将数据集分为训练集和测试集。

    3.1 缺失值处理

    3.1.1 按列删除缺失数据

    由于boat、cabin、body缺失比较严重,且对后续分析不能提供足够信息,所以删除掉boat、cabin、body这三个字段


    缺失值处理

    3.1.2 按行删除缺失数据

    因为年龄对于乘客能不能生还会产生较大的影响,所以我们选择删除年龄字段缺失的那部分数据。


    缺失值处理

    3.2 编码转换

    sex和embarked都是与类别(比如sex有两种值,male和female)对应的字符串值,因此通过LabelEncoder我们可以将类别字符串分别转换数值数据,比如将“male”和“female”转换成0和1。name、ticket、home.dest字段无法做编码转换成数值数据,所以我们从数据集中删除掉它们。


    labelEncoder

    4 机器学习

    4.1 机器学习简单预测

    决策树
    随机森林

    4.2 K折交叉验证

    K折交叉验证

    数据集选择的不同也会导致预测结果的不同。上述的决策树模型的平均预测准确率为79.61%,根据数据的不同可以有2%左右的浮动变化。

    4.3 特征选择

    我们还可以使用随机森林算法来获取各个不同特征在最终结果预测中的权重


    特征选择

    4.4 多模型效果比较

    模型比较

    由上图比较,我们可以看出随机森林算法在当前数据预测中表现良好,最优值能达到86%以上

    5 案例数据

    5.1 案例数据集

    链接:https://pan.baidu.com/s/1f4AIFes0yTW1ndQOyi-crg
    提取码:1uey

    5.2 完整代码

      #!/usr/bin/env python
    # coding: utf-8
    # 导入python三方库函数
    
    import os 
    import  matplotlib.pyplot  as plt
    get_ipython().run_line_magic('matplotlib', 'inline')
    
    import random
    import numpy as np
    import pandas as pd 
    from sklearn import preprocessing
    
    data_path='案例数据'
    titanic_df  = pd.read_excel(os.path.join(data_path,'titanic3.xls'),'titanic3',index_col=None,na_values=['NA'])
    titanic_df.head()
    titanic_df['survived'].mean()
    titanic_df.groupby('pclass').mean()
    class_sex_grouping  =  titanic_df.groupby(['pclass','sex']).mean()
    class_sex_grouping
    
    class_sex_grouping['survived'].plot.bar(figsize=(12,7),fontsize=12)
    plt.xticks(rotation=45)
    
    group_by_age = pd.cut(titanic_df['age'],np.arange(0,90,10))
    age_grouping = titanic_df.groupby(group_by_age).mean()
    age_grouping['survived'].plot.bar(figsize=(12, 7),colors=['r','y','b'],fontsize=12)
    plt.xticks(rotation=45)
    
    titanic_df.info()
    
    # axis = 1 按列删除
    titanic_df = titanic_df.drop(['body','boat','cabin'],axis=1)
    titanic_df['home.dest'] = titanic_df['home.dest'].fillna('NA')
    titanic_df.head()
    titanic_df = titanic_df.dropna()
    titanic_df.info()
    
    def preprocess_titanic_df(df):
        preprocess_df = df.copy()
        le = preprocessing.LabelEncoder()
        preprocess_df.sex = le.fit_transform(preprocess_df.sex)
        preprocess_df.embarked = le.fit_transform(preprocess_df.embarked)
        preprocess_df = preprocess_df.drop(['name','ticket','home.dest'],axis=1)
        return preprocess_df
    preprocess_df = preprocess_titanic_df(titanic_df)
    
    preprocess_df.head()
    
    # 机器学习简单预测
    x = preprocess_df.drop(['survived'],axis=1).values
    y = preprocess_df['survived'].values
    from sklearn.model_selection import train_test_split
    X_train,X_test,y_train,y_test = train_test_split(x,y,test_size=0.2)
    
    np.random.seed(42)
    # 决策树分类器
    from sklearn.tree import DecisionTreeClassifier
    clf_dt = DecisionTreeClassifier(max_depth = 5)
    clf_dt.fit(X_train,y_train)
    clf_dt.score(X_test,y_test)
    
    # 交叉验证衡量模型的表现能力
    
    from sklearn.model_selection import ShuffleSplit,cross_val_score
    # 随机拆分数据
    shuff_split = ShuffleSplit(n_splits=20,test_size=0.2,random_state=0)
    def test_classifier_suf(clf):  
        scores = cross_val_score(clf,x,y,cv=shuff_split)
        print ("Accuracy: %0.4f (+/- %0.2f)" % (scores.mean(), scores.std()))
        return scores
    clf_dt_scores = test_classifier_suf(clf_dt)
    
    # 随机森林
    # from sklearn.feature_selection import SelectFromModel
    np.random.seed(42)
    from sklearn.ensemble  import RandomForestClassifier
    clf = RandomForestClassifier(n_estimators=50)
    clf_rf_scores = test_classifier_suf(clf)
    
    np.random.seed(42)
    from sklearn.ensemble  import GradientBoostingClassifier
    # from sklearn.feature_selection import SelectFromModel
    clf = GradientBoostingClassifier(n_estimators=50)
    clf_grad_scores = test_classifier_suf(clf)
    
    # 随机森林
    from sklearn.ensemble  import RandomForestClassifier
    from sklearn.feature_selection import SelectFromModel
    np.random.seed(42)
    clf = RandomForestClassifier(n_estimators=50)
    clf = clf.fit(X_train,y_train)
    test_classifier_suf(clf)
    
    features = pd.DataFrame()
    features["feature"] = ["pclass","sex","age","sibsp","parch","fare","embarked"]
    features["importance"] = clf.feature_importances_
    features.sort_values(by=["importance"],ascending=True,inplace=True)
    features.set_index('feature',inplace=True)
    features.plot(kind="barh",figsize=(12,7),fontsize=12)
    plt.show()
    
    x = np.linspace(0,1,20) 
    plt.figure(figsize=(12,7))  #类似于先声明一张图片,这个figure后面所有的设置都是在这张图片上操作的
    plt.plot(x,clf_dt_scores,label="DecisionTreeClassifier")    #制图
    plt.plot(x,clf_grad_scores,color='r',linestyle='--',label="GradientBoostingClassifier") #设置函数线的颜色和线的样式
    plt.plot(x,clf_rf_scores,color='y',linestyle='--',label="RandomForestClassifier") #设置函数线的颜色和线的样式
    plt.legend(loc="upper right")
    plt.grid()
    plt.show() 
    

    相关文章

      网友评论

        本文标题:泰坦尼克号生还者预测案例分析

        本文链接:https://www.haomeiwen.com/subject/qsseqhtx.html