{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 26: Practice\n",
    "\n",
    "Asiman Data School, Module 3: Comprehensive Machine Learning. Week 13, Thursday.\n",
    "\n",
    "Thirteen problems in three levels, on the same ideas and at the same level as the lesson notebook. They are numbered 4 to 16, 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 Housing.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`, `linear`, `ridge`, `lasso`, `elastic`): the later steps run after your own answers to the earlier ones, so solve them in order."
   ],
   "id": "t26p-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Steps 4 to 8: look and prepare"
   ],
   "id": "t26p-001"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 4. Read and check\n",
    "\n",
    "Read `Housing.csv` into `df`. Print the shape, then the number of missing values."
   ],
   "id": "t26p-002"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t26p-003"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`df = pd.read_csv(\"Housing.csv\")`, then `print(df.shape)` and `print(df.isna().sum().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(\"Housing.csv\")\n",
    "\n",
    "print(df.shape)\n",
    "print(df.isna().sum().sum())\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "(545, 13)\n",
    "0\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t26p-004"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 5. Outliers of the area\n",
    "\n",
    "Calculate the upper limit of the IQR rule for `area`. Print the limit, then the number of areas above it. (They are real houses and stay in the data.) This step continues from Step 4."
   ],
   "id": "t26p-005"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t26p-006"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`q1 = df[\"area\"].quantile(0.25)`, the same with `0.75` for `q3`, then `upper = q3 + 1.5 * (q3 - q1)`. The number of areas above it is `(df[\"area\"] > upper).sum()`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "q1 = df[\"area\"].quantile(0.25)\n",
    "q3 = df[\"area\"].quantile(0.75)\n",
    "upper = q3 + 1.5 * (q3 - q1)\n",
    "\n",
    "print(upper)\n",
    "print((df[\"area\"] > upper).sum())\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "10500.0\n",
    "12\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t26p-007"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 6. The price in millions\n",
    "\n",
    "Turn `price` into millions: divide it by 1,000,000. Print the smallest and the largest price on one line. This step continues from Step 4."
   ],
   "id": "t26p-008"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t26p-009"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`df[\"price\"] = df[\"price\"] / 1000000`, then `print(df[\"price\"].min(), df[\"price\"].max())`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "df[\"price\"] = df[\"price\"] / 1000000\n",
    "\n",
    "print(df[\"price\"].min(), df[\"price\"].max())\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "1.75 13.3\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t26p-010"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 7. Yes and no\n",
    "\n",
    "Encode the six yes/no columns as 1 (yes) and 0 (no). The list of their names is in the editor. Print how many houses have air conditioning. This step continues from Step 6."
   ],
   "id": "t26p-011"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "yes_no = [\"mainroad\", \"guestroom\", \"basement\", \"hotwaterheating\", \"airconditioning\", \"prefarea\"]\n",
    "\n",
    "# Write your code here"
   ],
   "id": "t26p-012"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "A loop: `for name in yes_no:` and inside it `df[name] = df[name].map({\"no\": 0, \"yes\": 1})`. The number of houses is the sum of the column: `print(df[\"airconditioning\"].sum())`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "yes_no = [\"mainroad\", \"guestroom\", \"basement\", \"hotwaterheating\", \"airconditioning\", \"prefarea\"]\n",
    "\n",
    "for name in yes_no:\n",
    "    df[name] = df[name].map({\"no\": 0, \"yes\": 1})\n",
    "\n",
    "print(df[\"airconditioning\"].sum())\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "172\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t26p-013"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 8. The furnishing in order\n",
    "\n",
    "Encode `furnishingstatus` in its order: unfurnished 0, semi-furnished 1, furnished 2. Print the mean of the column, rounded to 2 decimals. This step continues from Step 7."
   ],
   "id": "t26p-014"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t26p-015"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`df[\"furnishingstatus\"] = df[\"furnishingstatus\"].map({\"unfurnished\": 0, \"semi-furnished\": 1, \"furnished\": 2})`, then `print(round(df[\"furnishingstatus\"].mean(), 2))`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "df[\"furnishingstatus\"] = df[\"furnishingstatus\"].map({\"unfurnished\": 0, \"semi-furnished\": 1, \"furnished\": 2})\n",
    "\n",
    "print(round(df[\"furnishingstatus\"].mean(), 2))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.93\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t26p-016"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Steps 9 to 11: split, scale, a first model"
   ],
   "id": "t26p-017"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 9. Split\n",
    "\n",
    "Make `X` (all columns without `price`) and `y` (`price`). Split them with `test_size=0.3` and `random_state=1`. Print the shapes of `X_train` and `X_test` on one line. This step continues from Step 8."
   ],
   "id": "t26p-018"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t26p-019"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`from sklearn.model_selection import train_test_split`, `X = df.drop(columns=[\"price\"])`, `y = df[\"price\"]`, then `X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=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\"])\n",
    "y = df[\"price\"]\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(X_train.shape, X_test.shape)\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "(381, 12) (164, 12)\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t26p-020"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 10. Scale\n",
    "\n",
    "Scale the features with a `StandardScaler` called `scaler` into `X_train_scaled` and `X_test_scaled`. Print the largest value of the scaled test data, rounded to 2 decimals. This step continues from Step 9."
   ],
   "id": "t26p-021"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t26p-022"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`from sklearn.preprocessing import StandardScaler`, `scaler.fit_transform(X_train)` for the training data and `scaler.transform(X_test)` for the test data, then `print(round(X_test_scaled.max(), 2))`. If your number differs, check `test_size=0.3` and `random_state=1` in Step 9.\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(round(X_test_scaled.max(), 2))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "4.49\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t26p-023"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 11. The starting point\n",
    "\n",
    "Train a `LinearRegression` called `linear` on the scaled training data. Print the training score, then the test score, each rounded to 3 decimals. This step continues from Step 10."
   ],
   "id": "t26p-024"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t26p-025"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`from sklearn.linear_model import LinearRegression`, `linear.fit(X_train_scaled, y_train)`, then `linear.score(X_train_scaled, y_train)` and `linear.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",
    "linear = LinearRegression()\n",
    "linear.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(linear.score(X_train_scaled, y_train), 3))\n",
    "print(round(linear.score(X_test_scaled, y_test), 3))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.68\n",
    "0.662\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t26p-026"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Steps 12 to 16: regularize, tune, compare"
   ],
   "id": "t26p-027"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 12. Ridge\n",
    "\n",
    "Train a `Ridge` called `ridge` with `alpha=100`. Print its training score, then its test score, each rounded to 3 decimals. This step continues from Step 10."
   ],
   "id": "t26p-028"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t26p-029"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`from sklearn.linear_model import Ridge`, then `ridge = Ridge(alpha=100)`. It is used exactly like `LinearRegression`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "from sklearn.linear_model import Ridge\n",
    "\n",
    "ridge = Ridge(alpha=100)\n",
    "ridge.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(ridge.score(X_train_scaled, y_train), 3))\n",
    "print(round(ridge.score(X_test_scaled, y_test), 3))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.669\n",
    "0.653\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t26p-030"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 13. Lasso and the weights that become 0\n",
    "\n",
    "Train a `Lasso` called `lasso` with `alpha=0.3`. Print the number of weights that are not 0, then the names of the features whose weight is 0, as a list. This step continues from Step 10."
   ],
   "id": "t26p-031"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t26p-032"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`from sklearn.linear_model import Lasso`. The number is `(lasso.coef_ != 0).sum()`, the names are `X.columns[lasso.coef_ == 0].tolist()`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "from sklearn.linear_model import Lasso\n",
    "\n",
    "lasso = Lasso(alpha=0.3)\n",
    "lasso.fit(X_train_scaled, y_train)\n",
    "\n",
    "print((lasso.coef_ != 0).sum())\n",
    "print(X.columns[lasso.coef_ == 0].tolist())\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "9\n",
    "['bedrooms', 'guestroom', 'hotwaterheating']\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t26p-033"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 14. Elastic net\n",
    "\n",
    "Train an `ElasticNet` called `elastic` with `alpha=0.05` and `l1_ratio=0.5`. Print its training score, then its test score, each rounded to 3 decimals, then the number of weights that are not 0. This step continues from Step 10."
   ],
   "id": "t26p-034"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t26p-035"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`from sklearn.linear_model import ElasticNet`, then `elastic = ElasticNet(alpha=0.05, l1_ratio=0.5)`. It is used like the other models; the number of weights is `(elastic.coef_ != 0).sum()`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "from sklearn.linear_model import ElasticNet\n",
    "\n",
    "elastic = ElasticNet(alpha=0.05, l1_ratio=0.5)\n",
    "elastic.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(elastic.score(X_train_scaled, y_train), 3))\n",
    "print(round(elastic.score(X_test_scaled, y_test), 3))\n",
    "print((elastic.coef_ != 0).sum())\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.678\n",
    "0.658\n",
    "12\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t26p-036"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 15. Choosing alpha\n",
    "\n",
    "Compare the elastic net alphas 0.01, 0.05, 0.1 and 0.3 (with `l1_ratio=0.5`) with a 5-fold cross-validation on the training data. Print every alpha with its mean score, rounded to 3 decimals, one alpha on a line. This step continues from Step 14."
   ],
   "id": "t26p-037"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t26p-038"
  },
  {
   "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 a loop: `for alpha in [0.01, 0.05, 0.1, 0.3]:` with `scores = cross_val_score(ElasticNet(alpha=alpha, l1_ratio=0.5), X_train_scaled, y_train, cv=5)` and `print(alpha, round(scores.mean(), 3))`.\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 alpha in [0.01, 0.05, 0.1, 0.3]:\n",
    "    scores = cross_val_score(ElasticNet(alpha=alpha, l1_ratio=0.5), X_train_scaled, y_train, cv=5)\n",
    "    print(alpha, round(scores.mean(), 3))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.01 0.643\n",
    "0.05 0.641\n",
    "0.1 0.635\n",
    "0.3 0.586\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t26p-039"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 16. The four models side by side\n",
    "\n",
    "Print the test scores of `linear`, `ridge`, `lasso` and `elastic` on four lines, each rounded to 3 decimals. Which model would you use? This step continues from Steps 11 to 14."
   ],
   "id": "t26p-040"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t26p-041"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`print(round(linear.score(X_test_scaled, y_test), 3))`, and the same for the other three. The plain model, the Ridge and the elastic net are close together, so the simplest one, plain linear regression, is a sensible choice here. The strong Lasso of Step 13 paid for the features it removed.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "print(round(linear.score(X_test_scaled, y_test), 3))\n",
    "print(round(ridge.score(X_test_scaled, y_test), 3))\n",
    "print(round(lasso.score(X_test_scaled, y_test), 3))\n",
    "print(round(elastic.score(X_test_scaled, y_test), 3))\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "0.662\n",
    "0.653\n",
    "0.512\n",
    "0.658\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t26p-042"
  },
  {
   "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": "t26p-043"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
