{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 30: Practice\n",
    "\n",
    "Asiman Data School, Module 3: Comprehensive Machine Learning. Week 15, 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`, `forest`, `predicted`, `bagged_trees`): 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": "t30p-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Steps 5 to 8: from the file to the data for the forest"
   ],
   "id": "t30p-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": "t30p-002"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t30p-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": "t30p-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 women. This step continues from Step 5."
   ],
   "id": "t30p-005"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t30p-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": "t30p-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 number of columns. This step continues from Step 6."
   ],
   "id": "t30p-008"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t30p-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": "t30p-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": "t30p-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": "t30p-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\"]`, `X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)`, then `print(len(y_test))` and `print(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": "t30p-013"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Steps 9 to 12: the random forest and its measures"
   ],
   "id": "t30p-014"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 9. A random forest\n",
    "\n",
    "Train a `RandomForestClassifier` called `forest` with `random_state=42`. Print its test accuracy, rounded to 4 decimals. This step continues from Step 8."
   ],
   "id": "t30p-015"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.ensemble import RandomForestClassifier\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t30p-016"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`forest = RandomForestClassifier(random_state=42)`, `forest.fit(X_train, y_train)`, then `print(round(forest.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.ensemble import RandomForestClassifier\n",
    "\n",
    "forest = RandomForestClassifier(random_state=42)\n",
    "forest.fit(X_train, y_train)\n",
    "\n",
    "print(round(forest.score(X_test, y_test), 4))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.862\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t30p-017"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 10. Inside the forest\n",
    "\n",
    "Print the number of trees in `forest`, then the depth of its first tree. This step continues from Step 9."
   ],
   "id": "t30p-018"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t30p-019"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`print(len(forest.estimators_))` and `print(forest.estimators_[0].get_depth())`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "print(len(forest.estimators_))\n",
    "print(forest.estimators_[0].get_depth())\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "100\n",
    "22\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t30p-020"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 11. The confusion matrix\n",
    "\n",
    "Put the test predictions of `forest` into `predicted` and print the confusion matrix. This step continues from Step 9."
   ],
   "id": "t30p-021"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import confusion_matrix\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t30p-022"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`predicted = forest.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",
    "predicted = forest.predict(X_test)\n",
    "\n",
    "print(confusion_matrix(y_test, predicted))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "[[2290   83]\n",
    " [ 331  296]]\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t30p-023"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 12. Recall, F1 and AUC\n",
    "\n",
    "Print the recall, the F1-score and the AUC of `forest`, in this order, each rounded to 4 decimals. This step continues from Step 11."
   ],
   "id": "t30p-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": "t30p-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 the probabilities `forest.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",
    "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, forest.predict_proba(X_test)[:, 1]), 4))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.4721\n",
    "0.5885\n",
    "0.8585\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t30p-026"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Steps 13 to 16: OOB, tuning, bagging and the scores"
   ],
   "id": "t30p-027"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 13. The OOB score\n",
    "\n",
    "Train a forest with `oob_score=True` and `random_state=42`. Print its OOB score, rounded to 4 decimals. This step continues from Step 9."
   ],
   "id": "t30p-028"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t30p-029"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`oob_forest = RandomForestClassifier(oob_score=True, random_state=42)`, `fit`, then `print(round(oob_forest.oob_score_, 4))`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "oob_forest = RandomForestClassifier(oob_score=True, random_state=42)\n",
    "oob_forest.fit(X_train, y_train)\n",
    "\n",
    "print(round(oob_forest.oob_score_, 4))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.8583\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t30p-030"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 14. A tuned forest\n",
    "\n",
    "Train a forest with `max_depth=10` and `random_state=42`. Print its test AUC rounded to 4 decimals, then the name of its most important feature by impurity importance. This step continues from Step 12."
   ],
   "id": "t30p-031"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t30p-032"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`tuned = RandomForestClassifier(max_depth=10, random_state=42)`, `fit`, `roc_auc_score(y_test, tuned.predict_proba(X_test)[:, 1])`, then `pd.Series(tuned.feature_importances_, index=X.columns).idxmax()`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "tuned = RandomForestClassifier(max_depth=10, random_state=42)\n",
    "tuned.fit(X_train, y_train)\n",
    "\n",
    "print(round(roc_auc_score(y_test, tuned.predict_proba(X_test)[:, 1]), 4))\n",
    "print(pd.Series(tuned.feature_importances_, index=X.columns).idxmax())\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.8668\n",
    "age\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t30p-033"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 15. Bagged trees\n",
    "\n",
    "Train a `BaggingClassifier` of 100 full decision trees with `random_state=42`, called `bagged_trees`. Print its test accuracy and its test AUC, each rounded to 4 decimals. This step continues from Step 12."
   ],
   "id": "t30p-034"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.ensemble import BaggingClassifier\n",
    "from sklearn.tree import DecisionTreeClassifier\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t30p-035"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`bagged_trees = BaggingClassifier(estimator=DecisionTreeClassifier(), n_estimators=100, random_state=42)`, `fit`, then `score` and `roc_auc_score` with `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.ensemble import BaggingClassifier\n",
    "from sklearn.tree import DecisionTreeClassifier\n",
    "\n",
    "bagged_trees = BaggingClassifier(estimator=DecisionTreeClassifier(), n_estimators=100, random_state=42)\n",
    "bagged_trees.fit(X_train, y_train)\n",
    "\n",
    "print(round(bagged_trees.score(X_test, y_test), 4))\n",
    "print(round(roc_auc_score(y_test, bagged_trees.predict_proba(X_test)[:, 1]), 4))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.8527\n",
    "0.8453\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t30p-036"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 16. Bagged logistic regression and the scores\n",
    "\n",
    "Scale the features (`StandardScaler` fitted on the training data), train a `BaggingClassifier` of 100 logistic regressions with `random_state=42` on the scaled data, and print its test AUC rounded to 4 decimals. Then draw the test AUC of `forest`, `bagged_trees` and this model as horizontal bars. This step continues from Step 15."
   ],
   "id": "t30p-037"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "from sklearn.linear_model import LogisticRegression\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t30p-038"
  },
  {
   "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)`; `BaggingClassifier(estimator=LogisticRegression(), n_estimators=100, random_state=42)`; then `plt.barh(names, aucs)` 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.preprocessing import StandardScaler\n",
    "from sklearn.linear_model import LogisticRegression\n",
    "\n",
    "scaler = StandardScaler()\n",
    "X_train_scaled = scaler.fit_transform(X_train)\n",
    "X_test_scaled = scaler.transform(X_test)\n",
    "\n",
    "bagged_logistic = BaggingClassifier(estimator=LogisticRegression(), n_estimators=100, random_state=42)\n",
    "bagged_logistic.fit(X_train_scaled, y_train)\n",
    "\n",
    "auc_logistic = roc_auc_score(y_test, bagged_logistic.predict_proba(X_test_scaled)[:, 1])\n",
    "print(round(auc_logistic, 4))\n",
    "\n",
    "names = [\"random forest\", \"bagged trees\", \"bagged logistic regression\"]\n",
    "aucs = [\n",
    "    roc_auc_score(y_test, forest.predict_proba(X_test)[:, 1]),\n",
    "    roc_auc_score(y_test, bagged_trees.predict_proba(X_test)[:, 1]),\n",
    "    auc_logistic,\n",
    "]\n",
    "\n",
    "plt.barh(names, aucs)\n",
    "plt.xlabel(\"test AUC\")\n",
    "plt.show()\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.7673\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t30p-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": "t30p-040"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
