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

1.Python机器学习kaggle案例

Numpy-python科学计算库;Pandas-python数据分析处理库;Scikit-learn-python机器学习库;

2.泰坦尼克号数据介绍

乘客编号、是否幸存、等级、姓名、性别、年龄、兄弟姐妹个数、带老人孩子个数、船票、船票价格、上船地点;

3.数据预处理

[python]  view plain  copy
  1. import pandas  #ipython notebook  
  2. titanic = pandas.read_csv("titanic_train.csv")  
  3. #titanic.head(3) //前3行打印出来  
  4. print titanic.describe()  //统计特性:count、mean、std、min、25%、50%、75%、max  

[python]  view plain  copy
  1. titanic ["Age"] = titanic ['Age'] . fillna(titanic['Age'].median())  //Age列中的缺失值用Age均值进行填充  
  2. printf  titanic.describe()  

[python]  view plain  copy
  1. print  titanic ["Sex"].unique()                               //male用0,female用1  
  2. #Replace all the occurences of male with the number 0.  
  3. titanic.loc[titanic["Sex"] == "male","Sex"] = 0  
  4. titanic.loc[titanic["Sex"] == "female","Sex"] = 1  

[python]  view plain  copy
  1. print titanic ["Embarked"].unique()  
  2. titanic["Embarked"] = titanic["Embarked"].fillna('S')     //缺失值用最多的S进行填充  
  3. titanic.loc[titanic["Embarked"] == "S","Embarked"] = 0    //地点用0,1,2  
  4. titanic.loc[titanic["Embarked"] == "C","Embarked"] = 1  
  5. titanic.loc[titanic["Embarked"] == "Q","Embarked"] = 2  

4.回归模型

[python]  view plain  copy
  1. #Import the linear regression class  
  2. from sklearn.linear_model import LinearRegression   //线性回归  
  3. #Sklearn also has a helper that makes it easy to do cross validation  
  4. from sklearn.cross_validation import KFold    //训练集交叉验证,得到平均值  
  5.   
  6. #The columns we'll use to predict the target  
  7. predictors = ["Pclass","Sex","Age","SibSp","Parch","Fare","Embarked"]     //要输入的特征  
  8.   
  9. #Initialize our algorithm class  
  10. alg = LinearRegression()  
  11. #Generate cross validation folds for the titanic dataset.   It return the row indices corresponding to train  
  12. kf = KFold(titanic.shape[0],n_folds=3,random_state=1)   //样本平均分成3份,交叉验证  
  13.   
  14. predictions = []  
  15. for train,test in kf:  
  16.     #The predictors we're using to train the algorithm.  Note how we only take then rows in the train folds.  
  17.     train_predictors = (titanic[predictors].iloc[train,:])  
  18.     #The target we're using to train the algorithm.  
  19.     train_target = titanic["Survived"].iloc[train]  
  20.     #Training the algorithm using the predictors and target.  
  21.     alg.fit(train_predictors,train_target)  
  22.     #We can now make predictions on the test fold  
  23.     test_predictions = alg.predict(titanic[predictors].iloc[test,:])  
  24.     predictions.append(test_predictions)  

[python]  view plain  copy
  1. import numpy as np  
  2.   
  3. #The predictions are in three aeparate numpy arrays.    Concatenate them into one.  
  4. #We concatenate them on axis 0,as they only have one axis.  
  5. predictions = np.concatenate(predictions,axis=0)  
  6.   
  7. #Map predictions to outcomes(only possible outcomes are 1 and 0)  
  8. predictions[predictions>.5] = 1  
  9. predictions[predictions<=.5] = 0  
  10. accuracy = sum(predictions[predictions == titanic["Survived"]]) / len(predictions)  
  11. print accuracy  

[python]  view plain  copy
  1. from sklearn import cross_validation  
  2. from sklearn.linear_model import LogisticRegression   //逻辑回归  
  3. #Initialize our algorithm  
  4. alg=LogisticRegression(random_state=1)  
  5. #Compute the accuracy score for all the cross validation folds.(much simpler than what we did before!)  
  6. scores = cross_validation.cross_val_score(alg,titanic[predictors],titanic["Survived"],cv=3)  
  7. #Take the mean of the scores (because we have one for each fold)  
  8. print(scores.mean())  

5.随机森林模型

(1)随机取样本(有放回的取样)

(2)随机选择特征

(3)多个决策树(投票机制)

[python]  view plain  copy
  1. from sklearn import cross_validation  
  2. from sklearn.ensemble import RandomForestClassifier  
  3.   
  4. predictors=["Pclass","Sex","Age","SibSp","Parch","Fare","Embarked"]  
  5.   
  6. #Initialize our algorithm with the default parameters  
  7. #n_estimators is the number of tress we want to make  
  8. #min_samples_split is the minimum number of rows we need to m,ake a split  
  9. #min_samples_leaf is the minimum number of samples we can have at the place where a tree branch ends (the b)  
  10. alg=RandomForestClassifier(random_state=1,n_estimators=10,min_samples_split=2,min_samples_leaf=1) //10棵决策树,停止的条件:样本个数为2,叶子节点个数为1  
  11. #Compute the accuracy score for all the cross validation folds.  (much simpler than what we did before!)  
  12. kf=cross_validation.KFold(titanic.shape[0],n_folds=3,random_state=1)  
  13. scores=cross_validation.cross_val_cross_val_score(alg,titanic[predictors],titanic["Survived"],cv=kf)  
  14.   
  15. #Take the mean of the scores (because we have one for each fold)  
  16. print(scores.mean())  

