Formula cheat sheet
Every definition, formula and complexity bound in 07-280, in course order, in the form the course states them. Built for the night before — not for learning from. Print it: the sidebar and top bar drop out automatically.
Each heading links back to the chapter that teaches the thing. If a line here looks like magic, follow the link. The traps section at the bottom is the highest-value 90 seconds on the page.
0. Notation you must not fumble
| Symbol | Reads as | Careful |
|---|---|---|
| $\X$, $\Y$ | input space, output space | classification: $\Y$ finite & unordered. Regression: $\Y$ continuous & ordered |
| $\H$ | hypothesis class — the set of $h$ you are allowed to pick from | ERM minimises over $\H$, not over all functions |
| $\D = \{(x^{(i)}, y^{(i)})\}_{i=1}^{N}$ | training set | $x^{(i)}$ is the $i$-th sample, not $x$ raised to $i$ |
| $N$, $d$ (or $K$, $M$) | sample size, number of features | $X \in \R^{N\times d}$: rows are samples, columns are features |
| $\theta$, $w$, $b$ | parameters; weights and bias | with $x_1 = 1$ fixed, $\theta = \begin{bmatrix} b \\ w\end{bmatrix}$ absorbs $b$ |
| $\hat y = h(x)$ | prediction | $\hat y$ vs $y$ argument order — see the traps |
| $b,\ d,\ m$ | branching factor, depth of shallowest goal, max depth of tree | search-side $d$ $\ne$ ML-side $d$ |
| $C^{*},\ \varepsilon$ | optimal solution cost, smallest step cost | UCS bounds are stated in $C^{*}/\varepsilon$, not $d$ |
1. Search problems & the node record
→ Ch. 1 · Search problems, BFS/DFS/UCS
- A state space
- A set of allowable actions $\mathrm{Actions}(s)$ for each state $s$
- A transition model $\mathrm{Result}(s,a)$
- A step-cost function $c(s,a,s')$
- A start state
- A goal test
A solution is a sequence of actions (a plan) transforming the start state into a goal state. A state-space graph has one vertex per state (each state occurs once); edges are action transitions; the goal test picks out a set of goal vertices. Search trees can repeat states; state-space graphs cannot.
Node record
Nodes carry state, parent, action, path-cost. A child of parent_node via action $a$:
state = result(parent_node.state, a)
parent = parent_node
action = a
path-cost = parent_node.path_cost
+ step_cost(parent_node.state, a, self.state)
Extract the solution by tracing back parent pointers and collecting actions (then reverse).
Tree search: frontier only. A state can be generated and expanded many times; infinite loops are possible on a cyclic graph.
Graph search: keep an explored/reached set; never expand the same state twice. Cheaper, but it can lock in a bad first path — which is exactly why A* graph search needs consistency, not merely admissibility.
2. BFS / DFS / UCS / Greedy / A* at a glance
| Algorithm | Frontier / priority | Complete? | Optimal? | Time | Space |
|---|---|---|---|---|---|
| BFS | FIFO queue | Yes ($b$ finite) | Only if all step costs equal | $O(b^{d})$ | $O(b^{d})$ |
| DFS | LIFO stack | No (infinite depth / cycles) | No | $O(b^{m})$ | $O(bm)$ |
| IDS | LIFO stack, depth limit $0,1,2,\dots$ | Yes | Only if all step costs equal | $O(b^{d})$ | $O(bd)$ |
| UCS | priority queue on $g(n)$ | Yes (step costs $\ge \varepsilon > 0$) | Yes | $O\!\left(b^{\,1+\lfloor C^{*}/\varepsilon\rfloor}\right)$ | $O\!\left(b^{\,1+\lfloor C^{*}/\varepsilon\rfloor}\right)$ |
| Greedy | priority queue on $h(n)$ | No for tree search; yes for graph search on a finite space | No | $O(b^{m})$ worst case | $O(b^{m})$ worst case |
| A* | priority queue on $f(n)=g(n)+h(n)$ | Yes (step costs $\ge \varepsilon > 0$) | Yes — admissible $h$ (tree), consistent $h$ (graph) | $O(b^{m})$ worst case; $\to$ UCS bound as $h \to 0$ | $O(b^{m})$ worst case (keeps all generated nodes) |
$b$ = branching factor · $d$ = depth of the shallowest goal · $m$ = maximum depth of the tree · $C^{*}$ = optimal solution cost · $\varepsilon$ = smallest step cost. Greedy and A* worst cases assume a useless heuristic; a good $h$ shrinks the effective branching factor but the worst case stays exponential.
What sits on the frontier at its worst moment? A whole tier $\Rightarrow b^{d}$ space. One path plus siblings $\Rightarrow bm$ space.
What must be examined before stopping? Everything shallower than the goal $\Rightarrow b^{d}$ time. Everything cheaper than the goal $\Rightarrow b^{C^{*}/\varepsilon}$ time. Optimality falls out of the second question.
Special cases worth memorising: UCS is A* with $h = 0$. BFS is UCS when every step costs the same. Greedy is "A* with $g = 0$".
3. Heuristics, admissibility, consistency
→ Ch. 2 · Heuristics, Greedy & A*
$$f(n) = g(n) + h(n)$$$g(n)$ = cost of the path from the start to $n$ (backward cost, known) · $h(n)$ = estimate of the cheapest cost from $n$ to a goal (forward cost, guessed) · $h^{*}(n)$ = the true cheapest cost from $n$ to a nearest goal.
| Property | Statement | Slogan |
|---|---|---|
| Admissible | $0 \le h(n) \le h^{*}(n)$ for all $n$ | never overestimates — optimistic |
| Consistent | $h(n) \le c(n,a,n') + h(n')$ for every edge $n \to n'$ (equivalently $h(n)-h(n') \le c(n,n')$) | "heuristic step cost" $\le$ actual step cost — a triangle inequality |
| Goal condition | $h(\text{goal}) = 0$ | required for both |
- Consistency $\Rightarrow$ admissibility. (Telescope the consistency inequality along an optimal path to the goal; the costs sum to $h^{*}(n)$ and $h(\text{goal})=0$.) The converse is false.
- Under a consistent $h$, $f$ never decreases along any path: $f(n') = g(n)+c+h(n') \ge g(n)+h(n) = f(n)$.
- Optimality: tree search needs admissible; graph search needs consistent. UCS is the special case $h=0$, which is consistent, so UCS is optimal in both.
A* tree-search optimality proof, in five lines
Let $A$ be an optimal goal node and $B$ a suboptimal goal node, both on the frontier, and let $n$ be an ancestor of $A$ on the frontier (possibly the start, possibly $A$ itself).
| $f(n) = g(n) + h(n)$ | definition of $f$-cost |
| $f(n) \le g(n) + h^{*}(n)$ | admissibility of $h$ |
| $g(n) + h^{*}(n) = g(A) = f(A)$ | $n$ on an optimal path to $A$; $h(A) = 0$ |
| $f(A) < f(B)$ | $B$ is suboptimal and $h(B) = 0$, so $f(B) = g(B) > g(A)$ |
| $\therefore f(n) < f(B)$ | every ancestor of $A$ is expanded before $B$, so $A$ is popped before $B$ $\;\blacksquare$ |
Comparing and building heuristics
| Idea | Statement |
|---|---|
| Dominance | $h_a \ge h_c$ iff $\forall n:\ h_a(n) \ge h_c(n)$. Larger is better as long as both are admissible — a dominant heuristic expands no more nodes. |
| Extremes | $h = 0$ is admissible but useless (A* degenerates to UCS). $h = h^{*}$ is perfect but usually as expensive as solving the problem. |
| Max of two | If $h_a, h_c$ are both admissible and neither dominates, $h(n) = \max\{h_a(n), h_c(n)\}$ is admissible and dominates both. (It is $\le h^{*}$ since each term is, and $\ge$ each term by definition of max.) |
| Where heuristics come from | Relaxed problems: delete constraints so new actions become available; the exact cost of the relaxed problem is an admissible heuristic for the original, because every real solution is also a relaxed solution. Most natural admissible heuristics — especially relaxed-problem ones — are also consistent. |
$h_{\text{TILES}}$ = number of misplaced tiles (relax: a tile may teleport anywhere). $h_{\text{start}} = 8$.
$h_{\text{MANHATTAN}}$ = total Manhattan distance (relax: a tile may move onto an occupied square). $h_{\text{start}} = 3+1+2+\dots = 18$.
| Avg nodes expanded | 4 steps | 8 steps | 12 steps |
|---|---|---|---|
| UCS | 112 | 6,300 | $3.6\times10^{6}$ |
| A*, TILES | 13 | 39 | 227 |
| A*, MANHATTAN | 12 | 25 | 73 |
4. Games: minimax and expectimax
→ Ch. 3 · Minimax, α-β, Expectimax
- Initial state $s_0$
- $\mathrm{Player}(s)$ — whose move it is
- $\mathrm{Actions}(s)$ — legal moves for the player on move
- $\mathrm{Result}(s,a)$ — transition model
- $\text{Terminal-Test}(s)$
- $\mathrm{Utility}(s,p)$ — terminal value for player $p$ (or just $\mathrm{Utility}(s)$ for the player deciding at the root)
"Standard" games are deterministic, observable, two-player, turn-taking and zero-sum. Zero-sum = opposite utilities, pure competition. General games = independent utilities, allowing cooperation, indifference, shifting alliances.
The one recursion that covers all three node types
function value(state)
if state.is_leaf: return state.value
if state.player is MAX: return max over a in state.actions of value(state.result(a))
if state.player is MIN: return min over a in state.actions of value(state.result(a))
if state.player is CHANCE: return sum over s' in state.next_states of P(s') * value(s')
| Node | Value rule |
|---|---|
| MAX | $V(s) = \max_{a} V(s'),\quad s' = \mathrm{Result}(s,a)$ |
| MIN | $V(s) = \min_{a} V(s'),\quad s' = \mathrm{Result}(s,a)$ |
| CHANCE | $V(s) = \sum_{s'} P(s')\, V(s')$ (more fully $\sum_{s'} P(s' \mid s,a) V(s')$) |
| Terminal | $V(s) = \mathrm{Utility}(s)$ |
The answer at the root is an action:
$$\hat a = \argmax_{a} V(s'), \qquad s' = \mathrm{Result}(s,a)$$Cost. Minimax is exhaustive DFS: time $O(b^{m})$, space $O(bm)$. Chess has $b \approx 35$, $m \approx 100$ — exact solution completely infeasible, hence bounded lookahead ("bounded rationality", Herbert Simon).
Evaluation functions (depth-limited search)
$$\mathrm{EVAL}(s) = w_1 f_1(s) + w_2 f_2(s) + \dots + w_n f_n(s) = \sum_i w_i f_i(s)$$$f_i$ = a feature of the position, $w_i$ = its weight. Chess example: $w_1 = 9$, $f_1(s) = (\#\text{white queens} - \#\text{black queens})$. The ideal evaluation function returns the true minimax value; in practice it is a weighted linear sum of features. Deeper search generally means better play — or the same quality of play from a less accurate evaluation function.
Generalized minimax
For non-zero-sum or multi-player games: terminals carry utility tuples, node values are also tuples, and each player maximises its own component. E.g. with three players and terminal tuples $(0,0,7), (8,8,1), (7,7,2), (0,0,8)$, the player at each node picks the child whose tuple has the largest value in that player's slot. Cooperation and competition then emerge dynamically rather than being assumed.
5. α-β pruning
→ Ch. 3
$\alpha$ = MAX's best option on the path to the root. (Best option so far from any MAX node on this path.)
$\beta$ = MIN's best option on the path to the root.
def max-value(state, α, β):
initialize v = -∞
for each successor of state:
v = max(v, value(successor, α, β))
if v ≥ β
return v
α = max(α, v)
return v
def min-value(state, α, β):
initialize v = +∞
for each successor of state:
v = min(v, value(successor, α, β))
if v ≤ α
return v
β = min(β, v)
return v
Order matters inside the loop: test the cutoff first, update the bound second. In max-value you cut on $v \ge \beta$ and then raise $\alpha$; in min-value you cut on $v \le \alpha$ and then lower $\beta$.
| Property | Statement |
|---|---|
| Correctness | Theorem: pruning has no effect on the minimax value computed for the root. |
| Interior nodes | Values of intermediate nodes may be wrong (they are bounds returned early, not true minimax values). |
| Ordering | Good child ordering improves pruning a lot; iterative deepening helps produce it. |
| Best case | With perfect ordering, time drops to $O(b^{m/2})$ — it doubles the solvable depth. At 1M nodes/move that is depth $\approx 8$. |
6. Constraint satisfaction problems
→ Ch. 4 · Constraint Satisfaction
Variables $X_1,\dots,X_n$ · domains $D_i$ (what each variable may take) · constraints (which combinations are legal). A state is a partial assignment; the goal test is "complete and all constraints satisfied". CSPs are identification problems: the assignment is the answer, the path to it is not.
With finite domains of size $d$ and $n$ variables there are $O(d^{n})$ complete assignments. A binary CSP has constraints over at most two variables; its constraint graph has variables as nodes and constraints as edges.
Backtracking search
Backtracking search = DFS + two improvements.
- Idea 1 — one variable at a time. Variable assignments are commutative ([WA=red then NT=green] $\equiv$ [NT=green then WA=red]), so only ever assign a single variable per step. This cuts the branching factor from $nd$ to $d$.
- Idea 2 — check constraints as you go. Only consider values that do not conflict with previous assignments ("incremental goal test"). No need to check constraints for a complete assignment at the end.
Plain backtracking solves $n$-queens for $n \approx 25$; adding filtering + ordering makes 1000 queens feasible.
Filtering
| Technique | Rule |
|---|---|
| Forward checking | After assigning $Y$, cross off values in the domains of unassigned neighbours that conflict. Formally: enforce $X \to Y$ for all edges $(X,Y)$ where $Y$ was newly assigned. Remove values from the tail ($X$). |
| Arc consistency | An arc $X \to Y$ is consistent iff for every value $x$ in the tail $X$ there is some value $y$ in the head $Y$ that could be assigned without violating a constraint. To enforce it: delete values from the domain of $X$ (the tail) that have no legal partner in $Y$. |
| AC-3 | Maintain a queue of arcs. Pop an arc, enforce it; if the tail's domain changed, re-enqueue all arcs pointing into that tail. Skips constraints unmodified since last analysed (unlike the naive "cycle over all pairs until nothing changes"). A wiped-out domain means failure. |
- $n$ nodes, each with $\le d$ values $\Rightarrow$ total number of value removals is $O(nd)$.
- After each removal, $\le n$ arcs are added back $\Rightarrow$ total arc insertions $O(n^{2}d)$.
- Checking consistency of one arc costs $O(d^{2})$ (each tail value against each head value).
- $\Rightarrow$ one run of AC-3 costs at most $O(n^{2}d^{3})$. not required Zhang & Yap (2001) tighten this to $O(n^{2}d^{2})$.
Backtracking with AC-3 calls AC-3 many times — once per node of the backtracking tree — so this is the cost of one run.
Ordering heuristics
| Heuristic | Chooses | Why that direction |
|---|---|---|
| MRV — minimum remaining values (variable ordering) | the variable with the fewest legal values left in its domain | "Fail-fast": if a variable is going to fail, find out now, at the top of the tree, not after building a huge subtree. Also called the most constrained variable. |
| LCV — least constraining value (value ordering) | the value that rules out the fewest values in the remaining variables | You only need one solution, so keep options open on the branch you are committing to. Determining LCV may take computation (e.g. re-running filtering). |
Not a contradiction: MRV picks a variable and you must eventually assign all of them, so fail fast. LCV picks a value and you only need one to work, so fail slow.
7. ML problem formulation
→ Ch. 5 · ML problem formulation
| Object | Definition |
|---|---|
| Goal | find $h : \X \to \Y$ such that for a new input $x$ with true label $y$, $h(x) = y$ |
| Data | $\D = \{(x^{(i)}, y^{(i)})\}_{i=1}^{N}$, with $x^{(i)} \in \X$, $y^{(i)} \in \Y$ for all $i$; $N$ = sample size |
| Task types | Classification: $\Y$ finite, unordered ($|\Y| = 2$ is binary). Regression: $\Y$ continuous, ordered. |
| Loss | $\ell : \Y \times \Y \to \R$, usually $\ge 0$, lower is better. In the lecture notes: first argument = your guess, second = the truth. |
| Zero-one loss | $\ell(\hat y, y) = \1\{\hat y \ne y\}$, where $\1\{\cdot\}$ is 1 if true and 0 if false |
| Squared loss | $\ell(\hat y, y) = (\hat y - y)^{2}$ |
| Inference | applying $h$ to $x^{(\mathrm{new})}$ to predict its label |
| Generalization | performance on unseen data — "generalization error" / "test error" |
The i.i.d. assumption: all datapoints, training and test, are drawn independently and identically distributed from one unknown distribution on $\X \times \Y$. Without it, training tells you nothing about test.
$$\text{Risk: } \quad R(h) = \E_{(X,Y)}\big[\ell(h(X), Y)\big] \qquad \text{“risk = expected loss”}$$ $$\text{Empirical risk: } \quad \hat R(h) = \frac{1}{N}\sum_{i=1}^{N} \ell\big(h(x^{(i)}), y^{(i)}\big)$$ $$\text{ERM: } \quad h^{*} = \argmin_{h \in \H} \hat R(h)$$We want to minimise $R(h)$ but we know neither $y^{(\mathrm{new})}$ nor the distribution — so we minimise the training average $\hat R(h)$ instead. That substitution is only defensible because of the i.i.d. assumption: $\hat R$ is an unbiased estimate of $R$.
Unsupervised learning (only $x^{(1)},\dots,x^{(N)}$, no labels): clustering; dimensionality reduction $\R^{d} \to \R^{\tilde d}$ with $\tilde d \ll d$ preserving $x^{(i)} \approx x^{(j)} \Rightarrow \tilde x^{(i)} \approx \tilde x^{(j)}$; representation learning and generation. Self-supervised learning converts unsupervised into supervised (hide a word, let it be $y$, the preceding text be $x$ — the basis of LLMs).
8. Decision trees
Internal nodes split on an attribute; leaves carry output labels. Major benefit: human interpretable. Setting: $\X = \{0,1\}^{d}$ ($d$ attributes), $\Y = \{0,1\}$.
Decision stump = split just once, then output a chosen label at each of the two leaves.
Construction (recursive)
function DT(dataset S, set of attributes A ⊆ {1,…,d}):
if A = ∅ or all examples in S have the same label:
return a leaf with value = majority vote of labels in S
b = BestAttribute(S, A) ∈ A
LeftNode = DT({(x,y) ∈ S | x_b = 1}, A \ {b})
RightNode = DT({(x,y) ∈ S | x_b = 0}, A \ {b})
return tree "Is the b-th attribute equal to 1?" → Y: LeftNode, N: RightNode
Called initially with $S = \{(x^{(i)}, y^{(i)})\}_{i=1}^{N}$ and $A = \{1,2,\dots,d\}$.
Majority vote at a leaf:
$$\hat y = \argmax_{k \in \Y} \ \sum_{i \,:\, (x^{(i)},y^{(i)}) \in S} \1\big(y^{(i)} = k\big)$$Count how many samples in this leaf carry each label $k$; output the most common. Ties: break arbitrarily but consistently.
Classification error rate of a node/tree $= \dfrac{\#\text{misclassified}}{\#\text{samples}}$ — i.e. the empirical risk under zero-one loss.
| $\mathrm{BestAttribute}(S,A)$ criterion | Pick the attribute that… |
|---|---|
| Training error | minimises the training error of the resulting stump (the original criterion; later called "problematic") |
| Gini impurity | minimises Gini impurity stated, not developed in this course |
| Mutual information | maximises $I(Y;W)$ — equivalently minimises the conditional entropy $H(Y \mid W)$, since $H(Y)$ is fixed at the node |
The algorithm picks the attribute that would be best if allowed only one split, then recurses. This is a greedy approach towards ERM: greediness is suboptimal, but it buys computational efficiency. A globally optimal tree may require a first split that looks bad in isolation.
Stopping criteria & extensions
- Stop when $A = \emptyset$ (no attributes left) or all examples in $S$ share a label (homogeneous leaf).
- Stop when the split doesn't reduce training error by much.
- Attributes with more than $\{0,1\}$ values; real-valued attributes give threshold tests ("Is $x_2 \ge 4.5$?") and axis-aligned decision boundaries — the set of lines separating the class-0 from the class-1 regions.
- You need not remove the chosen attribute from $A$ in the recursive call (necessary once thresholds are allowed, since the same feature can be split again at a different threshold).
9. Information theory
→ Ch. 7 · Entropy & mutual information
$$H(Y) = \sum_{y \in \Y} P(Y = y)\,\log \frac{1}{P(Y=y)}$$ $$H(Y \mid W = \omega) = \sum_{y \in \Y} P(Y = y \mid W = \omega)\,\log \frac{1}{P(Y = y \mid W = \omega)}$$ $$H(Y \mid W) = \sum_{\omega \in W} P(W = \omega)\; H(Y \mid W = \omega)$$ $$I(Y;W) = H(Y) - H(Y \mid W)$$| Quantity | In tree language |
|---|---|
| $H(Y)$ | label impurity at the current node. Units: bits when $\log = \log_2$. |
| $H(Y \mid W = \omega)$ | Specific conditional entropy: the entropy of one child. The conditioning $\mid W=\omega$ selects the left or right child; $P(Y \mid W=\omega)$ is the label distribution of that subset of $S$. |
| $H(Y \mid W)$ | the average entropy across the child nodes, weighted by the fraction of samples going each way. |
| $I(Y;W)$ | information gain = reduction in entropy, before vs. after splitting. $I \ge 0$ always; $I = 0$ iff the split tells you nothing. |
- $0 \cdot \log\frac{1}{0} := 0$ by definition. A label that never occurs contributes nothing.
- Twenty questions: 128 equally likely students needs $7 = \log_2 128 = \log_2 \frac{1}{1/128}$ questions, so $\log_2 \frac{1}{p}$ is the "surprise" of an outcome of probability $p$, and $H$ is its average.
- Course's worked non-uniform case: $p_1 = \tfrac14$, $p_2 = \dots = p_7 = \tfrac18$, rest 0 $\Rightarrow H = \tfrac14\cdot 2 + 6\cdot\tfrac18\cdot 3 = \tfrac{11}{4} = 2.75$ bits.
- $H$ is maximised by the uniform distribution ($\log_2 k$ bits over $k$ outcomes) and is 0 for a pure node.
Hand-computation lookup table
Everything below is $\log_2$, to 3 decimals. These nine numbers cover essentially every entropy an exam can ask you to compute by hand.
| $n$ | $\log_2 n$ |
|---|---|
| 2 | 1.000 |
| 3 | 1.585 |
| 4 | 2.000 |
| 5 | 2.322 |
| 6 | 2.585 |
| 7 | 2.807 |
| 8 | 3.000 |
| 9 | 3.170 |
| 10 | 3.322 |
| $p$ | $H(p)$ bits |
|---|---|
| $1/2 = 0.500$ | 1.000 |
| $1/3 \approx 0.333$ | 0.918 |
| $1/4 = 0.250$ | 0.811 |
| $1/5 = 0.200$ | 0.722 |
| $2/5 = 0.400$ | 0.971 |
| $3/8 = 0.375$ | 0.954 |
| $1/8 = 0.125$ | 0.544 |
| $3/10 = 0.300$ | 0.881 |
$H(p) = p\log_2\frac{1}{p} + (1-p)\log_2\frac{1}{1-p}$ is the binary entropy of a node that is a fraction $p$ one class and $1-p$ the other. It is symmetric: $H(p) = H(1-p)$, so $H(3/4) = H(1/4) = 0.811$, $H(7/8) = H(1/8) = 0.544$, $H(3/5) = H(2/5) = 0.971$, $H(5/8) = H(3/8) = 0.954$, $H(7/10)=H(3/10)=0.881$, $H(2/3)=H(1/3)=0.918$. Useful decompositions: $\log_2 6 = 1 + \log_2 3$, $\log_2 9 = 2\log_2 3$, $\log_2 10 = 1 + \log_2 5$, $\log_2 5 = \log_2 10 - 1 = 3.322 - 1$.
10. Linear regression
Model. With $\X = \R$: $h_{w,b}(x) = x\cdot w + b$. With $\X = \R^{d}$, fix the first coordinate $x_1 = 1$ and let $\theta = \begin{bmatrix} b \\ w \end{bmatrix}$ so that the bias is absorbed:
$$h_\theta(x) = x^{\top}\theta$$ERM under squared loss (squared loss because $\Y$ is real-valued):
$$\argmin_{\theta} \ \frac{1}{N}\sum_{i=1}^{N}\Big(y^{(i)} - {x^{(i)}}^{\top}\theta\Big)^{2} \;=\; \argmin_{\theta}\ \frac{1}{N}\big\|y - X\theta\big\|_2^{2}$$Closed forms
| Case | Solution |
|---|---|
| Scalar, no intercept ($b = 0$, so $h(0)=0$) | $\displaystyle w^{*} = \frac{\sum_{i=1}^{N} x^{(i)}y^{(i)}}{\sum_{i=1}^{N} {x^{(i)}}^{2}}$ |
| Scalar, with intercept | $\displaystyle w = \frac{\sum_{i}(x_i - \bar x)(y_i - \bar y)}{\sum_i (x_i - \bar x)^{2}}, \qquad b = \bar y - w\,\bar x$ |
| Vector — the normal equations | $\displaystyle \theta^{*} = (X^{\top}X)^{-1}X^{\top}y$ |
$\bar x = \frac1N\sum_i x_i$, $\bar y = \frac1N\sum_i y_i$. The with-intercept formula is the no-intercept formula applied to centred data — which is why $b = \bar y - w\bar x$ simply puts the line back through $(\bar x, \bar y)$.
Derivation of the normal equations (completing the square)
Let $A = X^{\top}X$ and $b = X^{\top}y$ (in the scalar case $X^{\top}X$ plays the role of $\sum x_i^{2}$ and $X^{\top}y$ of $\sum x_i y_i$). Assume $A$ invertible. Add and subtract the constant $b^{\top}A^{-1}b$:
$$= \argmin_\theta\ -2\theta^{\top}b + \theta^{\top}A\theta + b^{\top}A^{-1}b - b^{\top}A^{-1}b = \argmin_\theta\ (\theta - A^{-1}b)^{\top}A(\theta - A^{-1}b) - b^{\top}A^{-1}b$$ $$= \argmin_\theta\ \big\|X\big(\theta - (X^{\top}X)^{-1}X^{\top}y\big)\big\|_2^{2}$$A squared norm is $\ge 0$, so it is minimised exactly when its argument is zero: $\theta^{*} = (X^{\top}X)^{-1}X^{\top}y$. $\;\blacksquare$
Shapes and cost
| Object | Shape | Contents |
|---|---|---|
| $X$ (design matrix) | $\R^{N\times d}$ | row $i$ is ${x^{(i)}}^{\top}$; column 1 is all ones |
| $y$ | $\R^{N}$ | the labels $y^{(1)},\dots,y^{(N)}$ |
| $\theta$ | $\R^{d}$ | $\theta_1 = b$, the rest are weights |
| $X^{\top}X$ | $\R^{d\times d}$ | $O(Nd^{2})$ to form |
| $X^{\top}y$ | $\R^{d}$ | $O(Nd)$ to form |
Total cost of the closed form: $O(Nd^{2} + d^{3})$ — $O(Nd^{2})$ to build $X^{\top}X$, $O(d^{3})$ to invert/solve it. This is why huge $d$ pushes you to gradient descent instead.
When is $\sum_i {x^{(i)}}^{2} = 0$? Only when every $x^{(i)} = 0$ — all training points sit on the $y$-axis in a vertical stack. There is then no slope information at all, and $w^{*}$ is $0/0$: undefined.
Can you just set $\theta = X^{-1}y$? No — $X$ is $N \times d$, generally not square, so $X^{-1}$ does not exist.
What if $X^{\top}X$ is singular ($\det = 0$, e.g. duplicated/collinear features or $N < d$)? Use the pseudo-inverse in place of the inverse. beyond syllabus details not required for this course.
11. Optimization: GD, SGD, mini-batch
→ Ch. 9 · Optimization: GD & SGD
The idea. To the right of the minimum of a parabola the derivative is positive (move left); to the left it is negative (move right); the magnitude of the derivative is large when you are far away. So move against the gradient, proportionally to its magnitude.
| Algorithm | Update (repeat for $t = 1,2,\dots$ until a stopping criterion) | Cost per step |
|---|---|---|
| Gradient descent (a.k.a. batch GD) | $\theta^{(t)} = \theta^{(t-1)} - \alpha\,\nabla_\theta J(\theta)\big|_{\theta = \theta^{(t-1)}}$ | all $N$ samples |
| SGD | choose $j \sim \mathrm{Uniform}\{1,\dots,N\}$, then $\theta^{(t)} = \theta^{(t-1)} - \alpha\,\nabla_\theta\,\ell\big(h_\theta(x^{(j)}), y^{(j)}\big)$ | 1 sample — noisy but fast |
| Mini-batch GD | same, but average the gradient over $K$ samples chosen at random, $1 < K < N$ | $K$ samples |
$\alpha$ is the learning rate / step size. Simple choice: a constant such as 0.01. Another: decay it with $t$, e.g. $\alpha_t = 1/\sqrt{t}$. Initialise $\theta^{(0)}$ anywhere; return $\theta^{(t)}$.
Stop when (1) performance isn't improving much, (2) the derivative/gradient isn't changing much, (3) the iterate isn't moving much, or (4) you run out of compute.
Gradient identities (denominator layout)
For $J : \R^{d} \to \R$, $\nabla_\theta J(\theta) = \frac{\partial J(\theta)}{\partial \theta} = \big[\frac{\partial J}{\partial\theta_1}, \dots, \frac{\partial J}{\partial\theta_d}\big]^{\top} \in \R^{d}$ — a column vector, the same shape as $\theta$. That shape convention is denominator layout (more popular in ML than numerator layout). Generally, $\partial J/\partial\theta$ is just the collection of scalar-by-scalar partial derivatives arranged into a suitable shape.
| $J(\theta)$ | $\nabla_\theta J(\theta)$ |
|---|---|
| $\theta^{\top}v$, $v \in \R^{d}$ | $v$ |
| $\theta^{\top}A\theta$, $A \in \R^{d\times d}$ | $(A + A^{\top})\theta$ (so $2A\theta$ when $A$ is symmetric) |
| $\|y - X\theta\|_2^{2} = y^{\top}y - 2\theta^{\top}X^{\top}y + \theta^{\top}X^{\top}X\theta$ | $-2X^{\top}y + 2X^{\top}X\theta$ |
Setting $-2X^{\top}y + 2X^{\top}X\theta = 0$ recovers $\theta^{*} = (X^{\top}X)^{-1}X^{\top}y$ — linear regression is the special setting where a closed form exists. Most problems have none, which is why GD matters.
Learning rate and convergence
For $J(w) = cw^{2}$ with $c > 0$: $J'(w) = 2cw$, so one GD step is $w^{(t)} = w^{(t-1)} - \alpha\,2cw^{(t-1)} = (1 - 2\alpha c)\,w^{(t-1)}$, i.e. $w^{(t)} = (1-2\alpha c)^{t} w^{(0)}$. This converges iff $|1 - 2\alpha c| < 1$:
$$\boxed{\;0 < \alpha < \tfrac{1}{c}\;} \qquad \text{and for } J(w) = w^{2}\ (c=1):\quad 0 < \alpha < 1$$$\alpha = \frac{1}{2c}$ jumps to the minimum in one step. $\alpha = 1/c$ oscillates forever between $\pm w^{(0)}$. $\alpha > 1/c$ diverges.
| $\alpha$ | factor $1-2\alpha$ | $w^{(1)}$ | $w^{(2)}$ | $w^{(3)}$ | verdict |
|---|---|---|---|---|---|
| 0.25 | $+0.5$ | 0.5 | 0.25 | 0.125 | converging |
| 0.5 | $0$ | 0 | 0 | 0 | exact in one step |
| 1 | $-1$ | $-1$ | $1$ | $-1$ | oscillates, never converges |
| 2 | $-3$ | $-3$ | $9$ | $-27$ | diverges |
| Term | Definition |
|---|---|
| Local minimum | a $\theta \in \R^{d}$ that is lowest in its neighbourhood — there may be $\theta'$ farther away that is lower |
| Global minimum | a $\theta$ with $J(\theta) \le J(\theta')$ for every $\theta' \in \R^{d}$ |
GD may get stuck in a local minimum unless $J$ has special structure (a parabola / convex function has only one). It is still the workhorse because it finds a good solution efficiently. Note $\frac1N\sum_i (y^{(i)} - x^{(i)}w)^2$ is a parabola too, so the single-sample intuition carries over.
12. Feature engineering & overfitting
→ Ch. 10 · Feature engineering
The move. A model can be non-linear in the input while remaining linear in the parameters — and linear-in-parameters is all that linear regression requires. So transform the data, not the model.
$$h(x) = b + w_1x + w_2x^{2} \quad\text{is quadratic in } x \text{ but linear in } (b, w_1, w_2)$$| Object | Definition |
|---|---|
| Feature transform | $\phi : \R^{K} \to \R^{M}$ — $K$ original features in, $M$ produced features out |
| Transformed design matrix | $\Phi \in \R^{N\times M}$, row $i$ being $\phi(x^{(i)})^{\top}$ (often just renamed $X$ afterwards) |
| Degree-$M$ polynomial transform | $\phi(x) = [1,\ x,\ x^{2},\ \dots,\ x^{M}]^{\top}$ — the leading 1 supplies the bias column |
| Other transforms | anything you like: $\sin(x)$, $\|x\|_2$, … — as long as you apply the same $\phi$ at training and at prediction time |
Raise the polynomial degree on a simple dataset ($k = 1, 5, 11, 30$) and the curve starts matching the exact training points rather than the general trend.
The diagnostic: training error keeps falling while test error starts rising. Training error alone can never reveal overfitting — you need held-out data. More features $\Rightarrow$ a richer hypothesis class $\Rightarrow$ better fit and worse generalization past some point.
13. Logistic regression
→ Ch. 11 · Logistic regression
Why not thresholding. $\hat y = g_{\text{threshold}}(wx+b)$ produces valid class labels but is maximally over-confident right at the boundary, and it has derivative zero essentially everywhere, making it impossible to optimise by gradient methods. Replace the step with a smooth squash.
$$\sigma(z) = \frac{1}{1 + e^{-z}} \qquad \sigma:(-\infty,\infty) \to (0,1),\qquad \sigma(0) = 0.5$$| Identity | Use |
|---|---|
| $\sigma'(z) = \sigma(z)\,\big(1 - \sigma(z)\big)$ | makes every gradient collapse neatly; note $\sigma' \le 1/4$, maximal at $z=0$ |
| $\sigma(-z) = 1 - \sigma(z)$ | symmetry about $(0, \tfrac12)$: $P(Y=0\mid x) = \sigma(-\theta^{\top}x)$ |
| $\sigma(z) \ge \tfrac12 \iff z \ge 0$ | turns a probability threshold into a linear test |
The model
$$h(x) = \hat y = \sigma(\theta^{\top}x) = P(Y = 1 \mid x)$$Bias assumed absorbed into $x$ (first coordinate 1). One-dimensional version: $h(x) = \sigma(wx + b)$. Binary classification, $y \in \{0,1\}$.
| Fact | Formula |
|---|---|
| Decision boundary | predict 1 iff $h(x) \ge \tfrac12$ iff $\;\theta^{\top}x = 0\;$ is crossed — a hyperplane, hence a linear classifier |
| Log-odds (logit) | $\displaystyle \log\frac{h(x)}{1 - h(x)} = \theta^{\top}x$ — logistic regression is linear in the log-odds |
| Loss: binary cross-entropy | $\ell = -\big[\,y\log\hat y + (1-y)\log(1 - \hat y)\,\big]$ ($= -\log\hat y$ when $y=1$, $=-\log(1-\hat y)$ when $y=0$) |
| Objective | $\displaystyle J(\theta) = -\frac1N\sum_{i=1}^{N}\Big[y^{(i)}\log \sigma(\theta^{\top}x^{(i)}) + (1-y^{(i)})\log\big(1 - \sigma(\theta^{\top}x^{(i)})\big)\Big]$ |
| Gradient | $\displaystyle \nabla_\theta J(\theta) = \frac{1}{N}\sum_{i=1}^{N}\Big(\sigma(\theta^{\top}x^{(i)}) - y^{(i)}\Big)\,x^{(i)}$ |
| Fitting | no closed form — run GD / SGD with that gradient |
The gradient is literally (prediction − truth) × input, averaged — structurally identical to the linear-regression gradient. That is the payoff of pairing the sigmoid with cross-entropy: the $\sigma'$ factor cancels.
Multi-class: softmax
$$P(Y = k \mid x) = \mathrm{softmax}(z)_k = \frac{e^{z_k}}{\sum_{j=1}^{K} e^{z_j}}, \qquad z_k = \theta_k^{\top}x$$One weight vector $\theta_k$ per class; outputs are positive and sum to 1. With $K = 2$ this reduces exactly to the sigmoid. Loss generalises to cross-entropy $-\sum_k \1(y = k)\log P(Y=k\mid x)$.
Convexity
$f$ convex $\iff f(\lambda z_1 + (1-\lambda)z_2) \le \lambda f(z_1) + (1-\lambda)f(z_2)$ for all $z_1, z_2$, $\lambda\in[0,1]$ $\iff$ (if twice differentiable) $f'' \ge 0$. Every local minimum is global. Logistic cross-entropy is convex in $\theta$ ($\ell''(z) = \sigma(1-\sigma) \ge 0$); squared loss through a sigmoid is not.
14. Regularization & cross-validation
$$\theta^\star = \arg\min_{\theta} \frac1N\sum_{i=1}^{N}\big(\theta^\top\phi(x^{(i)}) - y^{(i)}\big)^2 + \lambda\, r(\theta)$$| Regularizer | $r(\theta)$ | Effect |
|---|---|---|
| $L_0$ | $\sum_j \1\{\theta_j \ne 0\}$ | sparse; arg min computationally hard |
| LASSO | $\sum_j |\theta_j|$ | sparse (exact zeros), tractable |
| Ridge | $\sum_j \theta_j^2$ | shrinks toward 0, rarely exactly 0 |
Don't regularize the bias. Standardize features (subtract mean, divide by standard deviation). Hyperparameters (degree, $\lambda$, tree depth) are chosen on held-out data. Holdout: 80:20 split, high variance with little data. $k$-fold: average error over $k$ folds, $k = 5$ or $10$; $k = N$ is LOOCV. Always retrain on all data with the chosen value. Trainings for $C$ candidates: $Ck + 1$.
15. Neural networks
| Fact | Formula |
|---|---|
| Neuron | $z = b + \sum_j w_jx_j,\ a = g(z)$ — logistic regression is one neuron |
| ReLU | $g(z) = \max(0, z)$, $g'(z) = \1\{z > 0\}$; sigmoid $g' = \sigma(1-\sigma)$ |
| Fully connected layer | $z_{l,i} = b_{l,i} + \sum_j w_{l,i,j}\,a_{l-1,j}$, $a_{l,i} = g(z_{l,i})$; weights indexed (layer, output, input) |
| Parameters per layer | $K$ neurons on $M$ inputs: $K(M+1)$. 3-3-2-1 network: $12 + 8 + 3 = 23$ |
| Chain rule (one path) | multiply edge derivatives: $\frac{df_4}{dx} = \frac{df_4}{df_3}\frac{df_3}{df_2}\frac{df_2}{df_1}\frac{df_1}{dx}$ |
| Multivariate chain rule | $\frac{d}{dx}f(g_1(x),\dots,g_n(x)) = \sum_i \frac{\partial f}{\partial g_i}\frac{dg_i}{dx}$ — multiply along each path, sum over paths; vector form $\frac{\partial\mathbf g}{\partial x}\frac{\partial f}{\partial\mathbf g}$ |
Without a nonlinear $g$, stacked layers collapse to one linear map. The network objective is not convex: results depend on initialization; ReLU neurons can "die" (zero gradient on every point). Vocabulary: output layer, hidden layers, "input layer" = data; fully connected = linear = dense; MLP.
16. Traps — the ten mistakes most likely to cost marks
| # | Trap |
|---|---|
| 1 | Arc consistency deletes from the TAIL. Enforcing $X \to Y$ removes values from $X$'s domain, never $Y$'s. → CSPs |
| 2 | α-β preserves the ROOT value only. Interior node values may be wrong — they are early-return bounds. Never quote a pruned node's number as "the minimax value". → Adversarial search |
| 3 | A specific conditional entropy $H(Y \mid W=\omega)$ CAN exceed $H(Y)$ — one child can be more confused than the parent. The average $H(Y\mid W)$ cannot, which is why $I(Y;W) \ge 0$. → Information theory |
| 4 | $x^{(i)}$ is a sample index, not an exponent. $(x^{(1)})^{2}$ is the square of the first sample; $x^{(2)}$ is the second sample. → ML formulation |
| 5 | Admissible is enough for A* TREE search; you need CONSISTENT for GRAPH search. Graph search discards repeats, so a merely-admissible $h$ can lock in a worse first path to a state. → Informed search |
| 6 | Greedy tree splits are locally, not globally, optimal. The best single split need not begin the best tree; the algorithm is a greedy approximation to ERM, traded for efficiency. → Decision trees |
| 7 | Logistic regression is CLASSIFICATION, not regression. The name comes from the logistic function and the linear log-odds, not from predicting a real-valued $y$. → Logistic regression |
| 8 | Argument order of the loss differs between sources. The lecture notes write $\ell(\hat y, y)$ — guess first, truth second. The pre-reading writes $\ell(y, \hat y)$. Squared and zero-one loss are symmetric so it never changes an answer, but it changes what a symbol means — read the header of the question. → ML formulation |
| 9 | UCS is A* with $h = 0$ (and $h=0$ is consistent, hence UCS is optimal in both tree and graph search). Greedy is the mirror image, $g = 0$, and is optimal in neither. → Search foundations · Informed search |
| 10 | The minimax answer is an ACTION, not just a value. $V(s)$ is the score; the deliverable at the root is $\hat a = \argmax_a V(\mathrm{Result}(s,a))$. Same for a search problem: the solution is the plan, recovered by tracing parent pointers. → Adversarial search |
- Consistency $\Rightarrow$ admissibility. Not the reverse.
- Max of admissible heuristics: admissible, and dominates both.
- $0\log\frac10 := 0$.
- MRV takes the fewest remaining values; LCV takes the value ruling out the fewest.
- $X \in \R^{N\times d}$: rows are samples. Closed form costs $O(Nd^{2}+d^{3})$.
- GD on $J = cw^{2}$ converges iff $0 < \alpha < 1/c$.
- Overfitting = training error $\downarrow$ while test error $\uparrow$.
- Logistic gradient $= \frac1N\sum_i(\hat y^{(i)} - y^{(i)})x^{(i)}$.