Kaggle--泰坦尼克号失踪者生死情况预测源码(附Titanic数据集)

本文主要是介绍Kaggle--泰坦尼克号失踪者生死情况预测源码(附Titanic数据集),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

数据可视化分析

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as nptitanic=pd.read_csv('train.csv')
#print(titanic.head())
#设置某一列为索引
#print(titanic.set_index('PassengerId').head())# =============================================================================
# #绘制一个展示男女乘客比例的扇形图
# #sum the instances of males and females
# males=(titanic['Sex']=='male').sum()
# females=(titanic['Sex']=='female').sum()
# #put them into a list called proportions
# proportions=[males,females]
# #Create a pie chart
# plt.pie(
# #        using proportions
#         proportions,
# #        with the labels being officer names
#         labels=['Males','Females'],
# #        with no shadows
#         shadow=False,
# #        with colors
#         colors=['blue','red'],
#         explode=(0.15,0),
#         startangle=90,
#         autopct='%1.1f%%'
#         )
# plt.axis('equal')
# plt.title("Sex Proportion")
# plt.tight_layout()
# plt.show()
# =============================================================================# =============================================================================
# #绘制一个展示船票Fare,与乘客年龄和性别的散点图
# #creates the plot using
# lm=sns.lmplot(x='Age',y='Fare',data=titanic,hue='Survived',fit_reg=False)
# #set title
# lm.set(title='Fare x Age')
# #get the axes object and tweak it
# axes=lm.axes
# axes[0,0].set_ylim(-5,)
# axes[0,0].set_xlim(-5,85)
# =============================================================================# =============================================================================
# #绘制一个展示船票价格的直方图
# #sort the values from the top to least value and slice the first 5 items
# df=titanic.Fare.sort_values(ascending=False)
# #create bins interval using numpy
# binsVal=np.arange(0,600,10)
# #create the plot
# plt.hist(df,bins=binsVal)
# plt.xlabel('Fare')
# plt.ylabel('Frequency')
# plt.title('Fare Payed Histrogram')
# plt.show()
# =============================================================================#哪个性别的年龄的平均值更大
#print(titanic.groupby('Sex').Age.mean())
#打印出不同性别的年龄的描述性统计信息
#print(titanic.groupby('Sex').Age.describe())
#print(titanic.groupby(['Sex','Survived']).Fare.describe())
#先对Survived再Fare进行排序
#a=titanic.sort_values(['Survived','Fare'],ascending=False)
#print(a)
#选取名字以字母A开头的数据
#b=titanic[titanic.Name.str.startswith('A')]
#print(b)
#找到其中三个人的存活情况
#c=titanic.loc[titanic.Name.isin(['Youseff, Mr. Gerious','Saad, Mr. Amin','Yousif, Mr. Wazli'])\
#              ,['Name','Survived']]
#print(c)
# =============================================================================
# ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
# ts = ts.cumsum()
# ts.plot()
# plt.show()
# 
# df = pd.DataFrame(np.random.randn(1000, 4),index=ts.index,columns=['A', 'B', 'C', 'D'])
# df=df.cumsum()
# plt.figure()
# df.plot()
# plt.legend(loc='best')
# plt.show()
# =============================================================================
#对应每一个location,一共有多少数据值缺失
#print(titanic.isnull().sum())
#对应每一个location,一共有多少数据值完整
#print(titanic.shape[0]-titanic.isnull().sum())
#查看每个列的数据类型
#print(titanic.info())
#print(titanic.dtypes)

