Titanic-乘客获救预测1

代码中数据集:https://github.com/jsusu/Titanic_passenger-survival-prediction/tree/master/titanic_data

# Titanic乘客生存预测1

#数据分析库
import pandas as pd
#科学计算库
import numpy as np 
from pandas import Series,DataFrame

# 1.获取数据样本
data_train = pd.read_csv("./titanic_data/titanic_train.csv")
data_test = pd.read_csv("./titanic_data/titanic_test.csv")
# 2.数据处理
data_train.head(10)
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
0103Braund, Mr. Owen Harrismale22.010A/5 211717.2500NaNS
1211Cumings, Mrs. John Bradley (Florence Briggs Th...female38.010PC 1759971.2833C85C
2313Heikkinen, Miss. Lainafemale26.000STON/O2. 31012827.9250NaNS
3411Futrelle, Mrs. Jacques Heath (Lily May Peel)female35.01011380353.1000C123S
4503Allen, Mr. William Henrymale35.0003734508.0500NaNS
5603Moran, Mr. JamesmaleNaN003308778.4583NaNQ
6701McCarthy, Mr. Timothy Jmale54.0001746351.8625E46S
7803Palsson, Master. Gosta Leonardmale2.03134990921.0750NaNS
8913Johnson, Mrs. Oscar W (Elisabeth Vilhelmina Berg)female27.00234774211.1333NaNS
91012Nasser, Mrs. Nicholas (Adele Achem)female14.01023773630.0708NaNC
data_test.head(10)
PassengerIdPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
08923Kelly, Mr. Jamesmale34.5003309117.8292NaNQ
18933Wilkes, Mrs. James (Ellen Needs)female47.0103632727.0000NaNS
28942Myles, Mr. Thomas Francismale62.0002402769.6875NaNQ
38953Wirz, Mr. Albertmale27.0003151548.6625NaNS
48963Hirvonen, Mrs. Alexander (Helga E Lindqvist)female22.011310129812.2875NaNS
58973Svensson, Mr. Johan Cervinmale14.00075389.2250NaNS
68983Connolly, Miss. Katefemale30.0003309727.6292NaNQ
78992Caldwell, Mr. Albert Francismale26.01124873829.0000NaNS
89003Abrahim, Mrs. Joseph (Sophie Halaut Easu)female18.00026577.2292NaNC
99013Davies, Mr. John Samuelmale21.020A/4 4887124.1500NaNS
data_train.info()
#从上面数据我们可以看到Age,Cabin和Embarked列的数据有缺失,
# Age列共有714条数据,缺失117条数据;Cabin列有204条数据,缺失687条数据;E
# mbarked列有889条数据,缺失2条数据,其他列都是891条数据;
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 891 entries, 0 to 890
Data columns (total 12 columns):
 #   Column       Non-Null Count  Dtype  
---  ------       --------------  -----  
 0   PassengerId  891 non-null    int64  
 1   Survived     891 non-null    int64  
 2   Pclass       891 non-null    int64  
 3   Name         891 non-null    object 
 4   Sex          891 non-null    object 
 5   Age          714 non-null    float64
 6   SibSp        891 non-null    int64  
 7   Parch        891 non-null    int64  
 8   Ticket       891 non-null    object 
 9   Fare         891 non-null    float64
 10  Cabin        204 non-null    object 
 11  Embarked     889 non-null    object 
dtypes: float64(2), int64(5), object(5)
memory usage: 83.7+ KB
data_train.describe()
#mean字段告诉我们,大概0.383838的人最后获救了,2/3等舱的人数比1等舱要多,平均乘客年龄大概是29.7岁(计算这个时候会略掉无记录的)等等
PassengerIdSurvivedPclassAgeSibSpParchFare
count891.000000891.000000891.000000714.000000891.000000891.000000891.000000
mean446.0000000.3838382.30864229.6991180.5230080.38159432.204208
std257.3538420.4865920.83607114.5264971.1027430.80605749.693429
min1.0000000.0000001.0000000.4200000.0000000.0000000.000000
25%223.5000000.0000002.00000020.1250000.0000000.0000007.910400
50%446.0000000.0000003.00000028.0000000.0000000.00000014.454200
75%668.5000001.0000003.00000038.0000001.0000000.00000031.000000
max891.0000001.0000003.00000080.0000008.0000006.000000512.329200
# 3.特征选取

# 3.1 数据空值处理
# 客舱号Cabin列由于存在大量的空值,如果直接对空值进行填空,带来的误差影响会比较大,先不选用Cabin列做特征
# 年龄列对于是否能够存活的判断很重要,采用Age均值对空值进行填充
# PassengerId是一个连续的序列,对于是否能够存活的判断无关,不选用PassengerId作为特征

#Age列中的缺失值用Age中位数进行填充
data_train["Age"] = data_train['Age'].fillna(data_train['Age'].median())  
data_train.describe()
PassengerIdSurvivedPclassAgeSibSpParchFare
count891.000000891.000000891.000000891.000000891.000000891.000000891.000000
mean446.0000000.3838382.30864229.3615820.5230080.38159432.204208
std257.3538420.4865920.83607113.0196971.1027430.80605749.693429
min1.0000000.0000001.0000000.4200000.0000000.0000000.000000
25%223.5000000.0000002.00000022.0000000.0000000.0000007.910400
50%446.0000000.0000003.00000028.0000000.0000000.00000014.454200
75%668.5000001.0000003.00000035.0000001.0000000.00000031.000000
max891.0000001.0000003.00000080.0000008.0000006.000000512.329200
# 4. 线性回归算法

#线性回归
from sklearn.linear_model import LinearRegression   
#训练集交叉验证,得到平均值
#from sklearn.cross_validation import KFold 
from sklearn.model_selection import KFold
 
#选取简单的可用输入特征
predictors = ["Pclass","Age","SibSp","Parch","Fare"]     
 
#初始化现行回归算法
alg = LinearRegression()
#样本平均分成3份,3折交叉验证
#kf = KFold(data_train.shape[0],n_folds=3,random_state=1)   
kf = KFold(n_splits=3,shuffle=False,random_state=1) 

predictions = []
for train,test in kf.split(data_train):
    #The predictors we're using to train the algorithm.  Note how we only take then rows in the train folds.
    train_predictors = (data_train[predictors].iloc[train,:])
    #The target we're using to train the algorithm.
    train_target = data_train["Survived"].iloc[train]
    #Training the algorithm using the predictors and target.
    alg.fit(train_predictors,train_target)
    #We can now make predictions on the test fold
    test_predictions = alg.predict(data_train[predictors].iloc[test,:])
    predictions.append(test_predictions)

/Users/susu/opt/anaconda3/envs/data_analysis/lib/python3.7/site-packages/sklearn/model_selection/_split.py:296: FutureWarning: Setting a random_state has no effect since shuffle is False. This will raise an error in 0.24. You should leave random_state to its default (None), or set shuffle=True.
  FutureWarning
import numpy as np
 
#The predictions are in three aeparate numpy arrays.	Concatenate them into one.
#We concatenate them on axis 0,as they only have one axis.
predictions = np.concatenate(predictions,axis=0)
 
#Map predictions to outcomes(only possible outcomes are 1 and 0)
predictions[predictions>.5] = 1
predictions[predictions<=.5] = 0
accuracy = sum(predictions == data_train["Survived"]) / len(predictions)
print ("准确率为: ", accuracy)
准确率为:  0.7037037037037037
# 5.逻辑回归算法
from sklearn import model_selection
#逻辑回归
from sklearn.linear_model import LogisticRegression   

#初始化逻辑回归算法
LogRegAlg=LogisticRegression(random_state=1)
re = LogRegAlg.fit(data_train[predictors],data_train["Survived"])

#使用sklearn库里面的交叉验证函数获取预测准确率分数
scores = model_selection.cross_val_score(LogRegAlg,data_train[predictors],data_train["Survived"],cv=3)

#使用交叉验证分数的平均值作为最终的准确率
print("准确率为: ",scores.mean())
准确率为:  0.7003367003367004
# 5.1 增加特征Sex和Embarked列,查看对预测的影响
# 对性别Sex列和登船港口Embarked列进行字符处理
data_train.head()
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
0103Braund, Mr. Owen Harrismale22.010A/5 211717.2500NaNS
1211Cumings, Mrs. John Bradley (Florence Briggs Th...female38.010PC 1759971.2833C85C
2313Heikkinen, Miss. Lainafemale26.000STON/O2. 31012827.9250NaNS
3411Futrelle, Mrs. Jacques Heath (Lily May Peel)female35.01011380353.1000C123S
4503Allen, Mr. William Henrymale35.0003734508.0500NaNS
#Sex性别列处理:male用0,female用1
data_train.loc[data_train["Sex"] == "male","Sex"] = 0
data_train.loc[data_train["Sex"] == "female","Sex"] = 1
#缺失值用最多的S进行填充
data_train["Embarked"] = data_train["Embarked"].fillna('S') 
#地点用0,1,2
data_train.loc[data_train["Embarked"] == "S","Embarked"] = 0    
data_train.loc[data_train["Embarked"] == "C","Embarked"] = 1
data_train.loc[data_train["Embarked"] == "Q","Embarked"] = 2
# 增加2个特征Sex和Embarked,继续使用逻辑回归算法进行预测
predictors = ["Pclass","Sex","Age","SibSp","Parch","Fare","Embarked"]  

LogRegAlg=LogisticRegression(random_state=1)
#Compute the accuracy score for all the cross validation folds.(much simpler than what we did before!)
re = LogRegAlg.fit(data_train[predictors],data_train["Survived"])
scores = model_selection.cross_val_score(LogRegAlg,data_train[predictors],data_train["Survived"],cv=3)
#Take the mean of the scores (because we have one for each fold)
print("准确率为: ",scores.mean())
准确率为:  0.7957351290684623


/Users/susu/opt/anaconda3/envs/data_analysis/lib/python3.7/site-packages/sklearn/linear_model/_logistic.py:940: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.

Increase the number of iterations (max_iter) or scale the data as shown in:
    https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
    https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
  extra_warning_msg=_LOGISTIC_SOLVER_CONVERGENCE_MSG)
/Users/susu/opt/anaconda3/envs/data_analysis/lib/python3.7/site-packages/sklearn/linear_model/_logistic.py:940: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.

Increase the number of iterations (max_iter) or scale the data as shown in:
    https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
    https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
  extra_warning_msg=_LOGISTIC_SOLVER_CONVERGENCE_MSG)
