{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 28: Practice\n",
    "\n",
    "Asiman Data School, Module 3: Comprehensive Machine Learning. Week 14, 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_test`, `scaler`, `X_test_scaled`, `model`, `predicted`, `tn`, `fp`, `fn`, `tp`, `leaving`): 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 numbers are right and a chart was drawn."
   ],
   "id": "t28p-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Steps 5 to 10: from the file to the model"
   ],
   "id": "t28p-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": "t28p-002"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t28p-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": "t28p-004"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 6. Drop and encode\n",
    "\n",
    "Drop the column `customer_id` and encode `gender` as 0 (Female) and 1 (Male). Print the number of women. This step continues from Step 5."
   ],
   "id": "t28p-005"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t28p-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 women are the rows with 0: `print((df[\"gender\"] == 0).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\"] == 0).sum())\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "4543\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t28p-007"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 7. One-hot encoding\n",
    "\n",
    "One-hot encode `country` and `products_number` inside the table, with `drop_first=True` and `dtype=int`. Print the number of columns. This step continues from Step 6."
   ],
   "id": "t28p-008"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t28p-009"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`df = pd.get_dummies(df, columns=[\"country\", \"products_number\"], 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\", \"products_number\"], drop_first=True, dtype=int)\n",
    "\n",
    "print(len(df.columns))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "14\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t28p-010"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 8. Split\n",
    "\n",
    "Make `X` (all columns without `churn`) and `y` (`churn`). Split them with `test_size=0.3` and `random_state=1`. Print the number of test customers, then how many of them left. This step continues from Step 7."
   ],
   "id": "t28p-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": "t28p-012"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`X = df.drop(columns=[\"churn\"])`, `y = df[\"churn\"]`, then `X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)`. Print `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": "t28p-013"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 9. Scale\n",
    "\n",
    "Scale the features with a `StandardScaler` called `scaler` into `X_train_scaled` and `X_test_scaled`. Print the shape of `X_test_scaled`. This step continues from Step 8."
   ],
   "id": "t28p-014"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import StandardScaler\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t28p-015"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`scaler = StandardScaler()`, `X_train_scaled = scaler.fit_transform(X_train)`, `X_test_scaled = scaler.transform(X_test)`, then `print(X_test_scaled.shape)`.\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(X_test_scaled.shape)\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "(3000, 13)\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t28p-016"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 10. Train and predict\n",
    "\n",
    "Train a `LogisticRegression` called `model` and put its predictions for the test customers into `predicted`. Print the test accuracy, rounded to 4 decimals, then the number of customers the model marks as leaving. This step continues from Step 9."
   ],
   "id": "t28p-017"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.linear_model import LogisticRegression\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t28p-018"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`model = LogisticRegression()`, `model.fit(X_train_scaled, y_train)`, `predicted = model.predict(X_test_scaled)`. Then `print(round(model.score(X_test_scaled, y_test), 4))` and `print(predicted.sum())`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "from sklearn.linear_model import LogisticRegression\n",
    "\n",
    "model = LogisticRegression()\n",
    "model.fit(X_train_scaled, y_train)\n",
    "\n",
    "predicted = model.predict(X_test_scaled)\n",
    "\n",
    "print(round(model.score(X_test_scaled, y_test), 4))\n",
    "print(predicted.sum())\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.84\n",
    "309\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t28p-019"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Steps 11 to 14: the confusion matrix and its measures"
   ],
   "id": "t28p-020"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 11. The confusion matrix\n",
    "\n",
    "Print the confusion matrix of the model. This step continues from Step 10."
   ],
   "id": "t28p-021"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import confusion_matrix\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t28p-022"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`print(confusion_matrix(y_test, predicted))`: the truth first, then the prediction.\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",
    "print(confusion_matrix(y_test, predicted))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "[[2292   81]\n",
    " [ 399  228]]\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t28p-023"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 12. Misses and false alarms\n",
    "\n",
    "Give the four counts the names `tn`, `fp`, `fn`, `tp`. Print the number of misses (leaving customers the model did not find), then the number of false alarms. This step continues from Step 11."
   ],
   "id": "t28p-024"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t28p-025"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`tn, fp, fn, tp = confusion_matrix(y_test, predicted).ravel()`. The misses are `fn`, the false alarms are `fp`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "tn, fp, fn, tp = confusion_matrix(y_test, predicted).ravel()\n",
    "\n",
    "print(fn)\n",
    "print(fp)\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "399\n",
    "81\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t28p-026"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 13. Precision, recall, F1\n",
    "\n",
    "Print the precision, the recall and the F1-score of the model, in this order, each rounded to 4 decimals. This step continues from Step 10."
   ],
   "id": "t28p-027"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import precision_score, recall_score, f1_score\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t28p-028"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`print(round(precision_score(y_test, predicted), 4))`, and the same with `recall_score` and `f1_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, recall_score, f1_score\n",
    "\n",
    "print(round(precision_score(y_test, predicted), 4))\n",
    "print(round(recall_score(y_test, predicted), 4))\n",
    "print(round(f1_score(y_test, predicted), 4))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.7379\n",
    "0.3636\n",
    "0.4872\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t28p-029"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 14. Specificity and balanced accuracy\n",
    "\n",
    "Print the specificity, calculated from the four counts, then the balanced accuracy with the function of scikit-learn, each rounded to 4 decimals. This step continues from Step 12."
   ],
   "id": "t28p-030"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import balanced_accuracy_score\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t28p-031"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "The specificity is `tn / (tn + fp)`. Then `print(round(balanced_accuracy_score(y_test, predicted), 4))`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "from sklearn.metrics import balanced_accuracy_score\n",
    "\n",
    "print(round(tn / (tn + fp), 4))\n",
    "print(round(balanced_accuracy_score(y_test, predicted), 4))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.9659\n",
    "0.6648\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t28p-032"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Steps 15 and 16: the threshold, the AUC and the Gini coefficient"
   ],
   "id": "t28p-033"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 15. Another threshold\n",
    "\n",
    "Put the probability of leaving of every test customer into `leaving`. With the threshold 0.3, print the precision, then the recall, each rounded to 4 decimals. This step continues from Step 13."
   ],
   "id": "t28p-034"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t28p-035"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`leaving = model.predict_proba(X_test_scaled)[:, 1]`, then `marked = (leaving >= 0.3).astype(int)` and the two functions with `(y_test, marked)`. The recall is much higher than in Step 13 and the precision lower: the same model, another cut.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "leaving = model.predict_proba(X_test_scaled)[:, 1]\n",
    "marked = (leaving >= 0.3).astype(int)\n",
    "\n",
    "print(round(precision_score(y_test, marked), 4))\n",
    "print(round(recall_score(y_test, marked), 4))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.5607\n",
    "0.6045\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t28p-036"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 16. AUC, Gini and the ROC curve\n",
    "\n",
    "Print the AUC of the model, then its Gini coefficient, each rounded to 4 decimals. Then draw the ROC curve with the diagonal of guessing. This step continues from Step 15."
   ],
   "id": "t28p-037"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "from sklearn.metrics import roc_auc_score, roc_curve\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t28p-038"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`auc = roc_auc_score(y_test, leaving)`, then `print(round(auc, 4))` and `print(round(2 * auc - 1, 4))`. For the curve: `fpr, tpr, thresholds = roc_curve(y_test, leaving)`, `plt.plot(fpr, tpr)`, `plt.plot([0, 1], [0, 1], linestyle=\"--\")` 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",
    "from sklearn.metrics import roc_auc_score, roc_curve\n",
    "\n",
    "auc = roc_auc_score(y_test, leaving)\n",
    "\n",
    "print(round(auc, 4))\n",
    "print(round(2 * auc - 1, 4))\n",
    "\n",
    "fpr, tpr, thresholds = roc_curve(y_test, leaving)\n",
    "\n",
    "plt.plot(fpr, tpr, label=\"the model\")\n",
    "plt.plot([0, 1], [0, 1], linestyle=\"--\", label=\"guessing\")\n",
    "plt.xlabel(\"False positive rate\")\n",
    "plt.ylabel(\"True positive rate (recall)\")\n",
    "plt.title(\"ROC curve\")\n",
    "plt.legend()\n",
    "plt.show()\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.8389\n",
    "0.6778\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t28p-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": "t28p-040"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
