import streamlit as st import numpy as np import pickle import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # Load Model model = pickle.load(open("life_expectancy_model.pkl", "rb")) # Set Page Config st.set_page_config( page_title="Life Expectancy Prediction", page_icon="πŸ“Š", layout="centered", ) # Styling st.markdown(""" """, unsafe_allow_html=True) # Navigation State if "current_page" not in st.session_state: st.session_state.current_page = "Model Pipeline" def switch_page(page): st.session_state.current_page = page # Sidebar Navigation st.sidebar.title("Navigation") if st.sidebar.button("Model Pipeline"): switch_page("Model Pipeline") if st.sidebar.button("Hands-on Model"): switch_page("Hands-on Model") ## Importing Data data = pd.read_csv("Life Expectancy Data.csv") data.columns = data.columns.str.strip() # Model Report Page if st.session_state.current_page == "Model Pipeline": st.markdown("

Model Pipeline

", unsafe_allow_html=True) st.markdown("
", unsafe_allow_html=True) #st.markdown("

Explore different stages of the Life Expectancy project

", unsafe_allow_html=True) st.image("images/Life_Expectancy.webp", caption="Life Expectancy Prediction Overview", use_container_width=True) if st.button("**Problem Statement**"): switch_page("Problem Statement") if st.button("**Data Collection**"): switch_page("Data Collection") if st.button("**Simple EDA**"): switch_page("Simple EDA") if st.button("**Data Pre-processing**"): switch_page("Data Pre-processing") if st.button("**Exploratory Data Analysis**"): switch_page("EDA") if st.button("**Model Building**"): switch_page("Model Building") if st.button("**Final Model**"): switch_page("Final Model") st.markdown("
", unsafe_allow_html=True) st.markdown( """
πŸ”— See Whole Code on GitHub
""", unsafe_allow_html=True ) st.markdown("
", unsafe_allow_html=True) st.markdown('''

About Author

Hello! I’m Yash Jadhav, a passionate Data Scientist and Data Analyst. I specialize in transforming raw data into actionable insights and helping others master the art of Machine Learning.

LinkedIn GitHub Medium
''', unsafe_allow_html=True) # Individual Sections elif st.session_state.current_page == "Problem Statement": st.markdown("

Problem Statement

", unsafe_allow_html=True) st.markdown("""
The Goal of this project is to build a predictive model that estimates the Life Expectancy of a country based on multiple influencing factors such as health indicators, economic conditions, and social parameters.
""", unsafe_allow_html=True) st.markdown("
", unsafe_allow_html=True) st.image("images/problem_statement.png", caption="Life Expectancy Prediction Overview", use_container_width=True) if st.button("πŸ”™ Go Back to Model Pipeline"): switch_page("Model Pipeline") elif st.session_state.current_page == "Data Collection": st.markdown("

Data Collection

", unsafe_allow_html=True) st.markdown("""
The dataset used in this project is sourced from Kaggle, containing information on life expectancy across different countries along with various health, economic, and demographic factors.
""", unsafe_allow_html=True) st.markdown("
", unsafe_allow_html=True) st.markdown("""
πŸ“Œ Click here to access the dataset on Kaggle
""", unsafe_allow_html=True) st.markdown("

Dataset Overview

", unsafe_allow_html=True) st.markdown("""
The dataset consists of 2938 rows and 22 columns, capturing crucial indicators such as life expectancy, mortality rates, GDP, schooling, immunization rates, and more. Below is a summary of the dataset features:
""", unsafe_allow_html=True) st.markdown("
", unsafe_allow_html=True) data_info = """
β€’ Country: Name of the country (Categorical)
β€’ Year: Year of observation (Numerical)
β€’ Status: Developing or Developed country (Categorical)
β€’ Life Expectancy: Average age a person is expected to live (Numerical)
β€’ Adult Mortality: Probability of dying between 15-60 years per 1000 population (Numerical)
β€’ Infant Deaths: Number of infant deaths per 1000 live births (Numerical)
β€’ Alcohol: Alcohol consumption per capita (Numerical)
β€’ Percentage Expenditure: Government expenditure on health as a percentage of GDP (Numerical)
β€’ Hepatitis B: Immunization coverage for Hepatitis B (Numerical)
β€’ Measles: Number of reported measles cases per year (Numerical)
β€’ BMI: Average Body Mass Index of the population (Numerical)
β€’ Under-five Deaths: Number of deaths under the age of five per 1000 live births (Numerical)
β€’ Polio: Immunization coverage for Polio (Numerical)
β€’ Total Expenditure: Total health expenditure as a percentage of GDP (Numerical)
β€’ Diphtheria: Immunization coverage for Diphtheria (Numerical)
β€’ HIV/AIDS: Death rate due to HIV/AIDS per 100,000 people (Numerical)
β€’ GDP: Gross Domestic Product per capita (Numerical)
β€’ Population: Total population of the country (Numerical)
β€’ Thinness 1-19 Years: Percentage of thin individuals aged 1-19 years (Numerical)
β€’ Thinness 5-9 Years: Percentage of thin individuals aged 5-9 years (Numerical)
β€’ Income Composition: Human development index based on income composition (Numerical)
β€’ Schooling: Average number of years of schooling (Numerical)
""" st.markdown(data_info, unsafe_allow_html=True) st.markdown("
", unsafe_allow_html=True) if st.button("πŸ”™ Go Back to Model Pipeline"): switch_page("Model Pipeline") elif st.session_state.current_page == "Simple EDA": st.markdown("

Simple Exploratory Data Analysis

", unsafe_allow_html=True) st.markdown("""
Exploratory Data Analysis (EDA) helps in understanding the structure, patterns, and missing values in the dataset. Below is an initial preview of the data, followed by a missing values summary.
""", unsafe_allow_html=True) st.markdown("
", unsafe_allow_html=True) # Display dataset sample st.markdown("

Sample Dataset

", unsafe_allow_html=True) st.dataframe(data.head()) st.markdown("
", unsafe_allow_html=True) # Display missing values count st.markdown("

Missing Values Summary

", unsafe_allow_html=True) missing_values = data.isna().sum().reset_index() missing_values.columns = ["Column Name", "Missing Values"] col1, col2, col3 = st.columns([1, 2, 1]) with col2: st.dataframe(missing_values) st.markdown("
", unsafe_allow_html=True) # Display missing values count st.markdown("

Data Description

", unsafe_allow_html=True) st.dataframe(data.describe()) st.markdown("
", unsafe_allow_html=True) # Add Boxplot Visualizations st.markdown("

Boxplots for Data Distribution

", unsafe_allow_html=True) # Define columns for visualization columns = ['Life expectancy', 'Adult Mortality', 'infant deaths', 'Alcohol', 'percentage expenditure', 'Hepatitis B', 'Measles', 'BMI', 'under-five deaths', 'Polio', 'Total expenditure', 'Diphtheria', 'HIV/AIDS', 'GDP', 'Population', 'thinness 1-19 years', 'thinness 5-9 years', 'Income composition of resources', 'Schooling'] # Matplotlib figure setup fig, axes = plt.subplots(nrows=10, ncols=2, figsize=(12, 30)) # Adjust grid size axes = axes.flatten() for i, col in enumerate(columns): sns.boxplot(x=data[col], ax=axes[i], color="skyblue") # Create boxplots axes[i].set_title(f'Boxplot of {col}', fontsize=12) axes[i].set_xlabel("") plt.tight_layout() st.pyplot(fig) st.markdown("
", unsafe_allow_html=True) if st.button("πŸ”™ Go Back to Model Pipeline"): switch_page("Model Pipeline") elif st.session_state.current_page == "Data Pre-processing": st.markdown("

Data Preprocessing

", unsafe_allow_html=True) st.markdown("
", unsafe_allow_html=True) st.markdown("

Handling Missing Values

", unsafe_allow_html=True) st.markdown("
", unsafe_allow_html=True) st.markdown("""
Using "Median" Imputation to Fill Highly Skewed Data
""", unsafe_allow_html=True) st.markdown("""
Median imputation is used for columns where data distribution is highly skewed. This approach ensures that extreme values do not overly influence the dataset. Examples include GDP, Population, and Adult Mortality.
""", unsafe_allow_html=True) st.markdown("
", unsafe_allow_html=True) st.markdown("""
Mean Imputation for Columns with Small Missing Values and Normally Distributed Data
""", unsafe_allow_html=True) st.markdown("""
Mean imputation is applied when missing values are small and the data is normally distributed. This helps maintain the overall dataset structure without being affected by extreme values. Suitable columns include BMI, Polio, and Schooling.
""", unsafe_allow_html=True) st.markdown("
", unsafe_allow_html=True) st.markdown("""
Applying One-Hot Encoding on "Status" Column
""", unsafe_allow_html=True) st.markdown("""
The "Status" column categorizes countries as either Developed or Developing. One-Hot Encoding is used to convert this categorical variable into a numerical format suitable for machine learning models. The "drop='first'" parameter is applied to prevent multicollinearity.
""", unsafe_allow_html=True) if st.button("πŸ”™ Go Back to Model Pipeline"): switch_page("Model Pipeline") elif st.session_state.current_page == "EDA": st.markdown("

Exploratory Data Analysis (EDA)

", unsafe_allow_html=True) st.markdown("
", unsafe_allow_html=True) # Target Column Distribution st.markdown("

Target Column Distribution

", unsafe_allow_html=True) st.image("images/target_column_distribution.png", caption="Life Expectancy Distribution", use_container_width=True) st.markdown("""
Insight: Mostly Life Expectancy is in range of 50-80.
""", unsafe_allow_html=True) st.markdown("
", unsafe_allow_html=True) # Correlation Heatmap st.markdown("

Correlation Heatmap

", unsafe_allow_html=True) st.image("images/Correlation_Heatmap.png", caption="Correlation Heatmap", use_container_width=True) st.markdown("""
Insight: Our target column Life Expectancy is mostly linearly dependent on Schooling, Income Composition of Resources, GDP, Diphtheria, Polio, BMI, and Percentage Expenditure.
""", unsafe_allow_html=True) st.markdown("
", unsafe_allow_html=True) # How Specific Columns Affect Life Expectancy st.markdown("

How Specific Columns Affect Life Expectancy

", unsafe_allow_html=True) # GDP vs. Life Expectancy st.image("images/specific_col_affecting_target.png", caption="Features vs. Life Expectancy", use_container_width=True) st.markdown("""
Insights: 1️⃣ **GDP vs. Life Expectancy** - Positive correlation: As GDP increases, Life Expectancy also increases. - Some countries with low GDP still have high Life Expectancy due to good healthcare policies. 2️⃣ **Schooling vs. Life Expectancy** - Strong positive correlation: More years of schooling β†’ longer life. - Educated populations follow better hygiene, diet, and medical care, increasing Life Expectancy. 3️⃣ **Income Composition vs. Life Expectancy** - Higher economic stability leads to better healthcare systems and lifestyles, improving Life Expectancy. 4️⃣ **Diphtheria & Polio vs. Life Expectancy** - Higher vaccination rates (80%-100%) correspond to Life Expectancy above 70 years. - Lower vaccination rates (<40%) lead to lower Life Expectancy (~40-60 years), indicating weak healthcare infrastructure. 5️⃣ **BMI vs. Life Expectancy** - No clear linear trend due to high variance in data points. - BMI < 18 (malnutrition) and BMI > 30 (obesity) reduce Life Expectancy. - Advanced healthcare and better nutrition in some countries help maintain high Life Expectancy despite malnutrition/obesity.
""", unsafe_allow_html=True) st.markdown("
", unsafe_allow_html=True) st.markdown("
", unsafe_allow_html=True) # Life Expectancy vs Developed / Undeveloped Countries st.markdown("

Life Expectancy vs Developed / Undeveloped Countries

", unsafe_allow_html=True) st.image("images/target_col vs countries.png", caption="Life Expectancy vs Developed / Undeveloped Countries", use_container_width=True) st.markdown("""
Insight: Life Expectancy is higher in Developed Countries due to Advanced Healthcare, Better Nutrition, Medical Interventions.
""", unsafe_allow_html=True) st.markdown("
", unsafe_allow_html=True) if st.button("πŸ”™ Go Back to Model Pipeline"): switch_page("Model Pipeline") # Model Building elif st.session_state.current_page == "Model Building": st.markdown("""

