Chapter 1: Introduction
Based on "Dive into Deep Learning" by Zhang et al.
Instructor: Guðmundur Einarsson
University of Iceland
Slides adapted from Hafsteinn Einarsson, 2025 fall course
The science of pattern recognition from data
How we've built software for decades
Building with traditional rules:
def add_to_cart(user_id, product_id):
# Explicit rule for every action
if cart_exists(user_id):
cart.add_item(product_id)
else:
create_cart(user_id)
cart.add_item(product_id)
Handle every corner case explicitly
Perfect for deterministic tasks!
Some problems resist explicit rules
Even the smartest programmers struggle with these...
These require learning, not programming!
Machine learning is the study of algorithms that can learn from experience, also known as...
"Machine Learning is programming with data instead of explicit instructions"
The paradigm shift that changed computing
How does "Hey Siri" or "OK Google" work?
Consider the technical challenge:
What rule could reliably detect "Alexa" in all these samples?
We don't know how to write such rules from scratch!
def detect_wake_word(audio):
if audio_matches_pattern("ah-lek-sah"):
return True
elif audio_matches_pattern("uh-lek-suh"):
return True
# ... hundreds more rules?
return False
Too many variations to code manually!
model = train_wake_word_detector(
positive_examples=["alexa_1.wav", "alexa_2.wav", ...],
negative_examples=["other_1.wav", "other_2.wav", ...]
)
def detect_wake_word(audio):
return model.predict(audio) > threshold
Learn patterns from examples instead!
ML transforms intractable coding problems into tractable data problems
An iterative process of improvement
Let's see how our four pillars work for "Alexa" detection
Problem: Audio snippet → "Yes/No" for wake word
Must precisely define inputs and outputs first!
The model has adjustable "knobs" (parameters)
Model family must be rich enough for the task
This is "learning" - finding the right parameter settings
Write explicit rules for wake word detection
Write program that learns from wake word examples
"Programming with data" instead of programming with rules
Similar tasks can share model families:
But fundamentally different tasks need different models:
The success of deep learning is largely due to data availability
Critical Applications: Predictive policing, resume screening, lending decisions
Example: Skin cancer detection trained only on light skin
Resume screening learning from biased hiring history
⚠️ This happens without intent or awareness from data scientists
How we encode information for models
A 3×3 grayscale image:
[[255, 128, 0],
[128, 64, 128],
[ 0, 128, 255]]
Each number represents pixel brightness
Words mapped to numbers:
"deep" → [0.2, -0.5, 0.8, ...]
"learning" → [-0.1, 0.7, 0.3, ...]
Captures semantic relationships
Death cap - highly poisonous!
Mushroom Classification Example
Classifier: "20% chance this is poisonous"
Expected value: -∞
Expected value: -1
Key Insight: In critical applications, even small error probabilities can be unacceptable when the cost of false negatives is catastrophic.
Field guides use complex decision trees:
Problem: Too many rules, too many exceptions!
What features help identify poisonous mushrooms?
ML can save lives by making expert knowledge accessible, but the benefit needs to outweigh the cost of mistakes (e.g. false negatives when someone is poisoned)
Goal: Learn function f where
y = f(x)
Given input x, predict output y
True Value
Predicted Value
(pronounced "y-hat")
Loss measures the difference: L(y, ŷ)
def linear_model(x, w, b):
return w * x + b
Perfect for appropriately simple problems
Linear regression, decision trees, basic classifiers
Many successive transformations chained together
The "deep" in deep learning = multiple layers
Complex problems stretch the limits of classical methods
Multiple layers of transformations
Machine learning = learning from experience
But what constitutes "improvement"?
Convention: Lower is better (hence "loss functions")
Loss = measure of prediction error
Lower loss = better predictions
Goal: minimize loss
Square of (prediction - true value)
Easy to optimize, differentiable
Fraction of incorrect predictions
Hard to optimize directly → use surrogates
For regression problems:
Penalizes large errors more
For classification problems:
Measures prediction confidence
Can be derived based on the maximum likelihood approach
Loss = function of model parameters
Like practice exam scores
Used to update parameters
Like final exam scores
Measures real performance
⚠️ Good training score ≠ Good test score (overfitting)
When overfitting, the model memorizes instead of generalizing
Finding the lowest point
| Type | Data | Goal |
|---|---|---|
| Supervised | Labeled | Predict labels |
| Unsupervised | Unlabeled | Find structure |
| Reinforcement | Rewards | Maximize reward |
Training data format:
(image of cat) → "cat"
(image of dog) → "dog"
(house features) → $500,000
(email text) → "spam"
Regression = predicting "how much" or "how many"
Multiple features: $\hat{y} = w_1x_1 + w_2x_2 + ... + b$
Each point is a house, line shows learned relationship
Other metrics: MAEMean Absolute Error: Average of absolute differences between predictions and actual values. Less sensitive to outliers than MSE. (Mean Absolute Error), R² scoreCoefficient of Determination: Proportion of variance in the dependent variable predictable from the independent variable(s). Ranges from 0 to 1, where 1 means perfect prediction.
When relationships are non-linear:
Classification = predicting "which type" or "what category"
Two possible outcomes:
Output: probability between 0 and 1
More than two categories:
Examples:
Converts raw scores to probabilities:
Example:
Scores: [2.0, 1.0, 0.1]
Probabilities: [0.66, 0.24, 0.10]
Prediction: Class 0 (highest probability)
All probabilities sum to 1.0
How classifiers separate classes:
Linear boundaries for simple problems, non-linear for complex ones
% of correct predictions
Good for balanced datasets
% of positive predictions that are correct
Important when false positives are costly
% of actual positives correctly identified
Important when false negatives are costly
Harmonic mean of precision and recall
Balanced metric
Visualizing classification errors:
| Predicted | ||
|---|---|---|
| Actual | True Positive | False Positive |
| False Negative | True Negative | |
Shows exactly where the model makes mistakes
One label per item
Multiple labels per item
Labels are not mutually exclusive in multi-label problems
Netflix movie: [Drama, Thriller, Based on Book, Award-Winning]
Patient conditions: [Diabetes, Hypertension, Obesity]
Photo tags: [Sunset, Beach, People, Vacation, Summer]
Research paper: [Machine Learning, Computer Vision, Neural Networks]
Independent binary classifiers for each label:
Input: Movie description
Output probabilities:
- Action: 0.85 ✓
- Comedy: 0.72 ✓
- Drama: 0.23 ✗
- Horror: 0.05 ✗
- Sci-Fi: 0.91 ✓
Threshold: 0.5
Tags: [Action, Comedy, Sci-Fi]
Each label has its own probability threshold
Example: "Action" and "Adventure" often co-occur in movies
Not just finding results, but ordering them:
Query: "machine learning"
Challenge: Millions of results - which first?
Users rarely look past the first page!
ML learns what makes results relevant:
Rank products by relevance, price, reviews, availability
Rank emails by importance to user
Rank apps by relevance, quality, popularity
Rank candidates or positions by fit
"Users like you also liked..."
"Because you liked X..."
Modern systems combine both approaches
How to recommend when you have no data?
Solutions:
Core technique for collaborative filtering:
User-Item matrix → User factors × Item factors
Learns latent features automatically
Users only see content similar to past behavior
Limits exposure to diverse perspectives
Reinforces existing beliefs and biases
Can amplify misinformation
Optimizing for engagement can exploit psychology
Particularly harmful for vulnerable users
⚠️ Recommender systems shape what billions of people see online
Sequential data is everywhere:
"Time is an arrow" ≠ "Arrow an is time"
Image → Caption (words)
Sentence → Sentiment
Video → Frame labels
English text → French text
Audio waveform → Text transcription
Networks with memory:
For each time step t:
hidden_state[t] = f(input[t], hidden_state[t-1])
output[t] = g(hidden_state[t])
Later evolved into Transformers (ChatGPT, etc.)
Can you spot the groups?
Groups emerge naturally — these points were sampled from three different distributions
The algorithm finds cluster assignments without ever seeing the true labels
Foundation of modern NLP (BERT, GPT)
The cat sat on [MASK] mat → the
Powers embedding models such as BERT and other variations power GPT models
Self-supervised learning for computer vision
🖼️ → 🖼️❓❓🖼️ → 🖼️🖼️🖼️🖼️
Original → Masked → Reconstructed
Achieves state-of-the-art with less labeled data
Not all learning needs labeled data
"Do some data science with it!"
No labels needed - let the data speak for itself!
Creating supervision from the data itself
Text: Mask words and predict them
"The [MASK] jumped over the fence" → "dog"
Images: Predict relative positions or masked patches
🖼️ → 🖼️❓❓🖼️ → 🖼️🖼️🖼️🖼️
Learn representations without manual labeling!
Traditional ML: Collect data → Train → Deploy
But what if our model affects the environment?
Actions impact future observations!
Learning without explicit labels
Unlike supervised learning with its "dictatorial boss" telling you exactly what to do...
Unsupervised learning is like having a boss who says:
"Here's data - do some data science with it!"
Creating supervision from the data itself
Fill in the [MASK]
"The cat sat on the [MASK]"
→ predict: "mat"
Predict relative positions
Two image patches
→ predict: above/below/left/right
💡 No manual labeling required - the data provides its own supervision!
Learning to generate new data
These models learn data distributions and can generate new, realistic samples
Supervised Learning: Collect data → Train offline → Deploy
But real agents need to:
This leads us to Reinforcement Learning...
Humans have sought to analyze data and predict outcomes for centuries
These tools enabled the experimental approach in natural sciences
Jacob Köbel (1460-1533): Early data collection
One of the earliest examples of a trimmed meanA robust statistical measure that removes extreme values before averaging!
Ronald Fisher (1890-1962)
⚠️ Note: Fisher was also a proponent of eugenics, reminding us that data science can be misused
Information theory
"Can machines think?"
Donald Hebb (1904-1985)
"Neurons that fire together, wire together"
The biological metaphor gave "neural networks" their name
Key ideas that persist today:
But from 1995-2005, neural networks fell out of favor...
Why neural networks struggled:
These methods gave predictable results with theoretical guarantees
The confluence of big dataWorld Wide Web, social networks, IoT sensors, cheap storageKryder's Law: Storage density doubles annually, and GPU computingOriginally for gaming, revolutionized deep learning enabled the deep learning revolution
| Decade | Dataset Size | Memory | Compute (FLOPS) |
|---|---|---|---|
| 1970 | 100 (Iris)Classic 150-sample flower classification dataset | 1 KB | 100K (Intel 8080) |
| 1980 | 1K (Boston Housing)506 samples of house prices with 13 features | 100 KB | 1M (Intel 80186) |
| 1990 | 10K (MNIST)60,000 handwritten digit images | 10 MB | 10M (Intel 80486) |
| 2000 | 10M (Web pages) | 100 MB | 1G (Intel Core) |
| 2010 | 10G (Advertising) | 1 GB | 1T (NVIDIA C2050)First Fermi GPU, 515 GFLOPS, game-changer for deep learning |
| 2020 | 1T (Social networks) | 100 GB | 1P (NVIDIA DGX-2)2 PFLOPS, 16 V100 GPUs, designed for AI |
From hidden applications to headline-grabbing achievements
ML has been pervasive, albeit often hidden
| Year | ImageNet Top-5 Error | Model |
|---|---|---|
| 2010 | 28% | Traditional ML |
| 2012 | 16% | AlexNetFirst deep CNN, started the revolution |
| 2015 | 3.5% | ResNet152 layers with skip connections |
| 2017 | 2.25% | SENetSqueeze-and-Excitation Networks |
Also: Birdsong ID, skin cancer diagnosis
What makes deep learning deep and why it revolutionized AI
Millions of automatic choices beat manual design
From PhD homework → 10 lines of code