/Users/susu/opt/anaconda3/envs/data_analysis/lib/python3.7/site-packages/sklearn/linear_model/_logistic.py:940: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.

Increase the number of iterations (max_iter) or scale the data as shown in:
    https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
    https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
  extra_warning_msg=_LOGISTIC_SOLVER_CONVERGENCE_MSG)
/Users/susu/opt/anaconda3/envs/data_analysis/lib/python3.7/site-packages/sklearn/linear_model/_logistic.py:940: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.

Increase the number of iterations (max_iter) or scale the data as shown in:
    https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
    https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
  extra_warning_msg=_LOGISTIC_SOLVER_CONVERGENCE_MSG)
# 通过增加了2个特征,模型的准确率提高到78.78%,说明好的特征有利于提升模型的预测能力。
data_test.describe()
PassengerIdPclassAgeSibSpParchFare
count418.000000418.000000332.000000418.000000418.000000417.000000
mean1100.5000002.26555030.2725900.4473680.39234435.627188
std120.8104580.84183814.1812090.8967600.98142955.907576
min892.0000001.0000000.1700000.0000000.0000000.000000
25%996.2500001.00000021.0000000.0000000.0000007.895800
50%1100.5000003.00000027.0000000.0000000.00000014.454200
75%1204.7500003.00000039.0000001.0000000.00000031.500000
max1309.0000003.00000076.0000008.0000009.000000512.329200
data_test.head()
PassengerIdPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
08923Kelly, Mr. Jamesmale34.5003309117.8292NaNQ
18933Wilkes, Mrs. James (Ellen Needs)female47.0103632727.0000NaNS
28942Myles, Mr. Thomas Francismale62.0002402769.6875NaNQ
38953Wirz, Mr. Albertmale27.0003151548.6625NaNS
48963Hirvonen, Mrs. Alexander (Helga E Lindqvist)female22.011310129812.2875NaNS
#新增:对测试集数据进行预处理,并进行结果预测
#Age列中的缺失值用Age均值进行填充
data_test["Age"] = data_test["Age"].fillna(data_test["Age"].median())
#Fare列中的缺失值用Fare最大值进行填充
data_test["Fare"] = data_test["Fare"].fillna(data_test["Fare"].max()) 

