学习了机器学习这么久,第一次真正用机器学习中的方法解决一个实际问题,一步步探索,虽然最后结果不是很准确,仅仅达到了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

这个问题参考了很多的博客或教材:

这个问题的视频讲解 http://study.163.com/course/courseLearn.htm?courseId=1003551009&from=study&edusave=1#/learn/video?lessonId=1004052093&courseId=1003551009

使用sklearn进行kaggle案例泰坦尼克Titanic船员获救预测

数据科学工程师面试宝典系列之二---Python机器学习kaggle案例:泰坦尼克号船员获救预测

kaggle之泰坦尼克的沉没

机器学习系列(3)_逻辑回归应用之Kaggle泰坦尼克之灾

经典又兼具备趣味性的Kaggle案例泰坦尼克号问题

kaggle实战之Titanic (1)-预处理

kaggle实战之Titanic(2)-分类器的选择与实现

kaggle入门泰坦尼克之灾内容总结

我的代码已经上传至   github

最新文章

  1. 在非SQL客户端使用命令行方式定期连接SQL Server 服务器并模拟用户查询操作,同时输出信息内容
  2. Win7系统.net framework 4.0没有注册导致部署在IIS的站点跑不起来怎么办
  3. C++ / CLI 调用 C++ /Native 随记
  4. HTML 5 应用程序缓存
  5. C++ 文件操作(CFile类)
  6. c程序设计语言_习题7-6_对比两个输入文本文件_输出它们不同的第一行_并且要记录行号
  7. C# 经典排序算法大全
  8. perl 正则表达式之匹配
  9. iconfont字体图标的使用方法--超简单!
  10. c#加密解密源码,md5、des、rsa
  11. ModelBiner不验证某个属性
  12. tensorboard OSError:[Errno 22] Invalid argument
  13. 语法的二义性和token的超前扫描
  14. [转]VR原理讲解及开发入门
  15. ida信息获取函数
  16. asp.net web form 的缺点
  17. vue-cli 脚手架搭建
  18. vue中请求本地的json数据
  19. Spring MVC 处理模型数据
  20. java-Runtime 调用命令

热门文章

  1. (转)tcp和udp能否发送0字节的数据包
  2. 系统中hosts文件有哪些作用
  3. sublime3 docblocker插件定制自己的注释,配置步骤
  4. 树莓派挂载ntfs优盘
  5. 关于Struts2的文件上传
  6. UNIX环境编程学习笔记(16)——进程管理之进程环境变量
  7. 非抢占式RCU中关于grace period的处理(限于方法)
  8. Vue-router路由判断页面未登录跳转到登录页面
  9. nvm安装node和npm,个人踩坑记录
  10. java中字符串太长,怎么自动换到下一行