Implementing The K-Means Algorithm to Predict Passenger Survival Status

Posted on Apr 25, 2023

Please see my Github Repo for code detail.

1. Introduction

To have a better understanding of the incident of Titanic's sinking, K-means algorithm is implemented using Scikit-learn on the Titanic dataset to try to predict if a passenger survived or not.

2. Data

The sinking of the RMS Titanic is a well-known shipwreck that occurred during its maiden voyage on April 15, 1912. Despite being deemed "unsinkable," the ship hit an iceberg and sank, leading to the tragic loss of 1502 out of 2224 passengers and crew members. Due to the shortage of lifeboats, survival largely depended on luck, although certain groups of people appeared to have had a better chance of surviving than others:

  • PassengerId: Unique Id of passenger
  • Survived: If the passenger survived (0-No, 1-Yes)
  • Pclass: Passenger Class (1=1st, 2=2nd, 3=3rd)
  • Name: Name of the passenger
  • Sex: Male/Female
  • SibSp: Number of siblings/spouses aboard
  • Parch: Number of parents/children aboard
  • Ticket: Ticket Number
  • Fare: Passenger Fare
  • Cabin: Passenger Fare
  • Embarked: Port of Embarkation (C=Cherbourg, Q=Queenstown, S=Southampton)

3. Process

  1. Load data from provided on Kaggle
  2. Explore data set
  3. Data cleaning
    • Impute missing data
    • Encode categorical feature to numerical feature
  4. Modeling
    • Scaling feature
    • Determine number of clusters
    • Model fitting
    • Evaluation

4. Data Exploration

Lightweight exploration is carried out on the training and testing data frames to see what the data looks like.
  • Data preview:

  • Description of numerical fields:

  • Missing values by field:

5. Data Cleaning

  • Empty values are imputed with the field's average value
  • Certain fields ("Name", "Ticket", "Cabin", "Embarked" columns) are dropped since they are irrelevant to the model
  • Categorical field encoded to be numeric ("Sex" column)

6. Modeling

  • To consider all features equally, the values for all features must be transformed into the same scale of measurement.
  • To attempt to choose the right number of clusters, the SSE is calculated to plot the elbow plot.
    • No obvious "bends" are visible in the elbow plot:
    • A cluster number of 3 is chosen arbitrarily to continue building the model.
  • Model evaluation is carried out by calculating the percentage of correctly predicted survival outcome of passengers.
  • Two attempts to improve the model are made:
    1. MinMaxScaler: to scale each feature to a given range in the training and testing data sets.
    2. Utilizing additional parameters in KMeans: to explore additional functionality of the KMeans module for better model performance.

7. Conclusion

From the data, there is not an optimal clustering number. However, with the improvement of the MinMaxScaler, the trained K-Means model can accurately predict the survival of the passengers more than 50% of the time.

8. References

About Author

Brian Kuo

A consultant and data engineering professional with 6+ years of experience in business intelligence, warehousing solutions, ETL, and project management. Enjoys collaboration in team projects to support multi-disciplinary stakeholders and generate valuable results that align with business goals.
View all posts by Brian Kuo >

Related Articles

Leave a Comment

No comments found.

View Posts by Categories


Our Recent Popular Posts


View Posts by Tags

#python #trainwithnycdsa 2019 2020 Revenue 3-points agriculture air quality airbnb airline alcohol Alex Baransky algorithm alumni Alumni Interview Alumni Reviews Alumni Spotlight alumni story Alumnus ames dataset ames housing dataset apartment rent API Application artist aws bank loans beautiful soup Best Bootcamp Best Data Science 2019 Best Data Science Bootcamp Best Data Science Bootcamp 2020 Best Ranked Big Data Book Launch Book-Signing bootcamp Bootcamp Alumni Bootcamp Prep boston safety Bundles cake recipe California Cancer Research capstone car price Career Career Day citibike classic cars classpass clustering Coding Course Demo Course Report covid 19 credit credit card crime frequency crops D3.js data data analysis Data Analyst data analytics data for tripadvisor reviews data science Data Science Academy Data Science Bootcamp Data science jobs Data Science Reviews Data Scientist Data Scientist Jobs data visualization database Deep Learning Demo Day Discount disney dplyr drug data e-commerce economy employee employee burnout employer networking environment feature engineering Finance Financial Data Science fitness studio Flask flight delay gbm Get Hired ggplot2 googleVis H20 Hadoop hallmark holiday movie happiness healthcare frauds higgs boson Hiring hiring partner events Hiring Partners hotels housing housing data housing predictions housing price hy-vee Income Industry Experts Injuries Instructor Blog Instructor Interview insurance italki Job Job Placement Jobs Jon Krohn JP Morgan Chase Kaggle Kickstarter las vegas airport lasso regression Lead Data Scienctist Lead Data Scientist leaflet league linear regression Logistic Regression machine learning Maps market matplotlib Medical Research Meet the team meetup methal health miami beach movie music Napoli NBA netflix Networking neural network Neural networks New Courses NHL nlp NYC NYC Data Science nyc data science academy NYC Open Data nyc property NYCDSA NYCDSA Alumni Online Online Bootcamp Online Training Open Data painter pandas Part-time performance phoenix pollutants Portfolio Development precision measurement prediction Prework Programming public safety PwC python Python Data Analysis python machine learning python scrapy python web scraping python webscraping Python Workshop R R Data Analysis R language R Programming R Shiny r studio R Visualization R Workshop R-bloggers random forest Ranking recommendation recommendation system regression Remote remote data science bootcamp Scrapy scrapy visualization seaborn seafood type Selenium sentiment analysis sentiment classification Shiny Shiny Dashboard Spark Special Special Summer Sports statistics streaming Student Interview Student Showcase SVM Switchup Tableau teachers team team performance TensorFlow Testimonial tf-idf Top Data Science Bootcamp Top manufacturing companies Transfers tweets twitter videos visualization wallstreet wallstreetbets web scraping Weekend Course What to expect whiskey whiskeyadvocate wildfire word cloud word2vec XGBoost yelp youtube trending ZORI