{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 35: Practice\n",
    "\n",
    "Asiman Data School, Module 3: Comprehensive Machine Learning. Week 18, 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 german_credit.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`, `svm`, `voters`, `hard`, `soft`): 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": "t35p-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Steps 5 to 8: from the raw file to the split"
   ],
   "id": "t35p-001"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 5. Read the raw file\n",
    "\n",
    "Read `german_credit.csv` into `df`. Print the shape, then the number of bad credits."
   ],
   "id": "t35p-002"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t35p-003"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`df = pd.read_csv(\"german_credit.csv\")`, then `print(df.shape)` and `print((df[\"risk\"] == \"bad\").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(\"german_credit.csv\")\n",
    "\n",
    "print(df.shape)\n",
    "print((df[\"risk\"] == \"bad\").sum())\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "(1000, 21)\n",
    "300\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t35p-004"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 6. The target and two columns\n",
    "\n",
    "Turn `risk` into 1 for bad and 0 for good, and drop `personal_status` and `foreign_worker`. Print the number of columns. This step continues from Step 5."
   ],
   "id": "t35p-005"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t35p-006"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`df[\"risk\"] = (df[\"risk\"] == \"bad\").astype(int)`, then `df.drop(columns=[...])` and `len(df.columns)`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "df[\"risk\"] = (df[\"risk\"] == \"bad\").astype(int)\n",
    "df = df.drop(columns=[\"personal_status\", \"foreign_worker\"])\n",
    "\n",
    "print(len(df.columns))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "19\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t35p-007"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 7. One-hot encoding\n",
    "\n",
    "One-hot encode the columns of `text_columns` with `drop_first=True` and `dtype=int`. Print the number of columns."
   ],
   "id": "t35p-008"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "text_columns = [\"checking_account\", \"credit_history\", \"purpose\", \"savings\", \"employment_years\", \"other_debtors\", \"property\", \"other_installments\", \"housing\", \"job\", \"telephone\"]\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t35p-009"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`df = pd.get_dummies(df, columns=text_columns, drop_first=True, dtype=int)`, then `len(df.columns)`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "text_columns = [\"checking_account\", \"credit_history\", \"purpose\", \"savings\", \"employment_years\", \"other_debtors\", \"property\", \"other_installments\", \"housing\", \"job\", \"telephone\"]\n",
    "\n",
    "df = pd.get_dummies(df, columns=text_columns, drop_first=True, dtype=int)\n",
    "\n",
    "print(len(df.columns))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "45\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t35p-010"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 8. Split\n",
    "\n",
    "Make `X` (all columns without `risk`) and `y`. Split them with `test_size=0.3` and `random_state=1`. Print the number of test applicants, then how many of them are bad."
   ],
   "id": "t35p-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": "t35p-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=[\"risk\"])\n",
    "y = df[\"risk\"]\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",
    "300\n",
    "86\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t35p-013"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Steps 9 to 12: scaling and the SVM"
   ],
   "id": "t35p-014"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 9. Scale\n",
    "\n",
    "Fit a `StandardScaler` on the training data and scale both parts into `X_train_scaled` and `X_test_scaled`. Print the shape of `X_test_scaled`."
   ],
   "id": "t35p-015"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import StandardScaler\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t35p-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)`.\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",
    "(300, 44)\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t35p-017"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 10. The default SVM\n",
    "\n",
    "Train an `SVC()` called `svm` on the scaled data. Print its test accuracy, rounded to 4 decimals."
   ],
   "id": "t35p-018"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.svm import SVC\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t35p-019"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`svm = SVC()`, `svm.fit(X_train_scaled, y_train)`, then `svm.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.svm import SVC\n",
    "\n",
    "svm = SVC()\n",
    "svm.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(svm.score(X_test_scaled, y_test), 4))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.74\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t35p-020"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 11. The support vectors\n",
    "\n",
    "Print the number of support vectors of `svm` for each class, then their total."
   ],
   "id": "t35p-021"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t35p-022"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`svm.n_support_` holds one number per class; `.sum()` adds them up.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "print(svm.n_support_)\n",
    "print(svm.n_support_.sum())\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "[272 207]\n",
    "479\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t35p-023"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 12. C with cross-validation\n",
    "\n",
    "For C = 0.1, 1 and 10, print C and the mean accuracy of a 5-fold cross-validation of `SVC(C=C)` on the scaled training data, rounded to 4 decimals."
   ],
   "id": "t35p-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": "t35p-025"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "A loop over `[0.1, 1, 10]` with `cross_val_score(SVC(C=C), X_train_scaled, y_train, cv=5).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 C in [0.1, 1, 10]:\n",
    "    scores = cross_val_score(SVC(C=C), X_train_scaled, y_train, cv=5)\n",
    "    print(C, round(scores.mean(), 4))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.1 0.6943\n",
    "1 0.7457\n",
    "10 0.7314\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t35p-026"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Steps 13 to 16: the class weight and the vote"
   ],
   "id": "t35p-027"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 13. A balanced SVM\n",
    "\n",
    "Train an `SVC(class_weight=\"balanced\")` and print its test recall, rounded to 4 decimals."
   ],
   "id": "t35p-028"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import recall_score\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t35p-029"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`fit` on the scaled training data, then `recall_score(y_test, model.predict(X_test_scaled))`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "from sklearn.metrics import recall_score\n",
    "\n",
    "svm_balanced = SVC(class_weight=\"balanced\")\n",
    "svm_balanced.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(recall_score(y_test, svm_balanced.predict(X_test_scaled)), 4))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.5814\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t35p-030"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 14. Two other models\n",
    "\n",
    "Train a `LogisticRegression()` and a `RandomForestClassifier(random_state=42)` on the scaled data. Print the test accuracy of each, rounded to 4 decimals."
   ],
   "id": "t35p-031"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.linear_model import LogisticRegression\n",
    "from sklearn.ensemble import RandomForestClassifier\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t35p-032"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`fit(X_train_scaled, y_train)` for each model, then `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",
    "from sklearn.ensemble import RandomForestClassifier\n",
    "\n",
    "logistic = LogisticRegression()\n",
    "logistic.fit(X_train_scaled, y_train)\n",
    "\n",
    "forest = RandomForestClassifier(random_state=42)\n",
    "forest.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(logistic.score(X_test_scaled, y_test), 4))\n",
    "print(round(forest.score(X_test_scaled, y_test), 4))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.7567\n",
    "0.7767\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t35p-033"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 15. A hard vote\n",
    "\n",
    "Make a hard `VotingClassifier` called `hard` with the voters in `voters` and print its test accuracy, rounded to 4 decimals."
   ],
   "id": "t35p-034"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.ensemble import VotingClassifier\n",
    "\n",
    "voters = [(\"logistic\", LogisticRegression()), (\"forest\", RandomForestClassifier(random_state=42)), (\"svm\", SVC(probability=True, random_state=42))]\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t35p-035"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`hard = VotingClassifier(estimators=voters, voting=\"hard\")`, `fit` on the scaled training data, then `score`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "from sklearn.ensemble import VotingClassifier\n",
    "\n",
    "voters = [(\"logistic\", LogisticRegression()), (\"forest\", RandomForestClassifier(random_state=42)), (\"svm\", SVC(probability=True, random_state=42))]\n",
    "\n",
    "hard = VotingClassifier(estimators=voters, voting=\"hard\")\n",
    "hard.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(hard.score(X_test_scaled, y_test), 4))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.7533\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t35p-036"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 16. A soft vote and a chart\n",
    "\n",
    "Make a soft `VotingClassifier` called `soft` with the same voters. Print its test accuracy and its AUC, rounded to 4 decimals. Then draw the test accuracies of `svm`, `hard` and `soft` as a bar chart."
   ],
   "id": "t35p-037"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "from sklearn.metrics import roc_auc_score\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t35p-038"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`voting=\"soft\"`; `roc_auc_score(y_test, soft.predict_proba(X_test_scaled)[:, 1])`; `plt.bar(names, 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",
    "from sklearn.metrics import roc_auc_score\n",
    "\n",
    "soft = VotingClassifier(estimators=voters, voting=\"soft\")\n",
    "soft.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(soft.score(X_test_scaled, y_test), 4))\n",
    "print(round(roc_auc_score(y_test, soft.predict_proba(X_test_scaled)[:, 1]), 4))\n",
    "\n",
    "names = [\"SVM\", \"hard vote\", \"soft vote\"]\n",
    "accuracies = [svm.score(X_test_scaled, y_test), hard.score(X_test_scaled, y_test), soft.score(X_test_scaled, y_test)]\n",
    "\n",
    "plt.bar(names, accuracies)\n",
    "plt.ylabel(\"test accuracy\")\n",
    "plt.show()\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.76\n",
    "0.7652\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t35p-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": "t35p-040"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
