{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"#导入相关包\nimport warnings \nwarnings.filterwarnings('ignore')\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\n#设置sns样式\nsns.set(style='white',context='notebook',palette='muted')\nimport matplotlib.pyplot as plt\n#导入数据\ntrain=pd.read_csv('../input/titanic/train.csv')\ntest=pd.read_csv('../input/titanic/test.csv')","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-07-10T03:38:36.509862Z","iopub.execute_input":"2022-07-10T03:38:36.510240Z","iopub.status.idle":"2022-07-10T03:38:37.651148Z","shell.execute_reply.started":"2022-07-10T03:38:36.510170Z","shell.execute_reply":"2022-07-10T03:38:37.648944Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"理解数据","metadata":{}},{"cell_type":"code","source":"#分别查看实验数据集和预测数据集数据\nprint('实验数据大小:',train.shape)\nprint('预测数据大小:',test.shape)","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:37.653130Z","iopub.execute_input":"2022-07-10T03:38:37.653855Z","iopub.status.idle":"2022-07-10T03:38:37.661202Z","shell.execute_reply.started":"2022-07-10T03:38:37.653823Z","shell.execute_reply":"2022-07-10T03:38:37.659619Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"训练集特征说明：\nPassengerID (ID)\nSurvived (是否存活)\nPclass (客舱等级，重要)\nName (姓名，可结合爬虫)\nSex (性别，重要)\nAge (年龄，重要)\nSibSp (旁系亲友)\nParch (直系亲属)\nTicket (票编号)\nFare (票价)\nCabin (客舱编号)\nEmbarked (上船港口编号)","metadata":{}},{"cell_type":"markdown","source":"该数据集共1309条数据，其中实验数据891条，预测数据418条；实验数据比预测数据多了一列：即标签\"result\"。","metadata":{}},{"cell_type":"markdown","source":"记录数据异常值、缺失值情况，方便下一步进行数据预处理。","metadata":{}},{"cell_type":"code","source":"#将实验数据和预测数据合并\nfull=train.append(test,ignore_index=True)\nfull.describe()","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:37.662964Z","iopub.execute_input":"2022-07-10T03:38:37.663341Z","iopub.status.idle":"2022-07-10T03:38:37.732493Z","shell.execute_reply.started":"2022-07-10T03:38:37.663308Z","shell.execute_reply":"2022-07-10T03:38:37.730930Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"无明显的异常值，几乎所有数据均在正常范围内。","metadata":{}},{"cell_type":"code","source":"full.info()","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:37.739274Z","iopub.execute_input":"2022-07-10T03:38:37.741232Z","iopub.status.idle":"2022-07-10T03:38:37.761235Z","shell.execute_reply.started":"2022-07-10T03:38:37.741175Z","shell.execute_reply":"2022-07-10T03:38:37.760001Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Age/Cabin/Embarked/Fare四项数据有缺失值，其中Cabin字段缺失近四分之三的数据。","metadata":{}},{"cell_type":"markdown","source":"结合图表查看各个特征与标签间的关系：","metadata":{}},{"cell_type":"markdown","source":" Embarked与Survived：法国登船的乘客生存率较高","metadata":{}},{"cell_type":"code","source":"sns.barplot(data=train,x='Embarked',y='Survived')","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:37.762489Z","iopub.execute_input":"2022-07-10T03:38:37.762749Z","iopub.status.idle":"2022-07-10T03:38:38.034922Z","shell.execute_reply.started":"2022-07-10T03:38:37.762726Z","shell.execute_reply":"2022-07-10T03:38:38.033425Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#计算不同类型embarked的乘客，其生存率为多少\nprint('Embarked为\"S\"的乘客，其生存率为%.2f'%full['Survived'][full['Embarked']=='S'].value_counts(normalize=True)[1])\nprint('Embarked为\"C\"的乘客，其生存率为%.2f'%full['Survived'][full['Embarked']=='C'].value_counts(normalize=True)[1])\nprint('Embarked为\"Q\"的乘客，其生存率为%.2f'%full['Survived'][full['Embarked']=='Q'].value_counts(normalize=True)[1])","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:38.035975Z","iopub.execute_input":"2022-07-10T03:38:38.036575Z","iopub.status.idle":"2022-07-10T03:38:38.048457Z","shell.execute_reply.started":"2022-07-10T03:38:38.036548Z","shell.execute_reply":"2022-07-10T03:38:38.047834Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"法国登船乘客生存率较高原因可能与其头等舱乘客比例较高有关，因此继续查看不同登船地点乘客各舱位乘客数量情况。","metadata":{}},{"cell_type":"code","source":"#法国登船乘客生存率较高原因可能与其头等舱乘客比例较高有关\nsns.factorplot('Pclass',col='Embarked',data=train,kind='count',size=3)","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:38.049885Z","iopub.execute_input":"2022-07-10T03:38:38.050171Z","iopub.status.idle":"2022-07-10T03:38:38.551301Z","shell.execute_reply.started":"2022-07-10T03:38:38.050147Z","shell.execute_reply":"2022-07-10T03:38:38.550301Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"果然，法国登船的乘客其头等舱所占比例更高","metadata":{}},{"cell_type":"markdown","source":"Parch与Survived：当乘客同行的父母及子女数量适中时，生存率较高","metadata":{}},{"cell_type":"code","source":"sns.barplot(data=train,x='Parch',y='Survived')","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:38.552959Z","iopub.execute_input":"2022-07-10T03:38:38.553263Z","iopub.status.idle":"2022-07-10T03:38:38.965540Z","shell.execute_reply.started":"2022-07-10T03:38:38.553234Z","shell.execute_reply":"2022-07-10T03:38:38.964252Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"SibSp与Survived：当乘客同行的同辈数量适中时生存率较高","metadata":{}},{"cell_type":"code","source":"sns.barplot(data=train,x='SibSp',y='Survived')","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:38.970995Z","iopub.execute_input":"2022-07-10T03:38:38.971673Z","iopub.status.idle":"2022-07-10T03:38:39.446942Z","shell.execute_reply.started":"2022-07-10T03:38:38.971625Z","shell.execute_reply":"2022-07-10T03:38:39.445637Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Pclass与Survived：乘客客舱等级越高，生存率越高","metadata":{}},{"cell_type":"code","source":"sns.barplot(data=train,x='Pclass',y='Survived')","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:39.452156Z","iopub.execute_input":"2022-07-10T03:38:39.453873Z","iopub.status.idle":"2022-07-10T03:38:39.664288Z","shell.execute_reply.started":"2022-07-10T03:38:39.453822Z","shell.execute_reply":"2022-07-10T03:38:39.662661Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Sex与Survived：女性的生存率远高于男性","metadata":{}},{"cell_type":"code","source":"sns.barplot(data=train,x='Sex',y='Survived')","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:39.666599Z","iopub.execute_input":"2022-07-10T03:38:39.666974Z","iopub.status.idle":"2022-07-10T03:38:39.863783Z","shell.execute_reply.started":"2022-07-10T03:38:39.666943Z","shell.execute_reply":"2022-07-10T03:38:39.862373Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Age与Survived：当乘客年龄段在0-10岁期间时生存率会较高","metadata":{}},{"cell_type":"code","source":"#创建坐标轴\nageFacet=sns.FacetGrid(train,hue='Survived',aspect=3)\n#作图，选择图形类型\nageFacet.map(sns.kdeplot,'Age',shade=True)\n#其他信息：坐标轴范围、标签等\nageFacet.set(xlim=(0,train['Age'].max()))\nageFacet.add_legend()","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:39.865496Z","iopub.execute_input":"2022-07-10T03:38:39.865829Z","iopub.status.idle":"2022-07-10T03:38:40.249594Z","shell.execute_reply.started":"2022-07-10T03:38:39.865796Z","shell.execute_reply":"2022-07-10T03:38:40.248854Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Fare与Survived：当票价低于18左右时乘客生存率较低，票价越高生存率一般越高","metadata":{}},{"cell_type":"code","source":"#创建坐标轴\nageFacet=sns.FacetGrid(train,hue='Survived',aspect=3)\nageFacet.map(sns.kdeplot,'Fare',shade=True)\nageFacet.set(xlim=(0,150))\nageFacet.add_legend()","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:40.250553Z","iopub.execute_input":"2022-07-10T03:38:40.251420Z","iopub.status.idle":"2022-07-10T03:38:40.713524Z","shell.execute_reply.started":"2022-07-10T03:38:40.251369Z","shell.execute_reply":"2022-07-10T03:38:40.712828Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"查看票价的分布特征","metadata":{}},{"cell_type":"code","source":"#查看fare分布\nfarePlot=sns.distplot(full['Fare'][full['Fare'].notnull()],label='skewness:%.2f'%(full['Fare'].skew()))\nfarePlot.legend(loc='best')","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:40.714626Z","iopub.execute_input":"2022-07-10T03:38:40.715359Z","iopub.status.idle":"2022-07-10T03:38:41.077628Z","shell.execute_reply.started":"2022-07-10T03:38:40.715325Z","shell.execute_reply":"2022-07-10T03:38:41.076036Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"fare的分布呈左偏的形态，其偏度skewness=4.37较大，说明数据偏移平均值较多，因此我们需要对数据进行对数化处理，防止数据权重分布不均匀。","metadata":{}},{"cell_type":"code","source":"#对数化处理fare值\nfull['Fare']=full['Fare'].map(lambda x: np.log(x) if x>0 else 0)","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:41.079616Z","iopub.execute_input":"2022-07-10T03:38:41.080510Z","iopub.status.idle":"2022-07-10T03:38:41.091061Z","shell.execute_reply.started":"2022-07-10T03:38:41.080469Z","shell.execute_reply":"2022-07-10T03:38:41.088478Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"数据预处理","metadata":{}},{"cell_type":"markdown","source":"Cabin缺失值填充","metadata":{}},{"cell_type":"code","source":"#对Cabin缺失值进行处理，利用U（Unknown）填充缺失值\nfull['Cabin']=full['Cabin'].fillna('U')\nfull['Cabin'].head()","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:41.092534Z","iopub.execute_input":"2022-07-10T03:38:41.093381Z","iopub.status.idle":"2022-07-10T03:38:41.103872Z","shell.execute_reply.started":"2022-07-10T03:38:41.093326Z","shell.execute_reply":"2022-07-10T03:38:41.103057Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Embarked缺失值填充","metadata":{}},{"cell_type":"code","source":"#对Embarked缺失值进行处理，查看缺失值情况\nfull[full['Embarked'].isnull()]","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:41.104957Z","iopub.execute_input":"2022-07-10T03:38:41.105570Z","iopub.status.idle":"2022-07-10T03:38:41.129596Z","shell.execute_reply.started":"2022-07-10T03:38:41.105541Z","shell.execute_reply":"2022-07-10T03:38:41.128095Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"查看Embarked数据分布情况，可知在英国南安普顿登船可能性最大，因此以此填充缺失值。","metadata":{}},{"cell_type":"code","source":"full['Embarked'].value_counts()","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:41.132729Z","iopub.execute_input":"2022-07-10T03:38:41.133930Z","iopub.status.idle":"2022-07-10T03:38:41.147131Z","shell.execute_reply.started":"2022-07-10T03:38:41.133867Z","shell.execute_reply":"2022-07-10T03:38:41.146409Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"full['Embarked']=full['Embarked'].fillna('S')","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:41.148988Z","iopub.execute_input":"2022-07-10T03:38:41.149584Z","iopub.status.idle":"2022-07-10T03:38:41.156803Z","shell.execute_reply.started":"2022-07-10T03:38:41.149557Z","shell.execute_reply":"2022-07-10T03:38:41.155843Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Fare缺失值填充","metadata":{}},{"cell_type":"code","source":"#查看缺失数据情况，该乘客乘坐3等舱，登船港口为法国，舱位未知\nfull[full['Fare'].isnull()]","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:41.158261Z","iopub.execute_input":"2022-07-10T03:38:41.158533Z","iopub.status.idle":"2022-07-10T03:38:41.176540Z","shell.execute_reply.started":"2022-07-10T03:38:41.158507Z","shell.execute_reply":"2022-07-10T03:38:41.175169Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"利用3等舱，登船港口为英国，舱位未知旅客的平均票价来填充缺失值。","metadata":{}},{"cell_type":"code","source":"full['Fare']=full['Fare'].fillna(full[(full['Pclass']==3)&(full['Embarked']=='S')&(full['Cabin']=='U')]['Fare'].mean())","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:41.179121Z","iopub.execute_input":"2022-07-10T03:38:41.179864Z","iopub.status.idle":"2022-07-10T03:38:41.187935Z","shell.execute_reply.started":"2022-07-10T03:38:41.179828Z","shell.execute_reply":"2022-07-10T03:38:41.186726Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"特征工程","metadata":{}},{"cell_type":"markdown","source":" Name中的头衔信息-Title","metadata":{}},{"cell_type":"code","source":"#构造新特征Title\nfull['Title']=full['Name'].map(lambda x:x.split(',')[1].split('.')[0].strip())\n#查看title数据分布\nfull['Title'].value_counts()","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:41.189351Z","iopub.execute_input":"2022-07-10T03:38:41.189639Z","iopub.status.idle":"2022-07-10T03:38:41.205009Z","shell.execute_reply.started":"2022-07-10T03:38:41.189607Z","shell.execute_reply":"2022-07-10T03:38:41.204016Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"将相近的Title信息整合在一起：","metadata":{}},{"cell_type":"code","source":"#将title信息进行整合\nTitleDict={}\nTitleDict['Mr']='Mr'\nTitleDict['Mlle']='Miss'\nTitleDict['Miss']='Miss'\nTitleDict['Master']='Master'\nTitleDict['Jonkheer']='Master'\nTitleDict['Mme']='Mrs'\nTitleDict['Ms']='Mrs'\nTitleDict['Mrs']='Mrs'\nTitleDict['Don']='Royalty'\nTitleDict['Sir']='Royalty'\nTitleDict['the Countess']='Royalty'\nTitleDict['Dona']='Royalty'\nTitleDict['Lady']='Royalty'\nTitleDict['Capt']='Officer'\nTitleDict['Col']='Officer'\nTitleDict['Major']='Officer'\nTitleDict['Dr']='Officer'\nTitleDict['Rev']='Officer'\n\nfull['Title']=full['Title'].map(TitleDict)\nfull['Title'].value_counts()","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:41.207969Z","iopub.execute_input":"2022-07-10T03:38:41.208350Z","iopub.status.idle":"2022-07-10T03:38:41.226294Z","shell.execute_reply.started":"2022-07-10T03:38:41.208324Z","shell.execute_reply":"2022-07-10T03:38:41.224491Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"可视化观察新特征与标签间关系","metadata":{}},{"cell_type":"code","source":"#可视化分析Title与Survived之间关系\nsns.barplot(data=full,x='Title',y='Survived')","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:41.227803Z","iopub.execute_input":"2022-07-10T03:38:41.228788Z","iopub.status.idle":"2022-07-10T03:38:41.613731Z","shell.execute_reply.started":"2022-07-10T03:38:41.228733Z","shell.execute_reply":"2022-07-10T03:38:41.612189Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"头衔为'Mr'及'Officer'的乘客，生存率明显较低。","metadata":{}},{"cell_type":"markdown","source":"FamilyNum及FamilySize信息","metadata":{}},{"cell_type":"markdown","source":"将Parch及SibSp字段整合得到一名乘客同行家庭成员总人数FamilyNum的字段，再根据家庭成员具体人数的多少得到家庭规模FamilySize这个新字段。","metadata":{}},{"cell_type":"code","source":"full['familyNum']=full['Parch']+full['SibSp']+1\n#查看familyNum与Survived\nsns.barplot(data=full,x='familyNum',y='Survived')","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:41.615768Z","iopub.execute_input":"2022-07-10T03:38:41.616341Z","iopub.status.idle":"2022-07-10T03:38:42.086432Z","shell.execute_reply.started":"2022-07-10T03:38:41.616313Z","shell.execute_reply":"2022-07-10T03:38:42.085581Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"家庭成员人数在2-4人时，乘客的生存率较高，当没有家庭成员同行或家庭成员人数过多时生存率较低。","metadata":{}},{"cell_type":"code","source":"#我们按照家庭成员人数多少，将家庭规模分为“小、中、大”三类：\ndef familysize(familyNum):\n    if familyNum==1:\n        return 0\n    elif (familyNum>=2)&(familyNum<=4):\n        return 1\n    else:\n        return 2\n\nfull['familySize']=full['familyNum'].map(familysize)\nfull['familySize'].value_counts()","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:42.087539Z","iopub.execute_input":"2022-07-10T03:38:42.088597Z","iopub.status.idle":"2022-07-10T03:38:42.100451Z","shell.execute_reply.started":"2022-07-10T03:38:42.088568Z","shell.execute_reply":"2022-07-10T03:38:42.099521Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#查看familySize与Survived\nsns.barplot(data=full,x='familySize',y='Survived')","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:42.101835Z","iopub.execute_input":"2022-07-10T03:38:42.103035Z","iopub.status.idle":"2022-07-10T03:38:42.381190Z","shell.execute_reply.started":"2022-07-10T03:38:42.102998Z","shell.execute_reply":"2022-07-10T03:38:42.379796Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"当家庭规模适中时，乘客的生存率更高。","metadata":{}},{"cell_type":"markdown","source":"Cabin客舱类型信息-Deck","metadata":{}},{"cell_type":"code","source":"#提取Cabin字段首字母\nfull['Deck']=full['Cabin'].map(lambda x:x[0])\n#查看不同Deck类型乘客的生存率\nsns.barplot(data=full,x='Deck',y='Survived')","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:42.389252Z","iopub.execute_input":"2022-07-10T03:38:42.389999Z","iopub.status.idle":"2022-07-10T03:38:42.756771Z","shell.execute_reply.started":"2022-07-10T03:38:42.389965Z","shell.execute_reply":"2022-07-10T03:38:42.755189Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"当乘客的客舱类型为B/D/E时，生存率较高；当客舱类型为U/T时，生存率较低。","metadata":{}},{"cell_type":"markdown","source":"共票号乘客数量TickCot及TickGroup","metadata":{}},{"cell_type":"code","source":"#提取各票号的乘客数量\nTickCountDict={}\nTickCountDict=full['Ticket'].value_counts()\nTickCountDict.head()","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:42.758356Z","iopub.execute_input":"2022-07-10T03:38:42.758697Z","iopub.status.idle":"2022-07-10T03:38:42.771127Z","shell.execute_reply.started":"2022-07-10T03:38:42.758666Z","shell.execute_reply":"2022-07-10T03:38:42.769975Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#将同票号乘客数量数据并入数据集中\nfull['TickCot']=full['Ticket'].map(TickCountDict)\nfull['TickCot'].head()","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:42.772472Z","iopub.execute_input":"2022-07-10T03:38:42.772797Z","iopub.status.idle":"2022-07-10T03:38:42.788129Z","shell.execute_reply.started":"2022-07-10T03:38:42.772765Z","shell.execute_reply":"2022-07-10T03:38:42.786569Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#查看TickCot与Survived之间关系\nsns.barplot(data=full,x='TickCot',y='Survived')","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:42.789421Z","iopub.execute_input":"2022-07-10T03:38:42.790464Z","iopub.status.idle":"2022-07-10T03:38:43.283665Z","shell.execute_reply.started":"2022-07-10T03:38:42.790430Z","shell.execute_reply":"2022-07-10T03:38:43.282445Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"当TickCot大小适中时，乘客生存率较高。","metadata":{}},{"cell_type":"code","source":"#按照TickCot大小，将TickGroup分为三类。\ndef TickCountGroup(num):\n    if (num>=2)&(num<=4):\n        return 0\n    elif (num==1)|((num>=5)&(num<=8)):\n        return 1\n    else :\n        return 2\n#得到各位乘客TickGroup的类别\nfull['TickGroup']=full['TickCot'].map(TickCountGroup)\n#查看TickGroup与Survived之间关系\nsns.barplot(data=full,x='TickGroup',y='Survived')\n","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:43.286719Z","iopub.execute_input":"2022-07-10T03:38:43.287163Z","iopub.status.idle":"2022-07-10T03:38:43.619598Z","shell.execute_reply.started":"2022-07-10T03:38:43.287133Z","shell.execute_reply":"2022-07-10T03:38:43.618628Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Age缺失值填充-构建随机森林模型预测缺失的数据","metadata":{}},{"cell_type":"markdown","source":"查看Age与Parch、Pclass、Sex、SibSp、Title、familyNum、familySize、Deck、TickCot、TickGroup等变量的相关系数大小，筛选出相关性较高的变量构建预测模型。","metadata":{}},{"cell_type":"code","source":"#查看缺失值情况\nfull[full['Age'].isnull()].head()","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:43.621567Z","iopub.execute_input":"2022-07-10T03:38:43.622009Z","iopub.status.idle":"2022-07-10T03:38:43.648847Z","shell.execute_reply.started":"2022-07-10T03:38:43.621975Z","shell.execute_reply":"2022-07-10T03:38:43.648139Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#筛选数据集\nAgePre=full[['Age','Parch','Pclass','SibSp','Title','familyNum','TickCot']]\n#进行one-hot编码\nAgePre=pd.get_dummies(AgePre)\nParAge=pd.get_dummies(AgePre['Parch'],prefix='Parch')\nSibAge=pd.get_dummies(AgePre['SibSp'],prefix='SibSp')\nPclAge=pd.get_dummies(AgePre['Pclass'],prefix='Pclass')\n#查看变量间相关性\nAgeCorrDf=pd.DataFrame()\nAgeCorrDf=AgePre.corr()\nAgeCorrDf['Age'].sort_values()","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:43.650045Z","iopub.execute_input":"2022-07-10T03:38:43.650519Z","iopub.status.idle":"2022-07-10T03:38:43.667171Z","shell.execute_reply.started":"2022-07-10T03:38:43.650494Z","shell.execute_reply":"2022-07-10T03:38:43.665607Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#拼接数据\nAgePre=pd.concat([AgePre,ParAge,SibAge,PclAge],axis=1)\nAgePre.head()","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:43.668134Z","iopub.execute_input":"2022-07-10T03:38:43.669178Z","iopub.status.idle":"2022-07-10T03:38:43.688335Z","shell.execute_reply.started":"2022-07-10T03:38:43.669131Z","shell.execute_reply":"2022-07-10T03:38:43.686771Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#拆分实验集和预测集\nAgeKnown=AgePre[AgePre['Age'].notnull()]\nAgeUnKnown=AgePre[AgePre['Age'].isnull()]\n\n#生成实验数据的特征和标签\nAgeKnown_X=AgeKnown.drop(['Age'],axis=1)\nAgeKnown_y=AgeKnown['Age']\n#生成预测数据的特征\nAgeUnKnown_X=AgeUnKnown.drop(['Age'],axis=1)\n\n#利用随机森林构建模型\nfrom sklearn.ensemble import RandomForestRegressor\nrfr=RandomForestRegressor(random_state=None,n_estimators=500,n_jobs=-1)\nrfr.fit(AgeKnown_X,AgeKnown_y)\n\n#模型得分\nrfr.score(AgeKnown_X,AgeKnown_y)","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:43.689709Z","iopub.execute_input":"2022-07-10T03:38:43.691039Z","iopub.status.idle":"2022-07-10T03:38:45.423677Z","shell.execute_reply.started":"2022-07-10T03:38:43.690992Z","shell.execute_reply":"2022-07-10T03:38:45.423011Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#预测年龄\nAgeUnKnown_y=rfr.predict(AgeUnKnown_X)\n#填充预测数据\nfull.loc[full['Age'].isnull(),['Age']]=AgeUnKnown_y\nfull.info()  #此时已无缺失值","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:45.425219Z","iopub.execute_input":"2022-07-10T03:38:45.425471Z","iopub.status.idle":"2022-07-10T03:38:45.647956Z","shell.execute_reply.started":"2022-07-10T03:38:45.425446Z","shell.execute_reply":"2022-07-10T03:38:45.647122Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"虽然通过分析数据已有特征与标签的关系可以构建有效的预测模型，但是部分具有明显共同特征的用户可能与整体模型逻辑并不一致。如果将这部分具有同组效应的用户识别出来并对其数据加以修正，就可以有效提高模型的准确率。在Titancic案例中，我们主要探究相同姓氏的乘客是否存在明显的同组效应。\n\n提取两部分数据，分别查看其“姓氏”是否存在同组效应（因为性别和年龄与乘客生存率关系最为密切，因此用这两个特征作为分类条件）：\n\n12岁以上男性：找出男性中同姓氏均获救的部分；\n女性以及年龄在12岁以下儿童：找出女性及儿童中同姓氏均遇难的部分。\n","metadata":{}},{"cell_type":"code","source":"#提取乘客的姓氏及相应的乘客数\nfull['Surname']=full['Name'].map(lambda x:x.split(',')[0].strip())\nSurNameDict={}\nSurNameDict=full['Surname'].value_counts()\nfull['SurnameNum']=full['Surname'].map(SurNameDict)\n\n#将数据分为两组\nMaleDf=full[(full['Sex']=='male')&(full['Age']>12)&(full['familyNum']>=2)]\nFemChildDf=full[((full['Sex']=='female')|(full['Age']<=12))&(full['familyNum']>=2)]","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:45.649332Z","iopub.execute_input":"2022-07-10T03:38:45.649872Z","iopub.status.idle":"2022-07-10T03:38:45.664443Z","shell.execute_reply.started":"2022-07-10T03:38:45.649837Z","shell.execute_reply":"2022-07-10T03:38:45.663151Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#分析男性同组效应\nMSurNamDf=MaleDf['Survived'].groupby(MaleDf['Surname']).mean()\nMSurNamDf.head()\nMSurNamDf.value_counts()","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:45.668102Z","iopub.execute_input":"2022-07-10T03:38:45.668518Z","iopub.status.idle":"2022-07-10T03:38:45.685730Z","shell.execute_reply.started":"2022-07-10T03:38:45.668484Z","shell.execute_reply":"2022-07-10T03:38:45.684939Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"大多数同姓氏的男性存在“同生共死”的特点，因此利用该同组效应，我们对生存率为1的姓氏里的男性数据进行修正，提升其预测为“可以幸存”的概率。","metadata":{}},{"cell_type":"code","source":"#获得生存率为1的姓氏\nMSurNamDict={}\nMSurNamDict=MSurNamDf[MSurNamDf.values==1].index\nMSurNamDict","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:45.688339Z","iopub.execute_input":"2022-07-10T03:38:45.688804Z","iopub.status.idle":"2022-07-10T03:38:45.697226Z","shell.execute_reply.started":"2022-07-10T03:38:45.688767Z","shell.execute_reply":"2022-07-10T03:38:45.696081Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#分析女性及儿童同组效应\nFCSurNamDf=FemChildDf['Survived'].groupby(FemChildDf['Surname']).mean()\nFCSurNamDf.head()\nFCSurNamDf.value_counts()","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:45.700466Z","iopub.execute_input":"2022-07-10T03:38:45.700836Z","iopub.status.idle":"2022-07-10T03:38:45.713844Z","shell.execute_reply.started":"2022-07-10T03:38:45.700806Z","shell.execute_reply":"2022-07-10T03:38:45.712974Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"与男性组特征相似，女性及儿童也存在明显的“同生共死”的特点，因此利用同组效应，对生存率为0的姓氏里的女性及儿童数据进行修正，提升其预测为“并未幸存”的概率。","metadata":{}},{"cell_type":"code","source":"#获得生存率为0的姓氏\nFCSurNamDict={}\nFCSurNamDict=FCSurNamDf[FCSurNamDf.values==0].index\nFCSurNamDict","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:45.715394Z","iopub.execute_input":"2022-07-10T03:38:45.716013Z","iopub.status.idle":"2022-07-10T03:38:45.726181Z","shell.execute_reply.started":"2022-07-10T03:38:45.715974Z","shell.execute_reply":"2022-07-10T03:38:45.724952Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"对数据集中这些姓氏的两组数据数据分别进行修正：\n\n男性数据修正为：1、性别改为女；2、年龄改为5；\n\n女性及儿童数据修正为：1、性别改为男；2、年龄改为60。","metadata":{}},{"cell_type":"code","source":"#对数据集中这些姓氏的男性数据进行修正：1、性别改为女；2、年龄改为5。\nfull.loc[(full['Survived'].isnull())&(full['Surname'].isin(MSurNamDict))&(full['Sex']=='male'),'Age']=5\nfull.loc[(full['Survived'].isnull())&(full['Surname'].isin(MSurNamDict))&(full['Sex']=='male'),'Sex']='female'\n\n#对数据集中这些姓氏的女性及儿童的数据进行修正：1、性别改为男；2、年龄改为60。\nfull.loc[(full['Survived'].isnull())&(full['Surname'].isin(FCSurNamDict))&((full['Sex']=='female')|(full['Age']<=12)),'Age']=60\nfull.loc[(full['Survived'].isnull())&(full['Surname'].isin(FCSurNamDict))&((full['Sex']=='female')|(full['Age']<=12)),'Sex']='male'","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:45.729827Z","iopub.execute_input":"2022-07-10T03:38:45.730334Z","iopub.status.idle":"2022-07-10T03:38:45.747821Z","shell.execute_reply.started":"2022-07-10T03:38:45.730297Z","shell.execute_reply":"2022-07-10T03:38:45.747128Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"在对数据进行分析处理的过程中，数据的维度更高了，为提升数据有效性需要对数据进行降维处理。通过找出与乘客生存率“Survived”相关性更高的特征，剔除重复的且相关性较低的特征，从而实现数据降维。","metadata":{}},{"cell_type":"code","source":"#人工筛选\nfullSel=full.drop(['Cabin','Name','Ticket','PassengerId','Surname','SurnameNum'],axis=1)\n#查看各特征与标签的相关性\ncorrDf=pd.DataFrame()\ncorrDf=fullSel.corr()\ncorrDf['Survived'].sort_values(ascending=True)","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:45.748999Z","iopub.execute_input":"2022-07-10T03:38:45.749743Z","iopub.status.idle":"2022-07-10T03:38:45.762569Z","shell.execute_reply.started":"2022-07-10T03:38:45.749705Z","shell.execute_reply":"2022-07-10T03:38:45.761230Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"通过热力图，查看Survived与其他特征间相关性大小。","metadata":{}},{"cell_type":"code","source":"#热力图，查看Survived与其他特征间相关性大小\nplt.figure(figsize=(8,8))\nsns.heatmap(fullSel[['Survived','Age','Embarked','Fare','Parch','Pclass',\n                    'Sex','SibSp','Title','familyNum','familySize','Deck',\n                     'TickCot','TickGroup']].corr(),cmap='BrBG',annot=True,\n           linewidths=.5)\nplt.xticks(rotation=45)","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:45.765050Z","iopub.execute_input":"2022-07-10T03:38:45.765737Z","iopub.status.idle":"2022-07-10T03:38:46.428367Z","shell.execute_reply.started":"2022-07-10T03:38:45.765704Z","shell.execute_reply":"2022-07-10T03:38:46.427360Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"先人工初步筛除与标签预测明显不相关或相关度很低的特征，再查看剩余特征与标签之间的相关性大小做进一步降维。","metadata":{}},{"cell_type":"code","source":"fullSel=fullSel.drop(['familyNum','SibSp','TickCot','Parch'],axis=1)\n#one-hot编码\nfullSel=pd.get_dummies(fullSel)\nPclassDf=pd.get_dummies(full['Pclass'],prefix='Pclass')\nTickGroupDf=pd.get_dummies(full['TickGroup'],prefix='TickGroup')\nfamilySizeDf=pd.get_dummies(full['familySize'],prefix='familySize')\n\nfullSel=pd.concat([fullSel,PclassDf,TickGroupDf,familySizeDf],axis=1)","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:46.429595Z","iopub.execute_input":"2022-07-10T03:38:46.429978Z","iopub.status.idle":"2022-07-10T03:38:46.448224Z","shell.execute_reply.started":"2022-07-10T03:38:46.429943Z","shell.execute_reply":"2022-07-10T03:38:46.447038Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#拆分实验数据与预测数据\nexperData=fullSel[fullSel['Survived'].notnull()]\npreData=fullSel[fullSel['Survived'].isnull()]\n\nexperData_X=experData.drop('Survived',axis=1)\nexperData_y=experData['Survived']\npreData_X=preData.drop('Survived',axis=1)\n\n#导入机器学习算法库\nfrom sklearn.ensemble import RandomForestClassifier,GradientBoostingClassifier,ExtraTreesClassifier\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import GridSearchCV,cross_val_score,StratifiedKFold\n\n#设置kfold，交叉采样法拆分数据集\nkfold=StratifiedKFold(n_splits=10)\n\n#汇总不同模型算法\nclassifiers=[]\nclassifiers.append(SVC())\nclassifiers.append(DecisionTreeClassifier())\nclassifiers.append(RandomForestClassifier())\nclassifiers.append(ExtraTreesClassifier())\nclassifiers.append(GradientBoostingClassifier())\nclassifiers.append(KNeighborsClassifier())\nclassifiers.append(LogisticRegression())\nclassifiers.append(LinearDiscriminantAnalysis())","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:46.449549Z","iopub.execute_input":"2022-07-10T03:38:46.449931Z","iopub.status.idle":"2022-07-10T03:38:46.476373Z","shell.execute_reply.started":"2022-07-10T03:38:46.449871Z","shell.execute_reply":"2022-07-10T03:38:46.475221Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"比较各种算法结果，进一步选择模型","metadata":{}},{"cell_type":"code","source":"#不同机器学习交叉验证结果汇总\ncv_results=[]\nfor classifier in classifiers:\n    cv_results.append(cross_val_score(classifier,experData_X,experData_y,\n                                      scoring='accuracy',cv=kfold,n_jobs=-1))","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:46.477637Z","iopub.execute_input":"2022-07-10T03:38:46.478258Z","iopub.status.idle":"2022-07-10T03:38:50.450983Z","shell.execute_reply.started":"2022-07-10T03:38:46.478223Z","shell.execute_reply":"2022-07-10T03:38:50.450184Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"求出模型得分的均值和标准差","metadata":{}},{"cell_type":"code","source":"#求出模型得分的均值和标准差\ncv_means=[]\ncv_std=[]\nfor cv_result in cv_results:\n    cv_means.append(cv_result.mean())\n    cv_std.append(cv_result.std())\n    \n#汇总数据\ncvResDf=pd.DataFrame({'cv_mean':cv_means,\n                     'cv_std':cv_std,\n                     'algorithm':['SVC','DecisionTreeCla','RandomForestCla','ExtraTreesCla',\n                                  'GradientBoostingCla','KNN','LR','LinearDiscrimiAna']})\n\ncvResDf","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:50.452040Z","iopub.execute_input":"2022-07-10T03:38:50.452344Z","iopub.status.idle":"2022-07-10T03:38:50.469625Z","shell.execute_reply.started":"2022-07-10T03:38:50.452314Z","shell.execute_reply":"2022-07-10T03:38:50.468006Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"可视化查看不同算法的表现情况","metadata":{}},{"cell_type":"code","source":"# sns.barplot(data=cvResDf,x='cv_mean',y='algorithm',**{'xerr':cv_std})\n\ncvResFacet=sns.FacetGrid(cvResDf.sort_values(by='cv_mean',ascending=False),sharex=False,\n            sharey=False,aspect=2)\ncvResFacet.map(sns.barplot,'cv_mean','algorithm',**{'xerr':cv_std},\n               palette='muted')\ncvResFacet.set(xlim=(0.7,0.9))\ncvResFacet.add_legend()","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:50.471345Z","iopub.execute_input":"2022-07-10T03:38:50.471705Z","iopub.status.idle":"2022-07-10T03:38:50.820218Z","shell.execute_reply.started":"2022-07-10T03:38:50.471662Z","shell.execute_reply":"2022-07-10T03:38:50.819166Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"综合以上模型表现，考虑选择GradientBoostingCla、LR、RandomForestCla三种模型进一步对比。\n\n分别建立GradientBoostingClassifier,LogisticRegression以及RandomForestClassifier模型，并进行模型调优。","metadata":{}},{"cell_type":"code","source":"#GradientBoostingClassifier模型\nGBC = GradientBoostingClassifier()\ngb_param_grid = {'loss' : [\"deviance\"],\n              'n_estimators' : [100,200,300],\n              'learning_rate': [0.1, 0.05, 0.01],\n              'max_depth': [4, 8],\n              'min_samples_leaf': [100,150],\n              'max_features': [0.3, 0.1]\n              }\nmodelgsGBC = GridSearchCV(GBC,param_grid = gb_param_grid, cv=kfold, \n                                     scoring=\"accuracy\", n_jobs= -1, verbose = 1)\nmodelgsGBC.fit(experData_X,experData_y)\nprint(modelgsGBC.best_params_,modelgsGBC.best_score_)\n#%%\n#LogisticRegression模型\nmodelLR=LogisticRegression()\nLR_param_grid = {'C' : [1,2,3],\n                'penalty':['l1','l2']}\nmodelgsLR = GridSearchCV(modelLR,param_grid = LR_param_grid, cv=kfold, \n                                     scoring=\"accuracy\", n_jobs= -1, verbose = 1)\nmodelgsLR.fit(experData_X,experData_y)\nprint(modelgsLR.best_params_,modelgsLR.best_score_)\n#%%RandomForestClassifier模型\nmodelRFC=RandomForestClassifier(max_features ='sqrt',\n                  random_state=10,warm_start=True)\nRFC_param_grid = {'n_estimators':list(range(20,40,1)),\n                'max_depth':list(range(3,20,2))\n                  }\nmodelRFC = GridSearchCV(modelRFC,param_grid =RFC_param_grid, cv=kfold,\n                                     scoring=\"accuracy\", n_jobs= -1, verbose = 1)\nmodelRFC.fit(experData_X,experData_y)\nprint(modelRFC.best_params_,modelRFC.best_score_)","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:38:50.821578Z","iopub.execute_input":"2022-07-10T03:38:50.822144Z","iopub.status.idle":"2022-07-10T03:39:58.871818Z","shell.execute_reply.started":"2022-07-10T03:38:50.822118Z","shell.execute_reply":"2022-07-10T03:39:58.870613Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#混合模型\nfrom sklearn.ensemble import VotingClassifier\nGBC1=GradientBoostingClassifier(learning_rate= 0.1, loss='deviance', max_depth=4, max_features=0.3, min_samples_leaf=150, n_estimators=300)\nLR1=LogisticRegression(C=1, penalty='l2')\nRFC1=RandomForestClassifier(max_depth=7, n_estimators=22,max_features ='sqrt',\n                  random_state=10,warm_start=True)\neclf1 = VotingClassifier(estimators=[('gbc', GBC1), ('lr', LR1), ('rfc', RFC1)], voting='soft')\neclf1.fit(experData_X,experData_y)","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:39:58.873677Z","iopub.execute_input":"2022-07-10T03:39:58.874063Z","iopub.status.idle":"2022-07-10T03:39:59.154790Z","shell.execute_reply.started":"2022-07-10T03:39:58.874026Z","shell.execute_reply":"2022-07-10T03:39:59.153964Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"查看模型准确度","metadata":{}},{"cell_type":"code","source":"#modelgsGBC模型\nprint('modelgsGBC模型得分为：%.3f'%modelgsGBC.best_score_)\n#modelgsLR模型\nprint('modelgsLR模型得分为：%.3f'%modelgsLR.best_score_)\n#modelRFC模型\nprint('modelRFC模型得分为：%.3f'%modelRFC.best_score_)\n#混合模型\nprint('混合模型得分为：%.3f'%eclf1.score(experData_X,experData_y))","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:39:59.156145Z","iopub.execute_input":"2022-07-10T03:39:59.156633Z","iopub.status.idle":"2022-07-10T03:39:59.179780Z","shell.execute_reply.started":"2022-07-10T03:39:59.156602Z","shell.execute_reply":"2022-07-10T03:39:59.178966Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"利用模型进行预测，并按规则导出预测结果。","metadata":{}},{"cell_type":"code","source":"#TitanicRFCmodle\npreData_y=modelRFC.predict(preData_X)\npreData_y=preData_y.astype(int)\n#导出预测结果\npreResultDf=pd.DataFrame()\npreResultDf['PassengerId']=full['PassengerId'][full['Survived'].isnull()]\npreResultDf['Survived']=preData_y\npreResultDf\n#将预测结果导出为csv文件\npreResultDf.to_csv('submission.csv',index=False)","metadata":{"execution":{"iopub.status.busy":"2022-07-10T03:40:39.600387Z","iopub.execute_input":"2022-07-10T03:40:39.600703Z","iopub.status.idle":"2022-07-10T03:40:39.614643Z","shell.execute_reply.started":"2022-07-10T03:40:39.600677Z","shell.execute_reply":"2022-07-10T03:40:39.613916Z"},"trusted":true},"execution_count":null,"outputs":[]}]}