ML Fundamentals: Bayes, Neural Nets, KNN, and Transformers
Machine LearningModel answerLast updated
Work through four sets of ML fundamentals: a Bayes' rule posterior with a rare event, neural network arithmetic, KNN concept checks, and Transformer mechanics.
You are preparing for a timed ML engineering assessment. The multiple-choice section covers four topic areas. For each part below, show enough intermediate work that you could confidently eliminate wrong options under time pressure.
Part 1 — Bayes' Rule
A fraud-detection system screens transactions. 3% of transactions are fraudulent. The system correctly flags 92% of fraudulent transactions and incorrectly flags 4% of legitimate ones.
- A transaction is flagged. What is the probability it is actually fraudulent?
- A second, independent screening tool (same detection and false-positive rates, conditionally independent of the first given the true label) also flags the same transaction. What is the probability now?
Your answer should identify the prior, both likelihoods, and the normalizing constant, and explain why the low base rate matters so much.
Part 2 — Forward-Pass Arithmetic and Parameter Counts
-
A single neuron has weights
(1.0, -0.5, 2.0)and bias0.5. It receives input(3, 2, 1). Compute its output under a ReLU activation and under a sigmoid activation. -
A fully connected feedforward network takes 5 input features, passes them through a hidden layer of 4 units, then produces 3 output values. Every layer includes bias terms. How many trainable parameters does the network have?
-
A small network has two inputs, two ReLU hidden units, and one linear output unit.
- Hidden unit 1: weights
(1, -2), bias0 - Hidden unit 2: weights
(0.5, 1), bias-1 - Output:
3·h1 + (-1)·h2 + 0
For input
(1, 1), compute both hidden activations and the final output. Which parameters receive a zero gradient from this single example during backpropagation, and why? - Hidden unit 1: weights
Part 3 — KNN Concept Checks
1. Mark each statement true or false, with a one-sentence reason.
- (a) KNN requires almost no computation during training, but prediction time scales with the size of the training set.
- (b) A larger k always reduces test error.
- (c) With k = 1, KNN achieves 100% accuracy on the training set, provided no two identical points carry different labels.
- (d) Multiplying one feature's values by 1,000 (e.g. converting meters to millimeters) does not affect KNN's predictions.
- (e) KNN generalizes just as well in 1,000-dimensional space as in 10-dimensional space, given the same training set size.
- (f) KNN can handle regression tasks by returning the mean of the k nearest neighbors' target values.
2. Worked prediction.
One-dimensional training set: class A at positions 0, 1, 3; class B at positions 4 and 6. Using absolute distance and majority vote, classify a query point at 3.5 with k = 1 and with k = 3.
Part 4 — Transformer Concept Checks
1. Mark each statement true or false, with a one-sentence reason.
- (a) The compute and memory cost of standard scaled dot-product attention grows quadratically with sequence length.
- (b) Without positional encodings or an attention mask, self-attention is permutation-equivariant: shuffling the input tokens only shuffles the outputs in the same way.
- (c) Dividing attention scores by √d_k is done primarily to keep the number of learnable parameters small.
- (d) A causal (autoregressive) mask prevents each token from attending to any token that appears later in the sequence.
- (e) Using h attention heads with the same model dimension multiplies the total parameter count of the attention projection matrices by h compared to single-head attention.
- (f) Layer normalization normalizes each feature dimension across all examples in the current batch.
2. Parameter count.
A multi-head attention module has model dimension d_model = 256 and 4 heads. Query, key, value, and output projections each have a bias term. What is the dimension per head? How many total trainable parameters do the four projection matrices (plus their biases) contain?
Hints
Hint 1
For Part 1, write out P(flagged) as a weighted sum over both classes first; this denominator is the piece most often dropped under time pressure. After the first posterior, treat it as the new prior before applying the second observation.
Hint 2
For Part 2 question 3, check the sign of each hidden unit's pre-activation before applying ReLU. Any unit that is inactive (output = 0) passes a zero gradient back to all of its incoming weights and its bias for this example.
Hint 3
For Part 4 question 2, each head works in a d_model/h dimensional subspace. The four projection matrices are W_Q, W_K, W_V (each d_model × d_head) and W_O (d_model × d_model when the heads are concatenated back); count rows × columns for each, then add biases separately.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Part 1 — Bayes' Rule
Setup. Let F = truly fraudulent, L = legitimate, Flagged = system raises an alert.
- P(F) = 0.03, P(L) = 0.97
- P(Flagged | F) = 0.92 (true positive rate)
- P(Flagged | L) = 0.04 (false positive rate)
Normalizing constant (total flag rate):
P(Flagged) = 0.92 × 0.03 + 0.04 × 0.97 = 0.0276 + 0.0388 = 0.0664
Posterior after one flag:
P(F | Flagged) = (0.92 × 0.03) / 0.0664 = 0.0276 / 0.0664 ≈ 0.416
Even with a 92% detection rate, fewer than half of flagged transactions are actually fraudulent. The low 3% base rate is the dominant factor: the false-positive pool (97% of transactions × 4%) swamps the true-positive pool.
After a second independent flag, treat 0.416 as the new prior and apply the same rates:
P(Flagged₂) = 0.92 × 0.416 + 0.04 × 0.584 = 0.383 + 0.023 = 0.406
P(F | both flagged) = (0.92 × 0.416) / 0.406 ≈ 0.383 / 0.406 ≈ 0.943
A second independent signal pushes confidence above 94%, showing how quickly posteriors update when observations are conditionally independent.
Part 2 — Forward-Pass Arithmetic
2.1 Pre-activation: z = 1.0×3 + (−0.5)×2 + 2.0×1 + 0.5 = 3 − 1 + 2 + 0.5 = 4.5
- ReLU(4.5) = 4.5
- sigmoid(4.5) = 1/(1 + e^{−4.5}) ≈ 0.9890
2.2 Parameter count for a 5→4→3 network with biases:
- Layer 1: 5×4 weights + 4 biases = 24
- Layer 2: 4×3 weights + 3 biases = 15
- Total: 39 parameters
2.3 Hidden activations for input (1, 1):
- h1 pre-activation: 1×1 + (−2)×1 + 0 = −1 → ReLU(−1) = 0 (inactive)
- h2 pre-activation: 0.5×1 + 1×1 + (−1) = 0.5 → ReLU(0.5) = 0.5
- Output: 3×0 + (−1)×0.5 + 0 = −0.5
Zero-gradient parameters: h1 is in the dead zone for this example. Its gradient is zero because ReLU's derivative at a negative pre-activation is 0, which zeroes out the chain rule signal flowing back through it. Specifically, h1's weights (1, −2) and its bias receive zero gradient. The output bias is also zero here (it equals 0 and contributes nothing, but if it were a learned parameter it would still receive a gradient from the output; confirm this is literal 0, not a trained value).
Common mistake: forgetting that the dead neuron blocks gradients for its own weights but not for neurons earlier in the graph that also feed h2.
Part 3 — KNN Concept Checks
(a) True. Training is just storing data. At prediction time, every stored point must be compared to the query, so cost is O(n·d).
(b) False. Increasing k reduces variance but increases bias; at some point test error rises again. The optimal k is a hyperparameter.
(c) True. With k = 1 each training point is its own nearest neighbor, so it is always classified correctly (assuming no label noise on duplicate points).
(d) False. Euclidean (or absolute) distances depend on scale. Multiplying one feature by 1,000 makes it dominate the distance calculation and can completely change which neighbors are nearest.
(e) False. This is the curse of dimensionality. In high dimensions, all points tend toward the same distance from a query, making "nearest" neighbors no longer meaningfully similar.
(f) True. KNN regression is well-defined: predict the mean (or median) of the k neighbors' target values.
Worked prediction, query at 3.5:
Distances: |3.5−0|=3.5 (A), |3.5−1|=2.5 (A), |3.5−3|=0.5 (A), |3.5−4|=0.5 (B), |3.5−6|=2.5 (B)
- k = 1: nearest neighbor is a tie between 3 (A) and 4 (B), both at distance 0.5. Break ties by lowest index or flag as ambiguous; most implementations pick the first encountered — predict A (or note the tie).
- k = 3: three nearest are 3 (A), 4 (B), 1 (A) or 6 (B) tied at 2.5. Taking 3, 4, and 1: two A, one B → predict A.
Part 4 — Transformer Concept Checks
(a) True. The attention matrix is n×n (where n is sequence length), and computing it requires O(n²·d) operations and O(n²) memory.
(b) True. Without position signals the attention weights are a function only of the content of tokens, which is symmetric over permutations. Each output is the same weighted combination regardless of token order.
(c) False. The scaling by √d_k has nothing to do with parameter count. It prevents the dot products from growing large in magnitude (which would push softmax into near-zero-gradient regions) when d_k is large.
(d) True. The causal mask sets attention logits to −∞ for all positions j > i before the softmax, so position i can only attend to positions 0 through i.
(e) False. In standard multi-head attention the projections per head are smaller (d_model/h), so the total parameter count of the four projections stays the same as single-head attention at the same d_model.
(f) False. Layer normalization normalizes across the feature (model) dimension for each individual example, not across examples. Batch normalization is the one that normalizes across the batch.
Parameter count, d_model = 256, h = 4:
- d_head = 256/4 = 64
- W_Q, W_K, W_V: each is 256×64, so 16,384 weights + 64 biases = 16,448 each → three projections: 49,344
- W_O: concatenates 4 heads of size 64 back to 256, so 256×256 = 65,536 weights + 256 biases = 65,792
- Total: 49,344 + 65,792 = 115,136 parameters
Common mistake: treating W_O as 64×256 (one head's worth) instead of (h·d_head)×d_model = 256×256.