Switch to unified view

a b/readmission_risk_prediction.ipynb
1
{
2
 "cells": [
3
  {
4
   "cell_type": "code",
5
   "execution_count": 8,
6
   "id": "ec2980fa-e433-4924-bf8e-ae890c9352f2",
7
   "metadata": {},
8
   "outputs": [
9
    {
10
     "name": "stdout",
11
     "output_type": "stream",
12
     "text": [
13
      "Fitting 5 folds for each of 90 candidates, totalling 450 fits\n",
14
      "Best parameters: {'classifier__criterion': 'entropy', 'classifier__max_depth': None, 'classifier__min_samples_leaf': 1, 'classifier__min_samples_split': 2}\n",
15
      "Decision Tree Model:\n",
16
      "Accuracy: 0.508\n",
17
      "Classification Report:\n",
18
      "              precision    recall  f1-score   support\n",
19
      "\n",
20
      "           0       0.51      0.52      0.51      1000\n",
21
      "           1       0.51      0.50      0.50      1000\n",
22
      "\n",
23
      "    accuracy                           0.51      2000\n",
24
      "   macro avg       0.51      0.51      0.51      2000\n",
25
      "weighted avg       0.51      0.51      0.51      2000\n",
26
      "\n",
27
      "Confusion Matrix:\n",
28
      "[[517 483]\n",
29
      " [501 499]]\n",
30
      "\n",
31
      "Top 10 Most Important Features:\n",
32
      "                        feature  importance\n",
33
      "4                        result    0.409878\n",
34
      "6         duration_result_ratio    0.279102\n",
35
      "0                           age    0.120918\n",
36
      "5   age_comorbidity_interaction    0.106891\n",
37
      "1                        gender    0.042323\n",
38
      "3                      duration    0.016378\n",
39
      "9                   age_group_2    0.006668\n",
40
      "10                  age_group_3    0.005753\n",
41
      "11                  age_group_4    0.004192\n",
42
      "8                   age_group_1    0.003047\n"
43
     ]
44
    }
45
   ],
46
   "source": [
47
    "import mysql.connector\n",
48
    "import pandas as pd\n",
49
    "import numpy as np\n",
50
    "from sklearn.model_selection import train_test_split, GridSearchCV\n",
51
    "from sklearn.tree import DecisionTreeClassifier\n",
52
    "from sklearn.preprocessing import StandardScaler\n",
53
    "from sklearn.impute import SimpleImputer\n",
54
    "from sklearn.pipeline import Pipeline\n",
55
    "from sklearn.metrics import accuracy_score, classification_report, confusion_matrix\n",
56
    "from imblearn.over_sampling import SMOTE\n",
57
    "\n",
58
    "# Database connection\n",
59
    "db = mysql.connector.connect(\n",
60
    "    host=\"localhost\",\n",
61
    "    user=\"root\",\n",
62
    "    password=\"HunnyS@1511\",\n",
63
    "    database=\"patient_readmission\"\n",
64
    ")\n",
65
    "\n",
66
    "# Create a cursor object to execute SQL queries\n",
67
    "cursor = db.cursor()\n",
68
    "\n",
69
    "# SQL query to retrieve patient features data\n",
70
    "query = \"\"\"\n",
71
    "    WITH patient_medications AS (\n",
72
    "        SELECT \n",
73
    "            patient_id,\n",
74
    "            medication_name,\n",
75
    "            start_date,\n",
76
    "            end_date,\n",
77
    "            DATEDIFF(end_date, start_date) AS duration\n",
78
    "        FROM \n",
79
    "            medications\n",
80
    "    ),\n",
81
    "    lab_result_averages AS (\n",
82
    "        SELECT \n",
83
    "            patient_id,\n",
84
    "            AVG(result_value) AS result\n",
85
    "        FROM \n",
86
    "            lab_results\n",
87
    "        GROUP BY \n",
88
    "            patient_id\n",
89
    "    ),\n",
90
    "    comorbidity_index AS (\n",
91
    "        SELECT \n",
92
    "            patient_id,\n",
93
    "            COUNT(icd_code) AS comorbidity_index\n",
94
    "        FROM \n",
95
    "            diagnoses\n",
96
    "        GROUP BY \n",
97
    "            patient_id\n",
98
    "    )\n",
99
    "    SELECT \n",
100
    "        p.patient_id,\n",
101
    "        p.age,\n",
102
    "        p.gender,\n",
103
    "        ci.comorbidity_index,\n",
104
    "        pm.duration,\n",
105
    "        lra.result,\n",
106
    "        r.readmission_risk\n",
107
    "    FROM \n",
108
    "        patients p\n",
109
    "    JOIN \n",
110
    "        comorbidity_index ci ON p.patient_id = ci.patient_id\n",
111
    "    JOIN \n",
112
    "        patient_medications pm ON p.patient_id = pm.patient_id\n",
113
    "    JOIN \n",
114
    "        lab_result_averages lra ON p.patient_id = lra.patient_id\n",
115
    "    JOIN \n",
116
    "        readmission_risk r ON p.patient_id = r.patient_id;\n",
117
    "\"\"\"\n",
118
    "\n",
119
    "# Execute the SQL query\n",
120
    "cursor.execute(query)\n",
121
    "\n",
122
    "# Fetch all the rows from the query result\n",
123
    "data = cursor.fetchall()\n",
124
    "\n",
125
    "# Create pandas dataframe from the retrieved data\n",
126
    "df = pd.DataFrame(data, columns=['patient_id', 'age', 'gender', 'comorbidity_count', 'duration', 'result', 'readmission_risk'])\n",
127
    "\n",
128
    "# Convert gender to numerical value\n",
129
    "df['gender'] = df['gender'].map({'Male': 0, 'Female': 1})\n",
130
    "\n",
131
    "# Feature engineering\n",
132
    "df['age_group'] = pd.cut(df['age'], bins=[0, 18, 35, 50, 65, 100], labels=[0, 1, 2, 3, 4])\n",
133
    "df['comorbidity_group'] = pd.cut(df['comorbidity_count'], bins=[0, 1, 3, 5, np.inf], labels=[0, 1, 2, 3])\n",
134
    "df['duration_group'] = pd.cut(df['duration'], bins=[-np.inf, 7, 14, 30, np.inf], labels=[0, 1, 2, 3])\n",
135
    "\n",
136
    "# Additional feature engineering\n",
137
    "df['age_comorbidity_interaction'] = df['age'] * df['comorbidity_count']\n",
138
    "df['duration_result_ratio'] = df['duration'] / (df['result'] + 1)  # Adding 1 to avoid division by zero\n",
139
    "\n",
140
    "# One-hot encode categorical variables\n",
141
    "df = pd.get_dummies(df, columns=['age_group', 'comorbidity_group', 'duration_group'])\n",
142
    "\n",
143
    "# Split data into features and target\n",
144
    "X = df.drop(['patient_id', 'readmission_risk'], axis=1)\n",
145
    "y = df['readmission_risk']\n",
146
    "\n",
147
    "# Split data into training and testing sets\n",
148
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
149
    "\n",
150
    "# Create a pipeline\n",
151
    "pipeline = Pipeline([\n",
152
    "    ('imputer', SimpleImputer(strategy='median')),\n",
153
    "    ('scaler', StandardScaler()),\n",
154
    "    ('classifier', DecisionTreeClassifier(random_state=42))\n",
155
    "])\n",
156
    "\n",
157
    "# Define the parameter grid for GridSearchCV\n",
158
    "param_grid = {\n",
159
    "    'classifier__max_depth': [5, 10, 15, 20, None],\n",
160
    "    'classifier__min_samples_split': [2, 5, 10],\n",
161
    "    'classifier__min_samples_leaf': [1, 2, 4],\n",
162
    "    'classifier__criterion': ['gini', 'entropy']\n",
163
    "}\n",
164
    "\n",
165
    "# Perform GridSearchCV\n",
166
    "grid_search = GridSearchCV(pipeline, param_grid, cv=5, n_jobs=-1, verbose=2)\n",
167
    "\n",
168
    "# Handle class imbalance with SMOTE\n",
169
    "smote = SMOTE(random_state=42)\n",
170
    "X_train_resampled, y_train_resampled = smote.fit_resample(X_train, y_train)\n",
171
    "\n",
172
    "# Fit the model\n",
173
    "grid_search.fit(X_train_resampled, y_train_resampled)\n",
174
    "\n",
175
    "# Print the best parameters\n",
176
    "print(\"Best parameters:\", grid_search.best_params_)\n",
177
    "\n",
178
    "# Make predictions\n",
179
    "y_pred = grid_search.predict(X_test)\n",
180
    "\n",
181
    "# Evaluate the model\n",
182
    "print('Decision Tree Model:')\n",
183
    "print('Accuracy:', accuracy_score(y_test, y_pred))\n",
184
    "print('Classification Report:')\n",
185
    "print(classification_report(y_test, y_pred))\n",
186
    "print('Confusion Matrix:')\n",
187
    "print(confusion_matrix(y_test, y_pred))\n",
188
    "\n",
189
    "# Feature importance\n",
190
    "feature_importance = grid_search.best_estimator_.named_steps['classifier'].feature_importances_\n",
191
    "feature_names = X.columns\n",
192
    "feature_importance_df = pd.DataFrame({'feature': feature_names, 'importance': feature_importance})\n",
193
    "feature_importance_df = feature_importance_df.sort_values('importance', ascending=False)\n",
194
    "print(\"\\nTop 10 Most Important Features:\")\n",
195
    "print(feature_importance_df.head(10))\n",
196
    "\n",
197
    "# Close the cursor and connection\n",
198
    "cursor.close()\n",
199
    "db.close()"
200
   ]
201
  },
202
  {
203
   "cell_type": "code",
204
   "execution_count": null,
205
   "id": "98c9f03e-5fc1-45cd-9173-925b70df4956",
206
   "metadata": {},
207
   "outputs": [],
208
   "source": []
209
  }
210
 ],
211
 "metadata": {
212
  "kernelspec": {
213
   "display_name": "Python 3 (ipykernel)",
214
   "language": "python",
215
   "name": "python3"
216
  },
217
  "language_info": {
218
   "codemirror_mode": {
219
    "name": "ipython",
220
    "version": 3
221
   },
222
   "file_extension": ".py",
223
   "mimetype": "text/x-python",
224
   "name": "python",
225
   "nbconvert_exporter": "python",
226
   "pygments_lexer": "ipython3",
227
   "version": "3.9.18"
228
  }
229
 },
230
 "nbformat": 4,
231
 "nbformat_minor": 5
232
}