{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 32: Practice\n",
    "\n",
    "Asiman Data School, Module 3: Comprehensive Machine Learning. Week 16, 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 Bank Customer Churn Prediction.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`, `X_train_scaled`, `X_test_scaled`, `knn`, `predicted`, `knn15`): 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": "t32p-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Steps 5 to 8: from the file to the split"
   ],
   "id": "t32p-001"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 5. Read the file\n",
    "\n",
    "Read `Bank Customer Churn Prediction.csv` into `df`. Print the shape, then the number of customers who left."
   ],
   "id": "t32p-002"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t32p-003"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`df = pd.read_csv(\"Bank Customer Churn Prediction.csv\")`, then `print(df.shape)` and `print(df[\"churn\"].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(\"Bank Customer Churn Prediction.csv\")\n",
    "\n",
    "print(df.shape)\n",
    "print(df[\"churn\"].sum())\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "(10000, 12)\n",
    "2037\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t32p-004"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 6. Drop and encode the gender\n",
    "\n",
    "Drop the column `customer_id` and encode `gender` as 0 (Female) and 1 (Male). Print the number of men. This step continues from Step 5."
   ],
   "id": "t32p-005"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t32p-006"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`df = df.drop(columns=[\"customer_id\"])` and `df[\"gender\"] = df[\"gender\"].map({\"Female\": 0, \"Male\": 1})`. The men are the rows with 1: `print(df[\"gender\"].sum())`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "df = df.drop(columns=[\"customer_id\"])\n",
    "df[\"gender\"] = df[\"gender\"].map({\"Female\": 0, \"Male\": 1})\n",
    "\n",
    "print(df[\"gender\"].sum())\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "5457\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t32p-007"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 7. One-hot encode the country\n",
    "\n",
    "One-hot encode `country` inside the table, with `drop_first=True` and `dtype=int`. Print the number of columns."
   ],
   "id": "t32p-008"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t32p-009"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`df = pd.get_dummies(df, columns=[\"country\"], drop_first=True, dtype=int)`, then `print(len(df.columns))`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "df = pd.get_dummies(df, columns=[\"country\"], drop_first=True, dtype=int)\n",
    "\n",
    "print(len(df.columns))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "12\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t32p-010"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 8. Split\n",
    "\n",
    "Make `X` (all columns without `churn`) and `y`. Split them with `test_size=0.3` and `random_state=1`. Print the number of test customers, then how many of them left."
   ],
   "id": "t32p-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": "t32p-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=[\"churn\"])\n",
    "y = df[\"churn\"]\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",
    "3000\n",
    "627\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t32p-013"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Steps 9 to 12: scaling, the model and its measures"
   ],
   "id": "t32p-014"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 9. Scale\n",
    "\n",
    "Fit a `StandardScaler` on `X_train` and scale both parts into `X_train_scaled` and `X_test_scaled`. Print the mean of the scaled test ages (column position 2), rounded to 4 decimals."
   ],
   "id": "t32p-015"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import StandardScaler\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t32p-016"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`scaler.fit_transform(X_train)` and `scaler.transform(X_test)`; then `X_test_scaled[:, 2].mean()`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "\n",
    "scaler = StandardScaler()\n",
    "X_train_scaled = scaler.fit_transform(X_train)\n",
    "X_test_scaled = scaler.transform(X_test)\n",
    "\n",
    "print(round(X_test_scaled[:, 2].mean(), 4))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "-0.0071\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t32p-017"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 10. The default model\n",
    "\n",
    "Train a `KNeighborsClassifier` called `knn` with its default settings on the scaled data. Print its test accuracy, rounded to 4 decimals."
   ],
   "id": "t32p-018"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t32p-019"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`knn = KNeighborsClassifier()`, `knn.fit(X_train_scaled, y_train)`, then `knn.score(X_test_scaled, y_test)`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "\n",
    "knn = KNeighborsClassifier()\n",
    "knn.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(knn.score(X_test_scaled, y_test), 4))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.82\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t32p-020"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 11. The confusion matrix\n",
    "\n",
    "Put the predictions of `knn` for the test customers into `predicted` and print the confusion matrix."
   ],
   "id": "t32p-021"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import confusion_matrix\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t32p-022"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`predicted = knn.predict(X_test_scaled)`, then `print(confusion_matrix(y_test, predicted))`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "from sklearn.metrics import confusion_matrix\n",
    "\n",
    "predicted = knn.predict(X_test_scaled)\n",
    "\n",
    "print(confusion_matrix(y_test, predicted))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "[[2243  130]\n",
    " [ 410  217]]\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t32p-023"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 12. Recall, F1 and AUC\n",
    "\n",
    "Print the recall, the F1-score and the AUC of `knn`, each rounded to 4 decimals."
   ],
   "id": "t32p-024"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import recall_score, f1_score, roc_auc_score\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t32p-025"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`recall_score` and `f1_score` with `(y_test, predicted)`; `roc_auc_score` with `knn.predict_proba(X_test_scaled)[:, 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, f1_score, roc_auc_score\n",
    "\n",
    "print(round(recall_score(y_test, predicted), 4))\n",
    "print(round(f1_score(y_test, predicted), 4))\n",
    "print(round(roc_auc_score(y_test, knn.predict_proba(X_test_scaled)[:, 1]), 4))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.3461\n",
    "0.4456\n",
    "0.7547\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t32p-026"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Steps 13 to 16: choosing k and a lower threshold"
   ],
   "id": "t32p-027"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 13. k with cross-validation\n",
    "\n",
    "For k = 5, 15 and 25, print k and the mean accuracy of a 5-fold cross-validation on the scaled training data, rounded to 4 decimals."
   ],
   "id": "t32p-028"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import cross_val_score\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t32p-029"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "A loop over `[5, 15, 25]`; `cross_val_score(KNeighborsClassifier(n_neighbors=k), X_train_scaled, y_train, cv=5)`, then `.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",
    "for k in [5, 15, 25]:\n",
    "    scores = cross_val_score(KNeighborsClassifier(n_neighbors=k), X_train_scaled, y_train, cv=5)\n",
    "    print(k, round(scores.mean(), 4))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "5 0.8281\n",
    "15 0.8324\n",
    "25 0.8314\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t32p-030"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 14. The model with k = 15\n",
    "\n",
    "Train a model with k = 15, called `knn15`. Print its test accuracy and its AUC, rounded to 4 decimals."
   ],
   "id": "t32p-031"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t32p-032"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`knn15 = KNeighborsClassifier(n_neighbors=15)`, `fit`; the AUC from `knn15.predict_proba(X_test_scaled)[:, 1]`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "knn15 = KNeighborsClassifier(n_neighbors=15)\n",
    "knn15.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(knn15.score(X_test_scaled, y_test), 4))\n",
    "print(round(roc_auc_score(y_test, knn15.predict_proba(X_test_scaled)[:, 1]), 4))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.8277\n",
    "0.7967\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t32p-033"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 15. A lower threshold\n",
    "\n",
    "Predict \"leaves\" when the probability of `knn15` is at least 0.3. Print the recall and the precision, rounded to 4 decimals."
   ],
   "id": "t32p-034"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import precision_score\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t32p-035"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`(knn15.predict_proba(X_test_scaled)[:, 1] >= 0.3).astype(int)`, then `recall_score` and `precision_score`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "from sklearn.metrics import precision_score\n",
    "\n",
    "predicted_03 = (knn15.predict_proba(X_test_scaled)[:, 1] >= 0.3).astype(int)\n",
    "\n",
    "print(round(recall_score(y_test, predicted_03), 4))\n",
    "print(round(precision_score(y_test, predicted_03), 4))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.5407\n",
    "0.5512\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t32p-036"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 16. Many k and a chart\n",
    "\n",
    "For k = 1, 3, 5, ..., 29, compute the test accuracy. Print the highest of these accuracies, rounded to 4 decimals, then draw the test accuracy against k as a line."
   ],
   "id": "t32p-037"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t32p-038"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`ks = list(range(1, 30, 2))`; append each `score` to a list; `max(...)`; `plt.plot(ks, accuracies)` 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",
    "ks = list(range(1, 30, 2))\n",
    "accuracies = []\n",
    "\n",
    "for k in ks:\n",
    "    model = KNeighborsClassifier(n_neighbors=k)\n",
    "    model.fit(X_train_scaled, y_train)\n",
    "    accuracies.append(model.score(X_test_scaled, y_test))\n",
    "\n",
    "print(round(max(accuracies), 4))\n",
    "\n",
    "plt.plot(ks, accuracies, marker=\"o\")\n",
    "plt.xlabel(\"k\")\n",
    "plt.ylabel(\"test accuracy\")\n",
    "plt.show()\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.8297\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t32p-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": "t32p-040"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