Model Building

""", unsafe_allow_html=True) st.markdown("
", unsafe_allow_html=True) st.markdown("""

Introduction

In this section, we explore different Ensemble Learning techniques to improve model performance.

We implemented three ensemble models: πŸ₯‡ Voting Regressor - 🎯 Bagging Regressor - 🌲 Random Forest Regressor

""", unsafe_allow_html=True) st.markdown("
", unsafe_allow_html=True) st.markdown("""
1️⃣ Voting Regressor
""", unsafe_allow_html=True) st.markdown("
", unsafe_allow_html=True) st.markdown("""
2️⃣ Bagging Regressor
""", unsafe_allow_html=True) st.markdown("
", unsafe_allow_html=True) st.markdown("""
3️⃣ Random Forest Regressor
""", unsafe_allow_html=True) st.markdown("
", unsafe_allow_html=True) st.markdown("""

Combining High & Low Variance Models

A crucial step to improve ensemble performance is choosing models with different variance levels:

This technique helps create a balanced ensemble, preventing excessive overfitting or underfitting! βœ…

""", unsafe_allow_html=True) st.markdown("
", unsafe_allow_html=True) # Hyperparameter Tuning st.markdown("""

Hyperparameter Tuning using Optuna ⚑

We optimized hyperparameters for KNN, Decision Tree, Bagging Regressor, and Random Forest using Optuna.