#Sex性别列处理:male用0,female用1
data_test.loc[data_test["Sex"] == "male","Sex"] = 0
data_test.loc[data_test["Sex"] == "female","Sex"] = 1
#缺失值用最多的S进行填充
data_test["Embarked"] = data_test["Embarked"].fillna('S') 
#地点用0,1,2
data_test.loc[data_test["Embarked"] == "S","Embarked"] = 0    
data_test.loc[data_test["Embarked"] == "C","Embarked"] = 1
data_test.loc[data_test["Embarked"] == "Q","Embarked"] = 2

test_features = ["Pclass","Sex","Age","SibSp","Parch","Fare","Embarked"] 
#构造测试集的Survived列,
data_test["Survived"] = -1

test_predictors = data_test[test_features]
data_test["Survived"] = LogRegAlg.predict(test_predictors)
data_test.head(10)
PassengerIdPclassNameSexAgeSibSpParchTicketFareCabinEmbarkedSurvived
08923Kelly, Mr. James034.5003309117.8292NaN20
18933Wilkes, Mrs. James (Ellen Needs)147.0103632727.0000NaN00
28942Myles, Mr. Thomas Francis062.0002402769.6875NaN20
38953Wirz, Mr. Albert027.0003151548.6625NaN00
48963Hirvonen, Mrs. Alexander (Helga E Lindqvist)122.011310129812.2875NaN01
58973Svensson, Mr. Johan Cervin014.00075389.2250NaN00
68983Connolly, Miss. Kate130.0003309727.6292NaN21
78992Caldwell, Mr. Albert Francis026.01124873829.0000NaN00
89003Abrahim, Mrs. Joseph (Sophie Halaut Easu)118.00026577.2292NaN11
99013Davies, Mr. John Samuel021.020A/4 4887124.1500NaN00
# 6.使用随机森林算法
from sklearn import model_selection
from sklearn.ensemble import RandomForestClassifier
 
