{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 29: Practice\n",
    "\n",
    "Asiman Data School, Module 3: Comprehensive Machine Learning. Week 15, Tuesday.\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`, `tree`, `final`, `predicted`): the later steps run after your own answers to the earlier ones, so solve them in order. The last step also draws the tree: it is accepted when the number is right and a chart was drawn."
   ],
   "id": "t29p-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Steps 5 to 8: from the file to the data for the tree"
   ],
   "id": "t29p-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": "t29p-002"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t29p-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": "t29p-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": "t29p-005"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t29p-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 number of men is the sum of the column.\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": "t29p-007"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 7. Encode the country\n",
    "\n",
    "One-hot encode `country` inside the table, with `drop_first=True` and `dtype=int`. Print the names of the columns as a list. This step continues from Step 6."
   ],
   "id": "t29p-008"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t29p-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(df.columns.tolist())`. `products_number` stays a number.\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(df.columns.tolist())\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "['credit_score', 'gender', 'age', 'tenure', 'balance', 'products_number', 'credit_card', 'active_member', 'estimated_salary', 'churn', 'country_Germany', 'country_Spain']\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t29p-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 shapes of `X_train` and `X_test` on one line. This step continues from Step 7."
   ],
   "id": "t29p-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": "t29p-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)` and `print(X_train.shape, X_test.shape)`.\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(X_train.shape, X_test.shape)\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "(7000, 11) (3000, 11)\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t29p-013"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Steps 9 to 12: the full tree, a small tree, the best depth"
   ],
   "id": "t29p-014"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 9. A tree without limits\n",
    "\n",
    "Train a `DecisionTreeClassifier` called `tree` with `random_state=42`. Print its training accuracy, then its test accuracy rounded to 4 decimals. This step continues from Step 8."
   ],
   "id": "t29p-015"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.tree import DecisionTreeClassifier\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t29p-016"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`tree = DecisionTreeClassifier(random_state=42)`, `tree.fit(X_train, y_train)`, then `print(tree.score(X_train, y_train))` and `print(round(tree.score(X_test, y_test), 4))`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "from sklearn.tree import DecisionTreeClassifier\n",
    "\n",
    "tree = DecisionTreeClassifier(random_state=42)\n",
    "tree.fit(X_train, y_train)\n",
    "\n",
    "print(tree.score(X_train, y_train))\n",
    "print(round(tree.score(X_test, y_test), 4))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "1.0\n",
    "0.7927\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t29p-017"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 10. How big is it?\n",
    "\n",
    "Print the depth of `tree`, then its number of leaves. This step continues from Step 9."
   ],
   "id": "t29p-018"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t29p-019"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`print(tree.get_depth())` and `print(tree.get_n_leaves())`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "print(tree.get_depth())\n",
    "print(tree.get_n_leaves())\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "23\n",
    "1006\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t29p-020"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 11. A small tree\n",
    "\n",
    "Train a tree with `max_depth=3` and `random_state=42`. Print its training accuracy and its test accuracy, each rounded to 4 decimals. This step continues from Step 9."
   ],
   "id": "t29p-021"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t29p-022"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`small = DecisionTreeClassifier(max_depth=3, random_state=42)`, `small.fit(X_train, y_train)`, then `score` on each part.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "small = DecisionTreeClassifier(max_depth=3, random_state=42)\n",
    "small.fit(X_train, y_train)\n",
    "\n",
    "print(round(small.score(X_train, y_train), 4))\n",
    "print(round(small.score(X_test, y_test), 4))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.8401\n",
    "0.8393\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t29p-023"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 12. The best depth\n",
    "\n",
    "For the depths 4, 5 and 6, print the depth and the mean AUC of a 5-fold cross-validation on the training data, rounded to 4 decimals. This step continues from Step 9."
   ],
   "id": "t29p-024"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import cross_val_score\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t29p-025"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "In a loop: `model = DecisionTreeClassifier(max_depth=depth, random_state=42)`, `scores = cross_val_score(model, X_train, y_train, cv=5, scoring=\"roc_auc\")`, `print(depth, round(scores.mean(), 4))`.\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 depth in [4, 5, 6]:\n",
    "    model = DecisionTreeClassifier(max_depth=depth, random_state=42)\n",
    "    scores = cross_val_score(model, X_train, y_train, cv=5, scoring=\"roc_auc\")\n",
    "    print(depth, round(scores.mean(), 4))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "4 0.8136\n",
    "5 0.8313\n",
    "6 0.8263\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t29p-026"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Steps 13 to 16: the tuned tree, its measures and its picture"
   ],
   "id": "t29p-027"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 13. The tuned tree\n",
    "\n",
    "Train the tree with `max_depth=5` and `random_state=42`, called `final`, and put its test predictions into `predicted`. Print the confusion matrix. This step continues from Step 9."
   ],
   "id": "t29p-028"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import confusion_matrix\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t29p-029"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`final.fit(X_train, y_train)`, `predicted = final.predict(X_test)`, then `print(confusion_matrix(y_test, predicted))`: the truth first.\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",
    "final = DecisionTreeClassifier(max_depth=5, random_state=42)\n",
    "final.fit(X_train, y_train)\n",
    "\n",
    "predicted = final.predict(X_test)\n",
    "\n",
    "print(confusion_matrix(y_test, predicted))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "[[2332   41]\n",
    " [ 398  229]]\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t29p-030"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 14. Its measures\n",
    "\n",
    "Print the recall, the F1-score and the AUC of `final`, in this order, each rounded to 4 decimals. This step continues from Step 13."
   ],
   "id": "t29p-031"
  },
  {
   "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": "t29p-032"
  },
  {
   "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 the probabilities `final.predict_proba(X_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, f1_score, roc_auc_score\n",
    "\n",
    "leaving = final.predict_proba(X_test)[:, 1]\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, leaving), 4))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.3652\n",
    "0.5106\n",
    "0.8442\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t29p-033"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 15. The most important feature\n",
    "\n",
    "Print the name of the most important feature of `final`, then its importance rounded to 3 decimals. This step continues from Step 13."
   ],
   "id": "t29p-034"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t29p-035"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`importances = pd.Series(final.feature_importances_, index=X.columns)`, then `print(importances.idxmax())` and `print(round(importances.max(), 3))`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "importances = pd.Series(final.feature_importances_, index=X.columns)\n",
    "\n",
    "print(importances.idxmax())\n",
    "print(round(importances.max(), 3))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "age\n",
    "0.415\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t29p-036"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 16. Draw a tree\n",
    "\n",
    "Train a tree with `max_depth=2` and `random_state=42`. Print its test accuracy rounded to 4 decimals, then draw it with `plot_tree`, with the names of the features and of the classes. This step continues from Step 9."
   ],
   "id": "t29p-037"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "from sklearn.tree import plot_tree\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t29p-038"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`two = DecisionTreeClassifier(max_depth=2, random_state=42)`, `fit`, `print(round(two.score(X_test, y_test), 4))`, then `plot_tree(two, feature_names=list(X.columns), class_names=[\"stays\", \"leaves\"], filled=True)` 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.tree import plot_tree\n",
    "\n",
    "two = DecisionTreeClassifier(max_depth=2, random_state=42)\n",
    "two.fit(X_train, y_train)\n",
    "\n",
    "print(round(two.score(X_test, y_test), 4))\n",
    "\n",
    "plt.figure(figsize=(12, 6))\n",
    "plot_tree(two, feature_names=list(X.columns), class_names=[\"stays\", \"leaves\"], filled=True, fontsize=10)\n",
    "plt.show()\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.8257\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t29p-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": "t29p-040"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
