{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 33: Practice\n",
    "\n",
    "Asiman Data School, Module 3: Comprehensive Machine Learning. Week 17, 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`, `X_train_scaled`, `X_test_scaled`, `knn`, `predicted`, `X_train_few`, `X_test_few`): 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": "t33p-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Steps 5 to 8: from the raw file to the split"
   ],
   "id": "t33p-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": "t33p-002"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t33p-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": "t33p-004"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 6. Copies, impossible rows, the model column\n",
    "\n",
    "Drop the repeated rows, keep only the cars made in 1950 or later with at most 1,000,000 km, and drop the column `model`. Print the number of rows. This step continues from Step 5."
   ],
   "id": "t33p-005"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t33p-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 `df.drop(columns=[\"model\"])` and `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",
    "df = df.drop(columns=[\"model\"])\n",
    "\n",
    "print(len(df))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "9259\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t33p-007"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 7. Categories and encoding\n",
    "\n",
    "Group the brands with fewer than 50 cars as `\"other\"`, fill the missing `market` with `\"unknown\"`, and one-hot encode the columns of `text_columns` with `drop_first=True` and `dtype=int`. Print the number of columns."
   ],
   "id": "t33p-008"
  },
  {
   "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": "t33p-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 `fillna(\"unknown\")` and `pd.get_dummies(df, columns=text_columns, drop_first=True, dtype=int)`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\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",
    "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": "t33p-010"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 8. 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": "t33p-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": "t33p-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 `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": "t33p-013"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Steps 9 to 12: fill, scale, the model and k"
   ],
   "id": "t33p-014"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 9. Fill and scale\n",
    "\n",
    "Fill `horsepower`, `seats` and `owners` in both parts with the training medians. Then fit a `StandardScaler` on `X_train` and scale both parts into `X_train_scaled` and `X_test_scaled`. Print the shape of `X_test_scaled`."
   ],
   "id": "t33p-015"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import StandardScaler\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t33p-016"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`medians = X_train[[\"horsepower\", \"seats\", \"owners\"]].median()`, `fillna(medians)` on both parts; then `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",
    "medians = X_train[[\"horsepower\", \"seats\", \"owners\"]].median()\n",
    "X_train = X_train.fillna(medians)\n",
    "X_test = X_test.fillna(medians)\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",
    "(2778, 83)\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t33p-017"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 10. The default model\n",
    "\n",
    "Train a `KNeighborsRegressor` called `knn` with its default settings on the scaled data. Print its test R², rounded to 4 decimals."
   ],
   "id": "t33p-018"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.neighbors import KNeighborsRegressor\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t33p-019"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`knn = KNeighborsRegressor()`, `knn.fit(X_train_scaled, y_train)`, then `knn.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.neighbors import KNeighborsRegressor\n",
    "\n",
    "knn = KNeighborsRegressor()\n",
    "knn.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(knn.score(X_test_scaled, y_test), 4))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.6296\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t33p-020"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 11. Its errors in manats\n",
    "\n",
    "Put the predictions of `knn` into `predicted`. Print the MAE and the RMSE as whole numbers."
   ],
   "id": "t33p-021"
  },
  {
   "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": "t33p-022"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`predicted = knn.predict(X_test_scaled)`, 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 = knn.predict(X_test_scaled)\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",
    "5178\n",
    "8284\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t33p-023"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 12. Three values of k\n",
    "\n",
    "For k = 1, 5 and 25, print k, the training R² and the test R², rounded to 4 decimals."
   ],
   "id": "t33p-024"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t33p-025"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "A loop over `[1, 5, 25]`; `KNeighborsRegressor(n_neighbors=k)`, `fit`, then `score` on both parts.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "for k in [1, 5, 25]:\n",
    "    model = KNeighborsRegressor(n_neighbors=k)\n",
    "    model.fit(X_train_scaled, y_train)\n",
    "    print(k, round(model.score(X_train_scaled, y_train), 4), round(model.score(X_test_scaled, y_test), 4))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "1 0.9991 0.5287\n",
    "5 0.7554 0.6296\n",
    "25 0.6021 0.5564\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t33p-026"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Steps 13 to 16: weights, nine features and the tuned model"
   ],
   "id": "t33p-027"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 13. Weighted and Manhattan\n",
    "\n",
    "Train a model with k = 5, `weights=\"distance\"` and `p=1` on the scaled data. Print its test R², rounded to 4 decimals."
   ],
   "id": "t33p-028"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t33p-029"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`KNeighborsRegressor(n_neighbors=5, weights=\"distance\", p=1)`, `fit`, then `score`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "model = KNeighborsRegressor(n_neighbors=5, weights=\"distance\", p=1)\n",
    "model.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(model.score(X_test_scaled, y_test), 4))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.7048\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t33p-030"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 14. Nine features\n",
    "\n",
    "Scale only the nine features of `columns` with a new `StandardScaler` into `X_train_few` and `X_test_few`, train a default `KNeighborsRegressor` called `knn_few` on them, and print its test R², rounded to 4 decimals."
   ],
   "id": "t33p-031"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "columns = [\"year\", \"engine_l\", \"horsepower\", \"mileage_km\", \"is_new\", \"gearbox_manual\", \"drive_front\", \"fuel_petrol\", \"body_sedan\"]\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t33p-032"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`scaler_few = StandardScaler()`, `X_train_few = scaler_few.fit_transform(X_train[columns])`, `X_test_few = scaler_few.transform(X_test[columns])`, then `fit` and `score`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "columns = [\"year\", \"engine_l\", \"horsepower\", \"mileage_km\", \"is_new\", \"gearbox_manual\", \"drive_front\", \"fuel_petrol\", \"body_sedan\"]\n",
    "\n",
    "scaler_few = StandardScaler()\n",
    "X_train_few = scaler_few.fit_transform(X_train[columns])\n",
    "X_test_few = scaler_few.transform(X_test[columns])\n",
    "\n",
    "knn_few = KNeighborsRegressor()\n",
    "knn_few.fit(X_train_few, y_train)\n",
    "\n",
    "print(round(knn_few.score(X_test_few, y_test), 4))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.7934\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t33p-033"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 15. k with cross-validation\n",
    "\n",
    "On the nine features, for k = 5, 7 and 10 with `weights=\"distance\"`, print k and the mean R² of a 5-fold cross-validation, rounded to 4 decimals."
   ],
   "id": "t33p-034"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import cross_val_score\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t33p-035"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "A loop over `[5, 7, 10]`; `cross_val_score(KNeighborsRegressor(n_neighbors=k, weights=\"distance\"), X_train_few, 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 k in [5, 7, 10]:\n",
    "    scores = cross_val_score(KNeighborsRegressor(n_neighbors=k, weights=\"distance\"), X_train_few, y_train, cv=5)\n",
    "    print(k, round(scores.mean(), 4))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "5 0.7811\n",
    "7 0.7831\n",
    "10 0.781\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t33p-036"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 16. The tuned model and a chart\n",
    "\n",
    "Train a model with k = 7 and `weights=\"distance\"` on the nine features. Print its test R² rounded to 4 decimals, then draw its predicted prices against the true test prices as a scatter plot."
   ],
   "id": "t33p-037"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t33p-038"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`tuned.predict(X_test_few)`; `plt.scatter(y_test, tuned_predicted)` 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",
    "\n",
    "tuned = KNeighborsRegressor(n_neighbors=7, weights=\"distance\")\n",
    "tuned.fit(X_train_few, y_train)\n",
    "\n",
    "tuned_predicted = tuned.predict(X_test_few)\n",
    "\n",
    "print(round(tuned.score(X_test_few, y_test), 4))\n",
    "\n",
    "plt.scatter(y_test, tuned_predicted, s=6)\n",
    "plt.xlabel(\"true price (AZN)\")\n",
    "plt.ylabel(\"predicted price (AZN)\")\n",
    "plt.show()\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.8251\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t33p-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": "t33p-040"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
