{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.11"
  },
  "colab": {
   "name": "week-03-practice.ipynb",
   "provenance": []
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "# Week 03: Regression, classification, and baselines\n\nMachine Learning in Engineering Science | NCKU + LAiMM | Fall 2026\n\n**Purpose:** a fully worked, self-paced in-class practice with an optional extension. Weeks 11 and 18 are optional examination-readiness materials. These notebooks do not create weekly graded assignments.\n\n**Before running:** choose a Python 3 kernel in Jupyter or a CPU runtime in Colab. Run every cell from top to bottom with Shift+Enter. Setup installs missing free packages. No API key or external dataset download is required.\n\n**Learning target:** complete the calculation, inspect intermediate values, and explain why the protocol supports a limited claim.\n\n**Time:** about 25-45 minutes including reading, prediction, execution, and explain-back.\n",
   "id": "cell-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 1. Set up and record the environment\n\nKeep the seed fixed for the first run. Record actual outputs and package versions rather than copying a claimed performance number.\n",
   "id": "cell-001"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "metadata": {},
   "source": "import sys, subprocess, importlib.util, platform, json, random, hashlib\nfrom pathlib import Path\nrequired = {\"numpy\": \"numpy\", \"matplotlib\": \"matplotlib\", \"sklearn\": \"scikit-learn\"}\nmissing = [package for module, package in required.items() if importlib.util.find_spec(module) is None]\nif missing:\n    subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", *missing])\nimport numpy as np\nimport matplotlib.pyplot as plt\nSEED = 2026\nrandom.seed(SEED)\nnp.random.seed(SEED)\nrng = np.random.default_rng(SEED)\nARTIFACTS = Path(\"artifacts\")\nARTIFACTS.mkdir(exist_ok=True)\nprint(\"Python:\", platform.python_version(), \"NumPy:\", np.__version__, \"Seed:\", SEED)\n",
   "id": "cell-002"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**Checkpoint.** The environment cell must finish before any analysis cell. Restart and run all if a variable is missing.\n",
   "id": "cell-003"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 2. Generate a regression problem\n\nThe target is continuous. Generate data from a known linear mechanism plus noise, then hold out test rows before fitting.\n",
   "id": "cell-004"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "metadata": {},
   "source": "from sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import Ridge,LogisticRegression\nfrom sklearn.dummy import DummyRegressor\nfrom sklearn.metrics import mean_absolute_error,accuracy_score\nX=rng.normal(size=(240,3)); y=3*X[:,0]-2*X[:,1]+rng.normal(0,.5,240)\nXtr,Xte,ytr,yte=train_test_split(X,y,test_size=.25,random_state=SEED)\nbaseline=DummyRegressor().fit(Xtr,ytr); regression=Ridge(alpha=1).fit(Xtr,ytr)\nprint(\"Mean baseline MAE:\",mean_absolute_error(yte,baseline.predict(Xte)))\nprint(\"Ridge MAE:\",mean_absolute_error(yte,regression.predict(Xte)))\n",
   "id": "cell-005"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**Checkpoint.** MAE is in target units. Predicting the training mean is a meaningful baseline, even when the fitted model performs better.\n",
   "id": "cell-006"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 3. Change the question to classification\n\nDefine whether the response exceeds zero. This changes the prediction target and metric; it does not turn a regression output into a calibrated probability.\n",
   "id": "cell-007"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "metadata": {},
   "source": "labels=(y>0).astype(int)\nAtr,Ate,btr,bte=train_test_split(X,labels,test_size=.25,stratify=labels,random_state=SEED)\nclassifier=LogisticRegression(random_state=SEED).fit(Atr,btr)\nprobability=classifier.predict_proba(Ate)[:,1]\nsummary={\"ridge_test_mae\":float(mean_absolute_error(yte,regression.predict(Xte))),\n         \"classification_accuracy\":float(accuracy_score(bte,probability>=.5))}\nprint(summary)\n",
   "id": "cell-008"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**Checkpoint.** Describe the event represented by class 1 and why accuracy and MAE answer different questions.\n",
   "id": "cell-009"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 4. Plot predicted versus observed\n\nA diagonal reference line shows perfect predictions. Residual scatter conveys error structure.\n",
   "id": "cell-010"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "metadata": {},
   "source": "prediction=regression.predict(Xte)\nplt.scatter(yte,prediction); limits=[min(yte),max(yte)]\nplt.plot(limits,limits,\"k--\"); plt.xlabel(\"Observed synthetic response\")\nplt.ylabel(\"Predicted response\"); plt.show()\nprint(\"Ridge coefficients:\",regression.coef_)\n",
   "id": "cell-011"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**Checkpoint.** Compare learned coefficients with the generating coefficients [3,-2,0]. Differences reflect sample size, noise, and regularization.\n",
   "id": "cell-012"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 6. Preserve your evidence\n\nExport a JSON record with a seed, package version, and measured result. Download the artifacts directory before leaving Colab; runtime storage is temporary.\n",
   "id": "cell-013"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "metadata": {},
   "source": "record={\"week\":3,\"seed\":SEED,\"numpy\":np.__version__,\"python\":platform.python_version(),\"result\":summary}\n(ARTIFACTS/\"week-03-evidence.json\").write_text(json.dumps(record,indent=2))\nprint(json.dumps(record,indent=2))\n",
   "id": "cell-014"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**Checkpoint.** The evidence file must match the result you actually obtained. A saved screenshot alone does not permit rerunning the calculation.\n",
   "id": "cell-015"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 7. Try one change and explain it\n1. Predict the effect of one change before editing code. Change one parameter, input, or boundary condition only.\n2. Rerun all cells in a fresh kernel. Keep the original evidence record and compare the observed difference.\n3. Explain the result using the mechanism, not just the final number.\n4. Name one assumption that limits the claim, and a new test that could challenge it.\n\n**Troubleshooting:** if installation fails, restore network access; if a variable is undefined, run earlier cells; if your output differs, compare package versions, seed, and data construction. Do not repeatedly edit code until a preferred score appears.\n\n**Completion criterion:** one executed notebook, one evidence JSON, and a brief claim/evidence/limitation statement.\n\n### Reference documentation\n- [NumPy user guide](https://numpy.org/doc/stable/user/)\n- [scikit-learn user guide](https://scikit-learn.org/stable/user_guide.html)\n- [Course repository](https://github.com/CHjonnyYu/MLES-Fall-2026)\n",
   "id": "cell-016"
  }
 ]
}