Below are the optimized parameters for each model:

πŸ”Ή K-Nearest Neighbors (KNN)
πŸ”Ή Decision Tree
πŸ”Ή Bagging Regressor
πŸ”Ή Random Forest
""", unsafe_allow_html=True) st.markdown("
", unsafe_allow_html=True) # Model Performance Insights st.markdown("""

Model Performance Insights πŸ“Š

Here’s how our ensemble models performed on training and test datasets:

""", unsafe_allow_html=True) st.markdown(""" """, unsafe_allow_html=True) st.markdown("""
Ensemble Training Score Test Score Generalized Score
Voting Ensemble 95.80% 92.13% 92.89%
Bagging Ensemble 98.68% 95.04% 95.45%
Random Forest 97.92% 94.71% 94.71%
""", unsafe_allow_html=True) st.markdown("
", unsafe_allow_html=True) if st.button("πŸ”™ Go Back to Model Pipeline"): switch_page("Model Pipeline") # Fianl Model elif st.session_state.current_page == "Final Model": st.markdown( """ """, unsafe_allow_html=True, ) # Title st.markdown("

Final Model

", unsafe_allow_html=True) st.markdown("
", unsafe_allow_html=True) st.markdown( "
" "

After experimenting with multiple trials using Optuna, we selected the best-fit model " "by analyzing the training and test scores of different trials. " "The following scatter plots provide insights into this selection process.

" "
", unsafe_allow_html=True, ) st.markdown("
", unsafe_allow_html=True) st.markdown("

Training vs Test Score (All Trials)

", unsafe_allow_html=True) st.markdown( "

This scatter plot visualizes the training and test scores of all trials. " "The goal was to identify a model where both scores are closely aligned, ensuring minimal overfitting or underfitting.

", unsafe_allow_html=True, ) st.image("images/bagging_trails.png", caption="All Trails", use_container_width=True) st.markdown("
", unsafe_allow_html=True) st.markdown("

Training vs Test Score (First 50 Trials)

", unsafe_allow_html=True) st.markdown( "

By filtering the first 50 trials, we focused on models that demonstrated balanced performance. " "The best-fit model was selected by ensuring that the training and test scores are close to each other.

", unsafe_allow_html=True, ) st.image("images/bagging_50trails.png", caption="50 Trails", use_container_width=True) st.markdown( "

" "From the above trials, we selected the 9th trial as its train score and test score have minimal difference." "

", unsafe_allow_html=True ) st.markdown("
", unsafe_allow_html=True) st.markdown("

Selected Best-Fit Model

", unsafe_allow_html=True) st.markdown( "
" "" "

This model was selected as it demonstrated a balance between generalization and performance.

" "
", unsafe_allow_html=True, ) if st.button("πŸ”™ Go Back to Model Pipeline"): switch_page("Model Pipeline") # Hands-on Model Page elif st.session_state.current_page == "Hands-on Model": st.markdown("

Hands-on Model

", unsafe_allow_html=True) st.markdown("
", unsafe_allow_html=True) st.markdown("

Provide inputs to predict Life Expectancy

", unsafe_allow_html=True) col1, col2 = st.columns(2) with col1: year = st.slider("Year", 2000, 2015, 2008) status = st.radio("Status", ["Developing", "Developed"], horizontal=True) status = 1 if status == "Developed" else 0 adult_mortality = st.slider("Adult Mortality Rate", 1, 723, 144) infant_deaths = st.slider("Infant Deaths", 0, 1800, 3) alcohol = st.slider("Alcohol Consumption", 0.01, 17.87, 4.55) percentage_expenditure = st.slider("Percentage Expenditure", 0.0, 19479.91, 738.25) hepatitis_b = st.slider("Hepatitis B Immunization (%)", 1, 99, 83) measles = st.slider("Measles Cases", 0, 212183, 2419) bmi = st.slider("BMI", 1.0, 87.3, 38.3) polio = st.slider("Polio Immunization (%)", 3, 99, 82) with col2: under_five_deaths = st.slider("Under-Five Deaths", 0, 2500, 4) total_expenditure = st.slider("Total Healthcare Expenditure (%)", 0.37, 17.6, 5.92) diphtheria = st.slider("Diphtheria Immunization (%)", 2, 99, 82) hiv_aids = st.slider("HIV/AIDS Prevalence Rate", 0.1, 50.6, 1.74) gdp = st.slider("GDP per Capita", 1.68, 119172.7, 6611.52) population = st.slider("Population", 34, 1293859000, 10230850) thinness_1_19 = st.slider("Thinness 1-19 years (%)", 0.1, 27.7, 4.83) thinness_5_9 = st.slider("Thinness 5-9 years (%)", 0.1, 28.6, 4.86) income_composition = st.slider("Income Composition of Resources", 0.0, 0.948, 0.63) schooling = st.slider("Schooling (Years)", 0.0, 20.7, 11.99) if st.button("Predict Life Expectancy"): features = np.array([[year, status, adult_mortality, infant_deaths, alcohol, percentage_expenditure, hepatitis_b, measles, bmi, under_five_deaths, polio, total_expenditure, diphtheria, hiv_aids, gdp, population, thinness_1_19, thinness_5_9, income_composition, schooling]]) prediction = model.predict(features)[0] st.markdown( f"""
Predicted Life Expectancy: {prediction:.2f} years
""", unsafe_allow_html=True, )