Switch to side-by-side view

--- a
+++ b/readmission_risk_prediction.ipynb
@@ -0,0 +1,232 @@
+{
+ "cells": [
+  {
+   "cell_type": "code",
+   "execution_count": 8,
+   "id": "ec2980fa-e433-4924-bf8e-ae890c9352f2",
+   "metadata": {},
+   "outputs": [
+    {
+     "name": "stdout",
+     "output_type": "stream",
+     "text": [
+      "Fitting 5 folds for each of 90 candidates, totalling 450 fits\n",
+      "Best parameters: {'classifier__criterion': 'entropy', 'classifier__max_depth': None, 'classifier__min_samples_leaf': 1, 'classifier__min_samples_split': 2}\n",
+      "Decision Tree Model:\n",
+      "Accuracy: 0.508\n",
+      "Classification Report:\n",
+      "              precision    recall  f1-score   support\n",
+      "\n",
+      "           0       0.51      0.52      0.51      1000\n",
+      "           1       0.51      0.50      0.50      1000\n",
+      "\n",
+      "    accuracy                           0.51      2000\n",
+      "   macro avg       0.51      0.51      0.51      2000\n",
+      "weighted avg       0.51      0.51      0.51      2000\n",
+      "\n",
+      "Confusion Matrix:\n",
+      "[[517 483]\n",
+      " [501 499]]\n",
+      "\n",
+      "Top 10 Most Important Features:\n",
+      "                        feature  importance\n",
+      "4                        result    0.409878\n",
+      "6         duration_result_ratio    0.279102\n",
+      "0                           age    0.120918\n",
+      "5   age_comorbidity_interaction    0.106891\n",
+      "1                        gender    0.042323\n",
+      "3                      duration    0.016378\n",
+      "9                   age_group_2    0.006668\n",
+      "10                  age_group_3    0.005753\n",
+      "11                  age_group_4    0.004192\n",
+      "8                   age_group_1    0.003047\n"
+     ]
+    }
+   ],
+   "source": [
+    "import mysql.connector\n",
+    "import pandas as pd\n",
+    "import numpy as np\n",
+    "from sklearn.model_selection import train_test_split, GridSearchCV\n",
+    "from sklearn.tree import DecisionTreeClassifier\n",
+    "from sklearn.preprocessing import StandardScaler\n",
+    "from sklearn.impute import SimpleImputer\n",
+    "from sklearn.pipeline import Pipeline\n",
+    "from sklearn.metrics import accuracy_score, classification_report, confusion_matrix\n",
+    "from imblearn.over_sampling import SMOTE\n",
+    "\n",
+    "# Database connection\n",
+    "db = mysql.connector.connect(\n",
+    "    host=\"localhost\",\n",
+    "    user=\"root\",\n",
+    "    password=\"HunnyS@1511\",\n",
+    "    database=\"patient_readmission\"\n",
+    ")\n",
+    "\n",
+    "# Create a cursor object to execute SQL queries\n",
+    "cursor = db.cursor()\n",
+    "\n",
+    "# SQL query to retrieve patient features data\n",
+    "query = \"\"\"\n",
+    "    WITH patient_medications AS (\n",
+    "        SELECT \n",
+    "            patient_id,\n",
+    "            medication_name,\n",
+    "            start_date,\n",
+    "            end_date,\n",
+    "            DATEDIFF(end_date, start_date) AS duration\n",
+    "        FROM \n",
+    "            medications\n",
+    "    ),\n",
+    "    lab_result_averages AS (\n",
+    "        SELECT \n",
+    "            patient_id,\n",
+    "            AVG(result_value) AS result\n",
+    "        FROM \n",
+    "            lab_results\n",
+    "        GROUP BY \n",
+    "            patient_id\n",
+    "    ),\n",
+    "    comorbidity_index AS (\n",
+    "        SELECT \n",
+    "            patient_id,\n",
+    "            COUNT(icd_code) AS comorbidity_index\n",
+    "        FROM \n",
+    "            diagnoses\n",
+    "        GROUP BY \n",
+    "            patient_id\n",
+    "    )\n",
+    "    SELECT \n",
+    "        p.patient_id,\n",
+    "        p.age,\n",
+    "        p.gender,\n",
+    "        ci.comorbidity_index,\n",
+    "        pm.duration,\n",
+    "        lra.result,\n",
+    "        r.readmission_risk\n",
+    "    FROM \n",
+    "        patients p\n",
+    "    JOIN \n",
+    "        comorbidity_index ci ON p.patient_id = ci.patient_id\n",
+    "    JOIN \n",
+    "        patient_medications pm ON p.patient_id = pm.patient_id\n",
+    "    JOIN \n",
+    "        lab_result_averages lra ON p.patient_id = lra.patient_id\n",
+    "    JOIN \n",
+    "        readmission_risk r ON p.patient_id = r.patient_id;\n",
+    "\"\"\"\n",
+    "\n",
+    "# Execute the SQL query\n",
+    "cursor.execute(query)\n",
+    "\n",
+    "# Fetch all the rows from the query result\n",
+    "data = cursor.fetchall()\n",
+    "\n",
+    "# Create pandas dataframe from the retrieved data\n",
+    "df = pd.DataFrame(data, columns=['patient_id', 'age', 'gender', 'comorbidity_count', 'duration', 'result', 'readmission_risk'])\n",
+    "\n",
+    "# Convert gender to numerical value\n",
+    "df['gender'] = df['gender'].map({'Male': 0, 'Female': 1})\n",
+    "\n",
+    "# Feature engineering\n",
+    "df['age_group'] = pd.cut(df['age'], bins=[0, 18, 35, 50, 65, 100], labels=[0, 1, 2, 3, 4])\n",
+    "df['comorbidity_group'] = pd.cut(df['comorbidity_count'], bins=[0, 1, 3, 5, np.inf], labels=[0, 1, 2, 3])\n",
+    "df['duration_group'] = pd.cut(df['duration'], bins=[-np.inf, 7, 14, 30, np.inf], labels=[0, 1, 2, 3])\n",
+    "\n",
+    "# Additional feature engineering\n",
+    "df['age_comorbidity_interaction'] = df['age'] * df['comorbidity_count']\n",
+    "df['duration_result_ratio'] = df['duration'] / (df['result'] + 1)  # Adding 1 to avoid division by zero\n",
+    "\n",
+    "# One-hot encode categorical variables\n",
+    "df = pd.get_dummies(df, columns=['age_group', 'comorbidity_group', 'duration_group'])\n",
+    "\n",
+    "# Split data into features and target\n",
+    "X = df.drop(['patient_id', 'readmission_risk'], axis=1)\n",
+    "y = df['readmission_risk']\n",
+    "\n",
+    "# Split data into training and testing sets\n",
+    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
+    "\n",
+    "# Create a pipeline\n",
+    "pipeline = Pipeline([\n",
+    "    ('imputer', SimpleImputer(strategy='median')),\n",
+    "    ('scaler', StandardScaler()),\n",
+    "    ('classifier', DecisionTreeClassifier(random_state=42))\n",
+    "])\n",
+    "\n",
+    "# Define the parameter grid for GridSearchCV\n",
+    "param_grid = {\n",
+    "    'classifier__max_depth': [5, 10, 15, 20, None],\n",
+    "    'classifier__min_samples_split': [2, 5, 10],\n",
+    "    'classifier__min_samples_leaf': [1, 2, 4],\n",
+    "    'classifier__criterion': ['gini', 'entropy']\n",
+    "}\n",
+    "\n",
+    "# Perform GridSearchCV\n",
+    "grid_search = GridSearchCV(pipeline, param_grid, cv=5, n_jobs=-1, verbose=2)\n",
+    "\n",
+    "# Handle class imbalance with SMOTE\n",
+    "smote = SMOTE(random_state=42)\n",
+    "X_train_resampled, y_train_resampled = smote.fit_resample(X_train, y_train)\n",
+    "\n",
+    "# Fit the model\n",
+    "grid_search.fit(X_train_resampled, y_train_resampled)\n",
+    "\n",
+    "# Print the best parameters\n",
+    "print(\"Best parameters:\", grid_search.best_params_)\n",
+    "\n",
+    "# Make predictions\n",
+    "y_pred = grid_search.predict(X_test)\n",
+    "\n",
+    "# Evaluate the model\n",
+    "print('Decision Tree Model:')\n",
+    "print('Accuracy:', accuracy_score(y_test, y_pred))\n",
+    "print('Classification Report:')\n",
+    "print(classification_report(y_test, y_pred))\n",
+    "print('Confusion Matrix:')\n",
+    "print(confusion_matrix(y_test, y_pred))\n",
+    "\n",
+    "# Feature importance\n",
+    "feature_importance = grid_search.best_estimator_.named_steps['classifier'].feature_importances_\n",
+    "feature_names = X.columns\n",
+    "feature_importance_df = pd.DataFrame({'feature': feature_names, 'importance': feature_importance})\n",
+    "feature_importance_df = feature_importance_df.sort_values('importance', ascending=False)\n",
+    "print(\"\\nTop 10 Most Important Features:\")\n",
+    "print(feature_importance_df.head(10))\n",
+    "\n",
+    "# Close the cursor and connection\n",
+    "cursor.close()\n",
+    "db.close()"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "id": "98c9f03e-5fc1-45cd-9173-925b70df4956",
+   "metadata": {},
+   "outputs": [],
+   "source": []
+  }
+ ],
+ "metadata": {
+  "kernelspec": {
+   "display_name": "Python 3 (ipykernel)",
+   "language": "python",
+   "name": "python3"
+  },
+  "language_info": {
+   "codemirror_mode": {
+    "name": "ipython",
+    "version": 3
+   },
+   "file_extension": ".py",
+   "mimetype": "text/x-python",
+   "name": "python",
+   "nbconvert_exporter": "python",
+   "pygments_lexer": "ipython3",
+   "version": "3.9.18"
+  }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}