kaggle 泰坦尼克号问题总结
学习了机器学习这么久,第一次真正用机器学习中的方法解决一个实际问题,一步步探索,虽然最后结果不是很准确,仅仅达到了0.78647,但是真是收获很多,为了防止以后我的记忆虫上脑,我决定还是记录下来好了。

1,看到样本是,查看样本的分布和统计情况
#查看数据的统计信息
print(data_train.info())
#查看数据关于数值的统计信息
print(data_train.describe())
通常遇到缺值的情况,我们会有几种常见的处理方式
- 如果缺值的样本占总数比例极高,我们可能就直接舍弃了,作为特征加入的话,可能反倒带入noise,影响最后的结果了,或者考虑有值的是一类,没有值的是一类,
- 如果缺值的样本适中,而该属性非连续值特征属性(比如说类目属性),那就把NaN作为一个新类别,加到类别特征中
- 如果缺值的样本适中,而该属性为连续值特征属性,有时候我们会考虑给定一个step(比如这里的age,我们可以考虑每隔2/3岁为一个步长),然后把它离散化,之后把NaN作为一个type加到属性类目中。
- 有些情况下,缺失的值个数并不是特别多,那我们也可以试着根据已有的值,拟合一下数据,补充上。
随机森林的方法用来填充数据
from sklearn.ensemble import RandomForestRegressor ### 使用 RandomForestClassifier 填补缺失的年龄属性
def set_missing_ages(df): # 把已有的数值型特征取出来丢进Random Forest Regressor中
age_df = df[['Age','Fare', 'Parch', 'SibSp', 'Pclass']] # 乘客分成已知年龄和未知年龄两部分
known_age = age_df[age_df.Age.notnull()].as_matrix()
unknown_age = age_df[age_df.Age.isnull()].as_matrix() # y即目标年龄
y = known_age[:, 0] # X即特征属性值
X = known_age[:, 1:] # fit到RandomForestRegressor之中
rfr = RandomForestRegressor(random_state=0, n_estimators=2000, n_jobs=-1)
rfr.fit(X, y) # 用得到的模型进行未知年龄结果预测
predictedAges = rfr.predict(unknown_age[:, 1::]) # 用得到的预测结果填补原缺失数据
df.loc[ (df.Age.isnull()), 'Age' ] = predictedAges return df, rfr def set_Cabin_type(df):
df.loc[ (df.Cabin.notnull()), 'Cabin' ] = "Yes"
df.loc[ (df.Cabin.isnull()), 'Cabin' ] = "No"
return df data_train, rfr = set_missing_ages(data_train)
data_train = set_Cabin_type(data_train)
2,接下来就是特征工程了,这一步比较复杂,就是选择特征,
特征工程的处理方法包括很多种,可以在我的特征工程的博客中找到。
随机森林特征选择方法:通过加入噪音值前后的错误率的差值来判断特征值的重要程度。
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"] #Perform feature selection
selector=SelectKBest(f_classif,k=5)
selector.fit(titanic[predictors],titanic["Survived"]) #Plot the raw p-values for each feature,and transform from p-values into scores
scores=-np.log10(selector.pvalues_) #Plot the scores. See how "Pclass","Sex","Title",and "Fare" are the best?
plt.bar(range(len(predictors)).scores)
plt.xticks(range(len(predictors)).predictors,rotation='vertical')
plt.show() #Pick only the four best features.
predictors=["Pclass","Sex","Fare","Title"] alg=RandomForestClassifier(random_state=1,n_estimators=50,min_samples_split=8,min_samples_leaf=4)

