AI 100 · WEDNESDAY, DECEMBER 2

Midterm 2 practice

In class during the regular period. Bring a calculator. Phones and computers stay away. The exam covers material since Midterm 1.

Exam format · 50 multiple-choice questions for 50 points, plus six written responses for 50 points. The four 10-point written topics are forests, metrics, transformers and search.

Study order

Suggested one-hour pass: work through the eight lessons in order. Cover each example and predict the result aloud. Then take the mixed challenge and revisit the explanations for any misses.

Trees and forests • Neural networks and training • Testing and generalization • Classification metrics • Language model foundations • Self-attention and transformers • Search and planning • Reinforcement learning

LESSON 1 OF 8 · 9 MIN

Trees and forests

Follow a prediction from root to leaf, then count the votes.

A feature is an input such as hours studied. An internal node asks one question about one feature. Follow the matching branch until a leaf supplies a prediction. While training a tree, the algorithm looks for splits that leave children with more uniform labels. A greedy choice improves the current split and can miss a better whole tree.

Worked example

Suppose a node contains four passes and four fails. Gini impurity is 1 − (½² + ½²) = 0.50. Split it into two groups of four, one all passes and the other all fails. Both children have impurity 0, so their weighted average is 0. For unequal group sizes, weight each impurity by its fraction of examples.

A single deep tree can fit quirks in its sample. A forest trains many trees on resampled records and tries random subsets of features at splits. If their errors differ, voting can cancel some errors. If all trees learn the same shortcut, voting preserves it.

LESSON 2 OF 8 · 8 MIN

Neural networks and training

Trace one prediction forward and its error backward.

A neuron multiplies each input by a learned weight, adds a bias, and applies an activation. Hidden layers combine these outputs into features for later layers. Nonlinear activations let the network represent relationships that a sequence of linear operations alone cannot capture.

Worked example

With input 3, weight 2, and bias −4, the weighted sum is 2. ReLU returns max(0, 2) = 2. If the target is 5, squared error is 9. Backpropagation computes how loss changes with each weight. Gradient descent uses those gradients to update the weights.

Direction matters. A negative gradient means increasing that parameter slightly should lower loss locally. The learning rate sets the size of the move. Too large a move can jump past the minimum.

LESSON 3 OF 8 · 6 MIN

Testing and generalization

Decide which evidence supports performance on new cases.

Training data fit the parameters. Validation data help choose the model, training duration, or threshold. Reserve the test set for a final check on unseen examples. Repeated tuning on test scores leaks information into those decisions.

Worked example

Model A scores 99% on training and 71% on validation. B scores 90% and 86%. With comparable samples, B has stronger evidence of generalization. High error on both sets can indicate underfitting. A large gap can indicate overfitting.

Consider a scanner logo that correlates with a diagnosis at one hospital. Even an excellent same-hospital test score can hide this shortcut. Evaluate on the hospitals and populations where the system will operate.

LESSON 4 OF 8 · 10 MIN

Classification metrics

Name the positive class before choosing a denominator.

Precision asks how many positive predictions were correct. Recall asks how many actual positives were found. Accuracy counts all correct predictions. F1 combines precision and recall through their harmonic mean, so a low value of either pulls F1 down.

Worked example

Out of 100 items, 5 are defective. Predicting “good” every time gets 95 correct and misses all 5 defects. Accuracy is 95%, recall is 0/5, and precision is undefined because there were zero positive predictions.

A threshold turns a score into a label. A score of 0.62 counts as positive at 0.60 and negative at 0.70. Lowering the cutoff can recover missed positives while also flagging more negatives. Choose the threshold using the costs of those errors.

LESSON 5 OF 8 · 6 MIN

Language model foundations

Explain where a next-token training label comes from.

A tokenizer splits text into units that may be words, word pieces, or punctuation. Each token ID looks up a learned vector. The model uses the sequence to produce a probability distribution over possible next tokens.

Worked example

In “please close the door,” the prefix “please close the” supplies input and “door” supplies its own target. A model assigning door probability 0.8 incurs less cross-entropy loss than one assigning it 0.1. Training updates parameters to make observed continuations more probable.

At inference the model selects a next token, appends it, and repeats using the available context. A likely continuation can contain a false claim because this objective rewards predicting text.

LESSON 6 OF 8 · 8 MIN

Self-attention and transformers

Explain how the representation of one token changes with context.

An embedding supplies a starting representation. A query represents what a position seeks, keys describe what other positions offer, and values carry information to combine. Query–key matches determine attention weights. In causal language modeling, each position can use earlier positions and itself.

Worked example

Suppose two positions receive weights 0.75 and 0.25. If their value vectors are (4, 0) and (0, 8), their weighted contribution is (3, 2). Real heads learn these weights from the sequence. Multiple heads can capture different relationships.

In “fruit bat” and “baseball bat,” bat can start from the same lookup vector. Different surrounding tokens change its contextual representation, affecting the distribution of what follows. The context window limits the tokens available in that forward pass.

LESSON 7 OF 8 · 9 MIN

Search and planning

Write the frontier after each expansion.

