{ "cells": [ { "cell_type": "markdown", "id": "191951c4", "metadata": {}, "source": [ "# Practice 02 · Linear regression in practice\n", "\n", "Machine Learning · DUT S3 · 2026-2027 · Dr. Soufiane Hourri\n", "\n", "**Before you start:** save this notebook as `Practice02_Lastname.ipynb` in your `ML_2026` folder, next to `penguins.csv` and `tips.csv`. Run each cell with **Shift+Enter**. Answer in a Markdown cell, with units." ] }, { "cell_type": "code", "execution_count": null, "id": "32c7d6cb", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import matplotlib.pyplot as plt\n", "from sklearn.model_selection import train_test_split\n", "from sklearn.linear_model import LinearRegression\n", "from sklearn.dummy import DummyRegressor\n", "from sklearn.metrics import mean_absolute_error, root_mean_squared_error, r2_score\n", "from sklearn.pipeline import make_pipeline\n", "from sklearn.compose import ColumnTransformer\n", "from sklearn.preprocessing import OneHotEncoder" ] }, { "cell_type": "markdown", "id": "649de00d", "metadata": {}, "source": [ "## Part A · Body mass from flipper length (guided)\n", "\n", "Run the two cells below, then answer the questions." ] }, { "cell_type": "code", "execution_count": null, "id": "8c6777b7", "metadata": {}, "outputs": [], "source": [ "df = pd.read_csv(\"penguins.csv\").dropna()\n", "print(df.shape)\n", "\n", "train, test = train_test_split(df, test_size=0.2, random_state=42)\n", "X_tr = train[[\"flipper_length_mm\"]]\n", "X_te = test[[\"flipper_length_mm\"]]\n", "y_tr = train[\"body_mass_g\"]\n", "y_te = test[\"body_mass_g\"]\n", "\n", "base = DummyRegressor().fit(X_tr, y_tr)\n", "p = base.predict(X_te)\n", "print(len(train), len(test), p[0])\n", "print(mean_absolute_error(y_te, p), r2_score(y_te, p))" ] }, { "cell_type": "code", "execution_count": null, "id": "dccefaf6", "metadata": {}, "outputs": [], "source": [ "lr = LinearRegression().fit(X_tr, y_tr)\n", "print(lr.coef_, lr.intercept_)\n", "\n", "p = lr.predict(X_te)\n", "print(mean_absolute_error(y_te, p))\n", "print(root_mean_squared_error(y_te, p))\n", "print(r2_score(y_te, p))" ] }, { "cell_type": "markdown", "id": "c7ee259e", "metadata": {}, "source": [ "**A1.** Interpret the slope for 1 mm and for 10 mm of flipper length." ] }, { "cell_type": "code", "execution_count": null, "id": "ffac4b18", "metadata": {}, "outputs": [], "source": [ "# your code\n" ] }, { "cell_type": "markdown", "id": "d1f5562c", "metadata": {}, "source": [ "*Your answer:*" ] }, { "cell_type": "markdown", "id": "acf36221", "metadata": {}, "source": [ "**A2.** Predict the mass of penguins with 200 mm and 150 mm flippers. Do you trust both predictions? (Check `df[\"flipper_length_mm\"].min()` and `.max()`.)" ] }, { "cell_type": "code", "execution_count": null, "id": "ab7d7253", "metadata": {}, "outputs": [], "source": [ "# your code\n" ] }, { "cell_type": "markdown", "id": "9430f961", "metadata": {}, "source": [ "*Your answer:*" ] }, { "cell_type": "markdown", "id": "49936572", "metadata": {}, "source": [ "**A3.** Compare MAE and R² with the baseline." ] }, { "cell_type": "code", "execution_count": null, "id": "195b1dd0", "metadata": {}, "outputs": [], "source": [ "# your code\n" ] }, { "cell_type": "markdown", "id": "527d33ff", "metadata": {}, "source": [ "*Your answer:*" ] }, { "cell_type": "markdown", "id": "ba3b9b48", "metadata": {}, "source": [ "**A4.** Plot the test residuals `y_te - p` against flipper length, with a horizontal line at 0 (`plt.axhline(0)`). Do you see a pattern?" ] }, { "cell_type": "code", "execution_count": null, "id": "eb3c2e1c", "metadata": {}, "outputs": [], "source": [ "# your code\n" ] }, { "cell_type": "markdown", "id": "dd9bee62", "metadata": {}, "source": [ "*Your answer:*" ] }, { "cell_type": "markdown", "id": "cc23c8c3", "metadata": {}, "source": [ "## Part B · Adding categories: species and sex\n", "\n", "Run the cell below: it fits bill depth with species." ] }, { "cell_type": "code", "execution_count": null, "id": "0ffc335d", "metadata": {}, "outputs": [], "source": [ "prep = ColumnTransformer([\n", " (\"num\", \"passthrough\", [\"bill_depth_mm\"]),\n", " (\"cat\", OneHotEncoder(drop=\"first\"), [\"species\"])])\n", "model = make_pipeline(prep, LinearRegression())\n", "cols = [\"bill_depth_mm\", \"species\"]\n", "model.fit(train[cols], y_tr)\n", "print(model[-1].coef_)" ] }, { "cell_type": "markdown", "id": "8b4334cb", "metadata": {}, "source": [ "**B1.** Fit `bill_depth_mm` alone, then with species (cell above). Compare the two slopes and the test R²." ] }, { "cell_type": "code", "execution_count": null, "id": "bac3f6f8", "metadata": {}, "outputs": [], "source": [ "# your code\n" ] }, { "cell_type": "markdown", "id": "52355df8", "metadata": {}, "source": [ "*Your answer:*" ] }, { "cell_type": "markdown", "id": "f6b70455", "metadata": {}, "source": [ "**B2.** Interpret the bill depth coefficient and the Gentoo coefficient of the model with species. Which species is the reference?" ] }, { "cell_type": "code", "execution_count": null, "id": "90520e93", "metadata": {}, "outputs": [], "source": [ "# your code\n" ] }, { "cell_type": "markdown", "id": "3ca39f81", "metadata": {}, "source": [ "*Your answer:*" ] }, { "cell_type": "markdown", "id": "f50cec94", "metadata": {}, "source": [ "**B3.** Add `flipper_length_mm`, `bill_length_mm` and `sex` (one-hot). Compute MAE, RMSE and R² on the test set. Interpret the `sex_Male` coefficient (`model[0].get_feature_names_out()` gives the names)." ] }, { "cell_type": "code", "execution_count": null, "id": "2580d96e", "metadata": {}, "outputs": [], "source": [ "# your code\n" ] }, { "cell_type": "markdown", "id": "c012287d", "metadata": {}, "source": [ "*Your answer:*" ] }, { "cell_type": "markdown", "id": "3568fcdb", "metadata": {}, "source": [ "**B4.** Predict the mass of a Gentoo female with a 210 mm flipper and a 45.0 × 15.0 mm bill. Use a one-row DataFrame with the same column names." ] }, { "cell_type": "code", "execution_count": null, "id": "867af5fe", "metadata": {}, "outputs": [], "source": [ "# your code\n" ] }, { "cell_type": "markdown", "id": "ba788d48", "metadata": {}, "source": [ "*Your answer:*" ] }, { "cell_type": "markdown", "id": "669355cd", "metadata": {}, "source": [ "## Part C · Restaurant tips, on your own\n", "\n", "`tips.csv`: 244 bills in US dollars. Columns: `total_bill`, `tip` (target), `sex`, `smoker`, `day`, `time`, `size`. Reuse the code of Parts A and B." ] }, { "cell_type": "markdown", "id": "2b4fc431", "metadata": {}, "source": [ "**C1.** Read `tips.csv`. How many rows? Mean tip? Correlation between `total_bill` and `tip`?" ] }, { "cell_type": "code", "execution_count": null, "id": "46491bfd", "metadata": {}, "outputs": [], "source": [ "# your code\n" ] }, { "cell_type": "markdown", "id": "fd513e88", "metadata": {}, "source": [ "*Your answer:*" ] }, { "cell_type": "markdown", "id": "51b61d5c", "metadata": {}, "source": [ "**C2.** Split (`test_size=0.2, random_state=42`) and compute the baseline MAE, RMSE and R² on the test set." ] }, { "cell_type": "code", "execution_count": null, "id": "57a7dd87", "metadata": {}, "outputs": [], "source": [ "# your code\n" ] }, { "cell_type": "markdown", "id": "b67eb0b4", "metadata": {}, "source": [ "*Your answer:*" ] }, { "cell_type": "markdown", "id": "ac4d8008", "metadata": {}, "source": [ "**C3.** Fit a model with `total_bill` only. Interpret the slope and the intercept. Predict the tip for a 20 $ bill." ] }, { "cell_type": "code", "execution_count": null, "id": "077879bf", "metadata": {}, "outputs": [], "source": [ "# your code\n" ] }, { "cell_type": "markdown", "id": "525c35fe", "metadata": {}, "source": [ "*Your answer:*" ] }, { "cell_type": "markdown", "id": "87f066f1", "metadata": {}, "source": [ "**C4.** Add `size`, then all columns (one-hot `sex`, `smoker`, `day`, `time`)." ] }, { "cell_type": "code", "execution_count": null, "id": "6ea1e686", "metadata": {}, "outputs": [], "source": [ "# your code\n" ] }, { "cell_type": "markdown", "id": "7c736379", "metadata": {}, "source": [ "*Your answer:*" ] }, { "cell_type": "markdown", "id": "8476b13b", "metadata": {}, "source": [ "**C5.** Build a table (a DataFrame) with MAE, RMSE, test R² and training R² for every model. Which model do you choose, and why?" ] }, { "cell_type": "code", "execution_count": null, "id": "f41da7d5", "metadata": {}, "outputs": [], "source": [ "# your code\n" ] }, { "cell_type": "markdown", "id": "55dc5ca5", "metadata": {}, "source": [ "*Your answer:*" ] }, { "cell_type": "markdown", "id": "90033f26", "metadata": {}, "source": [ "## Part D · Bonus, if you finish early" ] }, { "cell_type": "markdown", "id": "65023a44", "metadata": {}, "source": [ "**D1.** Create `tip_pct = 100 * tip / total_bill`. Mean, median, maximum? Look at the row with the maximum." ] }, { "cell_type": "code", "execution_count": null, "id": "8b42bd7f", "metadata": {}, "outputs": [], "source": [ "# your code\n" ] }, { "cell_type": "markdown", "id": "8c849559", "metadata": {}, "source": [ "*Your answer:*" ] }, { "cell_type": "markdown", "id": "92d1a725", "metadata": {}, "source": [ "**D2.** Compare the slope of C3 with the median percentage. What does the intercept change?" ] }, { "cell_type": "code", "execution_count": null, "id": "4cf5545f", "metadata": {}, "outputs": [], "source": [ "# your code\n" ] }, { "cell_type": "markdown", "id": "910ffd7d", "metadata": {}, "source": [ "*Your answer:*" ] }, { "cell_type": "markdown", "id": "1f0c3382", "metadata": {}, "source": [ "**D3.** Predict the tip for a 100 $ bill. Can you trust it?" ] }, { "cell_type": "code", "execution_count": null, "id": "315808ff", "metadata": {}, "outputs": [], "source": [ "# your code\n" ] }, { "cell_type": "markdown", "id": "2feaebfc", "metadata": {}, "source": [ "*Your answer:*" ] }, { "cell_type": "markdown", "id": "f783918a", "metadata": {}, "source": [ "**D4.** Plot the residuals of the C3 model against `total_bill`. What shape do you see?" ] }, { "cell_type": "code", "execution_count": null, "id": "f161a0ba", "metadata": {}, "outputs": [], "source": [ "# your code\n" ] }, { "cell_type": "markdown", "id": "a5cc93e7", "metadata": {}, "source": [ "*Your answer:*" ] }, { "cell_type": "markdown", "id": "e7f4e307", "metadata": {}, "source": [ "## Before you leave\n", "\n", "Kernel > Restart Kernel and Run All Cells, then File > Save and Export Notebook As > HTML." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 5 }