{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 34: Practice\n",
    "\n",
    "Asiman Data School, Module 3: Comprehensive Machine Learning. Week 17, Thursday.\n",
    "\n",
    "Twelve problems in three levels, on the same ideas and at the same level as the lesson notebook. They are numbered 5 to 16, as on the lesson page, where Problems 1 to 4 are solved by hand.\n",
    "\n",
    "How to work\n",
    "\n",
    "- Write your code in the cell under each problem and run it with Shift + Enter. Print exactly what the problem asks for.\n",
    "- Problem 16 also draws a chart. It appears under the cell when you run it; run the solution to see the chart it draws.\n",
    "- A hint and one possible solution are under each problem. Open them only after you have tried.\n",
    "- The problems are the steps of one project: every cell uses what the cells above it created, so work from top to bottom.\n",
    "- The file heart_disease.csv must be in the same folder as this notebook. On the Asiman Data School website it is already there.\n",
    "\n",
    "Tip: Only what your code prints is compared with the expected output, so any code that prints the same text is right. Use the names the steps give (`df`, `X`, `y`, `X_train`, `X_test`, `numbers`, `categories`, `gauss`, `encoder`, `codes_train`, `codes_test`, `cat_nb`): the later steps run after your own answers to the earlier ones, so solve them in order. The last step also draws a chart: it is accepted when the number is right and a chart was drawn."
   ],
   "id": "t34p-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Steps 5 to 8: from the raw file to the split"
   ],
   "id": "t34p-001"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 5. Read the raw file\n",
    "\n",
    "Read `heart_disease.csv` into `df`. Print the shape, then the number of patients with the disease."
   ],
   "id": "t34p-002"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t34p-003"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`df = pd.read_csv(\"heart_disease.csv\")`, then `print(df.shape)` and `print(df[\"disease\"].sum())`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"heart_disease.csv\")\n",
    "\n",
    "print(df.shape)\n",
    "print(df[\"disease\"].sum())\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "(920, 15)\n",
    "509\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t34p-004"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 6. Copies and impossible zeros\n",
    "\n",
    "Drop the repeated rows and turn the zeros of `cholesterol` and `resting_bp` into `NaN`. Print the number of gaps in `cholesterol`. This step continues from Step 5."
   ],
   "id": "t34p-005"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t34p-006"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`df = df.drop_duplicates()`, then `df.loc[df[\"cholesterol\"] == 0, \"cholesterol\"] = np.nan`, the same for `resting_bp`, then `df[\"cholesterol\"].isna().sum()`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "import numpy as np\n",
    "\n",
    "df = df.drop_duplicates()\n",
    "df.loc[df[\"cholesterol\"] == 0, \"cholesterol\"] = np.nan\n",
    "df.loc[df[\"resting_bp\"] == 0, \"resting_bp\"] = np.nan\n",
    "\n",
    "print(df[\"cholesterol\"].isna().sum())\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "201\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t34p-007"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 7. Drop three columns\n",
    "\n",
    "Drop the columns `major_vessels`, `thal` and `hospital`. Print the number of columns."
   ],
   "id": "t34p-008"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t34p-009"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`df = df.drop(columns=[\"major_vessels\", \"thal\", \"hospital\"])`, then `len(df.columns)`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "df = df.drop(columns=[\"major_vessels\", \"thal\", \"hospital\"])\n",
    "\n",
    "print(len(df.columns))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "12\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t34p-010"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 8. Split\n",
    "\n",
    "Make `X` (all columns without `disease`) and `y`. Split them with `test_size=0.3` and `random_state=1`. Print the number of test patients, then how many of them have the disease."
   ],
   "id": "t34p-011"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t34p-012"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)`, then `len(y_test)` and `y_test.sum()`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "X = df.drop(columns=[\"disease\"])\n",
    "y = df[\"disease\"]\n",
    "\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)\n",
    "\n",
    "print(len(y_test))\n",
    "print(y_test.sum())\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "276\n",
    "151\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t34p-013"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Steps 9 to 12: the gaps and two models"
   ],
   "id": "t34p-014"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 9. Fill the gaps\n",
    "\n",
    "Fill the columns of `numbers` with the training medians and the columns of `categories` with `\"unknown\"`, in both parts. Print the median cholesterol of the training data."
   ],
   "id": "t34p-015"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [\"age\", \"resting_bp\", \"cholesterol\", \"max_heart_rate\", \"st_depression\"]\n",
    "categories = [\"sex\", \"chest_pain\", \"fasting_sugar_high\", \"rest_ecg\", \"exercise_angina\", \"st_slope\"]\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t34p-016"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`medians = X_train[numbers].median()`, `fillna(medians)` on both parts, `fillna(\"unknown\")` for the categories, then `medians[\"cholesterol\"]`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "numbers = [\"age\", \"resting_bp\", \"cholesterol\", \"max_heart_rate\", \"st_depression\"]\n",
    "categories = [\"sex\", \"chest_pain\", \"fasting_sugar_high\", \"rest_ecg\", \"exercise_angina\", \"st_slope\"]\n",
    "\n",
    "medians = X_train[numbers].median()\n",
    "X_train[numbers] = X_train[numbers].fillna(medians)\n",
    "X_test[numbers] = X_test[numbers].fillna(medians)\n",
    "\n",
    "X_train[categories] = X_train[categories].fillna(\"unknown\")\n",
    "X_test[categories] = X_test[categories].fillna(\"unknown\")\n",
    "\n",
    "print(medians[\"cholesterol\"])\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "239.0\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t34p-017"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 10. Gaussian Naive Bayes\n",
    "\n",
    "Train a `GaussianNB` called `gauss` on the five numbers. Print its test accuracy, rounded to 4 decimals."
   ],
   "id": "t34p-018"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.naive_bayes import GaussianNB\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t34p-019"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`gauss = GaussianNB()`, `gauss.fit(X_train[numbers], y_train)`, then `gauss.score(X_test[numbers], y_test)`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "from sklearn.naive_bayes import GaussianNB\n",
    "\n",
    "gauss = GaussianNB()\n",
    "gauss.fit(X_train[numbers], y_train)\n",
    "\n",
    "print(round(gauss.score(X_test[numbers], y_test), 4))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.6884\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t34p-020"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 11. The class means\n",
    "\n",
    "Print the mean maximum heart rate of each class that `gauss` learned (the fourth column of `theta_`), rounded with `.round(1)`."
   ],
   "id": "t34p-021"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t34p-022"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`gauss.theta_[:, 3]` is the fourth column, one value per class.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "print(gauss.theta_[:, 3].round(1))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "[149.  128.4]\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t34p-023"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 12. Codes and Categorical Naive Bayes\n",
    "\n",
    "Fit an `OrdinalEncoder` called `encoder` on the training categories (with `.astype(str)`) and code both parts into `codes_train` and `codes_test`. Train a `CategoricalNB` called `cat_nb` on them and print its test accuracy, rounded to 4 decimals."
   ],
   "id": "t34p-024"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import OrdinalEncoder\n",
    "from sklearn.naive_bayes import CategoricalNB\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t34p-025"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`codes_train = encoder.fit_transform(X_train[categories].astype(str))`, `codes_test = encoder.transform(X_test[categories].astype(str))`, then `fit` and `score`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "from sklearn.preprocessing import OrdinalEncoder\n",
    "from sklearn.naive_bayes import CategoricalNB\n",
    "\n",
    "encoder = OrdinalEncoder()\n",
    "codes_train = encoder.fit_transform(X_train[categories].astype(str))\n",
    "codes_test = encoder.transform(X_test[categories].astype(str))\n",
    "\n",
    "cat_nb = CategoricalNB()\n",
    "cat_nb.fit(codes_train, y_train)\n",
    "\n",
    "print(round(cat_nb.score(codes_test, y_test), 4))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.7246\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t34p-026"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Steps 13 to 16: measures, both models together, alpha and the threshold"
   ],
   "id": "t34p-027"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 13. Recall and AUC\n",
    "\n",
    "Print the recall, then the AUC of `cat_nb` on the test data, each rounded to 4 decimals."
   ],
   "id": "t34p-028"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import recall_score, roc_auc_score\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t34p-029"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`recall_score(y_test, cat_nb.predict(codes_test))` and `roc_auc_score(y_test, cat_nb.predict_proba(codes_test)[:, 1])`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "from sklearn.metrics import recall_score, roc_auc_score\n",
    "\n",
    "print(round(recall_score(y_test, cat_nb.predict(codes_test)), 4))\n",
    "print(round(roc_auc_score(y_test, cat_nb.predict_proba(codes_test)[:, 1]), 4))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.7086\n",
    "0.8331\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t34p-030"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 14. Both models together\n",
    "\n",
    "Add the joint logarithms of `gauss` and `cat_nb` and subtract the logarithm of the prior once. Print the accuracy of the class with the larger sum, rounded to 4 decimals."
   ],
   "id": "t34p-031"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t34p-032"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`joint = gauss.predict_joint_log_proba(X_test[numbers]) + cat_nb.predict_joint_log_proba(codes_test) - np.log(gauss.class_prior_)`, then `joint.argmax(axis=1)` and its share equal to `y_test`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "joint = gauss.predict_joint_log_proba(X_test[numbers]) + cat_nb.predict_joint_log_proba(codes_test) - np.log(gauss.class_prior_)\n",
    "\n",
    "predicted_both = joint.argmax(axis=1)\n",
    "\n",
    "print(round((predicted_both == y_test).mean(), 4))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.7609\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t34p-033"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 15. alpha with cross-validation\n",
    "\n",
    "For `alpha` = 0.1, 1 and 10, print `alpha` and the mean accuracy of a 5-fold cross-validation of `CategoricalNB` on `codes_train`, rounded to 4 decimals. Give the model `min_categories=sizes`, the number of categories of each feature."
   ],
   "id": "t34p-034"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import cross_val_score\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t34p-035"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`sizes = [len(values) for values in encoder.categories_]`; a loop over `[0.1, 1, 10]` with `cross_val_score(CategoricalNB(alpha=alpha, min_categories=sizes), codes_train, y_train, cv=5).mean()`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "from sklearn.model_selection import cross_val_score\n",
    "\n",
    "sizes = [len(values) for values in encoder.categories_]\n",
    "\n",
    "for alpha in [0.1, 1, 10]:\n",
    "    scores = cross_val_score(CategoricalNB(alpha=alpha, min_categories=sizes), codes_train, y_train, cv=5)\n",
    "    print(alpha, round(scores.mean(), 4))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.1 0.8194\n",
    "1 0.8194\n",
    "10 0.8131\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t34p-036"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 16. A lower threshold and a chart\n",
    "\n",
    "Predict \"disease\" when the probability of `cat_nb` is at least 0.3, and print the recall rounded to 4 decimals. Then draw the probabilities of disease of the test patients as a histogram with 20 bins."
   ],
   "id": "t34p-037"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t34p-038"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`disease_prob = cat_nb.predict_proba(codes_test)[:, 1]`, `(disease_prob >= 0.3).astype(int)`, then `plt.hist(disease_prob, bins=20)` and `plt.show()`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "disease_prob = cat_nb.predict_proba(codes_test)[:, 1]\n",
    "predicted_03 = (disease_prob >= 0.3).astype(int)\n",
    "\n",
    "print(round(recall_score(y_test, predicted_03), 4))\n",
    "\n",
    "plt.hist(disease_prob, bins=20)\n",
    "plt.xlabel(\"probability of disease\")\n",
    "plt.show()\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.8874\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t34p-039"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When you have finished, compare your solutions with the hidden ones. A different solution that prints the same numbers and draws the same chart is just as good."
   ],
   "id": "t34p-040"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
