{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 24: Practice\n",
    "\n",
    "Asiman Data School, Module 3: Comprehensive Machine Learning. Week 12, Thursday.\n",
    "\n",
    "Nine problems in three levels, on the same ideas and at the same level as the lesson notebook. They are numbered 4 to 12, as on the lesson page, where Problems 1 to 3 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 motorcycles.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`): the later steps run after your own answers to the earlier ones, so solve them in order."
   ],
   "id": "t24p-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Steps 4 to 6: the columns"
   ],
   "id": "t24p-001"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 4. Read and drop\n",
    "\n",
    "Read `motorcycles.csv` into `df` and drop the columns `bike_id`, `owner_name` and `wheels`. Print the names of the remaining columns as a list."
   ],
   "id": "t24p-002"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t24p-003"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`df = pd.read_csv(\"motorcycles.csv\")`, `df = df.drop(columns=[\"bike_id\", \"owner_name\", \"wheels\"])`, then `print(df.columns.tolist())`.\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(\"motorcycles.csv\")\n",
    "df = df.drop(columns=[\"bike_id\", \"owner_name\", \"wheels\"])\n",
    "\n",
    "print(df.columns.tolist())\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "['year', 'mileage_km', 'engine_cc', 'horsepower', 'weight_kg', 'seats', 'price']\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t24p-004"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 5. Two new features\n",
    "\n",
    "Create the columns `age` (2026 minus `year`) and `power_to_weight` (`horsepower` divided by `weight_kg`). Print the first three rows of these two columns, rounded to 3 decimals. This step continues from Step 4."
   ],
   "id": "t24p-005"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t24p-006"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`df[\"age\"] = 2026 - df[\"year\"]`. Then `print(df[[\"age\", \"power_to_weight\"]].head(3).round(3))`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "df[\"age\"] = 2026 - df[\"year\"]\n",
    "df[\"power_to_weight\"] = df[\"horsepower\"] / df[\"weight_kg\"]\n",
    "\n",
    "print(df[[\"age\", \"power_to_weight\"]].head(3).round(3))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "   age  power_to_weight\n",
    "0   13            0.470\n",
    "1    8            0.421\n",
    "2    9            0.931\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t24p-007"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 6. Correlations with the price\n",
    "\n",
    "Print the correlation of every column with `price`, rounded to 2 decimals and sorted from the smallest to the largest. This step continues from Step 5."
   ],
   "id": "t24p-008"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t24p-009"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`print(df.corr()[\"price\"].round(2).sort_values())`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "print(df.corr()[\"price\"].round(2).sort_values())\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "weight_kg         -0.42\n",
    "age               -0.40\n",
    "mileage_km        -0.36\n",
    "seats              0.06\n",
    "year               0.40\n",
    "engine_cc          0.74\n",
    "horsepower         0.76\n",
    "power_to_weight    0.89\n",
    "price              1.00\n",
    "Name: price, dtype: float64\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t24p-010"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Steps 7 to 9: split, scale, train"
   ],
   "id": "t24p-011"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 7. X, y and the split\n",
    "\n",
    "Make `X` from the columns `age`, `mileage_km`, `horsepower`, `weight_kg` and `power_to_weight`, and `y` from `price`. Split them into `X_train`, `X_test`, `y_train`, `y_test` with `test_size=0.25` and `random_state=7`. Print the shapes of `X_train` and `X_test` on one line. This step continues from Step 5."
   ],
   "id": "t24p-012"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t24p-013"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`from sklearn.model_selection import train_test_split`, then `train_test_split(X, y, test_size=0.25, random_state=7)`. It returns four pieces.\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[[\"age\", \"mileage_km\", \"horsepower\", \"weight_kg\", \"power_to_weight\"]]\n",
    "y = df[\"price\"]\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=7)\n",
    "\n",
    "print(X_train.shape, X_test.shape)\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "(150, 5) (50, 5)\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t24p-014"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 8. Scale after the split\n",
    "\n",
    "Create a `StandardScaler` called `scaler`. Fit it on the training data, and make `X_train_scaled` and `X_test_scaled`. Print the standard deviations of the columns of `X_train_scaled`, rounded to 2 decimals, then the column means of `X_test_scaled`, rounded to 2 decimals. This step continues from Step 7."
   ],
   "id": "t24p-015"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t24p-016"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`scaler.fit_transform(X_train)` for the training data and `scaler.transform(X_test)` for the test data. The standard deviations are `.std(axis=0).round(2)`, the means `.mean(axis=0).round(2)`. The training columns have the standard deviation 1; the means of the test data are close to 0, not exactly 0. If your numbers differ, check `test_size=0.25` and `random_state=7` in Step 7.\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_train_scaled.std(axis=0).round(2))\n",
    "print(X_test_scaled.mean(axis=0).round(2))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "[1. 1. 1. 1. 1.]\n",
    "[-0.26 -0.22  0.06 -0.06  0.12]\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t24p-017"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 9. Train on the scaled data\n",
    "\n",
    "Train a `LinearRegression` called `model` on the scaled training data. Print the training score, then the test score, each rounded to 3 decimals. This step continues from Step 8."
   ],
   "id": "t24p-018"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t24p-019"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`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 LinearRegression\n",
    "\n",
    "model = LinearRegression()\n",
    "model.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(model.score(X_train_scaled, y_train), 3))\n",
    "print(round(model.score(X_test_scaled, y_test), 3))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.957\n",
    "0.962\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t24p-020"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Steps 10 to 12: read and compare"
   ],
   "id": "t24p-021"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 10. Weights that can be compared\n",
    "\n",
    "Print the weight of every feature of `model` next to its name, rounded to 2 decimals, one feature on a line. Which feature has the largest effect? This step continues from Step 9."
   ],
   "id": "t24p-022"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t24p-023"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`for name, weight in zip(X.columns, model.coef_):` and inside the loop `print(name, round(weight, 2))`. The features were standardised, so the weight furthest from 0 has the largest effect.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "for name, weight in zip(X.columns, model.coef_):\n",
    "    print(name, round(weight, 2))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "age -0.91\n",
    "mileage_km -0.59\n",
    "horsepower 0.22\n",
    "weight_kg -0.13\n",
    "power_to_weight 2.52\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t24p-024"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 11. A model that walks\n",
    "\n",
    "Train an `SGDRegressor` with `random_state=0` on the scaled training data and print its test score, rounded to 3 decimals. This step continues from Step 8."
   ],
   "id": "t24p-025"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t24p-026"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`from sklearn.linear_model import SGDRegressor`. It is used exactly like `LinearRegression`: `fit` with the scaled training data, `score` with the scaled test data.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "from sklearn.linear_model import SGDRegressor\n",
    "\n",
    "sgd = SGDRegressor(random_state=0)\n",
    "sgd.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(sgd.score(X_test_scaled, y_test), 3))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.953\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t24p-027"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 12. Min-max and the test data\n",
    "\n",
    "Fit a `MinMaxScaler` on `X_train` and transform `X_test` with it. Print the smallest value of every column of the scaled test data, rounded to 2 decimals, then the largest value of every column. This step continues from Step 7."
   ],
   "id": "t24p-028"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t24p-029"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`.min(axis=0).round(2)` and `.max(axis=0).round(2)` of the transformed test data. The values do not have to lie exactly between 0 and 1: the limits come from the training data.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "from sklearn.preprocessing import MinMaxScaler\n",
    "\n",
    "minmax = MinMaxScaler()\n",
    "minmax.fit(X_train)\n",
    "X_test_minmax = minmax.transform(X_test)\n",
    "\n",
    "print(X_test_minmax.min(axis=0).round(2))\n",
    "print(X_test_minmax.max(axis=0).round(2))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "[0.   0.01 0.09 0.03 0.04]\n",
    "[1.   0.81 1.04 1.03 0.94]\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t24p-030"
  },
  {
   "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": "t24p-031"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