predictors=["Pclass","Sex","Age","SibSp","Parch","Fare","Embarked"]
 

#10棵决策树,停止的条件:样本个数为2,叶子节点个数为1
alg=RandomForestClassifier(random_state=1,n_estimators=10,min_samples_split=2,min_samples_leaf=1) 

#Compute the accuracy score for all the cross validation folds.  (much simpler than what we did before!)
#kf=cross_validation.KFold(data_train.shape[0],n_folds=3,random_state=1)
kf=model_selection.KFold(n_splits=3,shuffle=False, random_state=1)


scores=model_selection.cross_val_score(alg,data_train[predictors],data_train["Survived"],cv=kf)
print(scores)
#Take the mean of the scores (because we have one for each fold)
print(scores.mean())
[0.75420875 0.8013468  0.8013468 ]
0.7856341189674523


/Users/susu/opt/anaconda3/envs/data_analysis/lib/python3.7/site-packages/sklearn/model_selection/_split.py:296: FutureWarning: Setting a random_state has no effect since shuffle is False. This will raise an error in 0.24. You should leave random_state to its default (None), or set shuffle=True.
  FutureWarning
#增加决策树的个数到30棵决策树,交叉验证方法采用10折交叉验证
#30棵决策树,停止的条件:样本个数为2,叶子节点个数为1
alg=RandomForestClassifier(random_state=1,n_estimators=30,min_samples_split=2,min_samples_leaf=1) 

#Compute the accuracy score for all the cross validation folds.  (much simpler than what we did before!)
#kf=cross_validation.KFold(data_train.shape[0],n_folds=10,random_state=1)
kf=model_selection.KFold(n_splits=10,shuffle=False,random_state=1)

scores=model_selection.cross_val_score(alg,data_train[predictors],data_train["Survived"],cv=kf)
 
print(scores)
#Take the mean of the scores (because we have one for each fold)
print(scores.mean())
/Users/susu/opt/anaconda3/envs/data_analysis/lib/python3.7/site-packages/sklearn/model_selection/_split.py:296: FutureWarning: Setting a random_state has no effect since shuffle is False. This will raise an error in 0.24. You should leave random_state to its default (None), or set shuffle=True.
  FutureWarning


[0.74444444 0.80898876 0.78651685 0.82022472 0.85393258 0.85393258
 0.7752809  0.7752809  0.84269663 0.85393258]
0.8115230961298376
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
好的,这是一个机器学习的任务,需要使用Python中的一些库和工具来完成。首先,你需要安装并导入以下库: ```python import pandas as pd from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score ``` 然后,你需要从train.csv文件中读取数据,并进行一些数据预处理,例如处理缺失值、将类别变量转换为数值变量等。 ```python # 读取数据 train_data = pd.read_csv('train.csv') # 处理缺失值 train_data = train_data.fillna(method='ffill') # 将类别变量转换为数值变量 train_data['Sex'] = train_data['Sex'].map({'male': 0, 'female': 1}) # 选择特征和目标变量 X = train_data[['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare']] y = train_data['Survived'] ``` 接下来,你可以将数据集划分为训练集和测试集,并使用决策树模型进行训练。 ```python # 划分数据集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # 训练模型 model = DecisionTreeClassifier() model.fit(X_train, y_train) ``` 最后,你可以使用测试集对模型进行评估,并对test.csv文件中的数据进行预测。 ```python # 在测试集上评估模型 y_pred = model.predict(X_test) accuracy = accuracy_score(y_test, y_pred) print('Accuracy:', accuracy) # 加载测试集数据 test_data = pd.read_csv('test.csv') # 处理缺失值 test_data = test_data.fillna(method='ffill') # 将类别变量转换为数值变量 test_data['Sex'] = test_data['Sex'].map({'male': 0, 'female': 1}) # 选择特征 X_test = test_data[['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare']] # 预测乘客获救情况 y_pred = model.predict(X_test) print(y_pred) ``` 这样,你就可以使用决策树模型对test.csv文件中的数据进行预测,并获得模型的Accuracy评估指标。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值