0% found this document useful (0 votes)
34 views7 pages

Titanic Dataset Analysis Overview

The Titanic dataset analysis project utilized Python to explore passenger demographics and survival rates, revealing that gender and ticket class significantly influenced survival outcomes. Data cleaning and preprocessing were performed, followed by exploratory data analysis (EDA) that indicated a survival rate of approximately 38%. A Random Forest Classifier was identified as the most effective predictive model, achieving around 83% accuracy.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views7 pages

Titanic Dataset Analysis Overview

The Titanic dataset analysis project utilized Python to explore passenger demographics and survival rates, revealing that gender and ticket class significantly influenced survival outcomes. Data cleaning and preprocessing were performed, followed by exploratory data analysis (EDA) that indicated a survival rate of approximately 38%. A Random Forest Classifier was identified as the most effective predictive model, achieving around 83% accuracy.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Titanic Dataset Analysis using Python

Introduction: The Titanic dataset is one of the most well-known datasets in data
science and machine learning. It provides data on passengers aboard the Titanic,
with features such as age, sex, ticket class, and whether or not they survived. This
project aims to analyze this dataset using Python to gain insights and build predictive
models.

• Contains demographics and passenger information from 891 of the 2224


passengers and crew on board the Titanic.
• Variable • Definition • Key
• Survived • Survival • 0 = No, 1 = Yes
• Pclass • Ticket class • 1 = 1st, 2 = 2nd, 3 = 3rd

• Sex • Sex
• Age • Age in years
• Sibsp • # of siblings / spouses aboard
the Titanic
• Parch • # of parents / children aboard
the Titanic
• Ticket • Ticket number
• Fare • Passenger fare
• Cabin • Cabin number
• Embarked • Port of Embarkation • C = Cherbourg, Q =
Queenstown,S =
Southampton

• Pclass: A proxy for socio-economic status (SES)


1st = Upper
2nd = Middle
3rd = Lower
• Age: Age is fractional if less than 1. If the age is estimated, is it in the form of
xx.5
• Sibsp: The dataset defines family relations in this way...
Sibling = brother, sister, stepbrother, stepsister
Spouse = husband, wife (mistresses and fiancés were ignored)
• Parch: The dataset defines family relations in this way...
Parent = mother, father
Child = daughter, son, stepdaughter, stepson
Some children travelled only with a nanny, therefore parch=0 for them.

Dataset Description :
import numpy as np
import pandas as pd
Titanic Dataset Analysis using Python

import [Link] as plt


import seaborn as sns
from [Link] import chi2_contingency
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
[Link]('seaborn-ticks')

SMALL_SIZE = 13
MEDIUM_SIZE = 14
BIGGER_SIZE = 16

[Link]('font', size=SMALL_SIZE) # controls default text sizes


