# Kaggle竞赛题目之——Titanic: Machine Learning from Disaster

The sinking of the RMS Titanic is one of the most infamous shipwrecks in history.  On April 15, 1912, during her maiden voyage, the Titanic sank after colliding with an iceberg, killing 1502 out of 2224 passengers and crew. This sensational tragedy shocked the international community and led to better safety regulations for ships.

One of the reasons that the shipwreck led to such loss of life was that there were not enough lifeboats for the passengers and crew. Although there was some element of luck involved in surviving the sinking, some groups of people were more likely to survive than others, such as women, children, and the upper-class.

In this challenge, we ask you to complete the analysis of what sorts of people were likely to survive. In particular, we ask you to apply the tools of machine learning to predict which passengers survived the tragedy.

#!/usr/bin/env python
#coding:utf-8
'''
Created on 2014年11月25日
@author: zhaohf
'''
import pandas as pd

female_tourist = len(df[df['Sex'] == 'female'])
female_survived = len(df[(df['Sex'] == 'female') & (df['Survived'] == 1)])
print female_survived * 1.0 / female_tourist

tf = pd.read_csv('../Data/test.csv',header=0)
ntf = tf.iloc[:,[0,3]]
ntf['Gender'] = ntf['Sex'].map( {'female': 1, 'male': 0} ).astype(int)
ids = ntf['PassengerId'].values
predicts = ntf['Gender'].values
predictions_file = open("../Submissions/gender_submission.csv", "wb")
open_file_object = csv.writer(predictions_file)
open_file_object.writerow(["PassengerId","Survived"])
open_file_object.writerows(zip(ids, predicts))
predictions_file.close()

import pandas as pd
print df.info()

Int64Index: 891 entries, 0 to 890
Data columns (total 12 columns):
PassengerId    891 non-null int64
Survived       891 non-null int64
Pclass         891 non-null int64
Name           891 non-null object
Sex            891 non-null object
Age            714 non-null float64
SibSp          891 non-null int64
Parch          891 non-null int64
Ticket         891 non-null object
Fare           891 non-null float64
Cabin          204 non-null object
Embarked       889 non-null object
dtypes: float64(2), int64(5), object(5)None


df = df.drop(['Ticket','Name','Cabin','Embarked'],axis=1)
mean = np.mean(m).astype(int)
df['Age'] = df['Age'].map(lambda x : mean if np.isnan(x) else x)
df['Sex'] = df['Sex'].map( {'female': 1, 'male': 0} ).astype(int)

X = df.values
y = df['Survived'].values
X = np.delete(X,1,axis=1)
X_train, X_test, y_train, y_test = cross_validation.train_test_split(X,y,test_size=0.3,random_state=0)
dt = tree.DecisionTreeClassifier(max_depth=5)
dt.fit(X_train, y_train)
print dt.score(X_test,y_test)

#!/usr/bin/env python
#coding:utf-8
'''
Created on 2014年11月25日
@author: zhaohf
'''
import pandas as pd
import numpy as np
from sklearn import tree
from sklearn import cross_validation
import csv
df = df.drop(['Ticket','Name','Cabin','Embarked'],axis=1)
mean = np.mean(m).astype(int)
df['Age'] = df['Age'].map(lambda x : mean if np.isnan(x) else x)
df['Sex'] = df['Sex'].map( {'female': 1, 'male': 0} ).astype(int)
X = df.values
y = df['Survived'].values
X = np.delete(X,1,axis=1)
X_train, X_test, y_train, y_test = cross_validation.train_test_split(X,y,test_size=0.3,random_state=0)
dt = tree.DecisionTreeClassifier(max_depth=5)
dt.fit(X_train, y_train)
print dt.score(X_test,y_test)

tf = test.drop(['Ticket','Name','Cabin','Embarked'],axis=1)
mean = np.mean(m).astype(int)
tf['Age'] = tf['Age'].map(lambda x : mean if np.isnan(x) else int(x))
tf['Sex'] = tf['Sex'].map( {'female': 1, 'male': 0} ).astype(int)
tf['Fare'] = tf['Fare'].map(lambda x : 0 if np.isnan(x) else int(x)).astype(int)
predicts = dt.predict(tf)
ids = tf['PassengerId'].values
predictions_file = open("../Submissions/dt_submission.csv", "wb")
open_file_object = csv.writer(predictions_file)
open_file_object.writerow(["PassengerId","Survived"])
open_file_object.writerows(zip(ids, predicts))
predictions_file.close()

[ 0.06664883  0.14876052  0.52117953  0.10608185  0.08553209  0.00525581 0.06654137]

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客 