data-science-ipython-notebooks/kaggle/titanic.ipynb

3162 lines
459 KiB
Plaintext
Raw Normal View History

{
2015-05-31 20:53:16 +08:00
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Kaggle Machine Learning Competition: Predicting Titanic Survivors"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Competition Site\n",
"* Description\n",
"* Evaluation\n",
"* Data Set\n",
"* Setup Imports and Variables\n",
"* Explore the Data\n",
"* Feature: Passenger Classes\n",
"* Feature: Sex\n",
"* Feature: Embarked\n",
"* Feature: Age\n",
"* Feature: Family Size\n",
"* Final Data Preparation for Machine Learning\n",
"* Data Wrangling Summary\n",
"* Random Forest: Training\n",
"* Random Forest: Predicting\n",
"* Random Forest: Prepare for Kaggle Submission\n",
"* Support Vector Machine: Training\n",
"* Support Vector Machine: Predicting"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Competition Site"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Description, Evaluation, and Data Set taken from the [competition site](https://www.kaggle.com/c/titanic-gettingStarted)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Description"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![alt text](http://upload.wikimedia.org/wikipedia/commons/6/6e/St%C3%B6wer_Titanic.jpg)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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.\n",
"\n",
"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.\n",
"\n",
"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."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Evaluation"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The historical data has been split into two groups, a 'training set' and a 'test set'. For the training set, we provide the outcome ( 'ground truth' ) for each passenger. You will use this set to build your model to generate predictions for the test set.\n",
"\n",
"For each passenger in the test set, you must predict whether or not they survived the sinking ( 0 for deceased, 1 for survived ). Your score is the percentage of passengers you correctly predict.\n",
"\n",
" The Kaggle leaderboard has a public and private component. 50% of your predictions for the test set have been randomly assigned to the public leaderboard ( the same 50% for all users ). Your score on this public portion is what will appear on the leaderboard. At the end of the contest, we will reveal your score on the private 50% of the data, which will determine the final winner. This method prevents users from 'overfitting' to the leaderboard."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Data Set"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"| File Name | Available Formats |\n",
"|------------------|-------------------|\n",
"| train | .csv (59.76 kb) |\n",
"| gendermodel | .csv (3.18 kb) |\n",
"| genderclassmodel | .csv (3.18 kb) |\n",
"| test | .csv (27.96 kb) |\n",
"| gendermodel | .py (3.58 kb) |\n",
"| genderclassmodel | .py (5.63 kb) |\n",
"| myfirstforest | .py (3.99 kb) |"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<pre>\n",
"VARIABLE DESCRIPTIONS:\n",
"survival Survival\n",
" (0 = No; 1 = Yes)\n",
"pclass Passenger Class\n",
" (1 = 1st; 2 = 2nd; 3 = 3rd)\n",
"name Name\n",
"sex Sex\n",
"age Age\n",
"sibsp Number of Siblings/Spouses Aboard\n",
"parch Number of Parents/Children Aboard\n",
"ticket Ticket Number\n",
"fare Passenger Fare\n",
"cabin Cabin\n",
"embarked Port of Embarkation\n",
" (C = Cherbourg; Q = Queenstown; S = Southampton)\n",
"\n",
"SPECIAL NOTES:\n",
"Pclass is a proxy for socio-economic status (SES)\n",
" 1st ~ Upper; 2nd ~ Middle; 3rd ~ Lower\n",
"\n",
"Age is in Years; Fractional if Age less than One (1)\n",
" If the Age is Estimated, it is in the form xx.5\n",
"\n",
"With respect to the family relation variables (i.e. sibsp and parch)\n",
"some relations were ignored. The following are the definitions used\n",
"for sibsp and parch.\n",
"\n",
"Sibling: Brother, Sister, Stepbrother, or Stepsister of Passenger Aboard Titanic\n",
"Spouse: Husband or Wife of Passenger Aboard Titanic (Mistresses and Fiances Ignored)\n",
"Parent: Mother or Father of Passenger Aboard Titanic\n",
"Child: Son, Daughter, Stepson, or Stepdaughter of Passenger Aboard Titanic\n",
"\n",
"Other family relatives excluded from this study include cousins,\n",
"nephews/nieces, aunts/uncles, and in-laws. Some children travelled\n",
"only with a nanny, therefore parch=0 for them. As well, some\n",
"travelled with very close friends or neighbors in a village, however,\n",
"the definitions do not support such relations.\n",
"</pre>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Setup Imports and Variables"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import pandas as pd\n",
"import numpy as np\n",
"import pylab as plt\n",
"\n",
"# Set the global default size of matplotlib figures\n",
"plt.rc('figure', figsize=(10, 5))\n",
"\n",
"# Size of matplotlib figures that contain subplots\n",
"fizsize_with_subplots = (10, 10)\n",
"\n",
"# Size of matplotlib histogram bins\n",
"bin_size = 10"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Explore the Data"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Read the data:"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/html": [
"<div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>PassengerId</th>\n",
" <th>Survived</th>\n",
" <th>Pclass</th>\n",
" <th>Name</th>\n",
" <th>Sex</th>\n",
" <th>Age</th>\n",
" <th>SibSp</th>\n",
" <th>Parch</th>\n",
" <th>Ticket</th>\n",
" <th>Fare</th>\n",
" <th>Cabin</th>\n",
" <th>Embarked</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td> 1</td>\n",
" <td> 0</td>\n",
" <td> 3</td>\n",
" <td> Braund, Mr. Owen Harris</td>\n",
" <td> male</td>\n",
" <td> 22</td>\n",
" <td> 1</td>\n",
" <td> 0</td>\n",
" <td> A/5 21171</td>\n",
" <td> 7.2500</td>\n",
" <td> NaN</td>\n",
" <td> S</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td> 2</td>\n",
" <td> 1</td>\n",
" <td> 1</td>\n",
" <td> Cumings, Mrs. John Bradley (Florence Briggs Th...</td>\n",
" <td> female</td>\n",
" <td> 38</td>\n",
" <td> 1</td>\n",
" <td> 0</td>\n",
" <td> PC 17599</td>\n",
" <td> 71.2833</td>\n",
" <td> C85</td>\n",
" <td> C</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td> 3</td>\n",
" <td> 1</td>\n",
" <td> 3</td>\n",
" <td> Heikkinen, Miss. Laina</td>\n",
" <td> female</td>\n",
" <td> 26</td>\n",
" <td> 0</td>\n",
" <td> 0</td>\n",
" <td> STON/O2. 3101282</td>\n",
" <td> 7.9250</td>\n",
" <td> NaN</td>\n",
" <td> S</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td> 4</td>\n",
" <td> 1</td>\n",
" <td> 1</td>\n",
" <td> Futrelle, Mrs. Jacques Heath (Lily May Peel)</td>\n",
" <td> female</td>\n",
" <td> 35</td>\n",
" <td> 1</td>\n",
" <td> 0</td>\n",
" <td> 113803</td>\n",
" <td> 53.1000</td>\n",
" <td> C123</td>\n",
" <td> S</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td> 5</td>\n",
" <td> 0</td>\n",
" <td> 3</td>\n",
" <td> Allen, Mr. William Henry</td>\n",
" <td> male</td>\n",
" <td> 35</td>\n",
" <td> 0</td>\n",
" <td> 0</td>\n",
" <td> 373450</td>\n",
" <td> 8.0500</td>\n",
" <td> NaN</td>\n",
" <td> S</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" PassengerId Survived Pclass \\\n",
"0 1 0 3 \n",
"1 2 1 1 \n",
"2 3 1 3 \n",
"3 4 1 1 \n",
"4 5 0 3 \n",
"\n",
" Name Sex Age SibSp \\\n",
"0 Braund, Mr. Owen Harris male 22 1 \n",
"1 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38 1 \n",
"2 Heikkinen, Miss. Laina female 26 0 \n",
"3 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35 1 \n",
"4 Allen, Mr. William Henry male 35 0 \n",
"\n",
" Parch Ticket Fare Cabin Embarked \n",
"0 0 A/5 21171 7.2500 NaN S \n",
"1 0 PC 17599 71.2833 C85 C \n",
"2 0 STON/O2. 3101282 7.9250 NaN S \n",
"3 0 113803 53.1000 C123 S \n",
"4 0 373450 8.0500 NaN S "
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"df_train = pd.read_csv('../data/titanic/train.csv')\n",
"df_train.head()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/html": [
"<div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>PassengerId</th>\n",
" <th>Survived</th>\n",
" <th>Pclass</th>\n",
" <th>Name</th>\n",
" <th>Sex</th>\n",
" <th>Age</th>\n",
" <th>SibSp</th>\n",
" <th>Parch</th>\n",
" <th>Ticket</th>\n",
" <th>Fare</th>\n",
" <th>Cabin</th>\n",
" <th>Embarked</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>886</th>\n",
" <td> 887</td>\n",
" <td> 0</td>\n",
" <td> 2</td>\n",
" <td> Montvila, Rev. Juozas</td>\n",
" <td> male</td>\n",
" <td> 27</td>\n",
" <td> 0</td>\n",
" <td> 0</td>\n",
" <td> 211536</td>\n",
" <td> 13.00</td>\n",
" <td> NaN</td>\n",
" <td> S</td>\n",
" </tr>\n",
" <tr>\n",
" <th>887</th>\n",
" <td> 888</td>\n",
" <td> 1</td>\n",
" <td> 1</td>\n",
" <td> Graham, Miss. Margaret Edith</td>\n",
" <td> female</td>\n",
" <td> 19</td>\n",
" <td> 0</td>\n",
" <td> 0</td>\n",
" <td> 112053</td>\n",
" <td> 30.00</td>\n",
" <td> B42</td>\n",
" <td> S</td>\n",
" </tr>\n",
" <tr>\n",
" <th>888</th>\n",
" <td> 889</td>\n",
" <td> 0</td>\n",
" <td> 3</td>\n",
" <td> Johnston, Miss. Catherine Helen \"Carrie\"</td>\n",
" <td> female</td>\n",
" <td>NaN</td>\n",
" <td> 1</td>\n",
" <td> 2</td>\n",
" <td> W./C. 6607</td>\n",
" <td> 23.45</td>\n",
" <td> NaN</td>\n",
" <td> S</td>\n",
" </tr>\n",
" <tr>\n",
" <th>889</th>\n",
" <td> 890</td>\n",
" <td> 1</td>\n",
" <td> 1</td>\n",
" <td> Behr, Mr. Karl Howell</td>\n",
" <td> male</td>\n",
" <td> 26</td>\n",
" <td> 0</td>\n",
" <td> 0</td>\n",
" <td> 111369</td>\n",
" <td> 30.00</td>\n",
" <td> C148</td>\n",
" <td> C</td>\n",
" </tr>\n",
" <tr>\n",
" <th>890</th>\n",
" <td> 891</td>\n",
" <td> 0</td>\n",
" <td> 3</td>\n",
" <td> Dooley, Mr. Patrick</td>\n",
" <td> male</td>\n",
" <td> 32</td>\n",
" <td> 0</td>\n",
" <td> 0</td>\n",
" <td> 370376</td>\n",
" <td> 7.75</td>\n",
" <td> NaN</td>\n",
" <td> Q</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" PassengerId Survived Pclass Name \\\n",
"886 887 0 2 Montvila, Rev. Juozas \n",
"887 888 1 1 Graham, Miss. Margaret Edith \n",
"888 889 0 3 Johnston, Miss. Catherine Helen \"Carrie\" \n",
"889 890 1 1 Behr, Mr. Karl Howell \n",
"890 891 0 3 Dooley, Mr. Patrick \n",
"\n",
" Sex Age SibSp Parch Ticket Fare Cabin Embarked \n",
"886 male 27 0 0 211536 13.00 NaN S \n",
"887 female 19 0 0 112053 30.00 B42 S \n",
"888 female NaN 1 2 W./C. 6607 23.45 NaN S \n",
"889 male 26 0 0 111369 30.00 C148 C \n",
"890 male 32 0 0 370376 7.75 NaN Q "
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"df_train.tail()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"View the data types of each column:"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"PassengerId int64\n",
"Survived int64\n",
"Pclass int64\n",
"Name object\n",
"Sex object\n",
"Age float64\n",
"SibSp int64\n",
"Parch int64\n",
"Ticket object\n",
"Fare float64\n",
"Cabin object\n",
"Embarked object\n",
"dtype: object"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"df_train.dtypes"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Type 'object' is a string for pandas, which poses problems with machine learning algorithms. If we want to use these as features, we'll need to convert these to number representations."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Get some basic information on the DataFrame:"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<class 'pandas.core.frame.DataFrame'>\n",
"Int64Index: 891 entries, 0 to 890\n",
"Data columns (total 12 columns):\n",
"PassengerId 891 non-null int64\n",
"Survived 891 non-null int64\n",
"Pclass 891 non-null int64\n",
"Name 891 non-null object\n",
"Sex 891 non-null object\n",
"Age 714 non-null float64\n",
"SibSp 891 non-null int64\n",
"Parch 891 non-null int64\n",
"Ticket 891 non-null object\n",
"Fare 891 non-null float64\n",
"Cabin 204 non-null object\n",
"Embarked 889 non-null object\n",
"dtypes: float64(2), int64(5), object(5)"
]
2015-05-31 20:53:16 +08:00
}
],
"source": [
"df_train.info()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Age, Cabin, and Embarked are missing values. Cabin has too many missing values, whereas we might be able to infer values for Age and Embarked."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Generate various descriptive statistics on the DataFrame:"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/html": [
"<div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>PassengerId</th>\n",
" <th>Survived</th>\n",
" <th>Pclass</th>\n",
" <th>Age</th>\n",
" <th>SibSp</th>\n",
" <th>Parch</th>\n",
" <th>Fare</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>count</th>\n",
" <td> 891.000000</td>\n",
" <td> 891.000000</td>\n",
" <td> 891.000000</td>\n",
" <td> 714.000000</td>\n",
" <td> 891.000000</td>\n",
" <td> 891.000000</td>\n",
" <td> 891.000000</td>\n",
" </tr>\n",
" <tr>\n",
" <th>mean</th>\n",
" <td> 446.000000</td>\n",
" <td> 0.383838</td>\n",
" <td> 2.308642</td>\n",
" <td> 29.699118</td>\n",
" <td> 0.523008</td>\n",
" <td> 0.381594</td>\n",
" <td> 32.204208</td>\n",
" </tr>\n",
" <tr>\n",
" <th>std</th>\n",
" <td> 257.353842</td>\n",
" <td> 0.486592</td>\n",
" <td> 0.836071</td>\n",
" <td> 14.526497</td>\n",
" <td> 1.102743</td>\n",
" <td> 0.806057</td>\n",
" <td> 49.693429</td>\n",
" </tr>\n",
" <tr>\n",
" <th>min</th>\n",
" <td> 1.000000</td>\n",
" <td> 0.000000</td>\n",
" <td> 1.000000</td>\n",
" <td> 0.420000</td>\n",
" <td> 0.000000</td>\n",
" <td> 0.000000</td>\n",
" <td> 0.000000</td>\n",
" </tr>\n",
" <tr>\n",
" <th>25%</th>\n",
" <td> 223.500000</td>\n",
" <td> 0.000000</td>\n",
" <td> 2.000000</td>\n",
" <td> 20.125000</td>\n",
" <td> 0.000000</td>\n",
" <td> 0.000000</td>\n",
" <td> 7.910400</td>\n",
" </tr>\n",
" <tr>\n",
" <th>50%</th>\n",
" <td> 446.000000</td>\n",
" <td> 0.000000</td>\n",
" <td> 3.000000</td>\n",
" <td> 28.000000</td>\n",
" <td> 0.000000</td>\n",
" <td> 0.000000</td>\n",
" <td> 14.454200</td>\n",
" </tr>\n",
" <tr>\n",
" <th>75%</th>\n",
" <td> 668.500000</td>\n",
" <td> 1.000000</td>\n",
" <td> 3.000000</td>\n",
" <td> 38.000000</td>\n",
" <td> 1.000000</td>\n",
" <td> 0.000000</td>\n",
" <td> 31.000000</td>\n",
" </tr>\n",
" <tr>\n",
" <th>max</th>\n",
" <td> 891.000000</td>\n",
" <td> 1.000000</td>\n",
" <td> 3.000000</td>\n",
" <td> 80.000000</td>\n",
" <td> 8.000000</td>\n",
" <td> 6.000000</td>\n",
" <td> 512.329200</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" PassengerId Survived Pclass Age SibSp \\\n",
"count 891.000000 891.000000 891.000000 714.000000 891.000000 \n",
"mean 446.000000 0.383838 2.308642 29.699118 0.523008 \n",
"std 257.353842 0.486592 0.836071 14.526497 1.102743 \n",
"min 1.000000 0.000000 1.000000 0.420000 0.000000 \n",
"25% 223.500000 0.000000 2.000000 20.125000 0.000000 \n",
"50% 446.000000 0.000000 3.000000 28.000000 0.000000 \n",
"75% 668.500000 1.000000 3.000000 38.000000 1.000000 \n",
"max 891.000000 1.000000 3.000000 80.000000 8.000000 \n",
"\n",
" Parch Fare \n",
"count 891.000000 891.000000 \n",
"mean 0.381594 32.204208 \n",
"std 0.806057 49.693429 \n",
"min 0.000000 0.000000 \n",
"25% 0.000000 7.910400 \n",
"50% 0.000000 14.454200 \n",
"75% 0.000000 31.000000 \n",
"max 6.000000 512.329200 "
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"df_train.describe()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now that we have a general idea of the data set contents, we can dive deeper into each column. We'll be doing exploratory data analysis and cleaning data to setup 'features' we'll be using in our machine learning algorithms.\n",
"\n",
"Plot a few features to get a better idea of each:"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"<matplotlib.text.Text at 0x10af2a5d0>"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAlIAAAJZCAYAAABiGNuwAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzs3XmcJXV97//Xm11Q6EF02AYGgyNiltEIJi6XVgkaF+De\nGwWNCSNmJQZv1MiM9yZAcsN2k59mIzdXo47INsaISyIwEMolCmjCuI0IGFsZYIa1WcSF5fP74/s9\n9Jkz3X16us/p76mq9/PxOI8+tZyqz/nWqW9/61ufqlJEYGZmZmbbb4fSAZiZmZnVlRtSZmZmZvPk\nhpSZmZnZPLkhZWZmZjZPbkiZmZmZzZMbUmZmZmbz5IZUTUh6XNIzCqx3eV538d+KpL+T9L8GsJwP\nSfrTQcRkZu0lqZL0ltJxWFnF/znWkaQJSQ9LekDSfZL+TdJvS9KAll+bnVPSiyV9UdKkpHskfUHS\n84exroj43Yj434NYVH5NS9J+kv5B0u15G39L0hmSdh/AumeU13HBMNdhNhddddyDkjZL+qCkPUrH\ntdgk7ZL3y5skPSTpu7luODjPMmtdMoR49pT0Xknfy9vmFknvkfTUIa93laTPD3MddeaG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0lPknQoqSdsNt3/F7YAB0raOce8s6RflbRXPuX6IC2um9yQmr9PSXqAdNSzBvgL\noHvnOo2U+Hdt7uZdTzqSg3Tq60mkruMvkk77df+z/UvgVyTdK2mm02TBzP+g30nqlXmAlB91Sc+8\nvZ/rXtb7SAmYXyVdSfKxWdbzIPAC4DpJD5EaUF8jHbUSEeuBS/O4L5Ou8Jlu3b0uIiVtfjQ3SqeL\nk4jYTCq/X8zr6fgwqUv
"text/plain": [
"<matplotlib.figure.Figure at 0x10a9ede50>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"# Set up a grid of plots\n",
"fig = plt.figure(figsize=fizsize_with_subplots) \n",
"fig_dims = (3, 2)\n",
"\n",
"# Plot death and survival counts\n",
"plt.subplot2grid(fig_dims, (0, 0))\n",
"df_train['Survived'].value_counts().plot(kind='bar', \n",
" title='Death and Survival Counts')\n",
"\n",
"# Plot Pclass counts\n",
"plt.subplot2grid(fig_dims, (0, 1))\n",
"df_train['Pclass'].value_counts().plot(kind='bar', \n",
" title='Passenger Class Counts')\n",
"\n",
"# Plot Sex counts\n",
"plt.subplot2grid(fig_dims, (1, 0))\n",
"df_train['Sex'].value_counts().plot(kind='bar', \n",
" title='Gender Counts')\n",
"plt.xticks(rotation=0)\n",
"\n",
"# Plot Embarked counts\n",
"plt.subplot2grid(fig_dims, (1, 1))\n",
"df_train['Embarked'].value_counts().plot(kind='bar', \n",
" title='Ports of Embarkation Counts')\n",
"\n",
"# Plot the Age histogram\n",
"plt.subplot2grid(fig_dims, (2, 0))\n",
"df_train['Age'].hist()\n",
"plt.title('Age Histogram')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Next we'll explore various features to view their impact on survival rates."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Feature: Passenger Classes"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"From our exploratory data analysis in the previous section, we see there are three passenger classes: First, Second, and Third class. We'll determine which proportion of passengers survived based on their passenger class."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Generate a cross tab of Pclass and Survived:"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/html": [
"<div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th>Survived</th>\n",
" <th>0</th>\n",
" <th>1</th>\n",
" </tr>\n",
" <tr>\n",
" <th>Pclass</th>\n",
" <th></th>\n",
" <th></th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>1</th>\n",
" <td> 80</td>\n",
" <td> 136</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td> 97</td>\n",
" <td> 87</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td> 372</td>\n",
" <td> 119</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
"Survived 0 1\n",
"Pclass \n",
"1 80 136\n",
"2 97 87\n",
"3 372 119"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pclass_xt = pd.crosstab(df_train['Pclass'], df_train['Survived'])\n",
"pclass_xt"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Plot the cross tab:"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"<matplotlib.text.Text at 0x10a9eda10>"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAl4AAAFMCAYAAAAa17KLAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3XuYJXV18PvvgiFyGXBAQOWW4QhywBEGBQJipJX3IIpI\n8BUm+IIZkldRIXJi9CUxXtoQoqgxmkAEiRGDyk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IyB/zdT/JiVFEfk1iqbxG4DV\n9y4rp10/TzGF9fkp9lHdVz9vAv4+IlZQ9H5Vz90zKArfeyimxXoUU2LrAH9FcU5/A/wxxWggmflf\nFCM855TTr9dQFMRTxVE9x2eUx3o1cDnFRRGrKj/311IUQ9cCy8vYntFnP/1PQDEKug/F+fpJObX6\nOYp8vK8aX9lf9WaKYnA5xS8RX6zsbgeKXwTupci7UzPz2xT9Xe+l6KW7nWJKe+KXjI9QTFd/rTzf\n36e4IACmPtfSrBCZT/qehFPvPOI/KK7auXPSMHh1m3+haBT9HbA4M5cOLSBJs1ZEvJOiIXvWTUuV\no0wfzcz5Tcci6ckZ9ojXJygaXfuKiJcDO2TmjhSXT390yPFImoXK6cc/p5j+bL1y6vXlUdyHbWuK\nqcE1jeRJaoGhFl6Z+V2K+7NM5ZUUTbFk5g+BeRP9BpI0iIh4HcVU5Vcy85Km45khQXE14HKK+639\nBHhXkwFJmhlNX6K7NY+/ZHobikZcSVqjzDyDR68knBUy8wEe7XmSNIuMQnP95Cuphtd0JkmS1KCm\nR7xu5bH3p9mmXPcYEWExJkmSWiMz+96ip+nC6wLgOIrLrfcGfpvlA1snG+bVl8MSEeXT6lroW8CL\nmw7iCRhvZ660mXnegHH
"text/plain": [
"<matplotlib.figure.Figure at 0x10a9abf90>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"# Normalize the cross tab to sum to 1:\n",
"pclass_xt_pct = pclass_xt.div(pclass_xt.sum(1).astype(float), axis=0)\n",
"\n",
"pclass_xt_pct.plot(kind='bar', \n",
" stacked=True, \n",
" title='Survival Rate by Passenger Classes')\n",
"plt.xlabel('Passenger Class')\n",
"plt.ylabel('Survival Rate')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can see that passenger class seems to have a significant impact on whether a passenger survived. Those in First Class the highest chance for survival."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Feature: Sex"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Gender might have also played a role in determining a passenger's survival rate. We'll need to map Sex from a string to a number to prepare it for machine learning algorithms."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Generate a mapping of Sex from a string to a number representation:"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"{'female': 0, 'male': 1}"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sexes = sort(df_train['Sex'].unique())\n",
"genders_mapping = dict(zip(sexes, range(0, len(sexes) + 1)))\n",
"genders_mapping"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Transform Sex from a string to a number representation:"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/html": [
"<div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>PassengerId</th>\n",
" <th>Survived</th>\n",
" <th>Pclass</th>\n",
" <th>Name</th>\n",
" <th>Sex</th>\n",
" <th>Age</th>\n",
" <th>SibSp</th>\n",
" <th>Parch</th>\n",
" <th>Ticket</th>\n",
" <th>Fare</th>\n",
" <th>Cabin</th>\n",
" <th>Embarked</th>\n",
" <th>Sex_Val</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td> 1</td>\n",
" <td> 0</td>\n",
" <td> 3</td>\n",
" <td> Braund, Mr. Owen Harris</td>\n",
" <td> male</td>\n",
" <td> 22</td>\n",
" <td> 1</td>\n",
" <td> 0</td>\n",
" <td> A/5 21171</td>\n",
" <td> 7.2500</td>\n",
" <td> NaN</td>\n",
" <td> S</td>\n",
" <td> 1</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td> 2</td>\n",
" <td> 1</td>\n",
" <td> 1</td>\n",
" <td> Cumings, Mrs. John Bradley (Florence Briggs Th...</td>\n",
" <td> female</td>\n",
" <td> 38</td>\n",
" <td> 1</td>\n",
" <td> 0</td>\n",
" <td> PC 17599</td>\n",
" <td> 71.2833</td>\n",
" <td> C85</td>\n",
" <td> C</td>\n",
" <td> 0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td> 3</td>\n",
" <td> 1</td>\n",
" <td> 3</td>\n",
" <td> Heikkinen, Miss. Laina</td>\n",
" <td> female</td>\n",
" <td> 26</td>\n",
" <td> 0</td>\n",
" <td> 0</td>\n",
" <td> STON/O2. 3101282</td>\n",
" <td> 7.9250</td>\n",
" <td> NaN</td>\n",
" <td> S</td>\n",
" <td> 0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td> 4</td>\n",
" <td> 1</td>\n",
" <td> 1</td>\n",
" <td> Futrelle, Mrs. Jacques Heath (Lily May Peel)</td>\n",
" <td> female</td>\n",
" <td> 35</td>\n",
" <td> 1</td>\n",
" <td> 0</td>\n",
" <td> 113803</td>\n",
" <td> 53.1000</td>\n",
" <td> C123</td>\n",
" <td> S</td>\n",
" <td> 0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td> 5</td>\n",
" <td> 0</td>\n",
" <td> 3</td>\n",
" <td> Allen, Mr. William Henry</td>\n",
" <td> male</td>\n",
" <td> 35</td>\n",
" <td> 0</td>\n",
" <td> 0</td>\n",
" <td> 373450</td>\n",
" <td> 8.0500</td>\n",
" <td> NaN</td>\n",
" <td> S</td>\n",
" <td> 1</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" PassengerId Survived Pclass \\\n",
"0 1 0 3 \n",
"1 2 1 1 \n",
"2 3 1 3 \n",
"3 4 1 1 \n",
"4 5 0 3 \n",
"\n",
" Name Sex Age SibSp \\\n",
"0 Braund, Mr. Owen Harris male 22 1 \n",
"1 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38 1 \n",
"2 Heikkinen, Miss. Laina female 26 0 \n",
"3 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35 1 \n",
"4 Allen, Mr. William Henry male 35 0 \n",
"\n",
" Parch Ticket Fare Cabin Embarked Sex_Val \n",
"0 0 A/5 21171 7.2500 NaN S 1 \n",
"1 0 PC 17599 71.2833 C85 C 0 \n",
"2 0 STON/O2. 3101282 7.9250 NaN S 0 \n",
"3 0 113803 53.1000 C123 S 0 \n",
"4 0 373450 8.0500 NaN S 1 "
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"df_train['Sex_Val'] = df_train['Sex'].map(genders_mapping).astype(int)\n",
"df_train.head()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Plot a normalized cross tab for Sex_Val and Survived:"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"<matplotlib.axes._subplots.AxesSubplot at 0x10a9ddd50>"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAk8AAAFNCAYAAAAZ54v4AAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3Xu0XHV99/H314SKIWBQvBGxh5ZLwUhCBYTiklH72HgJ\nFCtELLhCbcEKau9W6+XwULQs+7RaQEUfaygiAUUreIF66WgVxQYDqCQIllTCRYrhGtCHhO/zx+wT\nhsPknNlkNntnn/drrSzOb8/v7P2dw+SXz9n7O3siM5EkSdJwnlB3AZIkSdsSw5MkSVIJhidJkqQS\nDE+SJEklGJ4kSZJKMDxJkiSVYHiStFlEfDgi3jmC/SyPiFNHUdOoRcTaiHhp3XU8FhHRjYg31F2H\nNNMZnqSGi4gXRsTlEXFXRPw8Ir4VEQdUcazM/OPM/NtR7Kr48ygRsSwiNkXEvRFxd0RcExFHDrvj\nIvy8pIrayoqIHSPiHyLixoi4LyL+OyI+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zN8/daaedWLRoEd1u\nF4AvfOELLF68mFmzZnHCCSdwxhlnsHLlSt7//vfzpje9CYC3vvWtnHTSSVxzzTXsuuuuI32+hidJ\nkrRVdthhB6688ko++tGP8rSnPY2lS5eyfPnyLc6PCA4//HCe+MQnAnD00Ufzmc98BoALL7yQo446\n6lHfs3TpUi644AIAVqxYwdKlS7nvvvu4/PLLOeqoo9h///154xvfyG233QbA5ZdfzjHH9D6e99hj\njx3l07XnSQ1kX4KkKri2VOoJT3gChx12GIcddhjPe97zWL58ObNnz+ahhx4C4Be/+MUj5s+ZM2fz\n17vuuitPfepT+cEPfsC
"text/plain": [
"<matplotlib.figure.Figure at 0x10adb6d90>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"sex_val_xt = pd.crosstab(df_train['Sex_Val'], df_train['Survived'])\n",
"sex_val_xt_pct = sex_val_xt.div(sex_val_xt.sum(1).astype(float), axis=0)\n",
"sex_val_xt_pct.plot(kind='bar', stacked=True, title='Survival Rate by Gender')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The majority of females survived, whereas the majority of males did not."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Next we'll determine whether we can gain any insights on survival rate by looking at both Sex and Pclass."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Count males and females in each Pclass:"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"M: 1 122\n",
"F: 1 94\n",
"M: 2 108\n",
"F: 2 76\n",
"M: 3 347\n",
"F: 3 144\n"
]
2015-05-31 20:53:16 +08:00
}
],
"source": [
"# Get the unique values of Pclass:\n",
"passenger_classes = sort(df_train['Pclass'].unique())\n",
"\n",
"for p_class in passenger_classes:\n",
" print 'M: ', p_class, len(df_train[(df_train['Sex'] == 'male') & \n",
" (df_train['Pclass'] == p_class)])\n",
" print 'F: ', p_class, len(df_train[(df_train['Sex'] == 'female') & \n",
" (df_train['Pclass'] == p_class)])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Plot survival rate by Sex and Pclass:"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"collapsed": false
},
"outputs": [
{
2015-05-31 20:53:16 +08:00
"data": {
"text/plain": [
"<matplotlib.text.Text at 0x10b610e50>"
]
},
"execution_count": 14,
"metadata": {},
2015-05-31 20:53:16 +08:00
"output_type": "execute_result"
},
{
2015-05-31 20:53:16 +08:00
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAl4AAAFVCAYAAAA+DuHYAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3XuYHHWZ6PHvS8I9QLjpkdtOFpAFAwS5CAvKKB42XhDx\nCFlc4ARdUYGVc9Z1ObqKoxx2F9f1tniJyoJHuQroAgqsRxkVEDEQbkKEKDlyV4wQQESSvOePqgnF\n0JnphOmu7qnv53n6Sdelq97qfmfyzq/eqo7MRJIkSZ23Vt0BSJIkNYWFlyRJUpdYeEmSJHWJhZck\nSVKXWHhJkiR1iYWXJElSl1h4ST0mIgYiYkVE9PTPZ0S8MiIWTsB2BiPi3omIaaJFxFBEfK3uOJok\nIoYj4h11xyF1Sk//YpfqEBGLI+L3EfF4+VgaEf+l7rjaERHTI+LfI+LBMu6fR8TJndhXZv4oM/+s\nE9uuKovQJ8rP4v6I+GxETG3ztS+0cJqwGx2OyquHIuKsiNhworbfLyJinfJzuav8XO+JiDMj4k/K\nVZIJfN+lXmPhJT1fAm/MzI3Kx8aZ+VDdQbXpU8AGwJ9l5sbAm4BFa7KhiJgykYG9QLtl5kbAq4C3\nAMd1ab8xgdtamVfAy4G9gA9N4PZ7yhjF8UXAG4EjgY2B3YH5wGu6FJpUKwsvqU0RsUn5l/kDEXFf\nRJw6cjowIuZGxLUR8cmI+F1ELIqIP4+IYyPiVxHxcEQcU9nWGyJiQUQ8Vi7/yJrst4W9gPMy8zGA\nzPx5Zl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A+ouvOD5V9g8r+ksIvzCVEmS1Dcys+UVxHUX\nXvdTuUcOxWhXy6+S6OR
"text/plain": [
"<matplotlib.figure.Figure at 0x10b0c3710>"
]
},
"metadata": {},
2015-05-31 20:53:16 +08:00
"output_type": "display_data"
},
{
2015-05-31 20:53:16 +08:00
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAl4AAAFVCAYAAAA+DuHYAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3XmYXWWV6P/vMgEZAoZJW0A6tCKiEYIMwkWlRC8dB6Tx\nCmls8Mb2OoJye7D5aTtEubaN3e3UTrTSYisyCGgD2qhX3TggYiBMMghKfjKqyDxKYN0/9i5yKKuS\nk6TOfs+u8/08Tz2pPZx91j5nVWrV+66zd2QmkiRJGrzHlQ5AkiRpVFh4SZIktcTCS5IkqSUWXpIk\nSS2x8JIkSWqJhZckSVJLLLykAiJiXkQ8EhFD/TMYEc+PiKum4ThjEXH9dMQ03SJiSUR8sXQcoyQi\nqoh4Xek4pBKG+j99aRhFxPKIeDAitpiwfllTTG034OefGxH/HhE3R8RdEXF1RBw9iOfKzB9k5jMG\ncexezet2T0TcHRE3RsTHI2J2n49d18Jp2i5m2OTGfc153BIRn4+Ijafr+F0REes378vPm/f1uog4\nPiL+uNklmcbXXeoSCy9pzSXwS+DQ8RUR8WxgQ9r5ZfIRYCPgGZm5KfAK4Nq1OVBEzJrOwNbRzpm5\nCfAC4JXAG1p63pjGYyXw8uY8ngPsDrxrGo8/VFZRHJ8GvJz6Z2RTYBdgKbBfS6FJQ8vCS1o7XwJe\n07P8P4H/oOeXeES8rBkFuzMifhUR753qYBHxhGZE4KaIuCEijlnFNOTuwEmZeSdAZl6dmac3x/mD\nKczeaZ2IWBwRP4qID0fErcAxEXF7RDyrZ/+tmlGbLXunCCPi6Ij4yoS4PxYRH2u+f21EXNGMwv0i\nItaqcMrMXwA/Ap454Xl+1byWSyPiec36hcA7gEXN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-05-31 20:53:16 +08:00
"output_type": "display_data"
}
],
"source": [
"# Plot survival rate by Sex\n",
"females_df = df_train[df_train['Sex'] == 'female']\n",
"females_xt = pd.crosstab(females_df['Pclass'], df_train['Survived'])\n",
"females_xt_pct = females_xt.div(females_xt.sum(1).astype(float), axis=0)\n",
"females_xt_pct.plot(kind='bar', \n",
" stacked=True, \n",
" title='Female Survival Rate by Passenger Class')\n",
"plt.xlabel('Passenger Class')\n",
"plt.ylabel('Survival Rate')\n",
"\n",
"# Plot survival rate by Pclass\n",
"males_df = df_train[df_train['Sex'] == 'male']\n",
"males_xt = pd.crosstab(males_df['Pclass'], df_train['Survived'])\n",
"males_xt_pct = males_xt.div(males_xt.sum(1).astype(float), axis=0)\n",
"males_xt_pct.plot(kind='bar', \n",
" stacked=True, \n",
" title='Male Survival Rate by Passenger Class')\n",
"plt.xlabel('Passenger Class')\n",
"plt.ylabel('Survival Rate')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The vast majority of females in First and Second class survived. Males in First class had the highest chance for survival."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Feature: Embarked"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The Embarked column might be an important feature but it is missing a couple data points which might pose a problem for machine learning algorithms:"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/html": [
"<div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>PassengerId</th>\n",
" <th>Survived</th>\n",
" <th>Pclass</th>\n",
" <th>Name</th>\n",
" <th>Sex</th>\n",
" <th>Age</th>\n",
" <th>SibSp</th>\n",
" <th>Parch</th>\n",
" <th>Ticket</th>\n",
" <th>Fare</th>\n",
" <th>Cabin</th>\n",
" <th>Embarked</th>\n",
" <th>Sex_Val</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>61 </th>\n",
" <td> 62</td>\n",
" <td> 1</td>\n",
" <td> 1</td>\n",
" <td> Icard, Miss. Amelie</td>\n",
" <td> female</td>\n",
" <td> 38</td>\n",
" <td> 0</td>\n",
" <td> 0</td>\n",
" <td> 113572</td>\n",
" <td> 80</td>\n",
" <td> B28</td>\n",
" <td> NaN</td>\n",
" <td> 0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>829</th>\n",
" <td> 830</td>\n",
" <td> 1</td>\n",
" <td> 1</td>\n",
" <td> Stone, Mrs. George Nelson (Martha Evelyn)</td>\n",
" <td> female</td>\n",
" <td> 62</td>\n",
" <td> 0</td>\n",
" <td> 0</td>\n",
" <td> 113572</td>\n",
" <td> 80</td>\n",
" <td> B28</td>\n",
" <td> NaN</td>\n",
" <td> 0</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" PassengerId Survived Pclass Name \\\n",
"61 62 1 1 Icard, Miss. Amelie \n",
"829 830 1 1 Stone, Mrs. George Nelson (Martha Evelyn) \n",
"\n",
" Sex Age SibSp Parch Ticket Fare Cabin Embarked Sex_Val \n",
"61 female 38 0 0 113572 80 B28 NaN 0 \n",
"829 female 62 0 0 113572 80 B28 NaN 0 "
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"df_train[df_train['Embarked'].isnull()]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Prepare to map Embarked from a string to a number representation:"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"{nan: 0, 'C': 1, 'Q': 2, 'S': 3}"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Get the unique values of Embarked\n",
"embarked_locs = sort(df_train['Embarked'].unique())\n",
"\n",
"embarked_locs_mapping = dict(zip(embarked_locs, \n",
" range(0, len(embarked_locs) + 1)))\n",
"embarked_locs_mapping"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Transform Embarked from a string to a number representation to prepare it for machine learning algorithms:"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/html": [
"<div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>PassengerId</th>\n",
" <th>Survived</th>\n",
" <th>Pclass</th>\n",
" <th>Name</th>\n",
" <th>Sex</th>\n",
" <th>Age</th>\n",
" <th>SibSp</th>\n",
" <th>Parch</th>\n",
" <th>Ticket</th>\n",
" <th>Fare</th>\n",
" <th>Cabin</th>\n",
" <th>Embarked</th>\n",
" <th>Sex_Val</th>\n",
" <th>Embarked_Val</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td> 1</td>\n",
" <td> 0</td>\n",
" <td> 3</td>\n",
" <td> Braund, Mr. Owen Harris</td>\n",
" <td> male</td>\n",
" <td> 22</td>\n",
" <td> 1</td>\n",
" <td> 0</td>\n",
" <td> A/5 21171</td>\n",
" <td> 7.2500</td>\n",
" <td> NaN</td>\n",
" <td> S</td>\n",
" <td> 1</td>\n",
" <td> 3</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td> 2</td>\n",
" <td> 1</td>\n",
" <td> 1</td>\n",
" <td> Cumings, Mrs. John Bradley (Florence Briggs Th...</td>\n",
" <td> female</td>\n",
" <td> 38</td>\n",
" <td> 1</td>\n",
" <td> 0</td>\n",
" <td> PC 17599</td>\n",
" <td> 71.2833</td>\n",
" <td> C85</td>\n",
" <td> C</td>\n",
" <td> 0</td>\n",
" <td> 1</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td> 3</td>\n",
" <td> 1</td>\n",
" <td> 3</td>\n",
" <td> Heikkinen, Miss. Laina</td>\n",
" <td> female</td>\n",
" <td> 26</td>\n",
" <td> 0</td>\n",
" <td> 0</td>\n",
" <td> STON/O2. 3101282</td>\n",
" <td> 7.9250</td>\n",
" <td> NaN</td>\n",
" <td> S</td>\n",
" <td> 0</td>\n",
" <td> 3</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td> 4</td>\n",
" <td> 1</td>\n",
" <td> 1</td>\n",
" <td> Futrelle, Mrs. Jacques Heath (Lily May Peel)</td>\n",
" <td> female</td>\n",
" <td> 35</td>\n",
" <td> 1</td>\n",
" <td> 0</td>\n",
" <td> 113803</td>\n",
" <td> 53.1000</td>\n",
" <td> C123</td>\n",
" <td> S</td>\n",
" <td> 0</td>\n",
" <td> 3</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td> 5</td>\n",
" <td> 0</td>\n",
" <td> 3</td>\n",
" <td> Allen, Mr. William Henry</td>\n",
" <td> male</td>\n",
" <td> 35</td>\n",
" <td> 0</td>\n",
" <td> 0</td>\n",
" <td> 373450</td>\n",
" <td> 8.0500</td>\n",
" <td> NaN</td>\n",
" <td> S</td>\n",
" <td> 1</td>\n",
" <td> 3</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" PassengerId Survived Pclass \\\n",
"0 1 0 3 \n",
"1 2 1 1 \n",
"2 3 1 3 \n",
"3 4 1 1 \n",
"4 5 0 3 \n",
"\n",
" Name Sex Age SibSp \\\n",
"0 Braund, Mr. Owen Harris male 22 1 \n",
"1 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38 1 \n",
"2 Heikkinen, Miss. Laina female 26 0 \n",
"3 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35 1 \n",
"4 Allen, Mr. William Henry male 35 0 \n",
"\n",
" Parch Ticket Fare Cabin Embarked Sex_Val Embarked_Val \n",
"0 0 A/5 21171 7.2500 NaN S 1 3 \n",
"1 0 PC 17599 71.2833 C85 C 0 1 \n",
"2 0 STON/O2. 3101282 7.9250 NaN S 0 3 \n",
"3 0 113803 53.1000 C123 S 0 3 \n",
"4 0 373450 8.0500 NaN S 1 3 "
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"df_train['Embarked_Val'] = df_train['Embarked'] \\\n",
" .map(embarked_locs_mapping) \\\n",
" .astype(int)\n",
"df_train.head()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Plot the histogram for Embarked_Val:"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAmgAAAFRCAYAAADAclGxAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3X28bnVd5//XGxBvgQNShxvRY6OM0qQHFTRvco+po5Zg\nM5M3Ncaxxl+/McemyRKaJrAmBOpnM+bUVKMNWmBoDkF5w41cilPgGGyxjgiUpzwgxxtATaxAPr8/\nrrU9F9t9zrWuc/a11tp7v56Px/U4a61r3Xz2Zy8uPvu7PmtdqSokSZI0HAf0HYAkSZLuzwJNkiRp\nYCzQJEmSBsYCTZIkaWAs0CRJkgbGAk2SJGlgLNAktZLkGUluTvLVJKfM+Vj/K8kvreL+zkryzlXa\n1xlJfmc19rUPx/7hJB/s49iSumWBJg1Ykh1J7m6KotuT/G6Sh+7Hvp6zH+H8IvCWqjqkqi6ZEuvS\n6y37eKxqXqtln/aVZCHJZ++3o6o3VdWrVyes+x1rW5KrV1i+I8n3Nsf+/ar6Fy32taoFrqTuWaBJ\nw1bA91fVIcCTgKcAPz/LDpIcNLGv7EcsjwS27+X9b8Y68Xrdfhxvf2LdvZPdP/9atdrF6n5ZB/mU\n1gQLNGmNqKrbgA8A/wwgySlJ/jLJnUmuSvK4pXWbUZefTfIJ4O+SXMC4wLq0Gdl6/UrHSPLq5jLm\nl5L8UZKjm+V/BXxHs/1Xkjxgltib0aH/k+TNTby3JHl6klc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Vb09yUHAQ4H/BHyxqs5L8gbg8Ko6\nPckJwAXAScCxwBXA8VV138T+7EGTJPXKHjS1N8AetCSHAc+qqrcDVNW9VfVl4BTg/Ga184GXNNOn\nAhdW1T1VtQO4BTh5njF
"text/plain": [
"<matplotlib.figure.Figure at 0x10b0c3dd0>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"df_train['Embarked_Val'].hist(bins=len(embarked_locs), range=(0, 3))\n",
"plt.title('Port of Embarkation Histogram')\n",
"plt.xlabel('Port of Embarkation')\n",
"plt.ylabel('Count')\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Since the vast majority of passengers embarked in 'S': 3, we assign the missing values in Embarked to 'S': "
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"if len(df_train[df_train['Embarked'].isnull()] > 0):\n",
" df_train.replace({'Embarked_Val' : \n",
" { embarked_locs_mapping[nan] : embarked_locs_mapping['S'] \n",
" }\n",
" }, \n",
" inplace=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Verify we do not have any more NaNs for Embarked_Val:"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"array([1, 2, 3])"
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"embarked_locs = sort(df_train['Embarked_Val'].unique())\n",
"embarked_locs"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Plot a normalized cross tab for Embarked_Val and Survived:"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"<matplotlib.text.Text at 0x10b7e28d0>"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAl4AAAFMCAYAAAAa17KLAAAABHNCSVQICAgIfAhkiAAAAAlwSF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3AZ/pczySZoDy9OPv0zn9KUmt0dfCKzN/SOdiheM5mE6TLJl5\nJTA3Il7Sz5gktVtE/AGdU5UXZ+ZlTccjSVPRdI/XNjz/K8t3AS9rKBZJLZCZn8vM2Zn5nqZjkaSp\narrwgjW/mWMjpSRJmpGavkn23XRuVTHqZay+zswqEWExJkmSWiMzu17ypenC60LgOOCciNgbeDgz\nf95tw35++7JfImLNu5+1xfeB1zUdxFpY0s5caTPzvAFLzPO6mecNWNLePI8Y/zJ7fS28IuJsOvf2\n2jIi7qRzA9cNADLztMz8dkS8KSJupXPtm6P7GY+m4OGmA5BqYJ5rGJjnA6WvhVdmHtHDNsf1MwZJ\nkqRBMQjN9RpEC5oOQKqBea5hYJ4PFAsvdbf95JtIrWeeaxiY5wOl6eZ6Dao78C+rZj7zXMNgkPJ8\nydQ2n6hJfVBM9QsAFl6SJKk2bf2mYjdrUxh6qlHdDcpvR1I/mecaBub5QLHwkiRJqomFl7q7o+kA\npBqY5xoG5vlAsfCSJEmNOumkk5g/fz677bYbu+++Oz/+8Y/XecyLLrqIk08+eRqig9mzZ0/LOGBz\nvcZjT4CGgXmuYTDgeX7FFVfwrW99i2XLlrHBBhvw4IMP8swzz/T02hUrVjBrVvdS5qCDDuKggw6a\nlhin89uVznhJkqTG3HfffWy55ZZssMEGAGyxxRa89KUvZd68eTz44IMALF26lNe9rnPDySVLlnDU\nUUex33778fa3v5199tm
"text/plain": [
"<matplotlib.figure.Figure at 0x10ba3e790>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"embarked_val_xt = pd.crosstab(df_train['Embarked_Val'], df_train['Survived'])\n",
"embarked_val_xt_pct = \\\n",
" embarked_val_xt.div(embarked_val_xt.sum(1).astype(float), axis=0)\n",
"embarked_val_xt_pct.plot(kind='bar', stacked=True)\n",
"plt.title('Survival Rate by Port of Embarkation')\n",
"plt.xlabel('Port of Embarkation')\n",
"plt.ylabel('Survival Rate')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It appears those that embarked in location 'C': 1 had the highest rate of survival. We'll dig in some more to see why this might be the case. Below we plot a graphs to determine gender and passenger class makeup for each port:"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAlEAAAJKCAYAAAAMbRCGAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzs3X+wZWV95/v3RwgqmnjgmjTNDz0khMTONR6M9CQmGbaO\nGrQMMHOrUFPJ0P66VjlRmjtm7ObWTMzMLSPM1fRMprAmQZ3WCJH4K1JRoSE8JqmMGhK2EpEBcj13\n0oQ+KHCIjpNbIN/7x16nz+7j7uP+sdZ+1n7W51V1qs+zzvrxfdZ+vr2fvZ5nr6WIwMzMzMwm86Tc\nAZiZmZktIneizMzMzKbgTpSZmZnZFNyJMjMzM5uCO1FmZmZmU3AnyszMzGwK23aiJL1f0pqkO4eW\nnSrpkKR7JN0saWnob/sl3SvpbkkvazJwszaSdIKkOyTdWJXfIelwtewOSRfmjtGsbmO0+5cPrev3\nCSvG97oS9QFg63/6+4BDEXEucGtVRtIu4FXArmqbayT5Spd1zeXAXcDGDdgCeE9EnFf9fDZfaGaN\n+V7t/jPg9wkrz7aNNyL+FHhky+KLgIPV7weBS6rfLwauj4jHImIVuA/YXV+oZu0m6UzgFcC1gDYW\nD/1uVpwJ273fJ6wo03wC2BERa9Xva8CO6vfTgcND6x0GzpghNrNF81vArwFPDC0L4C2SviTpfcPD\n32aFmKTd+33CijLTZdQYPDNmu+fG+Jky1gmSXgk8GBF3cOwn8PcCZwMrwAPAuzOEZ9aImtq93yds\nYZ04xTZrkk6LiCOSdgIPVsvvB84aWu/MatkxJDlhrHUiYtYhtxcCF0l6BfAU4AckfTAi/vnGCpKu\nBW7cuqFzwtpozJyYtN37fcIW0vHyYZorUZ8CLqt+vwz45NDyV0s6SdLZwI8CXzxOMK3+ueyyy7LH\n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ed5NDn0cgdQhOH3ikU07cTy5wEf\nBs4H/gH4L8AXgWcDD0XEVZL2AUueWL7BEwbbqo5JtJKeAnwOeDJwEvCHEbFf0juANwBfr1bdHxGf\n3bKtc6KlunoeJ8mJCdr+lRHxmWqb/cDrgO8Ab42Im7fs0zlhrVH7xPKI+BLwQeB24MvV4t8B3gW8\nVNI9wIur8gJKuQMoxqKPd48rIv4BeFFErAA/CbxI0s8x+F/7PRFxXvXz2W131FopdwCFSLkDqN0E\nbX+jA7ULeBWwC7gQuEbSAt6zMOUOoAiL/h4x7XAeEXE1cPWWxQ8DL5kpIrMFFRHfrn49CTgBeKQq\nL8aYkNmUJmz7FwPXR8RjwKqk+4DdwOcbD9SsZgvY+5+HXu4AirHo492TkPQkSX0G30y9LSK+Uv3p\nLZK+JOl9i3sD2l7uAArRyx1AIyZs+6cDh4c2PwycMcdwa9LLHUARFv09YuorUWZ2rIh4AliR9Azg\nJkk94L3Av61W+XcMbg3y+q3bLsaXLeouV6UWfNlgu3J7ztfxyrN/eWPWL1vM0vY3drF1gXOiPTnQ\ntfKBAwfo9/tH2992pppYPovFmDCYqP9TRjcnDA7/595WTdydWdK/Bv5nRPzfQ8uWgRsj4rlb1nVO\ntFRXz+MsOfG92n71pSMi4l3V3z4L/HpEfGFofedERyz6e4SH88xqIOmZG8MVkp4KvBS4Q9JpQ6v9\nU+DOHPGZNWWKtv8p4NWSTpJ0NvCjDL7dbbZwfCVqbrr3CWNR1HSLg+cyeNTRk6qfD0XEv5f0QWCF\nQQP9GvCmobv6b2zrnGiprp7HCW9xMHHbl3Qlg1scPA5cHhE3bdmnc8JaY7t8cCdqbpwcbeWHrebS\n/pzo6nl0TuTS/pzoIg/nTSzlDqAYi34PENuQcgdQiJQ7AKtNyh1AERb9PcKdKDMzM7MpeDhvbnyZ\ntq08dJFL+3Oiq+fROZF
"text/plain": [
"<matplotlib.figure.Figure at 0x10b30de50>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"# Set up a grid of plots\n",
"fig = plt.figure(figsize=fizsize_with_subplots) \n",
"\n",
"rows = 2\n",
"cols = 3\n",
"col_names = ('Sex_Val', 'Pclass')\n",
"\n",
"for portIdx in embarked_locs:\n",
" for colIdx in range(0, len(col_names)):\n",
" plt.subplot2grid((rows, cols), (colIdx, portIdx - 1))\n",
" df_train[df_train['Embarked_Val'] == portIdx][col_names[colIdx]] \\\n",
" .value_counts().plot(kind='bar')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Leaving Embarked as integers implies ordering in the values, which does not exist. Another way to represent Embarked without ordering is to create dummy variables:"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"df_train = pd.concat([df_train, pd.get_dummies(df_train['Embarked_Val'], prefix='Embarked_Val')], axis=1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Feature: Age"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The Age column seems like an important feature--unfortunately it is missing many values. We'll need to fill in the missing values like we did with Embarked."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Filter to view missing Age values:"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/html": [
"<div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>Sex</th>\n",
" <th>Pclass</th>\n",
" <th>Age</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>5 </th>\n",
" <td> male</td>\n",
" <td> 3</td>\n",
" <td>NaN</td>\n",
" </tr>\n",
" <tr>\n",
" <th>17</th>\n",
" <td> male</td>\n",
" <td> 2</td>\n",
" <td>NaN</td>\n",
" </tr>\n",
" <tr>\n",
" <th>19</th>\n",
" <td> female</td>\n",
" <td> 3</td>\n",
" <td>NaN</td>\n",
" </tr>\n",
" <tr>\n",
" <th>26</th>\n",
" <td> male</td>\n",
" <td> 3</td>\n",
" <td>NaN</td>\n",
" </tr>\n",
" <tr>\n",
" <th>28</th>\n",
" <td> female</td>\n",
" <td> 3</td>\n",
" <td>NaN</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" Sex Pclass Age\n",
"5 male 3 NaN\n",
"17 male 2 NaN\n",
"19 female 3 NaN\n",
"26 male 3 NaN\n",
"28 female 3 NaN"
]
},
"execution_count": 24,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"df_train[df_train['Age'].isnull()][['Sex', 'Pclass', 'Age']].head()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Determine the Age typical for each passenger class by Sex_Val. We'll use the median instead of the mean because the Age histogram seems to be right skewed."
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# To keep Age in tact, make a copy of it called AgeFill \n",
"# that we will use to fill in the missing ages:\n",
"df_train['AgeFill'] = df_train['Age']\n",
"\n",
"# Populate AgeFill\n",
"df_train['AgeFill'] = df_train['AgeFill'] \\\n",
" .groupby([df_train['Sex_Val'], df_train['Pclass']]) \\\n",
" .apply(lambda x: x.fillna(x.median()))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Ensure AgeFill does not contain any missing values:"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"0"
]
},
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"len(df_train[df_train['AgeFill'].isnull()])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Plot a normalized cross tab for AgeFill and Survived:"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"<matplotlib.text.Text at 0x10c4125d0>"
]
},
"execution_count": 27,
"metadata": {},
"output_type": "execute_result"
},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FAnXPuV1usofpehS/BbFIPv3A4dm5pJe3sdw\nivFEz1K0lmxCz4lkVwzfp5jsMBfYnde6MbtMAnZh5V2aHwX+IzPnNCyzKWYUfrTc58Ple5tLkQRe\nTTFWqysJPBz4HDCHoiXtdHr5uZeZ/wacRtGdOKtcvl2udyXT3et3MUV38fso6ubfgePK+gX4ehnP\nbIrJGt9jxc/zp8D/ANMoxqv9V1m+J3BHRDxf7nNKZk7vpa56+o50v5VG1+shFAnWDIp6OwDoupfb\nLygG+M+KiDll2T9TJHB/Am6l+GwvK7ddSjFm7L7yPdwEvNrDd7J4UYzBPIUiqZtH8YfKT1/nvdTm\ndiBSf+maMdX3Jy7+CrwC2JTiP9clmfnNiOigmIHTNQD4c5n5/8pjzgb+F8Vfcadk5s1NCU5SpSLi\nAIqZpGNfd+fVO+/VFN23/9KX522WiFhKMfN2ZZMrBoyyJezizNy26likgWxNbi65qhYDn87Me8sx\nJ/8TEVMpErWvZebXGneOiJ0pBqnuTDHY9JaI2KHbX2CSBriyy+xUXhvntDbn2hOYD/yZovv2MODL\na3terZpyJvC7KVrPxlC0lv640qCkQaBp3ZqZOSsz7y1fv0Axa6xrrEdPYyEOByZn5uKy6f5xYO9m\nxSep/0XEThTJ1BhWb8ZqbzajuJfY8xRdiB/PzN/3wXn7y0DvsguKGbzzKO6L9wDw+SoDkgaDZrac\nLRMR21KMO7mDYir7P0fERykG855eDsbdotze5WmWn9YvaYDLzIeADfrwfDdSjNMakDJzaNUxrI3M\nXIh/REt9rukTAsouzR8
"text/plain": [
"<matplotlib.figure.Figure at 0x10c054390>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"# Set up a grid of plots\n",
"fig, axes = plt.subplots(2, 1, figsize=fizsize_with_subplots)\n",
"\n",
"# Histogram of AgeFill segmented by Survived\n",
"df1 = df_train[df_train['Survived'] == 0]['Age']\n",
"df2 = df_train[df_train['Survived'] == 1]['Age']\n",
"max_age = max(df_train['AgeFill'])\n",
"axes[0].hist([df1, df2], \n",
" bins=max_age / bin_size, \n",
" range=(1, max_age), \n",
" stacked=True)\n",
"axes[0].legend(('Died', 'Survived'), loc='best')\n",
"axes[0].set_title('Survivors by Age Groups Histogram')\n",
"axes[0].set_xlabel('Age')\n",
"axes[0].set_ylabel('Count')\n",
"\n",
"# Scatter plot Survived and AgeFill\n",
"axes[1].scatter(df_train['Survived'], df_train['AgeFill'])\n",
"axes[1].set_title('Survivors by Age Plot')\n",
"axes[1].set_xlabel('Survived')\n",
"axes[1].set_ylabel('Age')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Unfortunately, the graphs above do not seem to clearly show any insights. We'll keep digging further."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Plot AgeFill density by Pclass:"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"<matplotlib.legend.Legend at 0x10be093d0>"
]
},
"execution_count": 28,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAm0AAAFRCAYAAAAmW5r1AAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzs3Xd8FHX6wPHPQ+ikQUBagFClCIICKp5nzooIIqgoiohi\nORF/gPVOVEBFz4IoIqInh4oHeFIEFUFBg9hAVBAklAChg9TQW/L9/TGTEMIk2d3M7G42z/v12peZ\nndnvfPNkgk++VYwxKKWUUkqp8FYq1BVQSimllFKF06RNKaWUUqoY0KRNKaWUUqoY0KRNKaWUUqoY\n0KRNKaWUUqoY0KRNKaWUUqoY0KRNKeUKEakrIgdERIJwr3QRudylst4TkWfdKEv5xs2fn1IliSZt\nSgWRiKSIyB4RKevxPY6IyH4RyRCRxSLyuJf3BDDGbDTGxBh78Ue7Hn0DLU9EskTkoJ0IbhaRESKS\n/W+WsV+FlZEsIpsKq7ovZfmikDqXGCISKyKvicgGOxZpIjJSRBLsS1yLuVIlSY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nZ0ubrYLm8M5wMVjJ5HjDGGHMe1qyrf7hYN6WUUkqpYsXLlrYtnLnu1OZC\nrkm03xNgs70aOcAUHJI2EfFuFoVSSimllMuMMb7u1HIGL1vaFmNtv5JkrwV0M9Y08txmYi2HgL2a\n9T5jzA57m5JNItLEvu4K4A+nm5gw2Ass3F5DhgwJeR3C8aVx0bhoTDQuGheNSyhfReVZS5sx5qSI\n9AfmYC35Mc4Ykyoi99nn3zbGzBKRTiKShtUFmnt5gweB/9oJ39o851QB0tPTQ12FsKRxcaZxOZPG\nxJnGxZnGxZnGxX1edo9
"text/plain": [
"<matplotlib.figure.Figure at 0x10b6d4b50>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"for pclass in passenger_classes:\n",
" df_train.AgeFill[df_train.Pclass == pclass].plot(kind='kde')\n",
"plt.title('Age Density Plot by Passenger Class')\n",
"plt.xlabel('Age')\n",
"plt.legend(('1st Class', '2nd Class', '3rd Class'), loc='best')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"When looking at AgeFill density by Pclass, we see the first class passengers were generally older then second class passengers, which in turn were older than third class passengers. We've determined that first class passengers had a higher survival rate than second class passengers, which in turn had a higher survival rate than third class passengers."
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"<matplotlib.axes._subplots.AxesSubplot at 0x10d6c22d0>"
]
},
"execution_count": 29,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAlcAAAJPCAYAAABRvvFyAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzs3X2wpHdd9/n3NxkiBJCTWe6djBA4EY2AGzigRhQxHQxs\nYGHI7l0VoAorB4Wtun2AuD4wcWtF/1ghsbyNdVvW3iuGnZuC3IQHI/GJjDGX4uINAhkNCTHg2poo\ncwJ5IopIQr77R18np9P9O5Oc7mvO9evp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/Pzg5gU2PkinLeaynabvAirU9F1AlXwOlZlLmbl0w+ZKkiSpQ24LauG4LVhiJtPcFpQ0P7cF\nJUmSemZzVQn3ucvMZTtN3wVUqOm7gCr5HCozlzJz6YbNlSRJUoecudLCceaqxEymOXMlaX7OXEmS\nJPXM5qoS7nOXmct2mr4LqFDTdwFV8jlUZi5l5tINmytJkqQOOXOlhePMVYmZTHPmStL8nLmSJEnq\nmc1VJdznLjOX7TR9F1Chpu8CquRzqMxcysylGzZXkiRJHZp55ioiVoB3Ad/JaNjjjcDngfcDzwSG\nwEWZee/E/Zy50lycuSoxk2nOXEma327PXP068AeZ+RzgecCtwEHgcGaeBVzfriVJkpbGTM1VRDwF\neElmXgmQmQ9m5n3AAeBQe7NDwIWdVLkE3OcuM5ftNH0XUKGm7wKq5HOozFzKzKUbs565OhP4UkS8\nOyI+ExG/FRFPBPZl5kZ7mw1gXydVSpIkLYiZZq4i4ruBvwC+PzP/MiKuAO4HfiIzTxu73d2ZuXfi\nvs5caS7OXJWYyTRnriT
"text/plain": [
"<matplotlib.figure.Figure at 0x10d3a5290>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"# Set up a grid of plots\n",
"fig = plt.figure(figsize=fizsize_with_subplots) \n",
"fig_dims = (3, 1)\n",
"\n",
"# Plot the AgeFill histogram for Survivors\n",
"plt.subplot2grid(fig_dims, (0, 0))\n",
"survived_df = df_train[df_train['Survived'] == 1]\n",
"survived_df['AgeFill'].hist(bins=max_age / bin_size, range=(1, max_age))\n",
"\n",
"# Plot the AgeFill histogram for Females\n",
"plt.subplot2grid(fig_dims, (1, 0))\n",
"females_df = df_train[(df_train['Sex_Val'] == 0) & (df_train['Survived'] == 1)]\n",
"females_df['AgeFill'].hist(bins=max_age / bin_size, range=(1, max_age))\n",
"\n",
"# Plot the AgeFill histogram for first class passengers\n",
"plt.subplot2grid(fig_dims, (2, 0))\n",
"class1_df = df_train[(df_train['Pclass'] == 1) & (df_train['Survived'] == 1)]\n",
"class1_df['AgeFill'].hist(bins=max_age / bin_size, range=(1, max_age))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In the first graph, we see that most survivors come from the 20's to 30's age ranges and might be explained by the following two graphs. The second graph shows most females are within their 20's. The third graph shows most first class passengers are within their 30's."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Feature: Family Size"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Feature enginering involves creating new features or modifying existing features which might be advantageous to a machine learning algorithm.\n",
"\n",
"Define a new feature FamilySize that is the sum of Parch (number of parents or children on board) and SibSp (number of siblings or spouses):"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/html": [
"<div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>PassengerId</th>\n",
" <th>Survived</th>\n",
" <th>Pclass</th>\n",
" <th>Name</th>\n",
" <th>Sex</th>\n",
" <th>Age</th>\n",
" <th>SibSp</th>\n",
" <th>Parch</th>\n",
" <th>Ticket</th>\n",
" <th>Fare</th>\n",
" <th>Cabin</th>\n",
" <th>Embarked</th>\n",
" <th>Sex_Val</th>\n",
" <th>Embarked_Val</th>\n",
" <th>Embarked_Val_1</th>\n",
" <th>Embarked_Val_2</th>\n",
" <th>Embarked_Val_3</th>\n",
" <th>AgeFill</th>\n",
" <th>FamilySize</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td> 1</td>\n",
" <td> 0</td>\n",
" <td> 3</td>\n",
" <td> Braund, Mr. Owen Harris</td>\n",
" <td> male</td>\n",
" <td> 22</td>\n",
" <td> 1</td>\n",
" <td> 0</td>\n",
" <td> A/5 21171</td>\n",
" <td> 7.2500</td>\n",
" <td> NaN</td>\n",
" <td> S</td>\n",
" <td> 1</td>\n",
" <td> 3</td>\n",
" <td> 0</td>\n",
" <td> 0</td>\n",
" <td> 1</td>\n",
" <td> 22</td>\n",
" <td> 1</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td> 2</td>\n",
" <td> 1</td>\n",
" <td> 1</td>\n",
" <td> Cumings, Mrs. John Bradley (Florence Briggs Th...</td>\n",
" <td> female</td>\n",
" <td> 38</td>\n",
" <td> 1</td>\n",
" <td> 0</td>\n",
" <td> PC 17599</td>\n",
" <td> 71.2833</td>\n",
" <td> C85</td>\n",
" <td> C</td>\n",
" <td> 0</td>\n",
" <td> 1</td>\n",
" <td> 1</td>\n",
" <td> 0</td>\n",
" <td> 0</td>\n",
" <td> 38</td>\n",
" <td> 1</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td> 3</td>\n",
" <td> 1</td>\n",
" <td> 3</td>\n",
" <td> Heikkinen, Miss. Laina</td>\n",
" <td> female</td>\n",
" <td> 26</td>\n",
" <td> 0</td>\n",
" <td> 0</td>\n",
" <td> STON/O2. 3101282</td>\n",
" <td> 7.9250</td>\n",
" <td> NaN</td>\n",
" <td> S</td>\n",
" <td> 0</td>\n",
" <td> 3</td>\n",
" <td> 0</td>\n",
" <td> 0</td>\n",
" <td> 1</td>\n",
" <td> 26</td>\n",
" <td> 0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td> 4</td>\n",
" <td> 1</td>\n",
" <td> 1</td>\n",
" <td> Futrelle, Mrs. Jacques Heath (Lily May Peel)</td>\n",
" <td> female</td>\n",
" <td> 35</td>\n",
" <td> 1</td>\n",
" <td> 0</td>\n",
" <td> 113803</td>\n",
" <td> 53.1000</td>\n",
" <td> C123</td>\n",
" <td> S</td>\n",
" <td> 0</td>\n",
" <td> 3</td>\n",
" <td> 0</td>\n",
" <td> 0</td>\n",
" <td> 1</td>\n",
" <td> 35</td>\n",
" <td> 1</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td> 5</td>\n",
" <td> 0</td>\n",
" <td> 3</td>\n",
" <td> Allen, Mr. William Henry</td>\n",
" <td> male</td>\n",
" <td> 35</td>\n",
" <td> 0</td>\n",
" <td> 0</td>\n",
" <td> 373450</td>\n",
" <td> 8.0500</td>\n",
" <td> NaN</td>\n",
" <td> S</td>\n",
" <td> 1</td>\n",
" <td> 3</td>\n",
" <td> 0</td>\n",
" <td> 0</td>\n",
" <td> 1</td>\n",
" <td> 35</td>\n",
" <td> 0</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" PassengerId Survived Pclass \\\n",
"0 1 0 3 \n",
"1 2 1 1 \n",
"2 3 1 3 \n",
"3 4 1 1 \n",
"4 5 0 3 \n",
"\n",
" Name Sex Age SibSp \\\n",
"0 Braund, Mr. Owen Harris male 22 1 \n",
"1 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38 1 \n",
"2 Heikkinen, Miss. Laina female 26 0 \n",
"3 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35 1 \n",
"4 Allen, Mr. William Henry male 35 0 \n",
"\n",
" Parch Ticket Fare Cabin Embarked Sex_Val Embarked_Val \\\n",
"0 0 A/5 21171 7.2500 NaN S 1 3 \n",
"1 0 PC 17599 71.2833 C85 C 0 1 \n",
"2 0 STON/O2. 3101282 7.9250 NaN S 0 3 \n",
"3 0 113803 53.1000 C123 S 0 3 \n",
"4 0 373450 8.0500 NaN S 1 3 \n",
"\n",
" Embarked_Val_1 Embarked_Val_2 Embarked_Val_3 AgeFill FamilySize \n",
"0 0 0 1 22 1 \n",
"1 1 0 0 38 1 \n",
"2 0 0 1 26 0 \n",
"3 0 0 1 35 1 \n",
"4 0 0 1 35 0 "
]
},
"execution_count": 30,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"df_train['FamilySize'] = df_train['SibSp'] + df_train['Parch']\n",
"df_train.head()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Plot a histogram of FamilySize:"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"<matplotlib.text.Text at 0x10db78590>"
]
},
"execution_count": 31,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAlcAAAFCCAYAAADcyPgxAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAHiFJREFUeJzt3X+QZWdd5/H3hwxZwUCGLNaQhMBESAqiYqAwIqj0SohZ\nfiSpLU2iIomwVCmuEBTXCavGktqYUFqE0g27yo8dEYIxYCpYAvkhvSpoIksiP4ZsMkojA8xEIQnB\ngCTku3/c05lL10x338npOfPc835Vdc15Tp97z3P7OzP17ed87rmpKiRJktSPhw09AUmSpHlicyVJ\nktQjmytJkqQe2VxJkiT1yOZKkiSpRzZXkiRJPbK5krRuSe5JsrXb/t9JXr8B5/jzJD/d9/Ou47yf\nTPLDB/u8kuaPzZU0J5IsJbm3a4DuSfKVJI/r8xxV9aiqWloedl8zS/K6JP/YzfNzSd49dY4XVNU7\nepju9PmWkjxvxb7zk/zV1Hm/u6r+co3n2ZrkgST+3ylpv/wPQpofBbyoa4AeVVWPrqrdG3zOzPyA\n5DzgJcDzqupRwDOB6/ue2AoH3Ajux8yve11Pmhy2Ec8r6eCyuZLmWJLNSf4syR1JvpzkfUmOnfr+\nYpLXJ/lwt4p0TZLHJnlnkruT3JTkiVPHP5DkO6dOUd3+TyZ50dRxD0/yL0m+dx/Teibwwar6DEBV\n7amqt6yY08u77b+fWom7pzv/D3ffe1aSjyS5M8ktSZ4744/nW5qtbnXrR7rtU5J8tPsZ7E7y291h\nyytbd3Xz+f5M/Gr3+D1Jtid59NTzvjTJZ7ufx6+uOM9vJLkqyTuS3A2cl+T7kvxN97q+kOR3kzx8\n6vkeSPJzSW7vVid/M8mTusfcleTd08dLOvhsrqT5snJF5WHAW4EndF9fA35vxTHnMFlJOhZ4EvA3\n3WOOAj4NXLSO827vnmPZC4D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UFJkqQB2VxpZuYG2mXt2mb9\n2mb9xsPmSpIkqUdmriRJklZh5kqSJGlANleambmBdlm7tlm/tlm/8bC5kiRJ6pGZK0mSpFWYuZIk\nSRqQzZVmZm6gXdaubdavbdZvPGyuJEmSemTmSpIkaRVmriRJkgZkc6WZmRtol7Vrm/Vrm/UbD5sr\nSZKkHpm5kiRJWoWZK0mSpAHZXGlm5gbaZe3aZv3aZv3Gw+ZKkiSpR4Nlrt785jcf9PMeLM9+9rN5\n2tOeNvQ0JElSD2bNXG3ayMms5hd/8ZahTr2hvvnND3PppV+3uZIkaaQGa66+9rX/OdSpN9Thh18w\n9BQ23OLiIgsLC0NPQwfA2rXN+rXN+o2HmStJkqQeDZa5gvm8z9Xhh1/ApZdu5YIL5n8FS5KkMfA+\nV5IkSQOyudLMvFdLu6xd26xf26zfeNhcSZIk9cjMVc/MXEmSNF/MXEmSJA3I5kozMzfQLmvXNuvX\nNus3HjZXkiRJPTJz1TMzV5IkzRczV5IkSQNaV3OVZCnJx5PcnOSmbt9RSa5LcluSa5Nsnjr+wiS3\nJ7k1yWkbNXkNw9xAu6xd26xf26zfeKx35aqAhap6elWd0u3bBlxXVScCN3RjkpwEnAOcBJwOXJ7E\nFTJJkjQKszQ9K681ngFs77a3A2d122cCV1TVfVW1BOwETkFzw091b5e1a5v1a5v1G49ZVq6uT/LR\nJK/o9m2pqj3d9h5gS7d9DLBr6rG7gGMf8kwlSZIasGmdxz2nqr6Y5DuA65LcOv3NqqrJOwD3ax/f\nOx/Y2m1vBk4GFrrxYvdnm+OdO3eyuLj44G8py9fZ52V82WWXcfLJJx8y83G8/vF05uNQmI9j6zem\nsfVrZ7y8vbS0xIGY+VYMSS4Cvgq8Alioqt1JjgY+VFVPSbINoKou6Y7/AHBRVd049RzeiqFhi1ON\no9pi7dpm/dpm/drV+60
"text/plain": [
"<matplotlib.figure.Figure at 0x10be12450>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"df_train['FamilySize'].hist()\n",
"plt.title('Family Size Histogram')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Plot a histogram of AgeFill segmented by Survived:"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"<matplotlib.text.Text at 0x10dd85bd0>"
]
},
"execution_count": 32,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAlcAAAFCCAYAAADcyPgxAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3X+8VXWd7/HXR1DJHwiUoAL+mEkNKodMLDWvTENeCwHn\nOoqQinO9VjZN2lQ3vGkeq8GayampuVZaGf6AIvuFSik5ndLGnxOWSf7qCsIxwJRQcjDQz/1jL04b\nOJxffM/Z58Dr+Xjsh2ut/V1rffbex3PefL/ftXZkJpIkSSpjl0YXIEmStCMxXEmSJBVkuJIkSSrI\ncCVJklSQ4UqSJKkgw5UkSVJBhitJbYqIL0bExQ2u4esR8YlG1tBZEXFgRDwfEVGtN0fEuT1wnl9F\nxH8rfVxJ5RiupH4kIt4SEf8REb+PiGci4s6IOKonzpWZ52fmJ3vi2F0po3pst4h4OSLWVQHo+Yh4\ntsRxN8nMJzNz7/zTzQO7VXtE7BYRV0TE8qrOJyLis3XneV1m/rRU3ZLKG9joAiR1TkQMBm4G3g3M\nB3YHjgde7MaxAiB7+S7CETEwMzd2dbeCJRyRmf+v4PF6wkXAkcD4zFwZEQdR+5wl9RP2XEn9x2HU\n8tA3s2Z9Zi7KzAcBIqIpIq7b1DgiDq56a3ap1psj4pMR8TPgD8CHI+K++hNExAci4vvVcuuQXET8\nOiIm1bUbGBFPR8S4an1KRDwUEWsi4scR8Zq6tksj4n9HxC+B5yNiQER8JCJWRMRzEfFwRLy1ndf9\nqoi4rWrbHBEHVsf9vxHxmS3qXxARF3b2DY2IP4+If4+I31Wv5/qI2GeL2j8UEb+sepG+Gh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.figure.Figure at 0x10c473890>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"# Get the unique values of Embarked and its maximum\n",
"family_sizes = sort(df_train['FamilySize'].unique())\n",
"family_size_max = max(family_sizes)\n",
"\n",
"df1 = df_train[df_train['Survived'] == 0]['FamilySize']\n",
"df2 = df_train[df_train['Survived'] == 1]['FamilySize']\n",
"plt.hist([df1, df2], \n",
" bins=family_size_max + 1, \n",
" range=(0, family_size_max), \n",
" stacked=True)\n",
"plt.legend(('Died', 'Survived'), loc='best')\n",
"plt.title('Survivors by Family Size')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Based on the histograms, it is not immediately obvious what impact FamilySize has on survival. The machine learning algorithms might benefit from this feature.\n",
"\n",
"Additional features we might want to engineer might be related to the Name column, for example honorrary or pedestrian titles might give clues and better predictive power for a male's survival."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Final Data Preparation for Machine Learning"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Many machine learning algorithms do not work on strings and they usually require the data to be in an array, not a DataFrame.\n",
"\n",
"Show only the columns of type 'object' (strings):"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"Name object\n",
"Sex object\n",
"Ticket object\n",
"Cabin object\n",
"Embarked object\n",
"dtype: object"
]
},
"execution_count": 33,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"df_train.dtypes[df_train.dtypes.map(lambda x: x == 'object')]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Drop the columns we won't use:"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"df_train = df_train.drop(['Name', 'Sex', 'Ticket', 'Cabin', 'Embarked'], \n",
" axis=1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Drop the following columns:\n",
"* The Age column since we will be using the AgeFill column instead.\n",
"* The SibSp and Parch columns since we will be using FamilySize instead.\n",
"* The PassengerId column since it won't be used as a feature.\n",
"* The Embarked_Val as we decided to use dummy variables instead."
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"Survived int64\n",
"Pclass int64\n",
"Fare float64\n",
"Sex_Val int64\n",
"Embarked_Val_1 float64\n",
"Embarked_Val_2 float64\n",
"Embarked_Val_3 float64\n",
"AgeFill float64\n",
"FamilySize int64\n",
"dtype: object"
]
},
"execution_count": 35,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"df_train = df_train.drop(['Age', 'SibSp', 'Parch', 'PassengerId', 'Embarked_Val'], axis=1)\n",
"df_train.dtypes"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Convert the DataFrame to a numpy array:"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"array([[ 0. , 3. , 7.25 , ..., 1. , 22. , 1. ],\n",
" [ 1. , 1. , 71.2833, ..., 0. , 38. , 1. ],\n",
" [ 1. , 3. , 7.925 , ..., 1. , 26. , 0. ],\n",
" ..., \n",
" [ 0. , 3. , 23.45 , ..., 1. , 21.5 , 3. ],\n",
" [ 1. , 1. , 30. , ..., 0. , 26. , 0. ],\n",
" [ 0. , 3. , 7.75 , ..., 0. , 32. , 0. ]])"
]
},
"execution_count": 36,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"train_data = df_train.values\n",
"train_data"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Data Wrangling Summary"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Below is a summary of the data wrangling we performed on our training data set. We encapsulate this in a function since we'll need to do the same operations to our test set later."
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"def clean_data(df, drop_passenger_id):\n",
" \n",
" # Get the unique values of Sex\n",
" sexes = sort(df['Sex'].unique())\n",
" \n",
" # Generate a mapping of Sex from a string to a number representation \n",
" genders_mapping = dict(zip(sexes, range(0, len(sexes) + 1)))\n",
"\n",
" # Transform Sex from a string to a number representation\n",
" df['Sex_Val'] = df['Sex'].map(genders_mapping).astype(int)\n",
" \n",
" # Get the unique values of Embarked\n",
" embarked_locs = sort(df['Embarked'].unique())\n",
"\n",
" # Generate a mapping of Embarked from a string to a number representation \n",
" embarked_locs_mapping = dict(zip(embarked_locs, \n",
" range(0, len(embarked_locs) + 1)))\n",
" \n",
" # Transform Embarked from a string to dummy variables\n",
" df = pd.concat([df, pd.get_dummies(df['Embarked'], prefix='Embarked_Val')], axis=1)\n",
" \n",
" # Fill in missing values of Embarked\n",
" # Since the vast majority of passengers embarked in 'S': 3, \n",
" # we assign the missing values in Embarked to 'S':\n",
" if len(df[df['Embarked'].isnull()] > 0):\n",
" df.replace({'Embarked_Val' : \n",
" { embarked_locs_mapping[nan] : embarked_locs_mapping['S'] \n",
" }\n",
" }, \n",
" inplace=True)\n",
" \n",
" # Fill in missing values of Fare with the average Fare\n",
" if len(df[df['Fare'].isnull()] > 0):\n",
" avg_fare = df['Fare'].mean()\n",
" df.replace({ None: avg_fare }, inplace=True)\n",
" \n",
" # To keep Age in tact, make a copy of it called AgeFill \n",
" # that we will use to fill in the missing ages:\n",
" df['AgeFill'] = df['Age']\n",
"\n",
" # Determine the Age typical for each passenger class by Sex_Val. \n",
" # We'll use the median instead of the mean because the Age \n",
" # histogram seems to be right skewed.\n",
" df['AgeFill'] = df['AgeFill'] \\\n",
" .groupby([df['Sex_Val'], df['Pclass']]) \\\n",
" .apply(lambda x: x.fillna(x.median()))\n",
" \n",
" # Define a new feature FamilySize that is the sum of \n",
" # Parch (number of parents or children on board) and \n",
" # SibSp (number of siblings or spouses):\n",
" df['FamilySize'] = df['SibSp'] + df['Parch']\n",
" \n",
" # Drop the columns we won't use:\n",
" df = df.drop(['Name', 'Sex', 'Ticket', 'Cabin', 'Embarked'], axis=1)\n",
" \n",
" # Drop the Age column since we will be using the AgeFill column instead.\n",
" # Drop the SibSp and Parch columns since we will be using FamilySize.\n",
" # Drop the PassengerId column since it won't be used as a feature.\n",
" df = df.drop(['Age', 'SibSp', 'Parch'], axis=1)\n",
" \n",
" if drop_passenger_id:\n",
" df = df.drop(['PassengerId'], axis=1)\n",
" \n",
" return df"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Random Forest: Training"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Create the random forest object:"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from sklearn.ensemble import RandomForestClassifier\n",
"\n",
"clf = RandomForestClassifier(n_estimators=100)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Fit the training data and create the decision trees:"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"'Mean accuracy of Random Forest: 0.980920314254'"
]
},
"execution_count": 39,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Training data features, skip the first column 'Survived'\n",
"train_features = train_data[:, 1:]\n",
"\n",
"# 'Survived' column values\n",
"train_target = train_data[:, 0]\n",
"\n",
"# Fit the model to our training data\n",
"clf = clf.fit(train_features, train_target)\n",
"score = clf.score(train_features, train_target)\n",
"\"Mean accuracy of Random Forest: {0}\".format(score)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Random Forest: Predicting"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Read the test data:"
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/html": [
"<div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>PassengerId</th>\n",
" <th>Pclass</th>\n",
" <th>Name</th>\n",
" <th>Sex</th>\n",
" <th>Age</th>\n",
" <th>SibSp</th>\n",
" <th>Parch</th>\n",
" <th>Ticket</th>\n",
" <th>Fare</th>\n",
" <th>Cabin</th>\n",
" <th>Embarked</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td> 892</td>\n",
" <td> 3</td>\n",
" <td> Kelly, Mr. James</td>\n",
" <td> male</td>\n",
" <td> 34.5</td>\n",
" <td> 0</td>\n",
" <td> 0</td>\n",
" <td> 330911</td>\n",
" <td> 7.8292</td>\n",
" <td> NaN</td>\n",
" <td> Q</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td> 893</td>\n",
" <td> 3</td>\n",
" <td> Wilkes, Mrs. James (Ellen Needs)</td>\n",
" <td> female</td>\n",
" <td> 47.0</td>\n",
" <td> 1</td>\n",
" <td> 0</td>\n",
" <td> 363272</td>\n",
" <td> 7.0000</td>\n",
" <td> NaN</td>\n",
" <td> S</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td> 894</td>\n",
" <td> 2</td>\n",
" <td> Myles, Mr. Thomas Francis</td>\n",
" <td> male</td>\n",
" <td> 62.0</td>\n",
" <td> 0</td>\n",
" <td> 0</td>\n",
" <td> 240276</td>\n",
" <td> 9.6875</td>\n",
" <td> NaN</td>\n",
" <td> Q</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td> 895</td>\n",
" <td> 3</td>\n",
" <td> Wirz, Mr. Albert</td>\n",
" <td> male</td>\n",
" <td> 27.0</td>\n",
" <td> 0</td>\n",
" <td> 0</td>\n",
" <td> 315154</td>\n",
" <td> 8.6625</td>\n",
" <td> NaN</td>\n",
" <td> S</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td> 896</td>\n",
" <td> 3</td>\n",
" <td> Hirvonen, Mrs. Alexander (Helga E Lindqvist)</td>\n",
" <td> female</td>\n",
" <td> 22.0</td>\n",
" <td> 1</td>\n",
" <td> 1</td>\n",
" <td> 3101298</td>\n",
" <td> 12.2875</td>\n",
" <td> NaN</td>\n",
" <td> S</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" PassengerId Pclass Name Sex \\\n",
"0 892 3 Kelly, Mr. James male \n",
"1 893 3 Wilkes, Mrs. James (Ellen Needs) female \n",
"2 894 2 Myles, Mr. Thomas Francis male \n",
"3 895 3 Wirz, Mr. Albert male \n",
"4 896 3 Hirvonen, Mrs. Alexander (Helga E Lindqvist) female \n",
"\n",
" Age SibSp Parch Ticket Fare Cabin Embarked \n",
"0 34.5 0 0 330911 7.8292 NaN Q \n",
"1 47.0 1 0 363272 7.0000 NaN S \n",
"2 62.0 0 0 240276 9.6875 NaN Q \n",
"3 27.0 0 0 315154 8.6625 NaN S \n",
"4 22.0 1 1 3101298 12.2875 NaN S "
]
},
"execution_count": 40,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"df_test = pd.read_csv('../data/titanic/test.csv')\n",
"df_test.head()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note the test data does not contain the column 'Survived', we'll use our trained model to predict these values."
]
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Data wrangle the test set and convert it to a numpy array\n",
"df_test = clean_data(df_test, drop_passenger_id=False)\n",
"test_data = df_test.values"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Take the decision trees and run it on the test data:"
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Get the test data features, skipping the first column 'PassengerId'\n",
"test_x = test_data[:, 1:]\n",
"\n",
"# Predict the Survival values for the test data\n",
"test_y = clf.predict(test_x)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Random Forest: Prepare for Kaggle Submission\n",
"\n",
"Create a DataFrame by combining the index from the test data with the output of predictions, then write the results to the output:"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"df_test['Survived'] = test_y\n",
"df_test[['PassengerId', 'Survived']] \\\n",
" .to_csv('../data/titanic/results-rf.csv', index=False)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Evaluate Model Accuracy"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Submitting to Kaggle will give you an accuracy score. It would be helpful to get an idea of accuracy without submitting to Kaggle.\n",
"\n",
"We'll split our training data, 80% will go to \"train\" and 20% will go to \"test\":"
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"((891, 8), (891,))\n",
"((712, 8), (712,))\n",
"((179, 8), (179,))\n"
]
2015-05-31 20:53:16 +08:00
}
],
"source": [
"from sklearn import metrics\n",
"from sklearn.cross_validation import train_test_split\n",
"\n",
"# Split 80-20 train vs test data\n",
"train_x, test_x, train_y, test_y = train_test_split(train_features, \n",
" train_target, \n",
" test_size=0.20, \n",
" random_state=0)\n",
"print (train_features.shape, train_target.shape)\n",
"print (train_x.shape, train_y.shape)\n",
"print (test_x.shape, test_y.shape)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Use the new training data to fit the model, predict, and get the accuracy score:"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Accuracy = 0.83\n"
]
2015-05-31 20:53:16 +08:00
}
],
"source": [
"clf = clf.fit(train_x, train_y)\n",
"predict_y = clf.predict(test_x)\n",
"\n",
"from sklearn.metrics import accuracy_score\n",
"print (\"Accuracy = %.2f\" % (accuracy_score(test_y, predict_y)))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"View the Confusion Matrix:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"| | condition True | condition false|\n",
"|------|----------------|---------------|\n",
"|prediction true|True Positive|False positive|\n",
"|Prediction False|False Negative|True Negative|"
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAlgAAAE/CAYAAACaf72jAAAEJGlDQ1BJQ0MgUHJvZmlsZQAAOBGF\nVd9v21QUPolvUqQWPyBYR4eKxa9VU1u5GxqtxgZJk6XtShal6dgqJOQ6N4mpGwfb6baqT3uBNwb8\nAUDZAw9IPCENBmJ72fbAtElThyqqSUh76MQPISbtBVXhu3ZiJ1PEXPX6yznfOec7517bRD1fabWa\nGVWIlquunc8klZOnFpSeTYrSs9RLA9Sr6U4tkcvNEi7BFffO6+EdigjL7ZHu/k72I796i9zRiSJP\nwG4VHX0Z+AxRzNRrtksUvwf7+Gm3BtzzHPDTNgQCqwKXfZwSeNHHJz1OIT8JjtAq6xWtCLwGPLzY\nZi+3YV8DGMiT4VVuG7oiZpGzrZJhcs/hL49xtzH/Dy6bdfTsXYNY+5yluWO4D4neK/ZUvok/17X0\nHPBLsF+vuUlhfwX4j/rSfAJ4H1H0qZJ9dN7nR19frRTeBt4Fe9FwpwtN+2p1MXscGLHR9SXrmMgj\nONd1ZxKzpBeA71b4tNhj6JGoyFNp4GHgwUp9qplfmnFW5oTdy7NamcwCI49kv6fN5IAHgD+0rbyo\nBc3SOjczohbyS1drbq6pQdqumllRC/0ymTtej8gpbbuVwpQfyw66dqEZyxZKxtHpJn+tZnpnEdrY\nBbueF9qQn93S7HQGGHnYP7w6L+YGHNtd1FJitqPAR+hERCNOFi1i1alKO6RQnjKUxL1GNjwlMsiE\nhcPLYTEiT9ISbN15OY/jx4SMshe9LaJRpTvHr3C/ybFYP1PZAfwfYrPsMBtnE6SwN9ib7AhLwTrB\nDgUKcm06FSrTfSj187xPdVQWOk5Q8vxAfSiIUc7Z7xr6zY/+hpqwSyv0I0/QMTRb7RMgBxNodTfS\nPqdraz/sDjzKBrv4zu2+a2t0/HHzjd2Lbcc2sG7GtsL42K+xLfxtUgI7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Mbgvm6wOxssAhaBgEXASrACtmlswSwCFoH+IBACtx00syKBmX7q+RILwlO5Z4e0\n1NXIxEXL5IJf/0syTzlfOsprVJ0XEp4APtYgHWUgPd1uEKBkZBOK69XSUVENkhQBkhSHBKGe4zUQ\npfbyfKHXlW4Qt65ONy5hSTzu6myBxKypEYSNSUAlibTdDXXSVlAlnTUgVxEZ0ry6WmZeeasc+937\npXVjpXS1kVyBiIUlUUal5eioqIGZWGSffHugBmwr3yMdiN3dhXzdyJfGyyr46hWH4aoNFgGLQCAi\nYCVYgdgqtkwWAYvAwBDw8I2uzg7Z9fpL8so1X5EE2EnRVupTTxfJUZ/8nBT98SmJyouU1p2Vej5x\n8QppKd4mHbVl0lUjknL8iUqqat56U8IzIG2KSYN6rkq6G0TSTz1HIpJXi7ulwSE5kIJFwvHt1r/c\nLt3gSxFZiSBdHdKyo0Li5mVL+vJl0lKyU9prSoTayZyjFkpCdp5ET4XAKilXutphy9VUJ13gc6kn\nroCNWLvUrlmDdCjQQr61yBeCtAwQw4jYp8Td2qj5hoSCyVluNbC+YWNbBEYIAUuwRgh4m61FwCLg\newSwLB1SJJeoJzVo7GrfFWy1VItzkEohuyVfv1eaa6okd/5iiYSa7ekvnSxYnCenPPSkpE2YjO2Y\nIqRw0/uy5s5PgXhVSUzuVDn+/t9I+sTJ0lBRCgkTh8wQSJ8ipOVDkeP//CuJz8ySV2+4FMxIZOEd\nP5HZZ14EkZNb2iDJWvPAj2XSDefKxCUniRsSqIv+9YEUvbdGVn/nWomePE5OuPcBSRk/QcJQvn3v\nvyNrbr9S842dOFdOuPleSR03QepLvy7h0TEgcGBWUIPqIklLsnzfeWyKFgEfI2AJlo8BtclZBCwC\nI4CAqs0g3AHxiEtLk5z
"text/plain": [
"<IPython.core.display.Image at 0x10e2207d0>"
]
},
"execution_count": 46,
"metadata": {
"image/png": {
"width": 800
}
2015-05-31 20:53:16 +08:00
},
"output_type": "execute_result"
}
],
"source": [
"from IPython.core.display import Image \n",
"Image(filename='../data/confusion_matrix.png', width=800)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Get the model score and confusion matrix:"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Model Score 0.83 \n",
"\n",
2015-05-31 20:53:16 +08:00
"('Confusion Matrix ', array([[98, 12],\n",
" [19, 50]]))\n",
" Predicted\n",
" | 0 | 1 |\n",
" |-----|-----|\n",
" 0 | 98 | 12 |\n",
"Actual |-----|-----|\n",
" 1 | 19 | 50 |\n",
" |-----|-----|\n"
]
2015-05-31 20:53:16 +08:00
}
],
"source": [
"model_score = clf.score(test_x, test_y)\n",
"print (\"Model Score %.2f \\n\" % (model_score))\n",
"\n",
"confusion_matrix = metrics.confusion_matrix(test_y, predict_y)\n",
"print (\"Confusion Matrix \", confusion_matrix)\n",
"\n",
"print (\" Predicted\")\n",
"print (\" | 0 | 1 |\")\n",
"print (\" |-----|-----|\")\n",
"print (\" 0 | %3d | %3d |\" % (confusion_matrix[0, 0],\n",
" confusion_matrix[0, 1]))\n",
"print (\"Actual |-----|-----|\")\n",
"print (\" 1 | %3d | %3d |\" % (confusion_matrix[1, 0],\n",
" confusion_matrix[1, 1]))\n",
"print (\" |-----|-----|\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Display the classification report:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$Precision = \\frac{TP}{TP + FP}$$ \n",
"\n",
"$$Recall = \\frac{TP}{TP + FN}$$ \n",
"\n",
"$$F1 = \\frac{2TP}{2TP + FP + FN}$$ "
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" precision recall f1-score support\n",
"\n",
2015-05-31 20:53:16 +08:00
"Not Survived 0.84 0.89 0.86 110\n",
" Survived 0.81 0.72 0.76 69\n",
"\n",
2015-05-31 20:53:16 +08:00
" avg / total 0.83 0.83 0.82 179\n",
"\n"
]
}
],
2015-05-31 20:53:16 +08:00
"source": [
"from sklearn.metrics import classification_report\n",
"print(classification_report(test_y, \n",
" predict_y, \n",
" target_names=['Not Survived', 'Survived']))"
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 2",
"language": "python",
"name": "python2"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.9"
}
2015-05-31 20:53:16 +08:00
},
"nbformat": 4,
"nbformat_minor": 0
}