{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "code",
      "execution_count": 1,
      "metadata": {
        "id": "6N9ohvX7-tdE"
      },
      "outputs": [],
      "source": [
        "# Import necessary libraries\n",
        "import pandas as pd\n",
        "import numpy as np\n",
        "from sklearn.model_selection import train_test_split, GridSearchCV\n",
        "from sklearn.impute import SimpleImputer\n",
        "from sklearn.ensemble import RandomForestClassifier\n",
        "from sklearn.feature_selection import SelectKBest, f_classif, RFE\n",
        "from sklearn.metrics import classification_report, accuracy_score\n",
        "from sklearn.preprocessing import StandardScaler\n",
        "from xgboost import XGBClassifier"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "from google.colab import files\n",
        "uploaded = files.upload()\n",
        "\n",
        "import pandas as pd\n",
        "\n",
        "df = pd.read_csv('healthcare-dataset-stroke-data.csv')"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 71
        },
        "id": "LLlRtq2f_Aqy",
        "outputId": "8eaed53c-31df-433b-c9fe-d0f5fbc50224"
      },
      "execution_count": 3,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<IPython.core.display.HTML object>"
            ],
            "text/html": [
              "\n",
              "     <input type=\"file\" id=\"files-bb4306a0-f7fa-4aa9-9420-8463ca195d33\" name=\"files[]\" multiple disabled\n",
              "        style=\"border:none\" />\n",
              "     <output id=\"result-bb4306a0-f7fa-4aa9-9420-8463ca195d33\">\n",
              "      Upload widget is only available when the cell has been executed in the\n",
              "      current browser session. Please rerun this cell to enable.\n",
              "      </output>\n",
              "      <script>// Copyright 2017 Google LLC\n",
              "//\n",
              "// Licensed under the Apache License, Version 2.0 (the \"License\");\n",
              "// you may not use this file except in compliance with the License.\n",
              "// You may obtain a copy of the License at\n",
              "//\n",
              "//      http://www.apache.org/licenses/LICENSE-2.0\n",
              "//\n",
              "// Unless required by applicable law or agreed to in writing, software\n",
              "// distributed under the License is distributed on an \"AS IS\" BASIS,\n",
              "// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
              "// See the License for the specific language governing permissions and\n",
              "// limitations under the License.\n",
              "\n",
              "/**\n",
              " * @fileoverview Helpers for google.colab Python module.\n",
              " */\n",
              "(function(scope) {\n",
              "function span(text, styleAttributes = {}) {\n",
              "  const element = document.createElement('span');\n",
              "  element.textContent = text;\n",
              "  for (const key of Object.keys(styleAttributes)) {\n",
              "    element.style[key] = styleAttributes[key];\n",
              "  }\n",
              "  return element;\n",
              "}\n",
              "\n",
              "// Max number of bytes which will be uploaded at a time.\n",
              "const MAX_PAYLOAD_SIZE = 100 * 1024;\n",
              "\n",
              "function _uploadFiles(inputId, outputId) {\n",
              "  const steps = uploadFilesStep(inputId, outputId);\n",
              "  const outputElement = document.getElementById(outputId);\n",
              "  // Cache steps on the outputElement to make it available for the next call\n",
              "  // to uploadFilesContinue from Python.\n",
              "  outputElement.steps = steps;\n",
              "\n",
              "  return _uploadFilesContinue(outputId);\n",
              "}\n",
              "\n",
              "// This is roughly an async generator (not supported in the browser yet),\n",
              "// where there are multiple asynchronous steps and the Python side is going\n",
              "// to poll for completion of each step.\n",
              "// This uses a Promise to block the python side on completion of each step,\n",
              "// then passes the result of the previous step as the input to the next step.\n",
              "function _uploadFilesContinue(outputId) {\n",
              "  const outputElement = document.getElementById(outputId);\n",
              "  const steps = outputElement.steps;\n",
              "\n",
              "  const next = steps.next(outputElement.lastPromiseValue);\n",
              "  return Promise.resolve(next.value.promise).then((value) => {\n",
              "    // Cache the last promise value to make it available to the next\n",
              "    // step of the generator.\n",
              "    outputElement.lastPromiseValue = value;\n",
              "    return next.value.response;\n",
              "  });\n",
              "}\n",
              "\n",
              "/**\n",
              " * Generator function which is called between each async step of the upload\n",
              " * process.\n",
              " * @param {string} inputId Element ID of the input file picker element.\n",
              " * @param {string} outputId Element ID of the output display.\n",
              " * @return {!Iterable<!Object>} Iterable of next steps.\n",
              " */\n",
              "function* uploadFilesStep(inputId, outputId) {\n",
              "  const inputElement = document.getElementById(inputId);\n",
              "  inputElement.disabled = false;\n",
              "\n",
              "  const outputElement = document.getElementById(outputId);\n",
              "  outputElement.innerHTML = '';\n",
              "\n",
              "  const pickedPromise = new Promise((resolve) => {\n",
              "    inputElement.addEventListener('change', (e) => {\n",
              "      resolve(e.target.files);\n",
              "    });\n",
              "  });\n",
              "\n",
              "  const cancel = document.createElement('button');\n",
              "  inputElement.parentElement.appendChild(cancel);\n",
              "  cancel.textContent = 'Cancel upload';\n",
              "  const cancelPromise = new Promise((resolve) => {\n",
              "    cancel.onclick = () => {\n",
              "      resolve(null);\n",
              "    };\n",
              "  });\n",
              "\n",
              "  // Wait for the user to pick the files.\n",
              "  const files = yield {\n",
              "    promise: Promise.race([pickedPromise, cancelPromise]),\n",
              "    response: {\n",
              "      action: 'starting',\n",
              "    }\n",
              "  };\n",
              "\n",
              "  cancel.remove();\n",
              "\n",
              "  // Disable the input element since further picks are not allowed.\n",
              "  inputElement.disabled = true;\n",
              "\n",
              "  if (!files) {\n",
              "    return {\n",
              "      response: {\n",
              "        action: 'complete',\n",
              "      }\n",
              "    };\n",
              "  }\n",
              "\n",
              "  for (const file of files) {\n",
              "    const li = document.createElement('li');\n",
              "    li.append(span(file.name, {fontWeight: 'bold'}));\n",
              "    li.append(span(\n",
              "        `(${file.type || 'n/a'}) - ${file.size} bytes, ` +\n",
              "        `last modified: ${\n",
              "            file.lastModifiedDate ? file.lastModifiedDate.toLocaleDateString() :\n",
              "                                    'n/a'} - `));\n",
              "    const percent = span('0% done');\n",
              "    li.appendChild(percent);\n",
              "\n",
              "    outputElement.appendChild(li);\n",
              "\n",
              "    const fileDataPromise = new Promise((resolve) => {\n",
              "      const reader = new FileReader();\n",
              "      reader.onload = (e) => {\n",
              "        resolve(e.target.result);\n",
              "      };\n",
              "      reader.readAsArrayBuffer(file);\n",
              "    });\n",
              "    // Wait for the data to be ready.\n",
              "    let fileData = yield {\n",
              "      promise: fileDataPromise,\n",
              "      response: {\n",
              "        action: 'continue',\n",
              "      }\n",
              "    };\n",
              "\n",
              "    // Use a chunked sending to avoid message size limits. See b/62115660.\n",
              "    let position = 0;\n",
              "    do {\n",
              "      const length = Math.min(fileData.byteLength - position, MAX_PAYLOAD_SIZE);\n",
              "      const chunk = new Uint8Array(fileData, position, length);\n",
              "      position += length;\n",
              "\n",
              "      const base64 = btoa(String.fromCharCode.apply(null, chunk));\n",
              "      yield {\n",
              "        response: {\n",
              "          action: 'append',\n",
              "          file: file.name,\n",
              "          data: base64,\n",
              "        },\n",
              "      };\n",
              "\n",
              "      let percentDone = fileData.byteLength === 0 ?\n",
              "          100 :\n",
              "          Math.round((position / fileData.byteLength) * 100);\n",
              "      percent.textContent = `${percentDone}% done`;\n",
              "\n",
              "    } while (position < fileData.byteLength);\n",
              "  }\n",
              "\n",
              "  // All done.\n",
              "  yield {\n",
              "    response: {\n",
              "      action: 'complete',\n",
              "    }\n",
              "  };\n",
              "}\n",
              "\n",
              "scope.google = scope.google || {};\n",
              "scope.google.colab = scope.google.colab || {};\n",
              "scope.google.colab._files = {\n",
              "  _uploadFiles,\n",
              "  _uploadFilesContinue,\n",
              "};\n",
              "})(self);\n",
              "</script> "
            ]
          },
          "metadata": {}
        },
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Saving healthcare-dataset-stroke-data.csv to healthcare-dataset-stroke-data.csv\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Display initial data information\n",
        "df"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 461
        },
        "id": "BxoJ0rfO_VM0",
        "outputId": "6dabafe7-8b00-472e-b29c-6fe8e40a22a0"
      },
      "execution_count": 36,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "         id   age  hypertension  heart_disease  avg_glucose_level   bmi  \\\n",
              "0      9046  67.0             0              1             228.69  36.6   \n",
              "1     51676  61.0             0              0             202.21  28.1   \n",
              "2     31112  80.0             0              1             105.92  32.5   \n",
              "3     60182  49.0             0              0             171.23  34.4   \n",
              "4      1665  79.0             1              0             174.12  24.0   \n",
              "...     ...   ...           ...            ...                ...   ...   \n",
              "5105  18234  80.0             1              0              83.75  28.1   \n",
              "5106  44873  81.0             0              0             125.20  40.0   \n",
              "5107  19723  35.0             0              0              82.99  30.6   \n",
              "5108  37544  51.0             0              0             166.29  25.6   \n",
              "5109  44679  44.0             0              0              85.28  26.2   \n",
              "\n",
              "      stroke  gender_Male  gender_Other  ever_married_Yes  \\\n",
              "0          1         True         False              True   \n",
              "1          1        False         False              True   \n",
              "2          1         True         False              True   \n",
              "3          1        False         False              True   \n",
              "4          1        False         False              True   \n",
              "...      ...          ...           ...               ...   \n",
              "5105       0        False         False              True   \n",
              "5106       0        False         False              True   \n",
              "5107       0        False         False              True   \n",
              "5108       0         True         False              True   \n",
              "5109       0        False         False              True   \n",
              "\n",
              "      work_type_Never_worked  work_type_Private  work_type_Self-employed  \\\n",
              "0                      False               True                    False   \n",
              "1                      False              False                     True   \n",
              "2                      False               True                    False   \n",
              "3                      False               True                    False   \n",
              "4                      False              False                     True   \n",
              "...                      ...                ...                      ...   \n",
              "5105                   False               True                    False   \n",
              "5106                   False              False                     True   \n",
              "5107                   False              False                     True   \n",
              "5108                   False               True                    False   \n",
              "5109                   False              False                    False   \n",
              "\n",
              "      work_type_children  Residence_type_Urban  \\\n",
              "0                  False                  True   \n",
              "1                  False                 False   \n",
              "2                  False                 False   \n",
              "3                  False                  True   \n",
              "4                  False                 False   \n",
              "...                  ...                   ...   \n",
              "5105               False                  True   \n",
              "5106               False                  True   \n",
              "5107               False                 False   \n",
              "5108               False                 False   \n",
              "5109               False                  True   \n",
              "\n",
              "      smoking_status_formerly smoked  smoking_status_never smoked  \\\n",
              "0                               True                        False   \n",
              "1                              False                         True   \n",
              "2                              False                         True   \n",
              "3                              False                        False   \n",
              "4                              False                         True   \n",
              "...                              ...                          ...   \n",
              "5105                           False                         True   \n",
              "5106                           False                         True   \n",
              "5107                           False                         True   \n",
              "5108                            True                        False   \n",
              "5109                           False                        False   \n",
              "\n",
              "      smoking_status_smokes  \n",
              "0                     False  \n",
              "1                     False  \n",
              "2                     False  \n",
              "3                      True  \n",
              "4                     False  \n",
              "...                     ...  \n",
              "5105                  False  \n",
              "5106                  False  \n",
              "5107                  False  \n",
              "5108                  False  \n",
              "5109                  False  \n",
              "\n",
              "[5110 rows x 18 columns]"
            ],
            "text/html": [
              "\n",
              "  <div id=\"df-abbabda6-4e2e-42f3-a92c-9a99eff4bcfb\" class=\"colab-df-container\">\n",
              "    <div>\n",
              "<style scoped>\n",
              "    .dataframe tbody tr th:only-of-type {\n",
              "        vertical-align: middle;\n",
              "    }\n",
              "\n",
              "    .dataframe tbody tr th {\n",
              "        vertical-align: top;\n",
              "    }\n",
              "\n",
              "    .dataframe thead th {\n",
              "        text-align: right;\n",
              "    }\n",
              "</style>\n",
              "<table border=\"1\" class=\"dataframe\">\n",
              "  <thead>\n",
              "    <tr style=\"text-align: right;\">\n",
              "      <th></th>\n",
              "      <th>id</th>\n",
              "      <th>age</th>\n",
              "      <th>hypertension</th>\n",
              "      <th>heart_disease</th>\n",
              "      <th>avg_glucose_level</th>\n",
              "      <th>bmi</th>\n",
              "      <th>stroke</th>\n",
              "      <th>gender_Male</th>\n",
              "      <th>gender_Other</th>\n",
              "      <th>ever_married_Yes</th>\n",
              "      <th>work_type_Never_worked</th>\n",
              "      <th>work_type_Private</th>\n",
              "      <th>work_type_Self-employed</th>\n",
              "      <th>work_type_children</th>\n",
              "      <th>Residence_type_Urban</th>\n",
              "      <th>smoking_status_formerly smoked</th>\n",
              "      <th>smoking_status_never smoked</th>\n",
              "      <th>smoking_status_smokes</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "      <th>0</th>\n",
              "      <td>9046</td>\n",
              "      <td>67.0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>228.69</td>\n",
              "      <td>36.6</td>\n",
              "      <td>1</td>\n",
              "      <td>True</td>\n",
              "      <td>False</td>\n",
              "      <td>True</td>\n",
              "      <td>False</td>\n",
              "      <td>True</td>\n",
              "      <td>False</td>\n",
              "      <td>False</td>\n",
              "      <td>True</td>\n",
              "      <td>True</td>\n",
              "      <td>False</td>\n",
              "      <td>False</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>1</th>\n",
              "      <td>51676</td>\n",
              "      <td>61.0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>202.21</td>\n",
              "      <td>28.1</td>\n",
              "      <td>1</td>\n",
              "      <td>False</td>\n",
              "      <td>False</td>\n",
              "      <td>True</td>\n",
              "      <td>False</td>\n",
              "      <td>False</td>\n",
              "      <td>True</td>\n",
              "      <td>False</td>\n",
              "      <td>False</td>\n",
              "      <td>False</td>\n",
              "      <td>True</td>\n",
              "      <td>False</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>2</th>\n",
              "      <td>31112</td>\n",
              "      <td>80.0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>105.92</td>\n",
              "      <td>32.5</td>\n",
              "      <td>1</td>\n",
              "      <td>True</td>\n",
              "      <td>False</td>\n",
              "      <td>True</td>\n",
              "      <td>False</td>\n",
              "      <td>True</td>\n",
              "      <td>False</td>\n",
              "      <td>False</td>\n",
              "      <td>False</td>\n",
              "      <td>False</td>\n",
              "      <td>True</td>\n",
              "      <td>False</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>3</th>\n",
              "      <td>60182</td>\n",
              "      <td>49.0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>171.23</td>\n",
              "      <td>34.4</td>\n",
              "      <td>1</td>\n",
              "      <td>False</td>\n",
              "      <td>False</td>\n",
              "      <td>True</td>\n",
              "      <td>False</td>\n",
              "      <td>True</td>\n",
              "      <td>False</td>\n",
              "      <td>False</td>\n",
              "      <td>True</td>\n",
              "      <td>False</td>\n",
              "      <td>False</td>\n",
              "      <td>True</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>4</th>\n",
              "      <td>1665</td>\n",
              "      <td>79.0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>174.12</td>\n",
              "      <td>24.0</td>\n",
              "      <td>1</td>\n",
              "      <td>False</td>\n",
              "      <td>False</td>\n",
              "      <td>True</td>\n",
              "      <td>False</td>\n",
              "      <td>False</td>\n",
              "      <td>True</td>\n",
              "      <td>False</td>\n",
              "      <td>False</td>\n",
              "      <td>False</td>\n",
              "      <td>True</td>\n",
              "      <td>False</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>...</th>\n",
              "      <td>...</td>\n",
              "      <td>...</td>\n",
              "      <td>...</td>\n",
              "      <td>...</td>\n",
              "      <td>...</td>\n",
              "      <td>...</td>\n",
              "      <td>...</td>\n",
              "      <td>...</td>\n",
              "      <td>...</td>\n",
              "      <td>...</td>\n",
              "      <td>...</td>\n",
              "      <td>...</td>\n",
              "      <td>...</td>\n",
              "      <td>...</td>\n",
              "      <td>...</td>\n",
              "      <td>...</td>\n",
              "      <td>...</td>\n",
              "      <td>...</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>5105</th>\n",
              "      <td>18234</td>\n",
              "      <td>80.0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>83.75</td>\n",
              "      <td>28.1</td>\n",
              "      <td>0</td>\n",
              "      <td>False</td>\n",
              "      <td>False</td>\n",
              "      <td>True</td>\n",
              "      <td>False</td>\n",
              "      <td>True</td>\n",
              "      <td>False</td>\n",
              "      <td>False</td>\n",
              "      <td>True</td>\n",
              "      <td>False</td>\n",
              "      <td>True</td>\n",
              "      <td>False</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>5106</th>\n",
              "      <td>44873</td>\n",
              "      <td>81.0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>125.20</td>\n",
              "      <td>40.0</td>\n",
              "      <td>0</td>\n",
              "      <td>False</td>\n",
              "      <td>False</td>\n",
              "      <td>True</td>\n",
              "      <td>False</td>\n",
              "      <td>False</td>\n",
              "      <td>True</td>\n",
              "      <td>False</td>\n",
              "      <td>True</td>\n",
              "      <td>False</td>\n",
              "      <td>True</td>\n",
              "      <td>False</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>5107</th>\n",
              "      <td>19723</td>\n",
              "      <td>35.0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>82.99</td>\n",
              "      <td>30.6</td>\n",
              "      <td>0</td>\n",
              "      <td>False</td>\n",
              "      <td>False</td>\n",
              "      <td>True</td>\n",
              "      <td>False</td>\n",
              "      <td>False</td>\n",
              "      <td>True</td>\n",
              "      <td>False</td>\n",
              "      <td>False</td>\n",
              "      <td>False</td>\n",
              "      <td>True</td>\n",
              "      <td>False</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>5108</th>\n",
              "      <td>37544</td>\n",
              "      <td>51.0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>166.29</td>\n",
              "      <td>25.6</td>\n",
              "      <td>0</td>\n",
              "      <td>True</td>\n",
              "      <td>False</td>\n",
              "      <td>True</td>\n",
              "      <td>False</td>\n",
              "      <td>True</td>\n",
              "      <td>False</td>\n",
              "      <td>False</td>\n",
              "      <td>False</td>\n",
              "      <td>True</td>\n",
              "      <td>False</td>\n",
              "      <td>False</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>5109</th>\n",
              "      <td>44679</td>\n",
              "      <td>44.0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>85.28</td>\n",
              "      <td>26.2</td>\n",
              "      <td>0</td>\n",
              "      <td>False</td>\n",
              "      <td>False</td>\n",
              "      <td>True</td>\n",
              "      <td>False</td>\n",
              "      <td>False</td>\n",
              "      <td>False</td>\n",
              "      <td>False</td>\n",
              "      <td>True</td>\n",
              "      <td>False</td>\n",
              "      <td>False</td>\n",
              "      <td>False</td>\n",
              "    </tr>\n",
              "  </tbody>\n",
              "</table>\n",
              "<p>5110 rows × 18 columns</p>\n",
              "</div>\n",
              "    <div class=\"colab-df-buttons\">\n",
              "\n",
              "  <div class=\"colab-df-container\">\n",
              "    <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-abbabda6-4e2e-42f3-a92c-9a99eff4bcfb')\"\n",
              "            title=\"Convert this dataframe to an interactive table.\"\n",
              "            style=\"display:none;\">\n",
              "\n",
              "  <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
              "    <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
              "  </svg>\n",
              "    </button>\n",
              "\n",
              "  <style>\n",
              "    .colab-df-container {\n",
              "      display:flex;\n",
              "      gap: 12px;\n",
              "    }\n",
              "\n",
              "    .colab-df-convert {\n",
              "      background-color: #E8F0FE;\n",
              "      border: none;\n",
              "      border-radius: 50%;\n",
              "      cursor: pointer;\n",
              "      display: none;\n",
              "      fill: #1967D2;\n",
              "      height: 32px;\n",
              "      padding: 0 0 0 0;\n",
              "      width: 32px;\n",
              "    }\n",
              "\n",
              "    .colab-df-convert:hover {\n",
              "      background-color: #E2EBFA;\n",
              "      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
              "      fill: #174EA6;\n",
              "    }\n",
              "\n",
              "    .colab-df-buttons div {\n",
              "      margin-bottom: 4px;\n",
              "    }\n",
              "\n",
              "    [theme=dark] .colab-df-convert {\n",
              "      background-color: #3B4455;\n",
              "      fill: #D2E3FC;\n",
              "    }\n",
              "\n",
              "    [theme=dark] .colab-df-convert:hover {\n",
              "      background-color: #434B5C;\n",
              "      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
              "      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
              "      fill: #FFFFFF;\n",
              "    }\n",
              "  </style>\n",
              "\n",
              "    <script>\n",
              "      const buttonEl =\n",
              "        document.querySelector('#df-abbabda6-4e2e-42f3-a92c-9a99eff4bcfb button.colab-df-convert');\n",
              "      buttonEl.style.display =\n",
              "        google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
              "\n",
              "      async function convertToInteractive(key) {\n",
              "        const element = document.querySelector('#df-abbabda6-4e2e-42f3-a92c-9a99eff4bcfb');\n",
              "        const dataTable =\n",
              "          await google.colab.kernel.invokeFunction('convertToInteractive',\n",
              "                                                    [key], {});\n",
              "        if (!dataTable) return;\n",
              "\n",
              "        const docLinkHtml = 'Like what you see? Visit the ' +\n",
              "          '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
              "          + ' to learn more about interactive tables.';\n",
              "        element.innerHTML = '';\n",
              "        dataTable['output_type'] = 'display_data';\n",
              "        await google.colab.output.renderOutput(dataTable, element);\n",
              "        const docLink = document.createElement('div');\n",
              "        docLink.innerHTML = docLinkHtml;\n",
              "        element.appendChild(docLink);\n",
              "      }\n",
              "    </script>\n",
              "  </div>\n",
              "\n",
              "\n",
              "<div id=\"df-9af600d1-57d0-4eeb-abb6-b50cda13789d\">\n",
              "  <button class=\"colab-df-quickchart\" onclick=\"quickchart('df-9af600d1-57d0-4eeb-abb6-b50cda13789d')\"\n",
              "            title=\"Suggest charts\"\n",
              "            style=\"display:none;\">\n",
              "\n",
              "<svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\"viewBox=\"0 0 24 24\"\n",
              "     width=\"24px\">\n",
              "    <g>\n",
              "        <path d=\"M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z\"/>\n",
              "    </g>\n",
              "</svg>\n",
              "  </button>\n",
              "\n",
              "<style>\n",
              "  .colab-df-quickchart {\n",
              "      --bg-color: #E8F0FE;\n",
              "      --fill-color: #1967D2;\n",
              "      --hover-bg-color: #E2EBFA;\n",
              "      --hover-fill-color: #174EA6;\n",
              "      --disabled-fill-color: #AAA;\n",
              "      --disabled-bg-color: #DDD;\n",
              "  }\n",
              "\n",
              "  [theme=dark] .colab-df-quickchart {\n",
              "      --bg-color: #3B4455;\n",
              "      --fill-color: #D2E3FC;\n",
              "      --hover-bg-color: #434B5C;\n",
              "      --hover-fill-color: #FFFFFF;\n",
              "      --disabled-bg-color: #3B4455;\n",
              "      --disabled-fill-color: #666;\n",
              "  }\n",
              "\n",
              "  .colab-df-quickchart {\n",
              "    background-color: var(--bg-color);\n",
              "    border: none;\n",
              "    border-radius: 50%;\n",
              "    cursor: pointer;\n",
              "    display: none;\n",
              "    fill: var(--fill-color);\n",
              "    height: 32px;\n",
              "    padding: 0;\n",
              "    width: 32px;\n",
              "  }\n",
              "\n",
              "  .colab-df-quickchart:hover {\n",
              "    background-color: var(--hover-bg-color);\n",
              "    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
              "    fill: var(--button-hover-fill-color);\n",
              "  }\n",
              "\n",
              "  .colab-df-quickchart-complete:disabled,\n",
              "  .colab-df-quickchart-complete:disabled:hover {\n",
              "    background-color: var(--disabled-bg-color);\n",
              "    fill: var(--disabled-fill-color);\n",
              "    box-shadow: none;\n",
              "  }\n",
              "\n",
              "  .colab-df-spinner {\n",
              "    border: 2px solid var(--fill-color);\n",
              "    border-color: transparent;\n",
              "    border-bottom-color: var(--fill-color);\n",
              "    animation:\n",
              "      spin 1s steps(1) infinite;\n",
              "  }\n",
              "\n",
              "  @keyframes spin {\n",
              "    0% {\n",
              "      border-color: transparent;\n",
              "      border-bottom-color: var(--fill-color);\n",
              "      border-left-color: var(--fill-color);\n",
              "    }\n",
              "    20% {\n",
              "      border-color: transparent;\n",
              "      border-left-color: var(--fill-color);\n",
              "      border-top-color: var(--fill-color);\n",
              "    }\n",
              "    30% {\n",
              "      border-color: transparent;\n",
              "      border-left-color: var(--fill-color);\n",
              "      border-top-color: var(--fill-color);\n",
              "      border-right-color: var(--fill-color);\n",
              "    }\n",
              "    40% {\n",
              "      border-color: transparent;\n",
              "      border-right-color: var(--fill-color);\n",
              "      border-top-color: var(--fill-color);\n",
              "    }\n",
              "    60% {\n",
              "      border-color: transparent;\n",
              "      border-right-color: var(--fill-color);\n",
              "    }\n",
              "    80% {\n",
              "      border-color: transparent;\n",
              "      border-right-color: var(--fill-color);\n",
              "      border-bottom-color: var(--fill-color);\n",
              "    }\n",
              "    90% {\n",
              "      border-color: transparent;\n",
              "      border-bottom-color: var(--fill-color);\n",
              "    }\n",
              "  }\n",
              "</style>\n",
              "\n",
              "  <script>\n",
              "    async function quickchart(key) {\n",
              "      const quickchartButtonEl =\n",
              "        document.querySelector('#' + key + ' button');\n",
              "      quickchartButtonEl.disabled = true;  // To prevent multiple clicks.\n",
              "      quickchartButtonEl.classList.add('colab-df-spinner');\n",
              "      try {\n",
              "        const charts = await google.colab.kernel.invokeFunction(\n",
              "            'suggestCharts', [key], {});\n",
              "      } catch (error) {\n",
              "        console.error('Error during call to suggestCharts:', error);\n",
              "      }\n",
              "      quickchartButtonEl.classList.remove('colab-df-spinner');\n",
              "      quickchartButtonEl.classList.add('colab-df-quickchart-complete');\n",
              "    }\n",
              "    (() => {\n",
              "      let quickchartButtonEl =\n",
              "        document.querySelector('#df-9af600d1-57d0-4eeb-abb6-b50cda13789d button');\n",
              "      quickchartButtonEl.style.display =\n",
              "        google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
              "    })();\n",
              "  </script>\n",
              "</div>\n",
              "\n",
              "  <div id=\"id_b4367cdf-699b-43ef-8754-aa096c031b3d\">\n",
              "    <style>\n",
              "      .colab-df-generate {\n",
              "        background-color: #E8F0FE;\n",
              "        border: none;\n",
              "        border-radius: 50%;\n",
              "        cursor: pointer;\n",
              "        display: none;\n",
              "        fill: #1967D2;\n",
              "        height: 32px;\n",
              "        padding: 0 0 0 0;\n",
              "        width: 32px;\n",
              "      }\n",
              "\n",
              "      .colab-df-generate:hover {\n",
              "        background-color: #E2EBFA;\n",
              "        box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
              "        fill: #174EA6;\n",
              "      }\n",
              "\n",
              "      [theme=dark] .colab-df-generate {\n",
              "        background-color: #3B4455;\n",
              "        fill: #D2E3FC;\n",
              "      }\n",
              "\n",
              "      [theme=dark] .colab-df-generate:hover {\n",
              "        background-color: #434B5C;\n",
              "        box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
              "        filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
              "        fill: #FFFFFF;\n",
              "      }\n",
              "    </style>\n",
              "    <button class=\"colab-df-generate\" onclick=\"generateWithVariable('df')\"\n",
              "            title=\"Generate code using this dataframe.\"\n",
              "            style=\"display:none;\">\n",
              "\n",
              "  <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\"viewBox=\"0 0 24 24\"\n",
              "       width=\"24px\">\n",
              "    <path d=\"M7,19H8.4L18.45,9,17,7.55,7,17.6ZM5,21V16.75L18.45,3.32a2,2,0,0,1,2.83,0l1.4,1.43a1.91,1.91,0,0,1,.58,1.4,1.91,1.91,0,0,1-.58,1.4L9.25,21ZM18.45,9,17,7.55Zm-12,3A5.31,5.31,0,0,0,4.9,8.1,5.31,5.31,0,0,0,1,6.5,5.31,5.31,0,0,0,4.9,4.9,5.31,5.31,0,0,0,6.5,1,5.31,5.31,0,0,0,8.1,4.9,5.31,5.31,0,0,0,12,6.5,5.46,5.46,0,0,0,6.5,12Z\"/>\n",
              "  </svg>\n",
              "    </button>\n",
              "    <script>\n",
              "      (() => {\n",
              "      const buttonEl =\n",
              "        document.querySelector('#id_b4367cdf-699b-43ef-8754-aa096c031b3d button.colab-df-generate');\n",
              "      buttonEl.style.display =\n",
              "        google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
              "\n",
              "      buttonEl.onclick = () => {\n",
              "        google.colab.notebook.generateWithVariable('df');\n",
              "      }\n",
              "      })();\n",
              "    </script>\n",
              "  </div>\n",
              "\n",
              "    </div>\n",
              "  </div>\n"
            ],
            "application/vnd.google.colaboratory.intrinsic+json": {
              "type": "dataframe",
              "variable_name": "df",
              "summary": "{\n  \"name\": \"df\",\n  \"rows\": 5110,\n  \"fields\": [\n    {\n      \"column\": \"id\",\n      \"properties\": {\n        \"dtype\": \"number\",\n        \"std\": 21161,\n        \"min\": 67,\n        \"max\": 72940,\n        \"num_unique_values\": 5110,\n        \"samples\": [\n          40041,\n          55244,\n          70992\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"age\",\n      \"properties\": {\n        \"dtype\": \"number\",\n        \"std\": 22.61264672311352,\n        \"min\": 0.08,\n        \"max\": 82.0,\n        \"num_unique_values\": 104,\n        \"samples\": [\n          45.0,\n          24.0,\n          33.0\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"hypertension\",\n      \"properties\": {\n        \"dtype\": \"number\",\n        \"std\": 0,\n        \"min\": 0,\n        \"max\": 1,\n        \"num_unique_values\": 2,\n        \"samples\": [\n          1,\n          0\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"heart_disease\",\n      \"properties\": {\n        \"dtype\": \"number\",\n        \"std\": 0,\n        \"min\": 0,\n        \"max\": 1,\n        \"num_unique_values\": 2,\n        \"samples\": [\n          0,\n          1\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"avg_glucose_level\",\n      \"properties\": {\n        \"dtype\": \"number\",\n        \"std\": 45.28356015058203,\n        \"min\": 55.12,\n        \"max\": 271.74,\n        \"num_unique_values\": 3979,\n        \"samples\": [\n          178.29,\n          156.69\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"bmi\",\n      \"properties\": {\n        \"dtype\": \"number\",\n        \"std\": 7.699562318787533,\n        \"min\": 10.3,\n        \"max\": 97.6,\n        \"num_unique_values\": 418,\n        \"samples\": [\n          49.5,\n          18.5\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"stroke\",\n      \"properties\": {\n        \"dtype\": \"number\",\n        \"std\": 0,\n        \"min\": 0,\n        \"max\": 1,\n        \"num_unique_values\": 2,\n        \"samples\": [\n          0,\n          1\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"gender_Male\",\n      \"properties\": {\n        \"dtype\": \"boolean\",\n        \"num_unique_values\": 2,\n        \"samples\": [\n          false,\n          true\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"gender_Other\",\n      \"properties\": {\n        \"dtype\": \"boolean\",\n        \"num_unique_values\": 2,\n        \"samples\": [\n          true,\n          false\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"ever_married_Yes\",\n      \"properties\": {\n        \"dtype\": \"boolean\",\n        \"num_unique_values\": 2,\n        \"samples\": [\n          false,\n          true\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"work_type_Never_worked\",\n      \"properties\": {\n        \"dtype\": \"boolean\",\n        \"num_unique_values\": 2,\n        \"samples\": [\n          true,\n          false\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"work_type_Private\",\n      \"properties\": {\n        \"dtype\": \"boolean\",\n        \"num_unique_values\": 2,\n        \"samples\": [\n          false,\n          true\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"work_type_Self-employed\",\n      \"properties\": {\n        \"dtype\": \"boolean\",\n        \"num_unique_values\": 2,\n        \"samples\": [\n          true,\n          false\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"work_type_children\",\n      \"properties\": {\n        \"dtype\": \"boolean\",\n        \"num_unique_values\": 2,\n        \"samples\": [\n          true,\n          false\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"Residence_type_Urban\",\n      \"properties\": {\n        \"dtype\": \"boolean\",\n        \"num_unique_values\": 2,\n        \"samples\": [\n          false,\n          true\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"smoking_status_formerly smoked\",\n      \"properties\": {\n        \"dtype\": \"boolean\",\n        \"num_unique_values\": 2,\n        \"samples\": [\n          false,\n          true\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"smoking_status_never smoked\",\n      \"properties\": {\n        \"dtype\": \"boolean\",\n        \"num_unique_values\": 2,\n        \"samples\": [\n          true,\n          false\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"smoking_status_smokes\",\n      \"properties\": {\n        \"dtype\": \"boolean\",\n        \"num_unique_values\": 2,\n        \"samples\": [\n          true,\n          false\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    }\n  ]\n}"
            }
          },
          "metadata": {},
          "execution_count": 36
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Impute missing numerical values (e.g., BMI) with the median\n",
        "numerical_features = ['age', 'avg_glucose_level', 'bmi']\n",
        "imputer = SimpleImputer(strategy='median')\n",
        "df[numerical_features] = imputer.fit_transform(df[numerical_features])"
      ],
      "metadata": {
        "id": "xSZrnD8-_aeM"
      },
      "execution_count": 5,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Fill missing categorical values (if any) with the most frequent value\n",
        "categorical_features = ['smoking_status']\n",
        "imputer_cat = SimpleImputer(strategy='most_frequent')\n",
        "df[categorical_features] = imputer_cat.fit_transform(df[categorical_features])"
      ],
      "metadata": {
        "id": "6AWcGOHV_efU"
      },
      "execution_count": 6,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Confirm no missing values\n",
        "print(\"\\nMissing values after imputation:\")\n",
        "print(df.isnull().sum())"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "VgIVpFDz_g4H",
        "outputId": "0aec95d0-98ee-4247-e9e4-bbc695ca4a0b"
      },
      "execution_count": 7,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "Missing values after imputation:\n",
            "id                   0\n",
            "gender               0\n",
            "age                  0\n",
            "hypertension         0\n",
            "heart_disease        0\n",
            "ever_married         0\n",
            "work_type            0\n",
            "Residence_type       0\n",
            "avg_glucose_level    0\n",
            "bmi                  0\n",
            "smoking_status       0\n",
            "stroke               0\n",
            "dtype: int64\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Encode categorical variables\n",
        "df = pd.get_dummies(df, columns=['gender', 'ever_married', 'work_type', 'Residence_type', 'smoking_status'], drop_first=True)"
      ],
      "metadata": {
        "id": "LU5X4scl_lOG"
      },
      "execution_count": 8,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Separate features and target\n",
        "X = df.drop(columns=['id', 'stroke'])\n",
        "y = df['stroke']\n",
        "\n",
        "# Split the data into training and testing sets\n",
        "from sklearn.model_selection import train_test_split\n",
        "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # Adjust test_size and random_state as needed\n",
        "\n",
        "# Scale the features\n",
        "scaler = StandardScaler()\n",
        "X_train = scaler.fit_transform(X_train)\n",
        "X_test = scaler.transform(X_test)"
      ],
      "metadata": {
        "id": "LQzJyx8QAKYd"
      },
      "execution_count": 11,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Step 2: Apply machine learning models with grid search optimization\n",
        "print(\"\\nApplying Machine Learning Models with Grid Search...\")\n",
        "rf = RandomForestClassifier(random_state=42)\n",
        "param_grid_rf = {\n",
        "    'n_estimators': [100, 200, 300],\n",
        "    'max_depth': [None, 10, 20],\n",
        "    'min_samples_split': [2, 5, 10]\n",
        "}\n",
        "grid_search_rf = GridSearchCV(rf, param_grid_rf, cv=5, scoring='accuracy', n_jobs=-1)\n",
        "grid_search_rf.fit(X_train, y_train)\n",
        "\n",
        "best_rf = grid_search_rf.best_estimator_\n",
        "print(f\"Best Random Forest Parameters: {grid_search_rf.best_params_}\")\n",
        "\n",
        "# Evaluate the model\n",
        "y_pred_rf = best_rf.predict(X_test)\n",
        "print(\"\\nRandom Forest Classification Report:\")\n",
        "print(classification_report(y_test, y_pred_rf))\n",
        "\n",
        "\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "fCLuMHSUAXIU",
        "outputId": "dbb5359e-cfcb-4dae-b0ed-ebf2c0b90f02"
      },
      "execution_count": 15,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "Applying Machine Learning Models with Grid Search...\n",
            "Best Random Forest Parameters: {'max_depth': None, 'min_samples_split': 2, 'n_estimators': 100}\n",
            "\n",
            "Random Forest Classification Report:\n",
            "              precision    recall  f1-score   support\n",
            "\n",
            "           0       0.94      1.00      0.97       960\n",
            "           1       0.00      0.00      0.00        62\n",
            "\n",
            "    accuracy                           0.94      1022\n",
            "   macro avg       0.47      0.50      0.48      1022\n",
            "weighted avg       0.88      0.94      0.91      1022\n",
            "\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "/usr/local/lib/python3.10/dist-packages/sklearn/metrics/_classification.py:1531: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.\n",
            "  _warn_prf(average, modifier, f\"{metric.capitalize()} is\", len(result))\n",
            "/usr/local/lib/python3.10/dist-packages/sklearn/metrics/_classification.py:1531: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.\n",
            "  _warn_prf(average, modifier, f\"{metric.capitalize()} is\", len(result))\n",
            "/usr/local/lib/python3.10/dist-packages/sklearn/metrics/_classification.py:1531: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.\n",
            "  _warn_prf(average, modifier, f\"{metric.capitalize()} is\", len(result))\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Apply XGBoost model\n",
        "xgb = XGBClassifier(random_state=42, use_label_encoder=False, eval_metric='logloss')\n",
        "param_grid_xgb = {\n",
        "    'n_estimators': [100, 200],\n",
        "    'max_depth': [3, 6, 10],\n",
        "    'learning_rate': [0.01, 0.1, 0.2]\n",
        "}\n",
        "grid_search_xgb = GridSearchCV(xgb, param_grid_xgb, cv=5, scoring='accuracy', n_jobs=-1)\n",
        "grid_search_xgb.fit(X_train, y_train)\n",
        "\n",
        "best_xgb = grid_search_xgb.best_estimator_\n",
        "print(f\"Best XGBoost Parameters: {grid_search_xgb.best_params_}\")\n",
        "\n",
        "# Evaluate the model\n",
        "y_pred_xgb = best_xgb.predict(X_test)\n",
        "print(\"\\nXGBoost Classification Report:\")\n",
        "print(classification_report(y_test, y_pred_xgb))"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "SYBZFDYBBxE2",
        "outputId": "4b60d783-a892-4323-8594-8462032d8929"
      },
      "execution_count": 16,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Best XGBoost Parameters: {'learning_rate': 0.01, 'max_depth': 3, 'n_estimators': 100}\n",
            "\n",
            "XGBoost Classification Report:\n",
            "              precision    recall  f1-score   support\n",
            "\n",
            "           0       0.94      1.00      0.97       960\n",
            "           1       0.00      0.00      0.00        62\n",
            "\n",
            "    accuracy                           0.94      1022\n",
            "   macro avg       0.47      0.50      0.48      1022\n",
            "weighted avg       0.88      0.94      0.91      1022\n",
            "\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "/usr/local/lib/python3.10/dist-packages/xgboost/core.py:158: UserWarning: [12:40:12] WARNING: /workspace/src/learner.cc:740: \n",
            "Parameters: { \"use_label_encoder\" } are not used.\n",
            "\n",
            "  warnings.warn(smsg, UserWarning)\n",
            "/usr/local/lib/python3.10/dist-packages/sklearn/metrics/_classification.py:1531: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.\n",
            "  _warn_prf(average, modifier, f\"{metric.capitalize()} is\", len(result))\n",
            "/usr/local/lib/python3.10/dist-packages/sklearn/metrics/_classification.py:1531: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.\n",
            "  _warn_prf(average, modifier, f\"{metric.capitalize()} is\", len(result))\n",
            "/usr/local/lib/python3.10/dist-packages/sklearn/metrics/_classification.py:1531: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.\n",
            "  _warn_prf(average, modifier, f\"{metric.capitalize()} is\", len(result))\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "\n",
        "# Step 3: Feature Selection\n",
        "selector_kbest = SelectKBest(score_func=f_classif, k=10)\n",
        "X_new_kbest = selector_kbest.fit_transform(X, y)\n",
        "selected_features_kbest = X.columns[selector_kbest.get_support()]\n",
        "print(f\"Selected Features using SelectKBest: {list(selected_features_kbest)}\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "vK3_b9HADPwr",
        "outputId": "fc649610-9f1f-425e-9c77-cd771a1849be"
      },
      "execution_count": 26,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Selected Features using SelectKBest: ['age', 'hypertension', 'heart_disease', 'avg_glucose_level', 'bmi', 'ever_married_Yes', 'work_type_Self-employed', 'work_type_children', 'Residence_type_Urban', 'smoking_status_formerly smoked']\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Method 2: Recursive Feature Elimination (RFE) with Random Forest\n",
        "rfe = RFE(estimator=RandomForestClassifier(random_state=42), n_features_to_select=10)\n",
        "rfe.fit(X, y)\n",
        "selected_features_rfe = X.columns[rfe.support_]\n",
        "print(f\"Selected Features using RFE: {list(selected_features_rfe)}\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "EXTQA3DrDWBW",
        "outputId": "ae19d2a5-9e6c-4963-9902-b091c21fb783"
      },
      "execution_count": 27,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Selected Features using RFE: ['age', 'hypertension', 'heart_disease', 'avg_glucose_level', 'bmi', 'gender_Male', 'work_type_Private', 'Residence_type_Urban', 'smoking_status_formerly smoked', 'smoking_status_never smoked']\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Step 4: Apply models to selected features and evaluate\n",
        "print(\"\\nApplying Models to Selected Features...\")\n",
        "# Train-test split for SelectKBest features\n",
        "X_kbest_train, X_kbest_test, y_kbest_train, y_kbest_test = train_test_split(\n",
        "    X[selected_features_kbest], y, test_size=0.3, random_state=42, stratify=y)\n",
        "\n",
        "\n",
        "\n",
        "# Train-test split for RFE features\n",
        "X_rfe_train, X_rfe_test, y_rfe_train, y_rfe_test = train_test_split(\n",
        "    X[selected_features_rfe], y, test_size=0.3, random_state=42, stratify=y)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "cUBJwzXrDaLX",
        "outputId": "7e57008b-9722-48c8-e784-6ab7b84a17a7"
      },
      "execution_count": 29,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "Applying Models to Selected Features...\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Random Forest on SelectKBest features\n",
        "best_rf.fit(X_kbest_train, y_kbest_train)\n",
        "y_kbest_pred_rf = best_rf.predict(X_kbest_test)\n",
        "print(\"\\nRandom Forest on SelectKBest Features:\")\n",
        "print(classification_report(y_kbest_test, y_kbest_pred_rf))"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "5rew-ab0EumC",
        "outputId": "d94b5e14-ee49-48fd-9bd1-a4c36d00591c"
      },
      "execution_count": 30,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "Random Forest on SelectKBest Features:\n",
            "              precision    recall  f1-score   support\n",
            "\n",
            "           0       0.95      1.00      0.97      1458\n",
            "           1       0.00      0.00      0.00        75\n",
            "\n",
            "    accuracy                           0.95      1533\n",
            "   macro avg       0.48      0.50      0.49      1533\n",
            "weighted avg       0.90      0.95      0.93      1533\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Random Forest on RFE features\n",
        "best_rf.fit(X_rfe_train, y_rfe_train)\n",
        "y_rfe_pred_rf = best_rf.predict(X_rfe_test)\n",
        "print(\"\\nRandom Forest on RFE Features:\")\n",
        "print(classification_report(y_rfe_test, y_rfe_pred_rf))"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "idXO1_NWE3lB",
        "outputId": "c3500011-74ce-43f9-fb96-6a2538ed3f19"
      },
      "execution_count": 31,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "Random Forest on RFE Features:\n",
            "              precision    recall  f1-score   support\n",
            "\n",
            "           0       0.95      1.00      0.97      1458\n",
            "           1       0.00      0.00      0.00        75\n",
            "\n",
            "    accuracy                           0.95      1533\n",
            "   macro avg       0.48      0.50      0.49      1533\n",
            "weighted avg       0.90      0.95      0.93      1533\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# XGBoost on SelectKBest features\n",
        "best_xgb.fit(X_kbest_train, y_kbest_train)\n",
        "y_kbest_pred_xgb = best_xgb.predict(X_kbest_test)\n",
        "print(\"\\nXGBoost on SelectKBest Features:\")\n",
        "print(classification_report(y_kbest_test, y_kbest_pred_xgb))"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "T5R43QdDE5cB",
        "outputId": "9f80f155-2cef-45fc-eede-82e6d59e9fb2"
      },
      "execution_count": 32,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "/usr/local/lib/python3.10/dist-packages/xgboost/core.py:158: UserWarning: [12:52:39] WARNING: /workspace/src/learner.cc:740: \n",
            "Parameters: { \"use_label_encoder\" } are not used.\n",
            "\n",
            "  warnings.warn(smsg, UserWarning)\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "XGBoost on SelectKBest Features:\n",
            "              precision    recall  f1-score   support\n",
            "\n",
            "           0       0.95      1.00      0.97      1458\n",
            "           1       0.00      0.00      0.00        75\n",
            "\n",
            "    accuracy                           0.95      1533\n",
            "   macro avg       0.48      0.50      0.49      1533\n",
            "weighted avg       0.90      0.95      0.93      1533\n",
            "\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "/usr/local/lib/python3.10/dist-packages/sklearn/metrics/_classification.py:1531: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.\n",
            "  _warn_prf(average, modifier, f\"{metric.capitalize()} is\", len(result))\n",
            "/usr/local/lib/python3.10/dist-packages/sklearn/metrics/_classification.py:1531: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.\n",
            "  _warn_prf(average, modifier, f\"{metric.capitalize()} is\", len(result))\n",
            "/usr/local/lib/python3.10/dist-packages/sklearn/metrics/_classification.py:1531: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.\n",
            "  _warn_prf(average, modifier, f\"{metric.capitalize()} is\", len(result))\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# XGBoost on RFE features\n",
        "best_xgb.fit(X_rfe_train, y_rfe_train)\n",
        "y_rfe_pred_xgb = best_xgb.predict(X_rfe_test)\n",
        "print(\"\\nXGBoost on RFE Features:\")\n",
        "print(classification_report(y_rfe_test, y_rfe_pred_xgb))"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "i_3KsbaQFD2U",
        "outputId": "4a11bab6-8206-44c7-b9f0-b89d52e42d11"
      },
      "execution_count": 33,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "/usr/local/lib/python3.10/dist-packages/xgboost/core.py:158: UserWarning: [12:53:04] WARNING: /workspace/src/learner.cc:740: \n",
            "Parameters: { \"use_label_encoder\" } are not used.\n",
            "\n",
            "  warnings.warn(smsg, UserWarning)\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "XGBoost on RFE Features:\n",
            "              precision    recall  f1-score   support\n",
            "\n",
            "           0       0.95      1.00      0.97      1458\n",
            "           1       0.00      0.00      0.00        75\n",
            "\n",
            "    accuracy                           0.95      1533\n",
            "   macro avg       0.48      0.50      0.49      1533\n",
            "weighted avg       0.90      0.95      0.93      1533\n",
            "\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "/usr/local/lib/python3.10/dist-packages/sklearn/metrics/_classification.py:1531: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.\n",
            "  _warn_prf(average, modifier, f\"{metric.capitalize()} is\", len(result))\n",
            "/usr/local/lib/python3.10/dist-packages/sklearn/metrics/_classification.py:1531: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.\n",
            "  _warn_prf(average, modifier, f\"{metric.capitalize()} is\", len(result))\n",
            "/usr/local/lib/python3.10/dist-packages/sklearn/metrics/_classification.py:1531: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.\n",
            "  _warn_prf(average, modifier, f\"{metric.capitalize()} is\", len(result))\n"
          ]
        }
      ]
    }
  ]
}