{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 31: Practice\n",
    "\n",
    "Asiman Data School, Module 3: Comprehensive Machine Learning. Week 16, 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 car_prices.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`, `tuned`, `bagged_trees`): the later steps run after your own answers to the earlier ones, so solve them in order. The steps that train forests take a few seconds. The last step also draws a chart: it is accepted when the number is right and a chart was drawn."
   ],
   "id": "t31p-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Steps 5 to 8: from the raw file to the encoded table"
   ],
   "id": "t31p-001"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 5. Read the raw file\n",
    "\n",
    "Read `car_prices.csv` into `df`. Print the shape, then the number of repeated rows."
   ],
   "id": "t31p-002"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t31p-003"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`df = pd.read_csv(\"car_prices.csv\")`, then `print(df.shape)` and `print(df.duplicated().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(\"car_prices.csv\")\n",
    "\n",
    "print(df.shape)\n",
    "print(df.duplicated().sum())\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "(10000, 19)\n",
    "691\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t31p-004"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 6. Copies and impossible rows\n",
    "\n",
    "Drop the repeated rows, then keep only the cars made in 1950 or later and with at most 1,000,000 km. Print the number of rows. This step continues from Step 5."
   ],
   "id": "t31p-005"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t31p-006"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`df = df.drop_duplicates()`, then `df = df[(df[\"year\"] >= 1950) & (df[\"mileage_km\"] <= 1_000_000)]`, then `print(len(df))`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "df = df.drop_duplicates()\n",
    "df = df[(df[\"year\"] >= 1950) & (df[\"mileage_km\"] <= 1_000_000)]\n",
    "\n",
    "print(len(df))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "9259\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t31p-007"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 7. The categories\n",
    "\n",
    "Drop the column `model`, group the brands with fewer than 50 cars as `\"other\"`, and fill the missing `market` with `\"unknown\"`. Print the number of cars whose brand is now `\"other\"`."
   ],
   "id": "t31p-008"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t31p-009"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`counts = df[\"brand\"].value_counts()`, `rare = counts[counts < 50].index`, `df.loc[df[\"brand\"].isin(rare), \"brand\"] = \"other\"`; then `print((df[\"brand\"] == \"other\").sum())`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "df = df.drop(columns=[\"model\"])\n",
    "\n",
    "counts = df[\"brand\"].value_counts()\n",
    "rare = counts[counts < 50].index\n",
    "df.loc[df[\"brand\"].isin(rare), \"brand\"] = \"other\"\n",
    "\n",
    "df[\"market\"] = df[\"market\"].fillna(\"unknown\")\n",
    "\n",
    "print((df[\"brand\"] == \"other\").sum())\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "864\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t31p-010"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 8. Encode\n",
    "\n",
    "One-hot encode the eight text columns of `text_columns` with `drop_first=True` and `dtype=int`. Print the number of columns."
   ],
   "id": "t31p-011"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "text_columns = [\"brand\", \"fuel\", \"gearbox\", \"drive\", \"body\", \"colour\", \"market\", \"city\"]\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t31p-012"
  },
  {
   "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 `print(len(df.columns))`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "text_columns = [\"brand\", \"fuel\", \"gearbox\", \"drive\", \"body\", \"colour\", \"market\", \"city\"]\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",
    "84\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t31p-013"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Steps 9 to 12: split, fill, the random forest and its errors"
   ],
   "id": "t31p-014"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 9. Split\n",
    "\n",
    "Make `X` (all columns without `price_azn`) and `y`. Split them with `test_size=0.3` and `random_state=1`. Print the number of test cars, then their mean price rounded to 1 decimal."
   ],
   "id": "t31p-015"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t31p-016"
  },
  {
   "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 `round(y_test.mean(), 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=[\"price_azn\"])\n",
    "y = df[\"price_azn\"]\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(round(y_test.mean(), 1))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "2778\n",
    "23117.4\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t31p-017"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 10. Fill with the training medians\n",
    "\n",
    "Fill `horsepower`, `seats` and `owners` in `X_train` and `X_test` with the medians of the training data. Print the median of `horsepower`, then the number of missing values left in `X_test`."
   ],
   "id": "t31p-018"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t31p-019"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`medians = X_train[[\"horsepower\", \"seats\", \"owners\"]].median()`, then `X_train = X_train.fillna(medians)` and the same for `X_test`; `medians[\"horsepower\"]` and `X_test.isna().sum().sum()`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "medians = X_train[[\"horsepower\", \"seats\", \"owners\"]].median()\n",
    "\n",
    "X_train = X_train.fillna(medians)\n",
    "X_test = X_test.fillna(medians)\n",
    "\n",
    "print(medians[\"horsepower\"])\n",
    "print(X_test.isna().sum().sum())\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "150.0\n",
    "0\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t31p-020"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 11. A random forest\n",
    "\n",
    "Train a `RandomForestRegressor` called `forest` with `random_state=42`. Print its test R², rounded to 4 decimals."
   ],
   "id": "t31p-021"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.ensemble import RandomForestRegressor\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t31p-022"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`forest = RandomForestRegressor(random_state=42)`, `forest.fit(X_train, y_train)`, then `forest.score(X_test, y_test)`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "from sklearn.ensemble import RandomForestRegressor\n",
    "\n",
    "forest = RandomForestRegressor(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.8589\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t31p-023"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 12. Its errors in manats\n",
    "\n",
    "Put the predictions of `forest` for the test cars into `predicted`. Print the MAE and the RMSE as whole numbers."
   ],
   "id": "t31p-024"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import mean_absolute_error, root_mean_squared_error\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t31p-025"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`predicted = forest.predict(X_test)`, then `round(mean_absolute_error(y_test, predicted))` and the same with `root_mean_squared_error`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "from sklearn.metrics import mean_absolute_error, root_mean_squared_error\n",
    "\n",
    "predicted = forest.predict(X_test)\n",
    "\n",
    "print(round(mean_absolute_error(y_test, predicted)))\n",
    "print(round(root_mean_squared_error(y_test, predicted)))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "2709\n",
    "5113\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t31p-026"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Steps 13 to 16: OOB, tuning, bagging and the scores"
   ],
   "id": "t31p-027"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 13. The OOB R²\n",
    "\n",
    "Train a forest with `max_features=0.5`, `oob_score=True` and `random_state=42`. Print its OOB R², rounded to 4 decimals."
   ],
   "id": "t31p-028"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t31p-029"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`model = RandomForestRegressor(max_features=0.5, oob_score=True, random_state=42)`, `fit`, then `model.oob_score_`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "oob_forest = RandomForestRegressor(max_features=0.5, 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.8615\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t31p-030"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 14. The tuned forest\n",
    "\n",
    "Train a forest called `tuned` with `max_features=0.5` and `random_state=42`. Print its test R² rounded to 4 decimals, then the name of its most important feature."
   ],
   "id": "t31p-031"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t31p-032"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`tuned.score(X_test, y_test)`; `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 = RandomForestRegressor(max_features=0.5, random_state=42)\n",
    "tuned.fit(X_train, y_train)\n",
    "\n",
    "print(round(tuned.score(X_test, y_test), 4))\n",
    "print(pd.Series(tuned.feature_importances_, index=X.columns).idxmax())\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.8646\n",
    "year\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t31p-033"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 15. Bagged trees\n",
    "\n",
    "Train a `BaggingRegressor` of 100 full decision trees with `random_state=42`, called `bagged_trees`. Print its test R², rounded to 4 decimals."
   ],
   "id": "t31p-034"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.ensemble import BaggingRegressor\n",
    "from sklearn.tree import DecisionTreeRegressor\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t31p-035"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`bagged_trees = BaggingRegressor(estimator=DecisionTreeRegressor(), n_estimators=100, random_state=42)`, `fit`, then `score`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "from sklearn.ensemble import BaggingRegressor\n",
    "from sklearn.tree import DecisionTreeRegressor\n",
    "\n",
    "bagged_trees = BaggingRegressor(estimator=DecisionTreeRegressor(), 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",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.8581\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t31p-036"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 16. Bagged linear regression and the chart\n",
    "\n",
    "Train a `BaggingRegressor` of 100 linear regressions with `random_state=42` and print its test R², rounded to 4 decimals. Then draw the test R² of `forest`, `tuned`, `bagged_trees` and the bagged linear regression as horizontal bars."
   ],
   "id": "t31p-037"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "from sklearn.linear_model import LinearRegression\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t31p-038"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`BaggingRegressor(estimator=LinearRegression(), n_estimators=100, random_state=42)` on `X_train` (no scaling needed); a list of four names, a list of four scores, `plt.barh(names, r2s)` 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.linear_model import LinearRegression\n",
    "\n",
    "bagged_linear = BaggingRegressor(estimator=LinearRegression(), n_estimators=100, random_state=42)\n",
    "bagged_linear.fit(X_train, y_train)\n",
    "\n",
    "print(round(bagged_linear.score(X_test, y_test), 4))\n",
    "\n",
    "names = [\"random forest\", \"tuned forest\", \"bagged trees\", \"bagged linear regression\"]\n",
    "r2s = [\n",
    "    forest.score(X_test, y_test),\n",
    "    tuned.score(X_test, y_test),\n",
    "    bagged_trees.score(X_test, y_test),\n",
    "    bagged_linear.score(X_test, y_test),\n",
    "]\n",
    "\n",
    "plt.barh(names, r2s)\n",
    "plt.xlabel(\"test R²\")\n",
    "plt.show()\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.7037\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t31p-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": "t31p-040"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
