Certainly! Below is a comprehensive guide to building a predictive model for determining whether a person requires hospitalization based on their health conditions. This guide is structured as a Jupyter Notebook, covering all the deliverables outlined in your business logic. You can use this as a template for your analysis.
Hospitalization Prediction Model
1. Introduction
This project aims to build a machine learning model to predict whether a person requires hospitalization based on various health conditions. The target variable is outcome, where 1 indicates hospitalization is needed, and 0 indicates no hospitalization.
2. Table of Contents
- Importing Libraries
- Loading the Data
- Exploratory Data Analysis (EDA)
- Data Cleaning and Preprocessing
- Feature Engineering
- Feature Encoding
- Feature Selection
- Modeling
- Model Evaluation
- Making Predictions
- Submission
- Conclusion
Importing Libraries
# Data manipulation libraries
import pandas as pd
import numpy as np
# Visualization libraries
import matplotlib.pyplot as plt
import seaborn as sns
# Preprocessing and modeling
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.impute import SimpleImputer
# Machine Learning models
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
# Evaluation metrics
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
# Miscellaneous
import warnings
warnings.filterwarnings('ignore')
%matplotlib inline
Loading the Data
# Load training and test datasets
train = pd.read_csv('train.csv')
test = pd.read_csv('test.csv')
submission_sample = pd.read_csv('submission_sample.csv')
# Display first few rows
print("Training Data:")
display(train.head())
print("\nTest Data:")
display(test.head())
Exploratory Data Analysis (EDA)
Understanding the Data Structure
# Check the shape of the datasets
print(f"Training set shape: {train.shape}")
print(f"Test set shape: {test.shape}")
Summary Statistics
# Summary statistics for numerical features
display(train.describe())
# Check for categorical features
display(train.info())
Distribution of Target Variable
# Distribution of the target variable
sns.countplot(x='outcome', data=train)
plt.title('Distribution of Outcome')
plt.show()
Feature Distributions
# Histograms for numerical features
train.hist(bins=30, figsize=(15,10))
plt.tight_layout()
plt.show()
Correlation Analysis
# Correlation matrix
plt.figure(figsize=(12,8))
sns.heatmap(train.corr(), annot=True, cmap='coolwarm')
plt.title('Correlation Matrix')
plt.show()
Data Cleaning and Preprocessing
Handling Missing Values
# Check for missing values
print("Missing values in training set:")
print(train.isnull().sum())
print("\nMissing values in test set:")
print(test.isnull().sum())
# Drop rows with any missing values
train_clean = train.dropna()
test_clean = test.dropna()
print(f"Training set shape after dropping missing values: {train_clean.shape}")
print(f"Test set shape after dropping missing values: {test_clean.shape}")
Feature Engineering
Creating a New Feature: Pulse Pressure
Pulse Pressure is the difference between Systolic and Diastolic Blood Pressure. It can be an indicator of cardiovascular health.
# Create Pulse Pressure feature
train_clean['PulsePressure'] = train_clean['SystolicBP'] - train_clean['DiastolicBP']
test_clean['PulsePressure'] = test_clean['SystolicBP'] - test_clean['DiastolicBP']
# Display the new feature
display(train_clean[['SystolicBP', 'DiastolicBP', 'PulsePressure']].head())
Feature Encoding
Encoding Categorical Features
Assuming BodyTemp and other non-numeric features need encoding.
# Identify categorical features
categorical_features = ['BodyTemp']
# Initialize Label Encoder
le = LabelEncoder()
for feature in categorical_features:
train_clean[feature] = le.fit_transform(train_clean[feature])
test_clean[feature] = le.transform(test_clean[feature])
# Display encoded features
display(train_clean[categorical_features].head())
Feature Selection
Identifying Important Features
Using Random Forest to identify feature importance.
# Define features and target
X = train_clean.drop(['id', 'outcome'], axis=1)
y = train_clean['outcome']
# Initialize Random Forest
rf = RandomForestClassifier(random_state=42)
rf.fit(X, y)
# Feature importance
importances = rf.feature_importances_
feature_names = X.columns
feature_importance_df = pd.DataFrame({'Feature': feature_names, 'Importance': importances})
feature_importance_df = feature_importance_df.sort_values(by='Importance', ascending=False)
# Plot feature importance
plt.figure(figsize=(10,6))
sns.barplot(x='Importance', y='Feature', data=feature_importance_df)
plt.title('Feature Importance')
plt.show()
Modeling
Preprocessing Pipeline
# Define features and target
X = train_clean.drop(['id', 'outcome'], axis=1)
y = train_clean['outcome']
# Apply standard scaling
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# Apply the same transformation to test data
X_test = test_clean.drop(['id'], axis=1)
X_test_scaled = scaler.transform(X_test)
Splitting the Data
# Split the data into training and validation sets
X_train, X_val, y_train, y_val = train_test_split(X_scaled, y,
test_size=0.2,
random_state=42,
stratify=y)
Training Multiple Models
# Initialize models
models = {
'Logistic Regression': LogisticRegression(random_state=42),
'Random Forest': RandomForestClassifier(random_state=42),
'Gradient Boosting': GradientBoostingClassifier(random_state=42)
}
# Train models
for name, model in models.items():
model.fit(X_train, y_train)
print(f"{name} trained.")
Model Evaluation
Evaluating Models on Validation Set
# Evaluate each model
for name, model in models.items():
y_pred = model.predict(X_val)
acc = accuracy_score(y_val, y_pred)
print(f"{name} Accuracy: {acc:.4f}")
Confusion Matrix and Classification Report for Best Model
Assuming Random Forest performed the best.
best_model = models['Random Forest']
y_pred = best_model.predict(X_val)
# Confusion Matrix
cm = confusion_matrix(y_val, y_pred)
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues')
plt.title('Confusion Matrix - Random Forest')
plt.xlabel('Predicted')
plt.ylabel('Actual')
plt.show()
# Classification Report
print("Classification Report:")
print(classification_report(y_val, y_pred))
Making Predictions
# Make predictions on the test set
test_predictions = best_model.predict(X_test_scaled)
# Prepare submission dataframe
submission = pd.DataFrame({
'id': test_clean['id'],
'outcome': test_predictions
})
# Ensure the submission follows the sample format
submission = submission[['id', 'outcome']]
display(submission.head())
Submission
# Save the submission file
submission.to_csv('submission.csv', index=False)
print("Submission file 'submission.csv' created successfully.")
Conclusion
In this project, we successfully built a predictive model to determine whether a person requires hospitalization based on their health conditions. Through exploratory data analysis, feature engineering, and model evaluation, we identified the most significant features and selected the Random Forest classifier as our best-performing model. The final predictions have been saved in the submission.csv file as per the required format.
Additional Recommendations
-
Hyperparameter Tuning: To further improve model performance, consider using GridSearchCV or RandomizedSearchCV to tune hyperparameters of the chosen model.
-
Cross-Validation: Implement cross-validation to ensure the model's robustness and generalizability.
-
Handling Class Imbalance: If there's an imbalance in the target classes, techniques like SMOTE or class weighting can be employed.
-
Feature Importance Analysis: Delve deeper into feature importance to understand the key drivers affecting hospitalization needs.
Feel free to customize and expand upon this notebook based on your specific requirements and the nuances of your dataset. Good luck with your project!