然后就是模型选择了,
不能找到一个在所有数据上都表现好的模型,这就需要一步一步的验证了,而且同一个模型的不同参数,对结果影响也很大,在解决这个问题中我主要用了n折交叉验证来验证模型的准确率,选择准确率高的模型,然后通过曲线来模拟这些过程,还有一个可以考虑的点就是boosting方法,把许多个弱分类器的结果整合起来,还可以给每个弱分类器一定的权值。
//集成多种算法求平均的方法来进行机器学习求解
from sklearn.ensemble import GradientBoostingClassifier
import numpy as np #The algorithms we want to ensemble.
#We're using the more linear predictors for the logistic regression,and everything with the gradient boosting classifier
algorithms=[
[GradientBoostingClassifier(random_state=1,n_estimators=25,max_depth=3, ["Pclass","Sex","Age","Fare","FamilySize","Title","Age","Embarked"]]
[LogisticRegression(random_state=1),["Pclass","Sex","Fare","FamilySize","Title","Age","Embarked"]]
] #Initialize the cross validation folds
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=[]
#Make predictions for each algorithm on each fold
for alg,predictors in algorithms:
#Fit the algorithm on the training data
alg.fit(titanic[predictors].iloc[train,:],train_targegt)
#Select and predict on the test fold
#The .astype(float) is necessary to convert the dataframe to all floats and sklearn error.
test_predictions=alg.predict_proba(titanic[predictors].iloc[test,:].astype(float))[:,1]
#Use a simple ensembling scheme -- just average the predictions to get the final classification.
test_predictions=(full_test_predictions[0]+full_test_predictions[1])/2
#Any value over .5 is assumed to be a 1 prediction,and below .5 is a 0 prediction.
test_predictions[test_predictions<=0.5]=0
test_predictions[test_predictions>0.5]=1
predictions.append(test_predictions) #Put all the predictions together into one array.
predictions=np.concatenate(predictions,axis=0) #Compute accuracy by comparing to the training data
accuracy=sum(predictions[predictions==titanic["Survived"]])/len(predictions)
print(accuracy) #The gradient boosting classifier generates better predictions,so we weight it higher
predictions=(full_predictions[0]*3+full_predictions[1]*1)/4
predictions
这个问题参考了很多的博客或教材:
使用sklearn进行kaggle案例泰坦尼克Titanic船员获救预测
数据科学工程师面试宝典系列之二---Python机器学习kaggle案例:泰坦尼克号船员获救预测
我的代码已经上传至 github
kaggle 泰坦尼克号问题总结的更多相关文章
- 数据分析-kaggle泰坦尼克号生存率分析
概述 1912年4月15日,泰坦尼克号在首次航行期间撞上冰山后沉没,2224名乘客和机组人员中有1502人遇难.沉船导致大量伤亡的原因之一是没有足够的救生艇给乘客和船员.虽然幸存下来有一些运气因素,但 ...
- 【项目实战】Kaggle泰坦尼克号的幸存者预测
前言 这是学习视频中留下来的一个作业,我决定根据大佬的步骤来一步一步完成整个项目,项目的下载地址如下:https://www.kaggle.com/c/titanic/data 大佬的传送门:http ...
- Kaggle入门——泰坦尼克号生还者预测
前言 这个是Kaggle比赛中泰坦尼克号生存率的分析.强烈建议在做这个比赛的时候,再看一遍电源<泰坦尼克号>,可能会给你一些启发,比如妇女儿童先上船等.所以是否获救其实并非随机,而是基于一 ...
- 箱线图boxplot
箱线图boxplot--展示数据的分布 图表作用: 1.反映一组数据的分布特征,如:分布是否对称,是否存在离群点 2.对多组数据的分布特征进行比较 3.如果只有一个定量变量,很少用箱线图去看数据的分布 ...
- Kaggle竞赛 —— 泰坦尼克号(Titanic)
完整代码见kaggle kernel 或 NbViewer 比赛页面:https://www.kaggle.com/c/titanic Titanic大概是kaggle上最受欢迎的项目了,有7000多 ...
- kaggle入门--泰坦尼克号之灾(手把手教你)
作者:炼己者 具体操作请看这里-- https://www.jianshu.com/p/e79a8c41cb1a 大家也可以看PDF版,用jupyter notebook写的,视觉效果上感觉会更棒 链 ...
- 【Kaggle】泰坦尼克号
引言 Kaggle官方网站 这是泰坦尼克号事件的基本介绍: 我们需要做的就是通过给出的数据集,通过对特征值的分析以及运用机器学习模型,分析什么样的人最可能存活,并给出对测试集合的预测. 对于Kaggl ...
- 数据挖掘竞赛kaggle初战——泰坦尼克号生还预测
1.题目 这道题目的地址在https://www.kaggle.com/c/titanic,题目要求大致是给出一部分泰坦尼克号乘船人员的信息与最后生还情况,利用这些数据,使用机器学习的算法,来分析预测 ...
- 你能在泰坦尼克号上活下来吗?Kaggle的经典挑战
Kaggle Kaggle是一个数据科学家共享数据.交换思想和比赛的平台.人们通常认为Kaggle不适合初学者,或者它学习路线较为坎坷. 没有错.它们确实给那些像你我一样刚刚起步的人带来了挑战.作为一 ...
随机推荐
- Java如何创建用户自定义异常?
在Java编程中,如何创建用户自定义异常? 此示例显示如何通过扩展Exception类来创建用户定义的异常. package com.yiibai; class MyException extends ...
- e833. 获得JTabbedPane中的卡片
This example retrieves all the tabs in a tabbed pane: // To create a tabbed pane, see e828 创建JTabbed ...
- e742. 加入标签的可拖动能力
This example demonstrates how to modify a label component so that its text can be dragged and droppe ...
- css 阻止元素中的文本。双击选中
//firefox -moz-user-select: none; //chrome.safari -webkit-user-select: none; //ie -ms-user-select: n ...
- 7款效果惊人的HTML5/CSS3应用
今天是周末,我为大家收集7个比较经典的HTML5/CSS3应用,每一个都提供源代码,效果非常惊人. 1.CSS3/jQuery创意盒子动画菜单 作为前端开发者,各种各样的jQuery菜单见过不少,这款 ...
- linux中service的问题
1.描述问题 2.解决方案 systemctl stop firewalld systemctl mask firewalld Then, install the iptables-services ...
- java mysql 链接高版本出现SSL验证
key1: String url="jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf-8 ...
- PCL(Point Cloud Library)的第三方库简单介绍(boost,eigen,flann,vtk,qhull)
PCL由于融合了大量的第三方开源库,导致学习成本升高~在学习之前我们最好还是了解一下这些库都是干嘛的,以便有的放矢.在之后更好的使用 boost: C++的标准库的备用版,擅长从数学库到智能指针,从模 ...
- GCT之数学公式(微积分)
- [转] fitnesse中的Map处理
http://blog.csdn.net/doubeizhucele/article/details/42263887 fintesse会把!{}标记的变量视为HashTable对象,展现到页面上的将 ...