{ "nbformat": 4, "nbformat_minor": 5, "metadata": { "kernelspec": { "name": "python3", "display_name": "Python 3", "language": "python" }, "language_info": { "name": "python" } }, "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Lab 1.1 · A single neuron\n", "\n", "**Goal:** build one artificial neuron from plain Python, set its weights by hand, then let it\n", "learn the weights itself by nudging them downhill on a loss. No libraries for the neuron itself:\n", "every multiplication is visible.\n", "\n", "**Runs on:** any laptop, CPU only, in under a minute. Python 3.10+; `matplotlib` for the plots.\n", "\n", "**Versions tested:** see the last cell's output (it prints them).\n", "\n", "The data: 20 students. For each one we know how many hours they studied and slept before an\n", "exam, and whether they passed. Can one neuron learn to predict \"passed\" from those two numbers?" ], "id": "lab-1-1-neuron-00" }, { "cell_type": "code", "metadata": {}, "source": [ "import math\n", "\n", "# (hours studied, hours slept, passed: 1 = yes, 0 = no)\n", "STUDENTS = [\n", " (1.0, 8.0, 0), (2.0, 5.0, 0), (2.5, 9.0, 0), (3.0, 3.0, 0), (3.5, 7.0, 0),\n", " (4.0, 4.5, 0), (4.5, 8.5, 1), (5.0, 2.0, 0), (5.0, 7.0, 1), (5.5, 4.0, 0),\n", " (6.0, 7.5, 1), (6.0, 3.0, 0), (6.5, 5.5, 1), (7.0, 2.5, 0), (7.0, 8.0, 1),\n", " (7.5, 4.5, 1), (8.0, 6.0, 1), (8.5, 3.0, 1), (9.0, 7.0, 1), (3.0, 9.5, 1),\n", "]\n", "print(len(STUDENTS), \"students,\", sum(s[2] for s in STUDENTS), \"passed\")" ], "execution_count": null, "outputs": [], "id": "lab-1-1-neuron-01" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1 · Predict first\n", "\n", "Before running anything, write down your answers:\n", "\n", "1. A neuron with every weight and the bias at **0** outputs the same number for every student.\n", " Which number? (Hint: what is `sigmoid(0)`?)\n", "2. If we call an output above 0.5 \"passed\", how many of the 20 will that neuron get right?\n", "3. Look at the data. Roughly which straight line in the (studied, slept) plane separates the\n", " passes from the fails? Do you think one straight line can get all 20 right?" ], "id": "lab-1-1-neuron-02" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2 · Build the neuron\n", "\n", "A neuron does two things:\n", "\n", "1. **Weighted sum:** `z = w1·x1 + w2·x2 + b`. Each input is multiplied by its weight (how much\n", " that input matters, and in which direction), and the bias `b` shifts the result.\n", "2. **Activation:** squash `z` into a number between 0 and 1 with the sigmoid,\n", " `σ(z) = 1 / (1 + e^(−z))`, read as \"how sure the neuron is that this student passed\"." ], "id": "lab-1-1-neuron-03" }, { "cell_type": "code", "metadata": {}, "source": [ "def sigmoid(z):\n", " return 1.0 / (1.0 + math.exp(-z))\n", "\n", "\n", "def neuron(w1, w2, b, studied, slept):\n", " z = w1 * studied + w2 * slept + b # weighted sum\n", " return sigmoid(z) # activation\n", "\n", "\n", "def accuracy(w1, w2, b, data=STUDENTS):\n", " right = sum((neuron(w1, w2, b, x1, x2) > 0.5) == bool(y) for x1, x2, y in data)\n", " return right, len(data)\n", "\n", "\n", "for z in (-6, -2, 0, 2, 6):\n", " print(f\"sigmoid({z:+d}) = {sigmoid(z):.4f}\")\n", "print(\"all-zero neuron:\", accuracy(0, 0, 0))" ], "execution_count": null, "outputs": [], "id": "lab-1-1-neuron-04" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Check your prediction 1 and 2 against the output above.\n", "\n", "Now set the weights **by hand**. Studying should help (positive `w1`), sleep should help a\n", "bit (smaller positive `w2`), and the bias sets how much effort it takes in total. Try a few\n", "values until you get at least 18 right. The interactive explorer in Ch 1.1 does the same with\n", "sliders." ], "id": "lab-1-1-neuron-05" }, { "cell_type": "code", "metadata": {}, "source": [ "w1, w2, b = 1.0, 0.6, -9.0 # ← change these\n", "print(\"hand-tuned:\", accuracy(w1, w2, b))" ], "execution_count": null, "outputs": [], "id": "lab-1-1-neuron-06" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3 · A loss: one number that says how wrong we are\n", "\n", "Accuracy only changes when a prediction crosses 0.5, so small weight changes usually leave it\n", "exactly the same: it gives no hint about which direction is better. Learning needs a smooth\n", "score instead. The standard one for yes/no predictions is the **binary cross-entropy**:\n", "\n", "`loss = − average over students of [ y·log(p) + (1 − y)·log(1 − p) ]`\n", "\n", "where `p` is the neuron's output and `y` the true label. If a student passed (`y = 1`) the\n", "loss is `−log(p)`: near 0 when `p ≈ 1`, huge when `p ≈ 0`. Being confidently wrong costs most." ], "id": "lab-1-1-neuron-07" }, { "cell_type": "code", "metadata": {}, "source": [ "def loss(w1, w2, b, data=STUDENTS):\n", " total = 0.0\n", " for x1, x2, y in data:\n", " p = neuron(w1, w2, b, x1, x2)\n", " total += -(y * math.log(p) + (1 - y) * math.log(1 - p))\n", " return total / len(data)\n", "\n", "\n", "print(f\"all-zero loss: {loss(0, 0, 0):.4f} (= log 2 = {math.log(2):.4f}: a coin flip)\")\n", "print(f\"hand-tuned loss: {loss(w1, w2, b):.4f}\")" ], "execution_count": null, "outputs": [], "id": "lab-1-1-neuron-08" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4 · Learning: nudge every weight downhill\n", "\n", "For each weight, ask: *if I increase it a tiny bit, does the loss go up or down, and how fast?*\n", "That rate is the **gradient**. Measure it directly: compute the loss a little to the left and a\n", "little to the right, `(loss(w + h) − loss(w − h)) / 2h`. Then move every weight a small step\n", "against its gradient. The step size is the **learning rate**.\n", "\n", "This \"measure by nudging\" method is slow (two loss computations per weight per step) but\n", "honest. Ch 1.2 derives the same gradients exactly, with calculus, in one pass: backpropagation." ], "id": "lab-1-1-neuron-09" }, { "cell_type": "code", "metadata": {}, "source": [ "def numerical_gradient(params, data=STUDENTS, h=1e-5):\n", " grads = []\n", " for i in range(len(params)):\n", " up = list(params); up[i] += h\n", " down = list(params); down[i] -= h\n", " grads.append((loss(*up, data=data) - loss(*down, data=data)) / (2 * h))\n", " return grads\n", "\n", "\n", "def train(params, lr=0.1, steps=3000, every=500, quiet=False, data=STUDENTS):\n", " params = list(params)\n", " history = []\n", " for step in range(steps + 1):\n", " current = loss(*params, data=data)\n", " history.append(current)\n", " if not quiet and step % every == 0:\n", " r, n = accuracy(*params, data=data)\n", " print(f\"step {step:5d} loss {current:.4f} correct {r}/{n} \"\n", " f\"w1 {params[0]:+.3f} w2 {params[1]:+.3f} b {params[2]:+.3f}\")\n", " if step < steps:\n", " g = numerical_gradient(params, data=data)\n", " params = [p - lr * gi for p, gi in zip(params, g)]\n", " return params, history\n", "\n", "\n", "learned, history = train([0.0, 0.0, 0.0], lr=0.1, steps=3000)" ], "execution_count": null, "outputs": [], "id": "lab-1-1-neuron-10" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5 · Checkpoint\n", "\n", "With the starting weights `(0, 0, 0)`, `lr = 0.1` and 3000 steps, your output should match\n", "these lines (measured for this book; the last digit may differ between machines):\n", "\n", "```\n", "step 0 loss 0.6931 correct 10/20 w1 +0.000 w2 +0.000 b +0.000\n", "step 500 loss 0.4112 correct 19/20 w1 +0.427 w2 +0.265 b -3.490\n", "step 1000 loss 0.3158 correct 20/20 w1 +0.634 w2 +0.442 b -5.644\n", "step 3000 loss 0.1928 correct 20/20 w1 +1.116 w2 +0.826 b -10.459\n", "```\n", "\n", "- The loss starts at **0.6931** (a coin flip) and keeps falling, more and more slowly.\n", "- All 20 are right from about step 780 on: one straight line *can* separate this class.\n", "- `w1` and `w2` are positive (studying and sleep both help, studying a bit more) and `b` is\n", " negative (it takes effort to pass). The learned ratio `w2/w1 ≈ 0.74` is close to the 0.6\n", " you may have picked by hand." ], "id": "lab-1-1-neuron-11" }, { "cell_type": "code", "metadata": {}, "source": [ "try:\n", " import matplotlib.pyplot as plt\n", "\n", " fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))\n", " ax1.plot(history)\n", " ax1.set_xlabel(\"step\"); ax1.set_ylabel(\"loss\"); ax1.set_title(\"Loss while learning\")\n", " for x1, x2, y in STUDENTS:\n", " ax2.scatter(x1, x2, marker=\"o\" if y else \"x\", color=\"black\")\n", " a, bb, c = learned\n", " xs = [0, 10]\n", " ax2.plot(xs, [-(a * x + c) / bb for x in xs], color=\"gray\") # boundary: a·x1 + bb·x2 + c = 0\n", " ax2.set_xlim(0, 10); ax2.set_ylim(0, 10)\n", " ax2.set_xlabel(\"hours studied\"); ax2.set_ylabel(\"hours slept\")\n", " ax2.set_title(\"o passed, x failed, line = boundary\")\n", " plt.tight_layout(); plt.show()\n", "except ImportError:\n", " print(\"matplotlib not installed: skip the plot (pip install matplotlib)\")" ], "execution_count": null, "outputs": [], "id": "lab-1-1-neuron-12" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6 · Explore\n", "\n", "Change one knob at a time and answer the question next to it.\n", "\n", "| Knob | Try | Question |\n", "| --- | --- | --- |\n", "| learning rate | `0.05`, `0.2`, `0.7` | Which one reaches 20/20 first? Plot `history`: which one has a loss that sometimes goes *up*? |\n", "| steps | `300`, `10000` | Does the loss ever reach 0? Why do the weights keep growing? |\n", "| starting weights | `[5, -5, 0]` | Does it still end up in the same place? |\n", "| one more student | append `(2.0, 2.0, 1)` to the data | What is the best accuracy now? What happens to the loss after many steps? |" ], "id": "lab-1-1-neuron-13" }, { "cell_type": "code", "metadata": {}, "source": [ "# your experiments here, for example:\n", "# learned, history = train([0.0, 0.0, 0.0], lr=0.5, steps=3000)" ], "execution_count": null, "outputs": [], "id": "lab-1-1-neuron-14" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7 · Failure playground\n", "\n", "Three neurons below are broken in ways real models break. For each: run it, read the\n", "symptom, find the cause, fix it. Hints are in Review 1.1; answers are not." ], "id": "lab-1-1-neuron-15" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 7a · The over-confident neuron\n", "\n", "A colleague \"speeds up\" learning by starting from big weights." ], "id": "lab-1-1-neuron-16" }, { "cell_type": "code", "metadata": {}, "source": [ "try:\n", " print(loss(40.0, 40.0, -300.0))\n", "except Exception as e:\n", " print(\"CRASH:\", type(e).__name__, e)" ], "execution_count": null, "outputs": [], "id": "lab-1-1-neuron-17" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: a crash in `loss`. Which student, which line, and which value of `p`? Why does a real\n", "number like 0.999999999 become exactly 1.0 here? Write a `loss` that cannot crash (two common\n", "fixes exist; find one)." ], "id": "lab-1-1-neuron-18" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 7b · The impatient learner\n", "\n", "Another colleague raises the learning rate to 1.0, \"ten times faster\"." ], "id": "lab-1-1-neuron-19" }, { "cell_type": "code", "metadata": {}, "source": [ "try:\n", " _, h_fast = train([0.0, 0.0, 0.0], lr=1.0, steps=40, every=5)\n", "except Exception as e:\n", " print(\"CRASH:\", type(e).__name__, e)" ], "execution_count": null, "outputs": [], "id": "lab-1-1-neuron-20" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: the same crash as 7a, but nobody started from big weights. What pushed `p` to exactly\n", "1.0 this time?\n", "\n", "Then put a crash-proof `loss` in place (redefine `loss`) and run the cell again with `lr=1.0`\n", "and with `lr=2.0`. Try **both** fixes from 7a, one at a time:\n", "\n", "- **clipping** `p` into `[1e-12, 1 − 1e-12]`: at `lr=1.0` the loss jumps around wildly; at\n", " `lr=2.0` it freezes at the same value forever;\n", "- **the stable form** (compute `log σ(z)` and `log(1 − σ(z))` directly from `z`, as PyTorch's\n", " `BCEWithLogitsLoss` does): the loss still jumps, but it never freezes.\n", "\n", "Explain all three behaviours. Draw the loss as a valley and each step as a jump. For the frozen\n", "one: what is the slope of a clipped value? Why does the stable form keep a slope even when the\n", "neuron is confidently wrong? (This is why libraries use it.)\n", "\n", "### 7c · The pattern a line cannot draw\n", "\n", "A different class: students pass when they studied **and** slept enough, or when they did\n", "neither and the exam was cancelled for them (a made-up rule, but it has the shape of XOR)." ], "id": "lab-1-1-neuron-21" }, { "cell_type": "code", "metadata": {}, "source": [ "XOR_LIKE = [(2, 2, 1), (2, 8, 0), (8, 2, 0), (8, 8, 1),\n", " (1, 1, 1), (1, 9, 0), (9, 1, 0), (9, 9, 1)]\n", "params, _ = train([0.1, -0.1, 0.0], lr=0.1, steps=2000, quiet=True, data=XOR_LIKE)\n", "print(\"after 2000 steps:\", accuracy(*params, data=XOR_LIKE), f\"loss {loss(*params, data=XOR_LIKE):.4f}\")" ], "execution_count": null, "outputs": [], "id": "lab-1-1-neuron-22" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: training runs without errors, yet the loss sits at **0.6931**, exactly a coin flip,\n", "and about half the points are right, however long you train. Sketch the 8 points: why can **no** single straight line separate them? Ch 1.3 fixes\n", "this with a hidden layer. Hold on to this picture: it is why networks have layers." ], "id": "lab-1-1-neuron-23" }, { "cell_type": "code", "metadata": {}, "source": [ "import platform\n", "\n", "print(\"Versions tested:\", f\"Python {platform.python_version()} on {platform.system()} {platform.machine()}\")\n", "try:\n", " import matplotlib\n", " print(\"matplotlib\", matplotlib.__version__)\n", "except ImportError:\n", " pass" ], "execution_count": null, "outputs": [], "id": "lab-1-1-neuron-24" } ] }