主程序
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 10 17:21:16 2018@author: CSH
"""import pandas as pd
titanic=pd.read_csv("train.csv")
#print(titanic.describe())titanic["Age"]=titanic["Age"].fillna(titanic["Age"].median())
#print(titanic.describe())#print(titanic["Sex"].unique())
titanic.loc[titanic["Sex"]=="male","Sex"]=0
titanic.loc[titanic["Sex"]=="female","Sex"]=1#print(titanic["Embarked"].value_counts())
titanic["Embarked"]=titanic["Embarked"].fillna("S")
titanic.loc[titanic["Embarked"]=="S","Embarked"]=0
titanic.loc[titanic["Embarked"]=="C","Embarked"]=1
titanic.loc[titanic["Embarked"]=="Q","Embarked"]=2
#线性回归
# =============================================================================
# from sklearn.linear_model import LinearRegression
# from sklearn.cross_validation import KFold
# predictors=["Pclass","Sex","Age","SibSp","Parch","Fare","Embarked"]
# alg=LinearRegression()
# kf=KFold(titanic.shape[0],n_folds=3,random_state=1)
# predictions=[]
# for train,test in kf:
#     train_predictors=(titanic[predictors].iloc[train,:])
#     train_target=titanic["Survived"].iloc[train]
#     alg.fit(train_predictors,train_target)
#     test_predictions=alg.predict(titanic[predictors].iloc[test,:])
#     predictions.append(test_predictions)
# 
# 
# import numpy as np
# predictions=np.concatenate(predictions,axis=0)
# predictions[predictions>.5]=1
# predictions[predictions<=.5]=0
# accuracy=sum(predictions==titanic["Survived"])/len(predictions)
# print(accuracy)
# =============================================================================
#逻辑回归
# =============================================================================
from sklearn.linear_model import LogisticRegression
from sklearn import cross_validation
# predictors=["Pclass","Sex","Age","SibSp","Parch","Fare","Embarked"]
# alg=LogisticRegression(random_state=1)
# scores=cross_validation.cross_val_score(alg,titanic[predictors],titanic["Survived"],cv=3)
# print(scores.mean())
# =============================================================================
#随机森林
# =============================================================================
# from sklearn import cross_validation
# from sklearn.ensemble import RandomForestClassifier
# predictors=["Pclass","Sex","Age","SibSp","Parch","Fare","Embarked"]
# alg=RandomForestClassifier(random_state=1,n_estimators=150,min_samples_split=12,min_samples_leaf=1)
# kf=cross_validation.KFold(titanic.shape[0],n_folds=3,random_state=1)
# scores=cross_validation.cross_val_score(alg,titanic[predictors],titanic["Survived"],cv=kf)
# print(scores.mean())
# =============================================================================titanic["FamilySize"]=titanic["SibSp"]+titanic["Parch"]
titanic["NameLength"]=titanic["Name"].apply(lambda x:len(x))#提取名字信息
import re
def get_title(name):title_search=re.search('([A-Za-z]+)\.',name)if title_search:return title_search.group(1)return ""titles=titanic["Name"].apply(get_title)
#print(pd.value_counts(titles))title_mapping={"Mr":1,"Miss":2,"Mrs":3,"Master":4,"Dr":5,"Rev":6,"Mlle":7,"Major":8,"Col":9,"Ms":10,"Mme":11,"Lady":12,"Sir":13,"Capt":14,"Don":15,"Jonkheer":16,"Countess":17}
for k,v in title_mapping.items():titles[titles==k]=v
#print(pd.value_counts(titles))
titanic["Title"]=titles
#特征选择
# =============================================================================
# import numpy as np
# from sklearn.feature_selection import SelectKBest,f_classif
# import matplotlib.pyplot as plt
# predictors=["Pclass","Sex","Age","SibSp","Parch","Fare","Embarked","FamilySize","Title","NameLength"]
# selector=SelectKBest(f_classif,k=5)
# selector.fit(titanic[predictors],titanic["Survived"])
# scores=-np.log10(selector.pvalues_)
# 
# plt.bar(range(len(predictors)),scores)
# plt.xticks(range(len(predictors)),predictors,rotation='vertical')
# plt.show()
# =============================================================================# =============================================================================
# from sklearn import cross_validation
# from sklearn.ensemble import RandomForestClassifier
# predictors=["Pclass","Sex","Fare","Title","NameLength"]
# alg=RandomForestClassifier(random_state=1,n_estimators=50,min_samples_split=12,min_samples_leaf=1)
# kf=cross_validation.KFold(titanic.shape[0],n_folds=3,random_state=1)
# scores=cross_validation.cross_val_score(alg,titanic[predictors],titanic["Survived"],cv=kf)
# print(scores.mean())
# =============================================================================#集成学习
from sklearn.cross_validation import KFold
from sklearn.ensemble import GradientBoostingClassifier
import numpy as np
algorithms=[[GradientBoostingClassifier(random_state=1,n_estimators=25,max_depth=3),["Pclass","Sex","Fare","Title","NameLength"]],[LogisticRegression(random_state=1),["Pclass","Sex","Fare","Title","NameLength"]]]kf=KFold(titanic.shape[0],n_folds=3,random_state=1)
predictions=[]
for train,test in kf:train_target=titanic["Survived"].iloc[train]full_test_predictions=[]for alg,predictors in algorithms:alg.fit(titanic[predictors].iloc[train,:],train_target)test_predictions=alg.predict_proba(titanic[predictors].iloc[test,:].astype(float))[:,1]full_test_predictions.append(test_predictions)test_predictions=(full_test_predictions[0]+full_test_predictions[1])/2test_predictions[test_predictions<=.5]=0test_predictions[test_predictions>.5]=1predictions.append(test_predictions)predictions=np.concatenate(predictions,axis=0)
accuracy=sum(predictions==titanic["Survived"])/len(predictions)
print(accuracy)

附:链接:https://pan.baidu.com/s/1K1USWVQQOEM9OLr3M1pniw 密码:n8wz

这篇关于Kaggle--泰坦尼克号失踪者生死情况预测源码(附Titanic数据集)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/563037

相关文章

Python在二进制文件中进行数据搜索的实战指南

《Python在二进制文件中进行数据搜索的实战指南》在二进制文件中搜索特定数据是编程中常见的任务,尤其在日志分析、程序调试和二进制数据处理中尤为重要,下面我们就来看看如何使用Python实现这一功能吧... 目录简介1. 二进制文件搜索概述2. python二进制模式文件读取(rb)2.1 二进制模式与文本

C#实现将XML数据自动化地写入Excel文件

《C#实现将XML数据自动化地写入Excel文件》在现代企业级应用中,数据处理与报表生成是核心环节,本文将深入探讨如何利用C#和一款优秀的库,将XML数据自动化地写入Excel文件,有需要的小伙伴可以... 目录理解XML数据结构与Excel的对应关系引入高效工具:使用Spire.XLS for .NETC

MySQL数据目录迁移的完整过程

《MySQL数据目录迁移的完整过程》文章详细介绍了将MySQL数据目录迁移到新硬盘的整个过程,包括新硬盘挂载、创建新的数据目录、迁移数据(推荐使用两遍rsync方案)、修改MySQL配置文件和重启验证... 目录1,新硬盘挂载(如果有的话)2,创建新的 mysql 数据目录3,迁移 MySQL 数据(推荐两

Python数据验证神器Pydantic库的使用和实践中的避坑指南

《Python数据验证神器Pydantic库的使用和实践中的避坑指南》Pydantic是一个用于数据验证和设置的库,可以显著简化API接口开发,文章通过一个实际案例,展示了Pydantic如何在生产环... 目录1️⃣ 崩溃时刻:当你的API接口又双叒崩了!2️⃣ 神兵天降:3行代码解决验证难题3️⃣ 深度

MySQL快速复制一张表的四种核心方法(包括表结构和数据)

《MySQL快速复制一张表的四种核心方法(包括表结构和数据)》本文详细介绍了四种复制MySQL表(结构+数据)的方法,并对每种方法进行了对比分析,适用于不同场景和数据量的复制需求,特别是针对超大表(1... 目录一、mysql 复制表(结构+数据)的 4 种核心方法(面试结构化回答)方法 1:CREATE

详解C++ 存储二进制数据容器的几种方法

《详解C++存储二进制数据容器的几种方法》本文主要介绍了详解C++存储二进制数据容器,包括std::vector、std::array、std::string、std::bitset和std::ve... 目录1.std::vector<uint8_t>(最常用)特点:适用场景:示例:2.std::arra

MySQL中的DELETE删除数据及注意事项

《MySQL中的DELETE删除数据及注意事项》MySQL的DELETE语句是数据库操作中不可或缺的一部分,通过合理使用索引、批量删除、避免全表删除、使用TRUNCATE、使用ORDERBY和LIMI... 目录1. 基本语法单表删除2. 高级用法使用子查询删除删除多表3. 性能优化策略使用索引批量删除避免

MySQL 数据库进阶之SQL 数据操作与子查询操作大全

《MySQL数据库进阶之SQL数据操作与子查询操作大全》本文详细介绍了SQL中的子查询、数据添加(INSERT)、数据修改(UPDATE)和数据删除(DELETE、TRUNCATE、DROP)操作... 目录一、子查询:嵌套在查询中的查询1.1 子查询的基本语法1.2 子查询的实战示例二、数据添加:INSE

Linux服务器数据盘移除并重新挂载的全过程

《Linux服务器数据盘移除并重新挂载的全过程》:本文主要介绍在Linux服务器上移除并重新挂载数据盘的整个过程,分为三大步:卸载文件系统、分离磁盘和重新挂载,每一步都有详细的步骤和注意事项,确保... 目录引言第一步:卸载文件系统第二步:分离磁盘第三步:重新挂载引言在 linux 服务器上移除并重新挂p

使用MyBatis TypeHandler实现数据加密与解密的具体方案

《使用MyBatisTypeHandler实现数据加密与解密的具体方案》在我们日常的开发工作中,经常会遇到一些敏感数据需要存储,比如用户的手机号、身份证号、银行卡号等,为了保障数据安全,我们通常会对... 目录1. 核心概念:什么是 TypeHandler?2. 实战场景3. 代码实现步骤步骤 1:定义 E