[Link]('axes', titlesize=SMALL_SIZE) # fontsize of the axes title
[Link]('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels
[Link]('xtick', labelsize=MEDIUM_SIZE) # fontsize of the tick labels
[Link]('ytick', labelsize=MEDIUM_SIZE) # fontsize of the tick labels
[Link]('legend', fontsize=SMALL_SIZE) # legend fontsize

#Load the CSV into a Pandas Dataframe


titanic_data = pd.read_csv('[Link]')

titanic_data.head(5)

Passe Surv Pcl Name Se A Si Pa Ticket Far Ca Emba


ngerI ived as x g bS rc e bi rked
d s e p h n
0 1 0 3 Braund, Mr. Owen ma 2 1 0 A/5 7.25 Na S
Harris le 2 21171 00 N
.
0
1 2 1 1 Cumings, Mrs. fe 3 1 0 PC 71.2 C8 C
John Bradley ma 8 17599 833 5
(Florence Briggs le .
Th... 0
2 3 1 3 Heikkinen, Miss. fe 2 0 0 STON/O 7.92 Na S
Laina ma 6 2. 50 N
le . 3101282
0
3 4 1 1 Futrelle, Mrs. fe 3 1 0 113803 53.1 C1 S
Jacques Heath ma 5 000 23
(Lily May Peel) le .
0
4 5 0 3 Allen, Mr. William ma 3 0 0 373450 8.05 Na S
Henry le 5 00 N
.
0

titanic_data.info()

<class '[Link]'>
RangeIndex: 891 entries, 0 to 890
Titanic Dataset Analysis using Python

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)
memory usage: 83.6+ KB
We observe that there are missing values at the Age, Cabin and Embarked columns.
Data Cleaning :
We cleaned the dataset using the following steps:

• Handled missing values: Filled missing Age with median, Embarked with
mode, and dropped Cabin due to too many missing values.
• Encoded categorical features: Converted Sex and Embarked to numerical
format using label encoding or one-hot encoding.
• Dropped irrelevant columns: Such as PassengerId, Name, Ticket, and
Cabin.

#Drop the unwanted columns


n_titanic_data=titanic_data.drop(['Cabin','Ticket','Name', 'Fare','PassengerId'],axis=1)

n_titanic_data.head()

Survived Pclass Sex Age SibSp Parch Embarked


0 0 3 male 22.0 1 0 S
1 1 1 female 38.0 1 0 C

2 1 3 female 26.0 0 0 S
3 1 1 female 35.0 1 0 S
4 0 3 male 35.0 0 0 S

n_titanic_data.info()

<class '[Link]'>
RangeIndex: 891 entries, 0 to 890
Titanic Dataset Analysis using Python

Data columns (total 7 columns):


Survived 891 non-null int64
Pclass 891 non-null int64
Sex 891 non-null object
Age 714 non-null float64
SibSp 891 non-null int64
Parch 891 non-null int64
Embarked 889 non-null object
dtypes: float64(1), int64(4), object(2)
memory usage: 48.8+ KB

We have only 714 Age values out of 891 of the entries and 2 values missing from the
Embarked Variable. We will have to decide whether to omit these or impute them
with some values when we model relationships based on Age or Embarked.

Imputing missing data is a complicated procedure and creating and evaluating a


regression model to predict them based on the other variables is out of the scope of
this analysis.

Exploratory Data Analysis (EDA) :


Key insights from EDA:

• Survival Rate: ~38% survived, 62% did not.


• Gender: Females had a significantly higher survival rate.
• Class: First class passengers had better chances of survival.
• Age: Children and young adults had slightly better survival odds.

Visualizations used:

• Bar plots for survival distribution by Sex, Pclass, and Embarked.


• Histograms for Age and Fare.
• Heatmap for correlation between features.

To gain initial insights into the dataset, we can perform some basic exploratory

operations:

# Display the first few rows of the dataset

print([Link]())

# Check the dimensions of the dataset

print([Link])
Titanic Dataset Analysis using Python

# Get summary statistics of numerical variables

print([Link]())

# Check the data types of variables

print([Link])

# Check for missing values

print([Link]().sum())

Model Building :
We built a classification model to predict survival using the following steps:

• Train-Test Split: 80-20 split of data.

• Models Used:
o Logistic Regression
o Decision Tree Classifier
o Random Forest Classifier
• Evaluation Metrics: Accuracy, Precision, Recall, F1-score

Best performance was observed with the Random Forest Classifier, achieving:

• Accuracy: ~83%

Precision/Recall: Balanced across classes

#Import libraries

import pandas as pd from sklearn.model_selection import train_test_split from


[Link] import LabelEncoder from sklearn.linear_model import LogisticRegression
from [Link] import DecisionTreeClassifier from [Link] import
RandomForestClassifier from [Link] import accuracy_score, classification_report
Titanic Dataset Analysis using Python

#Load dataset

df = pd.read_csv('[Link]') # Use correct path if different

#Clean and preprocess data

df['Age'].fillna(df['Age'].median(), inplace=True) df['Embarked'].fillna(df['Embarked'].mode()[0],


inplace=True) [Link](['Cabin', 'Name', 'Ticket', 'PassengerId'], axis=1, inplace=True)

#Encode categorical features

label_encoder = LabelEncoder() df['Sex'] = label_encoder.fit_transform(df['Sex']) # male=1,


female=0 df = pd.get_dummies(df, columns=['Embarked'], drop_first=True)

#Define features (X) and target (y)

X = [Link]('Survived', axis=1) y = df['Survived']

#Split data into train and test sets

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

#Initialize models

log_model = LogisticRegression(max_iter=200) tree_model =


DecisionTreeClassifier(random_state=42) forest_model =
RandomForestClassifier(random_state=42)

#Train models

log_model.fit(X_train, y_train) tree_model.fit(X_train, y_train) forest_model.fit(X_train, y_train)

#Make predictions

log_preds = log_model.predict(X_test) tree_preds = tree_model.predict(X_test) forest_preds =


forest_model.predict(X_test)

#Evaluate models

print("Logistic Regression Accuracy:", accuracy_score(y_test, log_preds)) print("Decision Tree


Accuracy:", accuracy_score(y_test, tree_preds)) print("Random Forest Accuracy:",
accuracy_score(y_test, forest_preds))

#Detailed classification report for best model

print("\nRandom Forest Classification Report:") print(classification_report(y_test, forest_preds))


Titanic Dataset Analysis using Python

Conclusion :
This project successfully analyzed the Titanic dataset using Python. It identified key
factors influencing survival, such as gender and ticket class. The Random Forest
model proved most effective for prediction, and the analysis demonstrates the value
of preprocessing, feature selection, and visualization in machine learning projects.

You might also like