# -*- coding: utf-8 -*-
"""HET-17.ipynb

Automatically generated by Colab.

Original file is located at
    https://colab.research.google.com/drive/12tvRqaMFU-LaI3dILRrMBmMPbav04RVK

**Import Required Libraries**
"""

import pandas as pd
import numpy as np

# Visualization
import matplotlib.pyplot as plt
import seaborn as sns

# Preprocessing
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline

# Models
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier

# Evaluation
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
from sklearn.metrics import confusion_matrix, classification_report, roc_auc_score, roc_curve

"""**Load Dataset**"""

# Upload CSV using Colab file uploader OR load from Drive
df = pd.read_csv('hospital_readmissions.csv')

# Preview data
df.head()

"""**Basic Dataset Inspection**"""

print("Dataset Shape:", df.shape)
print("\nDataset Info:")
df.info()

print("\nMissing Values:")
print(df.isnull().sum())

"""**Data Cleaning**"""

# Replace 'Missing' with NaN
df.replace('Missing', np.nan, inplace=True)

# Fill missing categorical values with mode
categorical_cols = df.select_dtypes(include='object').columns
for col in categorical_cols:
    df[col].fillna(df[col].mode()[0], inplace=True)

# Convert target variable to binary
df['readmitted'] = df['readmitted'].map({'yes': 1, 'no': 0})

df.head()

"""**Feature & Target Separation**"""

X = df.drop('readmitted', axis=1)
y = df['readmitted']

"""**Encode Categorical Variables**"""

# Identify categorical and numerical columns
cat_features = X.select_dtypes(include='object').columns
num_features = X.select_dtypes(include=['int64', 'float64']).columns

# Preprocessing pipeline
preprocessor = ColumnTransformer(
    transformers=[
        ('num', StandardScaler(), num_features),
        ('cat', LabelEncoder(), cat_features)
    ],
    remainder='passthrough'
)

# Manual Label Encoding
le = LabelEncoder()
for col in cat_features:
    X[col] = le.fit_transform(X[col])

"""**Train–Test Split**"""

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

print("Training set:", X_train.shape)
print("Testing set:", X_test.shape)

"""**Model 1 – Logistic Regression (Baseline)**"""

log_model = LogisticRegression(max_iter=1000)
log_model.fit(X_train, y_train)

# Predictions
y_pred_log = log_model.predict(X_test)
y_prob_log = log_model.predict_proba(X_test)[:,1]

"""**Model 2 – Random Forest (Advanced)**"""

rf_model = RandomForestClassifier(
    n_estimators=200,
    random_state=42,
    class_weight='balanced'
)

rf_model.fit(X_train, y_train)

y_pred_rf = rf_model.predict(X_test)
y_prob_rf = rf_model.predict_proba(X_test)[:,1]

"""**Model Evaluation**"""

def evaluate_model(name, y_test, y_pred, y_prob):
    print(f"\n{name} Performance")
    print("-"*40)
    print("Accuracy :", accuracy_score(y_test, y_pred))
    print("Precision:", precision_score(y_test, y_pred))
    print("Recall   :", recall_score(y_test, y_pred))
    print("F1 Score :", f1_score(y_test, y_pred))
    print("ROC AUC  :", roc_auc_score(y_test, y_prob))
    print("\nClassification Report:\n", classification_report(y_test, y_pred))

evaluate_model("Logistic Regression", y_test, y_pred_log, y_prob_log)
evaluate_model("Random Forest", y_test, y_pred_rf, y_prob_rf)

"""**Confusion Matrix Visualization**"""

plt.figure(figsize=(6,4))
sns.heatmap(confusion_matrix(y_test, y_pred_rf),
            annot=True, fmt='d', cmap='Blues')
plt.title("Random Forest Confusion Matrix")
plt.xlabel("Predicted")
plt.ylabel("Actual")
plt.show()

"""**ROC Curve (Very Important for Dissertation)**"""

fpr, tpr, _ = roc_curve(y_test, y_prob_rf)

plt.figure(figsize=(6,4))
plt.plot(fpr, tpr, label="Random Forest (AUC = %.2f)" % roc_auc_score(y_test, y_prob_rf))
plt.plot([0,1],[0,1],'k--')
plt.xlabel("False Positive Rate")
plt.ylabel("True Positive Rate")
plt.title("ROC Curve – Readmission Prediction")
plt.legend()
plt.show()

"""**Feature Importance (Explainability)**"""

feature_importance = pd.Series(
    rf_model.feature_importances_, index=X.columns
).sort_values(ascending=False)

feature_importance.head(10)