[python]  view plain  copy
  1. #Generating a familysize column  
  2. titanic["FamilySize"]=titanic["SibSp"]+titanic["Parch"]  
  3.   
  4. #The .apply method generates a new series  
  5. titanic["NameLength"]=titanic["Name"].apply(lambda x:len(x))  

[python]  view plain  copy
  1. import re   
  2.   
  3. #A function to get the title from a name  
  4. def get_title(name):  
  5.     #Use a regular expression to search for a title. Titles always consist of capital and lowercase letters  
  6.     title_search = re.search('([A-Za-z]+)\.',name)  
  7.     #If the title exists,extract and return it.  
  8.     if title_search:  
  9.         return title_search.group(1)  
  10.     return ""  
  11.   
  12. #Get all the titles and print how often each one occurs.  
  13. titles=titanic["Name"].apply(get_title)  
  14. print(pandas.value_counts(titles))  
  15.   
  16. #Map each titles to an integer.  Some titles are very rare,and are compressed into the same codes as other  
  17. title_mapping = {"Mr":1,"Miss":2,"Mrs":3,"Master":4,"Dr":5,"Rev":6,"Major":7,"Col":7,"Mile":8,"Mme":8,"Don":9,"Lady":10,"Countess":10,"Jonkheer":10,"Str":9,"Capt":7}  
  18. for k,v in title_mapping.items()  
  19.     titles[titles==k]=v  
  20.   
  21. #Verify that we converted everything.  
  22. print(pandas.value_counts(titles))  
  23.   
  24. #Add in the title column  
  25. titanic["Title"]=titles  

6.特征选择

通过加入噪音值前后的错误率的差值来判断特征值的重要程度。

[python]  view plain  copy
  1. import numpy as np  
  2. from sklearn.feature_selection import SelectKBest,f_classif  
  3. import matplotlib.pyplot as plt  
  4. predictors = ["Pclass","Sex","Age","SibSp","Parch","Fare","Embarked","FamilySize","Title","NameLength"]  
  5.   
  6. #Perform feature selection  
  7. selector=SelectKBest(f_classif,k=5)  
  8. selector.fit(titanic[predictors],titanic["Survived"])  
  9.   
  10. #Plot the raw p-values for each feature,and transform from p-values into scores  
  11. scores=-np.log10(selector.pvalues_)  
  12.   
  13. #Plot the scores.   See how "Pclass","Sex","Title",and "Fare" are the best?  
  14. plt.bar(range(len(predictors)).scores)  
  15. plt.xticks(range(len(predictors)).predictors,rotation='vertical')  
  16. plt.show()  
  17.   
  18. #Pick only the four best features.  
  19. predictors=["Pclass","Sex","Fare","Title"]  
  20.   
  21. alg=RandomForestClassifier(random_state=1,n_estimators=50,min_samples_split=8,min_samples_leaf=4)  


[python]  view plain  copy
  1. //集成多种算法求平均的方法来进行机器学习求解  
  2. from sklearn.ensemble import GradientBoostingClassifier  
  3. import numpy as  np  
  4.   
  5. #The algorithms we want to ensemble.  
  6. #We're using the more linear predictors for the logistic regression,and everything with the gradient boosting classifier  
  7. algorithms=[  
  8.     [GradientBoostingClassifier(random_state=1,n_estimators=25,max_depth=3, ["Pclass","Sex","Age","Fare","FamilySize","Title","Age","Embarked"]]  
  9.     [LogisticRegression(random_state=1),["Pclass","Sex","Fare","FamilySize","Title","Age","Embarked"]]  
  10. ]  
  11.   
  12. #Initialize the cross validation folds  
  13. kf=KFold(titanic.shape[0],n_folds=3,random_state=1)  
  14.   
  15. predictions=[]  
  16. for train,test in kf:  
  17.     train_target=titanic["Survived"].iloc[train]  
  18.     full_test_predictions=[]  
  19.     #Make predictions for each algorithm on each fold  
  20.     for alg,predictors in algorithms:  
  21.         #Fit the algorithm on the training data  
  22.         alg.fit(titanic[predictors].iloc[train,:],train_targegt)  
  23.         #Select and predict on the test fold  
  24.         #The .astype(float) is necessary to convert the dataframe to all floats and sklearn error.  
  25.         test_predictions=alg.predict_proba(titanic[predictors].iloc[test,:].astype(float))[:,1]  
  26.     #Use a simple ensembling scheme -- just  average the predictions to get the final classification.  
  27.     test_predictions=(full_test_predictions[0]+full_test_predictions[1])/2  
  28.     #Any value over .5 is assumed to be a 1 prediction,and below .5 is a 0 prediction.  
  29.     test_predictions[test_predictions<=0.5]=0  
  30.     test_predictions[test_predictions>0.5]=1  
  31.     predictions.append(test_predictions)  
  32.   
  33. #Put all the predictions together into one array.  
  34. predictions=np.concatenate(predictions,axis=0)  
  35.   
  36. #Compute accuracy by comparing to the training data  
  37. accuracy=sum(predictions[predictions==titanic["Survived"]])/len(predictions)  
  38. print(accuracy)  

[python]  view plain  copy
  1. #The gradient boosting classifier generates better predictions,so we weight it higher  
  2. predictions=(full_predictions[0]*3+full_predictions[1]*1)/4  
  3. predictions  
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值