{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 27: Practice\n",
    "\n",
    "Asiman Data School, Module 3: Comprehensive Machine Learning. Week 14, 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",
    "- 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`, `scaler`, `X_train_scaled`, `model`, `leaving`): the later steps run after your own answers to the earlier ones, so solve them in order."
   ],
   "id": "t27p-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Steps 5 to 9: look and prepare"
   ],
   "id": "t27p-001"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 5. Read and check\n",
    "\n",
    "Read `Bank Customer Churn Prediction.csv` into `df`. Print the shape, then the number of missing values."
   ],
   "id": "t27p-002"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t27p-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.isna().sum().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.isna().sum().sum())\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "(10000, 12)\n",
    "0\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t27p-004"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 6. Drop and look at the target\n",
    "\n",
    "Drop the column `customer_id`. Print the number of customers who left, then the share of customers who left. This step continues from Step 5."
   ],
   "id": "t27p-005"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t27p-006"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`df = df.drop(columns=[\"customer_id\"])`, then `print(df[\"churn\"].sum())` and `print(df[\"churn\"].mean())`.\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",
    "\n",
    "print(df[\"churn\"].sum())\n",
    "print(df[\"churn\"].mean())\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "2037\n",
    "0.2037\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t27p-007"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 7. Outliers of the age\n",
    "\n",
    "Calculate the upper limit of the IQR rule for `age`. Print the limit, then the number of ages above it. (They are real customers and stay in the data.) This step continues from Step 6."
   ],
   "id": "t27p-008"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t27p-009"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`q1 = df[\"age\"].quantile(0.25)`, the same with `0.75` for `q3`, then `upper = q3 + 1.5 * (q3 - q1)`. The number of ages above it is `(df[\"age\"] > upper).sum()`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "q1 = df[\"age\"].quantile(0.25)\n",
    "q3 = df[\"age\"].quantile(0.75)\n",
    "upper = q3 + 1.5 * (q3 - q1)\n",
    "\n",
    "print(upper)\n",
    "print((df[\"age\"] > upper).sum())\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "62.0\n",
    "359\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t27p-010"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 8. Two values\n",
    "\n",
    "Encode `gender` as 0 (Female) and 1 (Male). Print the number of men. This step continues from Step 6."
   ],
   "id": "t27p-011"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t27p-012"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`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[\"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": "t27p-013"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 9. One-hot encoding\n",
    "\n",
    "One-hot encode `country` and `products_number` inside the table, with `drop_first=True` and `dtype=int`. Print the names of the columns as a list. This step continues from Step 8."
   ],
   "id": "t27p-014"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t27p-015"
  },
  {
   "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(df.columns.tolist())`.\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(df.columns.tolist())\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "['credit_score', 'gender', 'age', 'tenure', 'balance', 'credit_card', 'active_member', 'estimated_salary', 'churn', 'country_Germany', 'country_Spain', 'products_number_2', 'products_number_3', 'products_number_4']\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t27p-016"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Steps 10 to 13: split, scale, baseline, model"
   ],
   "id": "t27p-017"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 10. 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 9."
   ],
   "id": "t27p-018"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t27p-019"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`from sklearn.model_selection import train_test_split`, `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)`.\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, 13) (3000, 13)\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t27p-020"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 11. Scale\n",
    "\n",
    "Scale the features with a `StandardScaler` called `scaler` into `X_train_scaled` and `X_test_scaled`. Print the largest value of the scaled test data, rounded to 2 decimals. This step continues from Step 10."
   ],
   "id": "t27p-021"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t27p-022"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`from sklearn.preprocessing import StandardScaler`, `scaler.fit_transform(X_train)` for the training data and `scaler.transform(X_test)` for the test data, then `print(round(X_test_scaled.max(), 2))`. If your number differs, check `test_size=0.3` and `random_state=1` in Step 10.\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.max(), 2))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "12.57\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t27p-023"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 12. The baseline\n",
    "\n",
    "Print the baseline: the accuracy of always answering 0 (stays) for the test customers, rounded to 4 decimals. This step continues from Step 10."
   ],
   "id": "t27p-024"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t27p-025"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "It is the share of zeros in `y_test`: `print(round(1 - y_test.mean(), 4))`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "print(round(1 - y_test.mean(), 4))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.791\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t27p-026"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 13. Train and judge\n",
    "\n",
    "Train a `LogisticRegression` called `model` on the scaled training data. Print the training accuracy, then the test accuracy, each rounded to 4 decimals. This step continues from Step 11."
   ],
   "id": "t27p-027"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t27p-028"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`from sklearn.linear_model import LogisticRegression`, `model.fit(X_train_scaled, y_train)`, then `model.score(X_train_scaled, y_train)` and `model.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.linear_model import LogisticRegression\n",
    "\n",
    "model = LogisticRegression()\n",
    "model.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(model.score(X_train_scaled, y_train), 4))\n",
    "print(round(model.score(X_test_scaled, y_test), 4))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.8416\n",
    "0.84\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t27p-029"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Steps 14 to 16: probabilities and hyperparameters"
   ],
   "id": "t27p-030"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 14. Probabilities\n",
    "\n",
    "Make `leaving`, the probability of leaving of every test customer. Print the first three values, rounded to 3 decimals, then the number of test customers with a probability of at least 0.5. This step continues from Step 13."
   ],
   "id": "t27p-031"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t27p-032"
  },
  {
   "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 `print(leaving[:3].round(3))` and `print((leaving >= 0.5).sum())`.\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",
    "\n",
    "print(leaving[:3].round(3))\n",
    "print((leaving >= 0.5).sum())\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "[0.038 0.168 0.051]\n",
    "309\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t27p-033"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 15. A strong penalty\n",
    "\n",
    "Train a `LogisticRegression` with `C=0.001` and print its test accuracy, rounded to 4 decimals. Is this `C` a good choice? This step continues from Step 13."
   ],
   "id": "t27p-034"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t27p-035"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`strong = LogisticRegression(C=0.001)`, `fit`, then `print(round(strong.score(X_test_scaled, y_test), 4))`. The accuracy is lower than that of the default model: the penalty is too strong, and the model underfits.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "strong = LogisticRegression(C=0.001)\n",
    "strong.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(strong.score(X_test_scaled, y_test), 4))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.8157\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t27p-036"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 16. Balanced classes\n",
    "\n",
    "Train a `LogisticRegression` with `class_weight=\"balanced\"`. Print its test accuracy, rounded to 4 decimals, then the number of test customers it marks as leaving. This step continues from Step 13."
   ],
   "id": "t27p-037"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t27p-038"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`balanced = LogisticRegression(class_weight=\"balanced\")`, `fit`, then `score` and `print(balanced.predict(X_test_scaled).sum())`. The accuracy falls, and the model marks many more customers than the count of Step 14. Whether that is better is the question of Topic 28.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "balanced = LogisticRegression(class_weight=\"balanced\")\n",
    "balanced.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(balanced.score(X_test_scaled, y_test), 4))\n",
    "print(balanced.predict(X_test_scaled).sum())\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.7673\n",
    "1001\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t27p-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 is just as good."
   ],
   "id": "t27p-040"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
