-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgenerate_ml2_homeworks.py
More file actions
3042 lines (2565 loc) · 114 KB
/
generate_ml2_homeworks.py
File metadata and controls
3042 lines (2565 loc) · 114 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Generate homework assignments for ML2 course lectures.
Each homework combines programming exercises and knowledge questions.
Target completion time: ~1 hour
"""
import json
import os
# Homework content for each lecture
HOMEWORKS = {
1: {
"title": "Introduction to Deep Learning",
"programming": [
{
"title": "Experiment: Observing Feature Learning",
"description": "Run this code to visualize what happens when a network learns features automatically vs. using hand-crafted features. Observe the outputs and answer the reflection questions below.",
"time": "8 min",
"starter_code": """import torch
import torch.nn as nn
import numpy as np
# Simulate a simple pattern recognition task
# Pattern: Detect if sum of inputs > 5
np.random.seed(42)
torch.manual_seed(42)
# Generate data
X = torch.randn(100, 4) # 100 samples, 4 features
y = (X.sum(dim=1) > 0).float() # Label: 1 if sum > 0, else 0
# Network that LEARNS features
model = nn.Sequential(
nn.Linear(4, 8), # Learned feature extraction
nn.ReLU(),
nn.Linear(8, 1),
nn.Sigmoid()
)
# Train for a few steps
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
loss_fn = nn.BCELoss()
for epoch in range(20):
optimizer.zero_grad()
predictions = model(X).squeeze()
loss = loss_fn(predictions, y)
loss.backward()
optimizer.step()
print(f"Final loss: {loss.item():.4f}")
print(f"First layer weights (learned features):")
print(model[0].weight.data)
# TODO: After running, answer reflection questions below"""
},
{
"title": "Experiment: Network Without Nonlinearity",
"description": "This experiment demonstrates why activation functions are essential. Compare two networks: one with ReLU, one without.",
"time": "10 min",
"starter_code": """import torch
import torch.nn as nn
# Network WITH nonlinearity (ReLU)
network_with_relu = nn.Sequential(
nn.Linear(10, 20),
nn.ReLU(),
nn.Linear(20, 15),
nn.ReLU(),
nn.Linear(15, 5)
)
# Network WITHOUT nonlinearity (just linear layers)
network_without_relu = nn.Sequential(
nn.Linear(10, 20),
nn.Linear(20, 15),
nn.Linear(15, 5)
)
# Test input
x = torch.randn(1, 10)
# Compare outputs
output_with = network_with_relu(x)
output_without = network_without_relu(x)
print("With ReLU output:", output_with)
print("Without ReLU output:", output_without)
# TODO: Now manually compute what network_without_relu is equivalent to
# Hint: Multiple linear transformations collapse into a single linear transformation
# Can you express the 3-layer linear network as a SINGLE equivalent linear layer?"""
}
],
"knowledge": [
{
"type": "short",
"question": "**Question 1 - Automatic Feature Learning (Conceptual)**\n\nTraditional machine learning for image classification requires manually designing features (e.g., edge detectors, color histograms, texture filters). Deep learning does not.\n\nExplain in 3-4 sentences:\n1. WHY can deep networks learn features automatically?\n2. WHAT enables this (what architectural property)?\n3. What is the tradeoff (what does deep learning need more of)?",
"hint": "Think about what happens in each layer of a deep network and how backpropagation adjusts those layers."
},
{
"type": "short",
"question": "**Question 2 - Feature Hierarchy (Conceptual)**\n\nIn a deep CNN for face recognition:\n- Layer 1 might detect edges\n- Layer 2 might detect facial features (eyes, nose)\n- Layer 3 might detect whole faces\n\nExplain: Why does depth create this hierarchy? What would happen if you used a single-layer network instead?",
"hint": "Consider how each layer builds on representations from the previous layer."
},
{
"type": "short",
"question": "**Question 3 - Nonlinearity Experiment Reflection**\n\nBased on the 'Network Without Nonlinearity' experiment above:\n\nProve mathematically or explain conceptually why the 3-layer network without ReLU is equivalent to a SINGLE linear layer. What does this tell you about the necessity of activation functions?",
"hint": "Remember: Linear(Linear(x)) = Linear(x) because you can multiply weight matrices together."
},
{
"type": "mc",
"question": "**Question 4 - Understanding Nonlinearity**\n\nA neural network with 10 layers but NO activation functions can represent:\n\nA) Any possible function (universal approximation)\nB) Only linear functions\nC) Only polynomial functions\nD) Only step functions",
"options": [
"A) Any possible function (universal approximation)",
"B) Only linear functions",
"C) Only polynomial functions",
"D) Only step functions"
],
"hint": "What happens when you compose linear transformations?"
},
{
"type": "short",
"question": "**Question 5 - ReLU Design Choice**\n\nReLU(x) = max(0, x) is one of the simplest possible nonlinear functions. Yet it became the dominant activation function (replacing sigmoid).\n\nExplain TWO advantages ReLU has over sigmoid for deep networks. One should relate to gradients, one to computation.",
"hint": "Think about what happens to gradients when x is large and positive in sigmoid vs ReLU."
},
{
"type": "short",
"question": "**Question 6 - Gradient Descent Intuition**\n\nGradient descent updates weights using: θ_new = θ_old - α × ∇L\n\nWhere ∇L is the gradient of the loss.\n\nExplain in simple terms:\n1. What does the gradient ∇L represent geometrically?\n2. Why do we SUBTRACT it (the negative sign)?\n3. What role does α (learning rate) play?",
"hint": "Think of the loss function as a landscape/terrain you're trying to navigate."
},
{
"type": "mc",
"question": "**Question 7 - Loss Function Purpose**\n\nThe loss function in deep learning serves to:\n\nA) Measure how wrong the model is, providing a signal for gradient descent\nB) Prevent overfitting by penalizing complex models\nC) Speed up training by reducing computation\nD) Automatically select which features to learn",
"options": [
"A) Measure how wrong the model is, providing a signal for gradient descent",
"B) Prevent overfitting by penalizing complex models",
"C) Speed up training by reducing computation",
"D) Automatically select which features to learn"
],
"hint": "What do we need to compute gradients?"
},
{
"type": "short",
"question": "**Question 8 - Feature Learning Reflection**\n\nAfter running the 'Observing Feature Learning' experiment:\n\nLook at the learned weights in the first layer. These represent the FEATURES the network learned.\n\nExplain: How did the network 'know' which features to learn? What guided it to learn useful features rather than random ones?",
"hint": "The answer involves both the loss function and backpropagation."
},
{
"type": "short",
"question": "**Question 9 - Connecting the Concepts**\n\nIntegrate all three key insights:\n\nExplain how (1) automatic feature learning, (2) nonlinearity, and (3) gradient descent work TOGETHER to enable deep learning. \n\nYour answer should show how all three are necessary and how they interact.",
"hint": "Think: What would happen if you removed any one of these three components?"
},
{
"type": "short",
"question": "**Question 10 - Scaling to Real Problems**\n\nImageNet (image classification) has 1000 classes and ~1.2 million training images. Traditional ML would require human experts to manually design thousands of features.\n\nExplain: Why does deep learning have an advantage that GROWS as the problem gets more complex (more classes, more data)? What breaks down in the traditional approach?",
"hint": "Consider both the human effort required and what happens when you have more data."
}
]
},
2: {
"title": "Neural Networks & Backpropagation",
"programming": [
{
"title": "Experiment: Tracing the Chain Rule",
"description": "This experiment demonstrates how backpropagation systematically applies the chain rule. You'll manually trace gradients through a simple computation graph.",
"time": "12 min",
"starter_code": """import torch
# Simple computation graph: z = (x * w + b)^2
x = torch.tensor(2.0, requires_grad=True)
w = torch.tensor(3.0, requires_grad=True)
b = torch.tensor(1.0, requires_grad=True)
# Forward pass
y = x * w + b # Intermediate value
z = y ** 2 # Final output
print(f"Forward pass: x={x.item()}, w={w.item()}, b={b.item()}")
print(f"Intermediate y = x*w + b = {y.item()}")
print(f"Final z = y^2 = {z.item()}")
# Backpropagation (automatic)
z.backward()
print(f"\\nAutomatic gradients:")
print(f"dz/dx = {x.grad.item()}")
print(f"dz/dw = {w.grad.item()}")
print(f"dz/db = {b.grad.item()}")
# TODO: Now manually compute these gradients using the chain rule:
# dz/dx = dz/dy * dy/dx
# What is dz/dy? What is dy/dx?
# Verify your manual calculation matches PyTorch's automatic result"""
},
{
"title": "Experiment: Gradient Descent with Different Batch Sizes",
"description": "Compare how different batch sizes affect training dynamics. Observe convergence speed, stability, and final loss.",
"time": "10 min",
"starter_code": """import torch
import torch.nn as nn
import matplotlib.pyplot as plt
# Generate synthetic data: y = 2x + 1 + noise
torch.manual_seed(42)
X = torch.randn(1000, 1) * 10
y = 2 * X + 1 + torch.randn(1000, 1) * 2
def train_with_batch_size(batch_size, epochs=50):
model = nn.Linear(1, 1)
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
criterion = nn.MSELoss()
losses = []
for epoch in range(epochs):
# Shuffle and create batches
perm = torch.randperm(len(X))
epoch_loss = 0
num_batches = 0
for i in range(0, len(X), batch_size):
batch_idx = perm[i:i+batch_size]
X_batch, y_batch = X[batch_idx], y[batch_idx]
optimizer.zero_grad()
pred = model(X_batch)
loss = criterion(pred, y_batch)
loss.backward()
optimizer.step()
epoch_loss += loss.item()
num_batches += 1
losses.append(epoch_loss / num_batches)
return losses, model.weight.item(), model.bias.item()
# Compare different batch sizes
batch_sizes = [1, 32, 256, 1000] # SGD, mini-batch, large batch, full batch
results = {}
for bs in batch_sizes:
losses, final_w, final_b = train_with_batch_size(bs)
results[bs] = {'losses': losses, 'w': final_w, 'b': final_b}
print(f"Batch size {bs}: Final w={final_w:.3f}, b={final_b:.3f}")
# TODO: After running, answer reflection questions about what you observe"""
}
],
"knowledge": [
{
"type": "short",
"question": """**Question 1 - The Chain Rule IS Backpropagation (Conceptual)**
Consider a 3-layer network: Input → Layer1 → Layer2 → Layer3 → Loss
To update Layer1's weights, you need dLoss/dWeights_Layer1.
Explain:
1. Why must you compute gradients for Layer3, then Layer2, THEN Layer1 (in that order)?
2. What mathematical principle requires this backward ordering?
3. What would go wrong if you tried to compute Layer1's gradient first?""",
"hint": "Think about the chain rule: df/dx = df/dg × dg/dx. What do you need to know first?"
},
{
"type": "short",
"question": """**Question 2 - Manual Chain Rule Calculation**
Based on the 'Tracing the Chain Rule' experiment:
For the computation graph z = (x*w + b)², manually calculate dz/dw step by step:
1. What is dz/dy (where y = x*w + b)?
2. What is dy/dw?
3. Using the chain rule, what is dz/dw = dz/dy × dy/dw?
4. Verify this matches the PyTorch automatic gradient.""",
"hint": "Remember: d/dy(y²) = 2y and d/dw(x*w + b) involves x."
},
{
"type": "short",
"question": """**Question 3 - Why Backward Propagation?**
Explain why we call it "backpropagation" rather than just "gradient computation."
What specific property of the chain rule makes the backward direction necessary and efficient?""",
"hint": "Consider: could you compute gradients going forward instead? Why or why not?"
},
{
"type": "mc",
"question": """**Question 4 - Vanishing Gradients**
In a very deep network (100 layers), gradients in early layers become extremely small. This is called the "vanishing gradient problem."
Why does this happen?
A) Early layers have fewer parameters
B) The chain rule multiplies many numbers less than 1 together
C) Early layers receive less data
D) Backpropagation doesn't reach early layers""",
"options": [
"A) Early layers have fewer parameters",
"B) The chain rule multiplies many numbers less than 1 together",
"C) Early layers receive less data",
"D) Backpropagation doesn't reach early layers"
],
"hint": "Think about what happens when you multiply 0.5 × 0.5 × 0.5 × 0.5... many times."
},
{
"type": "short",
"question": """**Question 5 - Gradient as Directional Information**
A gradient magnitude of 0.001 vs 100.0 tells you very different things about the loss landscape.
Explain:
1. What does a gradient magnitude of 0.001 indicate?
2. What does a gradient magnitude of 100.0 indicate?
3. Which situation might require adjusting the learning rate, and how?""",
"hint": "Large gradient = steep slope. Small gradient = flat region (or near minimum)."
},
{
"type": "short",
"question": """**Question 6 - Batch Size Experiment Reflection**
After running the 'Gradient Descent with Different Batch Sizes' experiment:
Compare batch_size=1 vs batch_size=1000:
1. Which had smoother loss curves?
2. Which made more weight updates per epoch?
3. Which do you think explored the solution space better? Why?""",
"hint": "More updates = more opportunities to correct course, but also more noise."
},
{
"type": "short",
"question": """**Question 7 - The Bias-Variance Tradeoff in Batch Size**
Large batch sizes give accurate gradient estimates (low variance) but fewer updates.
Small batch sizes give noisy estimates (high variance) but more frequent updates.
Explain: Why might the NOISE from small batches actually be BENEFICIAL for finding better solutions?""",
"hint": "Think about escaping local minima. Can noise help you 'jump out' of a bad spot?"
},
{
"type": "mc",
"question": """**Question 8 - Learning Rate Impact**
If your learning rate is too large, what typically happens?
A) Training is slow but converges smoothly
B) The loss oscillates wildly or increases
C) Gradients become more accurate
D) The model memorizes the training data""",
"options": [
"A) Training is slow but converges smoothly",
"B) The loss oscillates wildly or increases",
"C) Gradients become more accurate",
"D) The model memorizes the training data"
],
"hint": "Think about taking huge steps in the direction of the gradient. Can you overshoot the minimum?"
},
{
"type": "short",
"question": """**Question 9 - Connecting Backpropagation to Learning**
Integrate the concepts:
Explain how backpropagation (chain rule) and gradient descent work together to enable learning.
Your answer should connect:
- How backpropagation computes what gradients are
- How gradient descent uses those gradients to update weights
- Why you need both for deep learning to work""",
"hint": "Backpropagation tells you the direction, gradient descent tells you how far to step."
},
{
"type": "short",
"question": """**Question 10 - Real-World Implications**
Modern deep learning models (like GPT or BERT) have billions of parameters across hundreds of layers.
Explain:
1. Why is automatic differentiation (backpropagation) absolutely essential for training these models?
2. What would be impossible without it?""",
"hint": "Imagine manually calculating gradients for 175 billion parameters. How long would that take?"
}
]
},
3: {
"title": "Building Real-World Housing Price Predictor",
"programming": [
{
"title": "Experiment: Comparing Evaluation Metrics",
"description": "Train a simple regression model and observe how different metrics (MSE, MAE, R²) tell different stories about model performance.",
"time": "10 min",
"starter_code": """import torch
import torch.nn as nn
import numpy as np
# Generate synthetic regression data with some outliers
torch.manual_seed(42)
X = torch.randn(100, 1) * 10
y_true = 2 * X + 5 + torch.randn(100, 1) * 2
# Add 5 outliers
outlier_idx = torch.randint(0, 100, (5,))
y_true[outlier_idx] += torch.randn(5, 1) * 20
# Simple model
model = nn.Linear(1, 1)
optimizer = torch.optim.SGD(model.parameters(), lr=0.001)
# Train
for epoch in range(200):
optimizer.zero_grad()
pred = model(X)
loss = nn.MSELoss()(pred, y_true)
loss.backward()
optimizer.step()
# Evaluate with different metrics
with torch.no_grad():
final_pred = model(X)
mse = nn.MSELoss()(final_pred, y_true).item()
mae = nn.L1Loss()(final_pred, y_true).item()
# R-squared
ss_res = torch.sum((y_true - final_pred) ** 2).item()
ss_tot = torch.sum((y_true - y_true.mean()) ** 2).item()
r2 = 1 - (ss_res / ss_tot)
print(f"MSE: {mse:.4f}")
print(f"MAE: {mae:.4f}")
print(f"R²: {r2:.4f}")
# TODO: Answer reflection questions about what each metric tells you"""
},
{
"title": "Experiment: Detecting Overfitting",
"description": "Observe what overfitting looks like by comparing train vs validation performance.",
"time": "12 min",
"starter_code": """import torch
import torch.nn as nn
# Generate data
torch.manual_seed(42)
X_train = torch.randn(50, 1) * 5
y_train = 3 * X_train + 2 + torch.randn(50, 1) * 1
X_val = torch.randn(20, 1) * 5
y_val = 3 * X_val + 2 + torch.randn(20, 1) * 1
# Model with too much capacity (overly complex for the task)
overfit_model = nn.Sequential(
nn.Linear(1, 100),
nn.ReLU(),
nn.Linear(100, 100),
nn.ReLU(),
nn.Linear(100, 1)
)
optimizer = torch.optim.Adam(overfit_model.parameters(), lr=0.01)
criterion = nn.MSELoss()
train_losses = []
val_losses = []
for epoch in range(500):
# Train
optimizer.zero_grad()
train_pred = overfit_model(X_train)
train_loss = criterion(train_pred, y_train)
train_loss.backward()
optimizer.step()
# Validate
with torch.no_grad():
val_pred = overfit_model(X_val)
val_loss = criterion(val_pred, y_val)
train_losses.append(train_loss.item())
val_losses.append(val_loss.item())
if epoch % 100 == 0:
print(f"Epoch {epoch}: Train Loss = {train_loss:.4f}, Val Loss = {val_loss:.4f}")
# TODO: Observe the pattern. When does overfitting start?"""
}
],
"knowledge": [
{
"type": "short",
"question": """**Question 1 - Understanding MSE vs MAE**
MSE = mean((y_true - y_pred)²)
MAE = mean(|y_true - y_pred|)
Explain:
1. Why does MSE use squaring? What effect does this have?
2. When would you prefer MAE over MSE?
3. If you have outliers in your data, which metric would be more affected? Why?""",
"hint": "Think about what happens when you square large errors vs small errors."
},
{
"type": "short",
"question": """**Question 2 - What R² Really Means**
R² = 1 - (SS_residual / SS_total)
R² ranges from 0 to 1 (or sometimes negative for very bad models).
Explain in plain language:
1. What does R² = 0.8 mean about your model?
2. What does R² = 0 mean?
3. Why is R² more interpretable than MSE for comparing models across different datasets?""",
"hint": "R² represents the proportion of variance explained by the model."
},
{
"type": "mc",
"question": """**Question 3 - Metric Selection**
You're building a house price predictor. Buyers care most about absolute dollar errors (not squared errors), and there are some mansions that could skew your metrics.
Which metric should you prioritize?
A) MSE - emphasizes large errors
B) MAE - treats all errors equally
C) R² - explains variance
D) RMSE - root of MSE""",
"options": [
"A) MSE - emphasizes large errors",
"B) MAE - treats all errors equally",
"C) R² - explains variance",
"D) RMSE - root of MSE"
],
"hint": "Which metric is in dollars and doesn't over-penalize mansion outliers?"
},
{
"type": "short",
"question": """**Question 4 - Experiment Reflection: Metrics**
After running the 'Comparing Evaluation Metrics' experiment:
The data had 5 outliers added. Compare the MSE vs MAE values you observed.
Explain: Which metric was more affected by the outliers, and why does this happen mathematically?""",
"hint": "Remember that MSE squares all errors."
},
{
"type": "short",
"question": """**Question 5 - Detecting Overfitting**
Based on the 'Detecting Overfitting' experiment:
You should see training loss decrease continuously while validation loss eventually increases.
Explain:
1. At what point does overfitting start?
2. What is the model doing when train loss drops but val loss rises?
3. How would you prevent this in practice?""",
"hint": "The model starts memorizing training data instead of learning patterns."
},
{
"type": "short",
"question": """**Question 6 - Train/Val Split Purpose**
Explain the PURPOSE of splitting data into train and validation sets.
What specific problem does this solve? What would happen if you only evaluated on training data?""",
"hint": "You need separate data to detect when the model stops generalizing."
},
{
"type": "mc",
"question": """**Question 7 - Model Complexity and Overfitting**
You have 100 training examples. Which model is MORE likely to overfit?
A) Linear model: y = wx + b (2 parameters)
B) Deep network with 10,000 parameters
C) Both equally likely
D) Neither will overfit""",
"options": [
"A) Linear model: y = wx + b (2 parameters)",
"B) Deep network with 10,000 parameters",
"C) Both equally likely",
"D) Neither will overfit"
],
"hint": "More parameters = more capacity to memorize training data."
},
{
"type": "short",
"question": """**Question 8 - Systematic Improvement**
You train a model and get: Train R² = 0.60, Val R² = 0.58
Then you try a deeper network and get: Train R² = 0.95, Val R² = 0.50
What does this tell you? Should you use the deeper model? Why or why not?""",
"hint": "The gap between train and val performance reveals overfitting."
},
{
"type": "short",
"question": """**Question 9 - Learning Rate Impact on Metrics**
You train two models on the same data:
- Model A (LR=0.001): Final MSE = 10.5 after 1000 epochs
- Model B (LR=0.1): Final MSE = 45.2 after 1000 epochs
What does this suggest about Model B's learning rate? How would you diagnose this?""",
"hint": "A learning rate that's too high causes instability."
},
{
"type": "short",
"question": """**Question 10 - Real-World Trade-offs**
In production, you must choose between:
- Model A: Avg error $50,000 (but only $10,000 on cheap houses, $200,000 on mansions)
- Model B: Avg error $60,000 (but consistent across all price ranges)
Which do you deploy? Explain your reasoning using metric selection concepts.""",
"hint": "This is about MSE vs MAE philosophy. Do you care more about average or consistency?"
}
]
},
4: {
"title": "Vector Representations & Similarity",
"programming": [
{
"title": "Experiment: Cosine vs Euclidean Similarity",
"description": "Observe how cosine similarity and Euclidean distance behave differently, especially with vector magnitude.",
"time": "10 min",
"starter_code": """import numpy as np
# User preferences (ratings 1-5 for 5 movies)
user_a = np.array([5, 5, 1, 1, 1]) # Loves action, hates romance
user_b = np.array([4, 4, 1, 1, 1]) # Same pattern, slightly lower ratings
user_c = np.array([1, 1, 5, 5, 5]) # Opposite preferences
def cosine_similarity(v1, v2):
return np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2))
def euclidean_distance(v1, v2):
return np.linalg.norm(v1 - v2)
print("User A vs User B:")
print(f" Cosine similarity: {cosine_similarity(user_a, user_b):.4f}")
print(f" Euclidean distance: {euclidean_distance(user_a, user_b):.4f}")
print("\\nUser A vs User C:")
print(f" Cosine similarity: {cosine_similarity(user_a, user_c):.4f}")
print(f" Euclidean distance: {euclidean_distance(user_a, user_c):.4f}")
# Now scale user_b by 2x (enthusiastic rater)
user_b_scaled = user_b * 2
print("\\nUser A vs User B (2x scaled):")
print(f" Cosine similarity: {cosine_similarity(user_a, user_b_scaled):.4f}")
print(f" Euclidean distance: {euclidean_distance(user_a, user_b_scaled):.4f}")
# TODO: Answer reflection questions about what this tells you"""
},
{
"title": "Experiment: Sparsity Problem",
"description": "See how sparse vectors (mostly zeros) make similarity search difficult.",
"time": "8 min",
"starter_code": """import numpy as np
np.random.seed(42)
# Sparse binary vectors (1000 dimensions, only 10 are 1)
def create_sparse_vector(dim=1000, num_ones=10):
vec = np.zeros(dim)
indices = np.random.choice(dim, num_ones, replace=False)
vec[indices] = 1
return vec
# Create 5 users with sparse preferences
users = [create_sparse_vector() for _ in range(5)]
# Compute pairwise similarities
print("Pairwise Cosine Similarities:")
for i in range(len(users)):
for j in range(i+1, len(users)):
sim = np.dot(users[i], users[j]) / (np.linalg.norm(users[i]) * np.linalg.norm(users[j]))
overlap = int(np.dot(users[i], users[j])) # Number of shared 1s
print(f"User {i} vs User {j}: similarity={sim:.4f}, shared items={overlap}")
# TODO: What pattern do you notice? Why is this a problem?"""
}
],
"knowledge": [
{
"type": "short",
"question": """**Question 1 - Cosine vs Euclidean Conceptual Understanding**
Cosine similarity measures the ANGLE between vectors.
Euclidean distance measures the MAGNITUDE of difference.
Explain:
1. Why is cosine similarity better for comparing user preferences?
2. Give an example where two users have the same taste but different cosine vs Euclidean similarity.
3. What does a cosine similarity of 1.0 mean? What about -1.0?""",
"hint": "Think about rating scales. One user might rate everything 1-5, another 2-4, but have the same preferences."
},
{
"type": "short",
"question": """**Question 2 - Experiment Reflection: Scaling**
In the 'Cosine vs Euclidean' experiment, User B was scaled by 2x (all ratings doubled).
Observe what happened to:
1. Cosine similarity (did it change?)
2. Euclidean distance (did it change?)
3. Which metric correctly recognizes that User A and User B (scaled) have the SAME preferences?""",
"hint": "Cosine is scale-invariant. It only cares about direction (pattern), not magnitude (enthusiasm)."
},
{
"type": "mc",
"question": """**Question 3 - When to Use Which Metric**
You're building a movie recommendation system. Users rate movies 1-5 stars. Some users are "easy graders" (average 4.0) and some are "harsh critics" (average 2.5), but they might have similar taste.
Which similarity metric should you use?
A) Euclidean distance
B) Cosine similarity
C) Manhattan distance
D) Doesn't matter""",
"options": [
"A) Euclidean distance",
"B) Cosine similarity",
"C) Manhattan distance",
"D) Doesn't matter"
],
"hint": "You want to capture PREFERENCE PATTERNS, not absolute rating levels."
},
{
"type": "short",
"question": """**Question 4 - The Sparsity Problem**
Based on the 'Sparsity Problem' experiment:
With 1000 possible items and users only rating 10 items each, most users had NO shared items (overlap=0).
Explain:
1. Why does sparsity make similarity computation difficult?
2. What happens to cosine similarity when two vectors share no non-zero elements?
3. How might you solve this problem in practice?""",
"hint": "If vectors don't overlap, you can't find similarity even if users actually have similar tastes."
},
{
"type": "short",
"question": """**Question 5 - Dimensionality Reduction Motivation**
High-dimensional sparse vectors → hard to find similarities
Low-dimensional dense vectors → easier to find patterns
Explain: How could you transform high-dimensional sparse movie ratings into low-dimensional dense embeddings? What would the embeddings capture?""",
"hint": "Think about learning latent factors like 'action fan' or 'romance lover' instead of storing raw ratings."
},
{
"type": "mc",
"question": """**Question 6 - Curse of Dimensionality**
In very high dimensions (e.g., 10,000), strange things happen to distances. Most points appear roughly equidistant from each other.
Why is this a problem for nearest neighbor search?
A) It makes computation slow
B) It makes all similarities look the same (less informative)
C) It uses too much memory
D) It requires more training data""",
"options": [
"A) It makes computation slow",
"B) It makes all similarities look the same (less informative)",
"C) It uses too much memory",
"D) It requires more training data"
],
"hint": "When everything is equally far apart, you can't distinguish near from far."
},
{
"type": "short",
"question": """**Question 7 - Learned Representations vs Manual Features**
Manual approach: Design features like "likes action", "likes romance" (requires domain expertise)
Learned approach: Let a neural network discover features automatically from data
Explain:
1. What advantage does the learned approach have?
2. What disadvantage might it have?
3. When would you prefer manual features?""",
"hint": "Learned = automatic but less interpretable. Manual = interpretable but requires expertise."
},
{
"type": "short",
"question": """**Question 8 - Dot Product Interpretation**
Cosine similarity = (A · B) / (||A|| × ||B||)
The numerator is the dot product A · B.
Explain in intuitive terms: What does a high dot product between two vectors mean? What about a dot product of zero?""",
"hint": "Dot product measures alignment. High = pointing same direction. Zero = perpendicular."
},
{
"type": "short",
"question": """**Question 9 - Normalization Impact**
If you normalize all vectors to unit length (magnitude 1), what happens to the relationship between cosine similarity and Euclidean distance?
Hint: Try the math with ||A|| = ||B|| = 1""",
"hint": "When vectors are normalized, cosine similarity and Euclidean distance become related."
},
{
"type": "short",
"question": """**Question 10 - Real-World Application**
Spotify has 100 million songs and wants to find "similar songs" for recommendations.
Explain:
1. Why can't they store a 100M × 100M similarity matrix?
2. How do learned embeddings (e.g., 128-dimensional vectors per song) solve this?
3. What tradeoff are they making?""",
"hint": "100M × 100M floats = massive storage. 100M × 128 floats = much smaller. But you lose some information in compression."
}
]
},
5: {
"title": "Autoencoders & Embeddings",
"programming": [
{
"title": "Experiment: Compression Forces Learning",
"description": "Observe how different bottleneck sizes affect reconstruction quality and feature learning.",
"time": "12 min",
"starter_code": """import torch
import torch.nn as nn
import torchvision
import matplotlib.pyplot as plt
class Autoencoder(nn.Module):
def __init__(self, latent_dim):
super().__init__()
self.encoder = nn.Sequential(
nn.Linear(784, 256),
nn.ReLU(),
nn.Linear(256, latent_dim)
)
self.decoder = nn.Sequential(
nn.Linear(latent_dim, 256),
nn.ReLU(),
nn.Linear(256, 784),
nn.Sigmoid()
)
def forward(self, x):
encoded = self.encoder(x)
decoded = self.decoder(encoded)
return decoded, encoded
# Train autoencoders with different bottleneck sizes
latent_dims = [2, 8, 32, 128]
# TODO: Train each and observe reconstruction quality
# Question: What happens to reconstruction as latent_dim changes?
# What is the model learning to fit into the bottleneck?"""
}
],
"knowledge": [
{
"type": "short",
"question": """**Question 1 - Why Compression Forces Learning**
An autoencoder with 784-dim input → 32-dim latent → 784-dim output must compress 784 numbers into 32.
Explain:
1. Why can't the model just memorize each input?
2. What must it learn instead?
3. What happens if latent_dim = 784 (no compression)?""",
"hint": "Compression = information bottleneck. The model must learn the ESSENCE of the data."
},
{
"type": "short",
"question": """**Question 2 - Latent Space as Learned Representation**
After training an autoencoder on MNIST digits, the 32-dimensional latent space captures what makes each digit unique.
Explain:
1. Why might similar digits (like 3 and 8) be close in latent space?
2. How is this different from pixel space (raw 784 dimensions)?
3. What makes the latent representation 'better' than raw pixels?""",
"hint": "Latent space captures semantic similarity, not just pixel similarity."
},
{
"type": "mc",
"question": """**Question 3 - Reconstruction Loss**
You train an autoencoder and get: Train reconstruction loss = 0.01, Test reconstruction loss = 0.10
What does this suggest?
A) The model is working perfectly
B) The model is overfitting
C) The latent dimension is too large
D) The model needs more training""",
"options": [
"A) The model is working perfectly",
"B) The model is overfitting",
"C) The latent dimension is too large",
"D) The model needs more training"
],
"hint": "Large gap between train and test = overfitting."
},
{
"type": "short",
"question": """**Question 4 - Autoencoders vs Supervised Learning**
Autoencoders are UNSUPERVISED - they don't need labels.
Explain:
1. What is the 'label' that an autoencoder trains on?
2. Why is this useful when you don't have labeled data?
3. How could you use an autoencoder's learned representations for a downstream supervised task?""",
"hint": "The input IS the label (reconstruct yourself). The latent space can be used for other tasks."
},
{
"type": "short",
"question": """**Question 5 - VAE vs Standard Autoencoder**
Variational Autoencoders (VAEs) learn a DISTRIBUTION in latent space, not just a point.
Explain:
1. Why is learning a distribution useful for GENERATION?
2. What can VAEs do that standard autoencoders cannot?
3. What's the tradeoff?""",
"hint": "Distribution = you can sample new points. Standard AE only encodes existing data."
},
{
"type": "mc",
"question": """**Question 6 - Bottleneck Size Selection**
You're building an autoencoder for 1000x1000 images. Which latent dimension is most reasonable?
A) latent_dim = 2 (extreme compression)
B) latent_dim = 256 (moderate compression)
C) latent_dim = 1000000 (no compression)
D) latent_dim = 100000 (minimal compression)""",
"options": [
"A) latent_dim = 2 (extreme compression)",
"B) latent_dim = 256 (moderate compression)",
"C) latent_dim = 1000000 (no compression)",
"D) latent_dim = 100000 (minimal compression)"
],
"hint": "Too small = loss of information. Too large = no compression benefit. Need balance."
},
{
"type": "short",
"question": """**Question 7 - Denoising Autoencoders**
A denoising autoencoder is trained with: corrupted_input → encoder → decoder → clean_output
Explain:
1. Why does this make the learned features MORE robust?
2. What additional capability does the model gain?
3. How is this related to data augmentation?""",
"hint": "Learning to denoise forces the model to learn the underlying structure, not memorize noise."
},
{
"type": "short",
"question": """**Question 8 - Embeddings as Dimensionality Reduction**
Autoencoder latent space, PCA, and t-SNE all reduce dimensionality.
Compare:
1. How does an autoencoder differ from PCA?
2. When would you prefer an autoencoder over PCA?
3. What's the computational tradeoff?""",
"hint": "PCA = linear. Autoencoder = nonlinear (with activation functions). PCA is faster."
},
{
"type": "short",
"question": """**Question 9 - Interpolation in Latent Space**
You encode two images to latent vectors z1 and z2. Then you decode MIDPOINT (z1 + z2)/2.
What do you expect to see? Why is this useful?""",
"hint": "If latent space is smooth, the midpoint should be a blend of the two images."
},
{
"type": "short",
"question": """**Question 10 - Real-World Application**
Google Photos uses learned embeddings to search photos by similarity without tags.
Explain:
1. How does an autoencoder-style approach enable this?
2. Why is pixel-space similarity not good enough?
3. What must the latent space capture to make semantic search work?""",
"hint": "Latent space must capture 'what the image contains' not 'what pixels look like'."
}
]
},
# Continuing with lectures 6-15...