{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 23: Practice\n",
    "\n",
    "Asiman Data School, Module 3: Comprehensive Machine Learning. Week 12, Tuesday.\n",
    "\n",
    "Eight problems in three levels, on the same ideas and at the same level as the lesson notebook.\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 flats.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`, `model`, `y_pred`): the later steps run after your own answers to the earlier ones, so solve them in order."
   ],
   "id": "t23p-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Steps 1 to 3: the data and the split"
   ],
   "id": "t23p-001"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 1. Read the data\n",
    "\n",
    "Import pandas and read `flats.csv` into `df`. Print the shape of `df`."
   ],
   "id": "t23p-002"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t23p-003"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`import pandas as pd`, then `df = pd.read_csv(\"flats.csv\")` and `print(df.shape)`.\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(\"flats.csv\")\n",
    "\n",
    "print(df.shape)\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "(200, 11)\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t23p-004"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 2. X and y\n",
    "\n",
    "Make `X` from the columns `area`, `rooms`, `age` and `distance_km`, and `y` from `price`. Print both shapes on one line. This step continues from Step 1."
   ],
   "id": "t23p-005"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t23p-006"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "A list of column names in double brackets: `X = df[[\"area\", \"rooms\", \"age\", \"distance_km\"]]`. Then `print(X.shape, y.shape)`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "X = df[[\"area\", \"rooms\", \"age\", \"distance_km\"]]\n",
    "y = df[\"price\"]\n",
    "\n",
    "print(X.shape, y.shape)\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "(200, 4) (200,)\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t23p-007"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 3. The split\n",
    "\n",
    "Split `X` and `y` into `X_train`, `X_test`, `y_train`, `y_test`: 25 percent for testing, `random_state=7`. Print the shapes of `X_train` and `X_test` on one line. This step continues from Step 2."
   ],
   "id": "t23p-008"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t23p-009"
  },
  {
   "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_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, 4) (50, 4)\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t23p-010"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Steps 4 to 6: the model"
   ],
   "id": "t23p-011"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 4. Train the model\n",
    "\n",
    "Create a `LinearRegression` called `model` and train it on the training data. Print the intercept (rounded to 2 decimals), then the weights (rounded to 2 decimals). This step continues from Step 3."
   ],
   "id": "t23p-012"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t23p-013"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`model.fit(X_train, y_train)`, then `print(round(model.intercept_, 2))` and `print(model.coef_.round(2))`.\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, y_train)\n",
    "\n",
    "print(round(model.intercept_, 2))\n",
    "print(model.coef_.round(2))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "44.35\n",
    "[ 1.34  9.73 -0.52 -3.48]\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t23p-014"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 5. The two scores\n",
    "\n",
    "Print the training score, then the test score, each rounded to 3 decimals. Is the gap normal? This step continues from Step 4."
   ],
   "id": "t23p-015"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t23p-016"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`model.score(X_train, y_train)` and `model.score(X_test, y_test)`. Two high scores that are almost equal are a good fit.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "print(round(model.score(X_train, y_train), 3))\n",
    "print(round(model.score(X_test, y_test), 3))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.948\n",
    "0.945\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t23p-017"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 6. Predict the test rows\n",
    "\n",
    "Store the predictions for the test rows in `y_pred`. Print the first five predictions (rounded to 1 decimal), then the first five true prices, `y_test.values[:5]`. This step continues from Step 4."
   ],
   "id": "t23p-018"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t23p-019"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`y_pred = model.predict(X_test)`, then `print(y_pred[:5].round(1))` and `print(y_test.values[:5])`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "y_pred = model.predict(X_test)\n",
    "\n",
    "print(y_pred[:5].round(1))\n",
    "print(y_test.values[:5])\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "[274.  103.7 178.2 236.  240.1]\n",
    "[272 108 185 262 238]\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t23p-020"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Steps 7 and 8: the measures"
   ],
   "id": "t23p-021"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 7. R², MSE and RMSE\n",
    "\n",
    "Print R², MSE and RMSE on the test data, on three lines: R² rounded to 3 decimals, the other two to 2 decimals. This step continues from Step 6."
   ],
   "id": "t23p-022"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t23p-023"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`r2_score`, `mean_squared_error` and `root_mean_squared_error` from `sklearn.metrics`, each with `y_test` first and `y_pred` second.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "from sklearn.metrics import mean_squared_error, r2_score, root_mean_squared_error\n",
    "\n",
    "print(round(r2_score(y_test, y_pred), 3))\n",
    "print(round(mean_squared_error(y_test, y_pred), 2))\n",
    "print(round(root_mean_squared_error(y_test, y_pred), 2))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.945\n",
    "227.89\n",
    "15.1\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t23p-024"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 8. Five folds\n",
    "\n",
    "Run a 5-fold cross-validation of a linear regression on `X` and `y`. Print the mean of the five scores, rounded to 3 decimals. Does it agree with the test score of Step 7? This step continues from Step 4."
   ],
   "id": "t23p-025"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t23p-026"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`from sklearn.model_selection import cross_val_score`, then `scores = cross_val_score(LinearRegression(), X, y, cv=5)` and `print(round(scores.mean(), 3))`. When the mean agrees with the test score of Step 7, the model is good and the one split was not a lucky accident.\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",
    "scores = cross_val_score(LinearRegression(), X, y, cv=5)\n",
    "\n",
    "print(round(scores.mean(), 3))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.94\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t23p-027"
  },
  {
   "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": "t23p-028"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