Represent each state as a configuration, each action as a transition, and the goal as a test. BFS uses a queue: expand the shallowest states first. DFS follows one branch deeply using a stack. Greedy best-first search chooses the smallest estimated remaining cost h.

Worked example

If the frontier contains X at depth 1 with h = 7 and Y at depth 3 with h = 2, BFS chooses X and greedy chooses Y. Greedy can chase a misleading estimate. BFS gives a shortest path by number of steps when each step costs the same.

A plan must respect preconditions and effects. Unlocking a door requires the key and changes the door to unlocked. A proposed sequence that opens the locked door before acquiring the key is invalid, even if its destination is correct.

LESSON 8 OF 8 · 6 MIN

Reinforcement learning

Follow the loop from state to action to reward to next state.

An agent observes a state, chooses an action under its policy, and receives a reward and a new state from the environment. Its objective is expected cumulative reward. Exploration tries actions whose value is uncertain. Exploitation picks the best known action.

Worked example

A shortcut pays +3 now and ends the episode. A detour pays −1 now and +8 one step later. With no discount, their returns are 3 and 7. With a discount of 0.5, the detour returns −1 + 0.5 × 8 = 3. The timing of reward can change the preferred policy.

A Q-value estimates the future return of taking an action in a state and then following a policy. A reward based on clicks can favor sensational items. Specify the desired outcome and ask how an agent might collect the reward without delivering it.

Practice challenge

24 original multiple-choice questions across all eight lessons. Choose one answer to see the explanation. Retry missed questions at the end.

Written practice

Try all six on paper, then reveal each solution. Show the calculations and explain each decision in your own words.

Forest vote · 10 points

Three trees vote yes under these respective rules: hours ≥ 4, score ≥ 70, and both hours ≥ 3 and score ≥ 80. For 4 hours and a score of 72, trace the votes. What changes at 3 hours? Why use several trees?

Check your reasoning

At 4 hours the votes are yes, yes, no. The majority predicts yes. At 3 hours they become no, yes, no, flipping the majority. Each tree follows feature tests to a leaf. Training trees on different bootstrap samples and feature subsets makes their errors less correlated. Voting can reduce variance, at the cost of computation and interpretability.

Classification metrics · 10 points

A detector flags 30 items. Of those, 18 are truly defective. It misses 6 defective items and correctly clears 64 good ones. Label the four cells, calculate all four metrics, and explain what lowering the threshold could do.

Check your reasoning

TP = 18, FP = 12, FN = 6, TN = 64. Accuracy = (18 + 64)/100 = 82%. Precision = 18/30 = 60% of flags are correct. Recall = 18/24 = 75% of defects are caught. F1 = 2(0.60)(0.75)/(0.60 + 0.75) ≈ 0.667. Lowering the threshold can catch missed defects and trigger more false alarms. Favor recall when a missed defect is costly. Canvas says formulas are supplied and you must show your work.

Embeddings and attention · 10 points

Compare “she deposited cash at the bank” with “she sat on the river bank.” Assume bank has the same token ID. What stays the same at lookup, what changes inside the transformer, and how does that affect prediction?

Check your reasoning

The ID indexes the same learned vector in both sentences. Training adjusts vector coordinates to reduce prediction loss, so tokens used similarly can acquire similar vectors. Self-attention compares queries with keys and mixes value vectors according to relevance. Cash and river supply different evidence, changing the contextual representation of bank. The resulting next-token distributions can favor different continuations.

Trace the search · 10 points

A has children B,C. B has D,E. C has F,G. D has H. Goal F. Visit children left to right and stop when the goal is visited. List BFS and DFS visits, count them, and say when greedy search could choose a longer route.

Check your reasoning

BFS: A B C D E F (6). A queue finishes each depth first, giving a shortest path in edge count with equal step costs, though the frontier can consume memory. DFS: A B D H E C F (7). A stack follows one branch deeply and can find a deep goal early or spend time down a poor branch. Greedy search ranks frontier states by estimated distance to goal and ignores cost already paid. A promising estimate can lead into a long detour.

Train one weight · 5 points

A network predicts too high. Explain one training step. If a weight is 0.8, its loss gradient is +2 and the learning rate is 0.05, where does it move?

Check your reasoning

The forward pass uses weights, biases and activations to predict. Loss measures error against the target. Backpropagation computes how loss changes with each parameter. Gradient descent updates this weight to 0.8 − 0.05 × 2 = 0.7. Repeat over batches. A large learning rate can overshoot and a small one can slow learning.

Reward design · 5 points

A cleaning robot earns a point each time it picks up litter. It starts dropping the same object and picking it up again. Identify the agent, environment, state, actions, reward and policy. Repair the incentive.

Check your reasoning

The robot is the agent and the room is its environment. State can include its position, litter locations and whether it holds an item. Moving, dropping and picking up are actions. Pickup earns the reward. Its policy maps states to action choices and can learn the profitable loop. Reward a lasting reduction in litter or verified disposal of distinct items so the loop yields no extra return.

November 24 Canvas exam announcement · Instructor’s MC practice download