Lecture 1 - Preliminaries I

Updated 14 Oct 2026

(Course: CSS485 Deep Learning — Jessada Karnjana, Aug 2026)

Sources

  • Jeremy Watt, Reza Borhani, and Aggelos K. Katsaggelos, Machine Learning Refined: Foundations, Algorithms, and Applications, 2020
    • Chapter 1: Introduction
  • Ian Goodfellow, Yoshua Bengio, Aaron Courville, Deep Learning, 2016
    • Chapter 1: Introduction
    • Chapter 5: Machine Learning Basics
  • Christopher M. Bishop, Hugh Bishop, Deep Learning: Foundations and Concepts, 2024
    • Chapter 1: The Deep Learning Revolution
    • Chapter 4: Single-layer Networks: Regression
    • Chapter 5: Single-layer Networks: Classification
  • Ovidiu Calin, Deep Learning Architectures: A Mathematical Approach, 2020
    • Chapter 2: Activation Functions
    • Chapter 3: Cost Functions
    • Chapter 4: Finding Minima Algorithm
    • Chapter 5: Abstract Neurons
    • Chapter 6: Neural Networks

Contents of Preliminaries I

  1. Pattern Recognition
  2. A Bit About AI
  3. Machine Learning & Deep Learning
  4. Math Review (Part 1)
    • Probability
    • Bayesian Reasoning
    • Maximum Likelihood
    • Expected Value
    • Variance & Covariance Matrix

1. Pattern Recognition

Example: Machine that takes one number and produces another number

  • Setup: a black-box "Machine" takes input xx and outputs yy.
xx2850226
yy4161004412
  • Question: What is yy if x=4x = 4? (Ask yourself: how confident are you?)
  • Question: What is yy if x=3x = 3?

Analogy: You're guessing a hidden rule (like y=2xy = 2x) just by looking at input/output pairs — this is exactly what a learning algorithm does: it never sees the rule directly, only examples.

But when x=3x = 3, we shouldn’t be that 100% confidence since there’s input bias (we already know when it’s even number)

Pattern Recognition

  • Pattern recognition = searching for patterns (or regularities) in data.
  • Generalization is a central goal in pattern recognition — i.e., performing well on new, unseen data, not just the examples you already have.

Example: Raise your right hand

  • The human brain has evolved to look for and recognize patterns.

Signal processing from your ear to brain

  • If you raise your right hand, it means your brain can recognize a pattern of electrical signals associated with a command that asks you to raise your hand.

Analogy: Your nervous system is itself a "pattern recognizer" — sound waves become electrical spikes, and your brain matches the spike pattern to the concept "raise your hand," the same way a neural network matches pixel patterns to the concept "cat."


2. A Bit About AI

Computing Machine and Intelligence (1950)

  • Inventors have long dreamed of creating machines that think.
  • When programmable computers were first conceived, people wondered whether such machines might become intelligent.
  • In 1950, Alan Turing considered the question "Can machines think?"
  • Turing Test (or Imitation Game): a test of a machine's ability to exhibit intelligent behavior equivalent to, or indistinguishable from, that of a human.
    • Player C is given the task of trying to determine, by interrogation, which player (A or B) is a computer, and which is a human.

"Official" Root of AI (1956)

  • John McCarthy and Marvin Minsky persuaded Claude Shannon to join them in organizing a summer program at Dartmouth College.

"The study is to proceed on the basis of the conjecture that every aspect of learning or any other feature of intelligence can in principle be so precisely described that a machine can be made to simulate it. An attempt will be made to find how to make machines use language, form abstractions and concepts, solve kinds of problems now reserved for human, and improve themselves. We think that a significant advance can be made in one or more of these problems if a carefully selected group of scientists work on it together for a summer."

AI: Standard Definition

  • Humans are intelligent to the extent that our actions can be expected to achieve our objectives.
  • From the very beginnings of AI, intelligence in machines has been defined the same way: Machines are intelligent to the extent that their actions can be expected to achieve their objectives.
  • Stuart Russell calls this the standard model.

Chinook vs Marion Tinsley (1994)

  • Chinook is the first computer program to win the world champion title in a competition against humans, in 1994, in a match against Marion Tinsley after six drawn games and Tinsley's withdrawal due to pancreatic cancer.
  • On July 19, 2007, the journal Science published an article titled "Checkers Is Solved," proving that the best a player playing against Chinook can achieve is a draw.
  • Source: Wikipedia; Image source: http://jonathanschaeffer.blogspot.com/2012/08/chinook-twenty-years-later.html

Deep Blue vs Garry Kasparov (1997)

  • In 1996, in a 6-game match, Deep Blue won its first game against Garry Kasparov, but Kasparov won three and drew two of the following games — final score 4-2 (Kasparov).
  • In 1997, Deep Blue won the last game in a 6-game match by a score of 3.5-2.5 (Kasparov won the first game, lost the second, and drew games 3, 4, and 5 — despite having advantageous positions in all three).
  • Deep Blue derived its playing strength from brute-force computing power.

The Only Game He Won

  • The first game in 1997 is one of the most interesting games.

  • Deep Blue played black. The first figure shows the position after Kasparov played b4.
  • This was the only game Kasparov won in the match.
  • Kasparov attributed Deep Blue's move to "superior intelligence." Nate Silver (statistician and _New York Times_journalist), in his book The Signal and the Noise, suggested that Kasparov's assessment of the first game led him to lose the second game. According to Silver's interview, the move (the 44th move) was actually a bug in the program.
  • Source: Wikipedia & Bruce Pandolfini's Kasparov and Deep Blue

AlphaGo vs Lee Sedol (2016)

  • AlphaGo, which played against Lee Sedol, used 1,202 CPUs and 176 GPUs.
  • AlphaGo's algorithm used a combination of machine learning and tree-search techniques, combined with extensive training.
  • DeepMind's AlphaGo AI made a highly creative move on line 5, in defiance of millennia of human wisdom, which about fifty moves later proved crucial to its defeat of Go legend Lee Sedol.

Drawback of the Standard Model (1960)

  • Norbert Wiener (a legendary professor at MIT), after seeing Arthur Samuel's checker-playing program learn to play checkers far better than its creator, wrote a paper, "Some Moral and Technical Consequences of Automation."

"If we use, to achieve our purposes, a mechanical agency with whose operation we cannot interfere effectively … we had better be quite sure that the purpose put into the machine is the purpose which we really desire."

Analogy: This is the classic "genie/monkey's paw" problem — you get exactly what you asked for, not what you meant. It's the earliest articulation of what we now call the AI alignment problem.

AI: Redefined

  • Machines are intelligent to the extent that their actions can be expected to achieve their objectives.
  • Machines are beneficial to the extent that their actions can be expected to achieve our objectives.

Ulam-Neumann Conversation (1958)

"One conversation centered on the ever-accelerating progress of technology and changes in the mode of human life, which gives the appearance of approaching some essential singularity in the history of the race beyond which human affairs, as we know them, could not continue."

Let’s say we have a machine, that smart enough to produce another machine (smart than A)

Intelligence Explosion (1965) - SKIP

I. J. Good's Intelligence Explosion

  • Let an ultra-intelligent machine be defined as a machine that can far surpass all the intellectual activities of any man, however clever.
  • Since the design of machines is one of these intellectual activities, an ultra-intelligent machine could design even better machines; there would then unquestionably be an "intelligence explosion," and the intelligence of man would be left far behind.
  • Thus, the first ultra-intelligent machine is the last invention that man need ever make — provided that the machine is docile enough to tell us how to keep it under control.

Analogy: Think of compound interest, but for intelligence — each smarter generation of machine designs an even smarter one, faster than the last, so growth runs away from human control (an "explosion").

AI, ML, and DL

  • Knowledge-based approach
  • Machine learning
  • Representation learning

Knowledge-based Approach: Blocks World (1960s)

  • MIT AI Lab in the 1960s.
  • To simplify the problem of vision, Blocks World consisted of rectangular building blocks that could be stacked to create structures.
  • The goal was to write a program that could interpret a command such as "Find a large yellow block and put it on top of the red block," and plan the steps needed for a robot arm to carry out the command.
  • Source: Terrence J. Sejnowski, The Deep Learning Revolution, 2018

Terrence J. Sejnowski is the one who proposed ICA (Independent component analysis)

Cocktail party problem - singall that reach your ear are mixed signal
Mix signal → ICA → Separate them

11

Knowledge-based, we use the logic alone!! Machine follow those rules

Machine Learning

  • The difficulties faced by systems relying on hard-coded knowledge suggest that AI systems need the ability to acquire their own knowledge, by extracting patterns from raw data.

  • อย่างตัวอย่างแรก x = 2, y = 4 ,… จะทำได้ยังไง
    1. ก็ให้ logic มันไป ว่า y=2xy=2x มันก็ทำตามนั้น
    2. ให้ Data มันไปเยอะ ๆ {(2,4),(10,20),(5,10)}\{(2,4),(10,20),(5,10)\} มันควรจะรู้ relationship เอง

Perceptron (1943)

  • In 1943, Warren McCulloch and Walter Pitts showed that it was possible to build a digital computer out of simple binary threshold units like the perceptron, which could be wired up to make elementary logical gates. (This paper inspired John von Neumann to think about computers.)
  • In 1962, Frank Rosenblatt published Principles of Neurodynamics: Perceptrons and the Theory of Brain Mechanisms, which introduced a learning algorithm for neural network models with a single layer of variable weights — the precursor of today's learning algorithms for deep neural network models.

A Perceptron Reveals the Face of Sex (1995)

  • A perceptron was trained to discriminate male from female faces. The pixels from the image of a face are multiplied by corresponding weights, and the sum is compared to a threshold.

ทำไมแต่ละ weight มันไม่ใช่สีใดสีนึงตาม greyscale?


Contents

SEXNET (1990)

  • Beatrice Golomb used faces of college students as inputs to a perceptron that was trained to classify the sex of a face with 81% accuracy.

Perceptrons Eclipsed (1969)

  • In 1969, Marvin Minsky and Seymour Papert published a book, Perceptrons, whose definitive geometric analysis showed that the capabilities of perceptrons are limited: they can only separate categories that are linearly separable.
  • The cover of their book illustrates a geometric problem (two disconnected spirals vs. a single connected spiral) that Minsky and Papert proved a single perceptron could not solve.
  • Although, at the end of the book, Minsky and Papert considered the prospect of generalizing single- to multiple-layer perceptrons (one layer feeding into the next), they doubted there would ever be a way to train even these more powerful perceptrons.

Prove that perceptron doesn’t work, when … (fails in some cases) → It can be solved by multi-layer perceptron??

Data Representation

  • The performance of simple machine learning algorithms depends heavily on the representation of the data they are given.

AI Engineer ตอนนั้น try to find the new representation to apply ให้มันเวิร์คอะ แต่ตอนนี้ Deep Learning ไม่ต้องทำอะไรแบบนี้แล้ว, a machine find good representation by itself

Representation Learning

  • Which choice of representation is best?
  • One solution to this problem is to use machine learning to discover not only the mapping from representation to output, but also the representation itself.
  • Learned representations often result in much better performance than can be obtained with hand-designed representations.

Deep Learning

  • Deep learning deals with finding representations automatically, from raw data.

Illustration of a Deep Learning Model

  • Deep learning enables the computer to build complex concepts out of simpler ones.
  • The quintessential example of a deep learning model is the feedforward deep network, or multilayer perceptron (MLP).

Analogy: Think of a deep network like a factory assembly line — early layers detect simple parts (edges, colors), and each successive layer combines those parts into more complex products (shapes → faces → identities), all learned automatically from raw material (data).


3. Machine Learning & Deep Learning

Example: Cat and Dog Classification

  • We want to teach a machine to distinguish cats from dogs.
  • This kind of task is referred to as a classification problem in ML.
  • Think about how parents teach their children the difference between cats and dogs.

Collecting Data (Training Set)

Designing Feature

  • For most practical applications, the original input variables are preprocessed to transform them into a new space of variables (called features) where, it is hoped, the pattern recognition problem will be easier to solve.
  • Feature = distinctive characteristic of an input (e.g., an object or phenomenon).
  • For our toy example, the features are:
    • size of nose, relative to the size of the head (ranging from small to big)
    • shape of ears (ranging from round to pointy)
  • Keyword: feature extraction

Feature Space Representation (of the training set)

Training a Model

  • For our toy example, classification = a simple geometric problem, i.e., having the machine find a line or linear model that clearly separates the cats from the dogs in feature space.
  • A set of tools used to find the parameters of this line is called numerical optimization.
  • Question: How many parameters does the model have?
    • ก็สมการของเส้นตรง x2=ax1+bx_2=ax_1+b
    • จากสมการก็มีแค่ 2 parameters (a,ba,b)

Analogy: Drawing the separating line is like drawing a fence between two herds of animals in a field — once the fence is built, any new animal's side of the fence tells you which "class" it belongs to.

การจะหา optimal line เราก็มี algorithm อย่าง gradient descent

Testing the Model (Testing Set)

  • เวลาเรา test model ก็ test จาก unseen data ไง ว่ามัน generalize enough รึเปล่า

ML Pipeline


(Diagram of the full pipeline: raw data → features → training → trained model → testing → prediction — insert image here)

Predictive Learning Problems

  • Two major predictive problems:
    • Regression
    • Classification

Regression

  • Example: We want to predict the share price of a company that is about to go public.

If we want to find value (within the range of data) → Interpolation
But if out range of range of data → Extrapolation
Machine learning, deep learning technique works really well with interpolation (not very well with extrapolation)

Student Loan Debt in US

  • What will the total debt be by the year 2026?

Classification

  • Example: object recognition.
  • Geometrically speaking, a common way of viewing classification is finding a separating line (or hyperplane in higher dimensions) that separates two classes of data from a training set as best as possible.

Object Detection


(Example image with bounding boxes around detected objects — insert image here)

YOLO: it try to perform regression model on regression task??

Sentiment Analysis

  • Determining the aggregated feelings of a large base of customers (the "voice of the consumer"), using text-based content like product reviews, tweets, and comments, is commonly referred to as sentiment analysis.
  • Classification models are often used to perform sentiment analysis, learning to identify consumer data as either positive or negative.

Impact of Deep Learning I

  • Medical diagnosis: the problem of diagnosing skin cancer.
  • Melanoma is the most dangerous kind of skin cancer but is curable if detected early.
  • This problem has been successfully addressed using deep learning (Esteva et al., 2017).
  • Through the use of DL, classification of skin lesion images has reached a level of accuracy that exceeds that of professional dermatologists (Brinker et al., 2019).

Key terms

  • Supervised learning
  • Classification problem
  • Training set: 129,000 labelled training images (from a biopsy test)
  • Weights in a DNN: 25 million adjustable parameter values
  • The DNN was first trained on a much larger data set of 1.28 million images of everyday objects (e.g., dogs, buildings, mushrooms) and then fine-tuned on the data set of lesion images.
  • Transfer learning → we’ll talk in detail later!!

Impact of Deep Learning II

  • Protein structure: calculating the 3D structure of a protein, given the amino acid sequence.
  • Proteins are biological molecules consisting of one or more long chains of units called amino acids (22 different types); a protein is specified by its sequence of amino acids.
  • Once synthesized inside a living cell, a protein folds into a complex 3D structure whose behavior and interactions are strongly determined by its shape.
  • The 3D structure can be measured using X-ray crystallography, but this is time-consuming and challenging.
  • The amino acid sequence can be determined at lower cost and higher throughput.
  • Calculating this 3D structure, given the amino acid sequence, had been a fundamental open problem in biology for half a century, with relatively little progress until the advent of deep learning.

Protein Structure and DNN

  • A DNN model can be trained to take an amino acid sequence as input and generate the 3D structure as output, using training data consisting of proteins for which both the amino acid sequence and 3D structure are known.
  • Once trained, the system can take a new amino acid sequence as input and predict the associated 3D structure (Jumper et al., 2021 — AlphaFold).

Impact of Deep Learning III

  • Image synthesis: an example where training data consists simply of a set of sample images, and the goal of the trained network is to create new images of the same kind.

Key terms

  • Unsupervised learning
  • This is an example of a generative model because it can generate new output examples that differ from those used to train the model, but which share the same statistical properties.
  • A variant of this approach allows images to be generated depending on an input text string (a prompt), so the image content reflects the semantics of the text input.
  • The term generative AI describes DL models that generate outputs in the form of images, video, audio, text, candidate drug molecules, or other modalities.

Impact of Deep Learning IV

  • Large language models, e.g., GPT-4, Gemini, …
  • Recently, massive deep learning systems called LLMs have started to exhibit remarkable capabilities described as the first indications of AGI (Bubeck et al., 2023).
  • Such models can be trained on large text data by extracting training pairs, each consisting of a randomly selected sequence of words as input with the known next word as the target output. This is an example of self-supervised learning.

Try the following prompt (2024)

  • "Write a proof of the fact that there are infinitely many primes; do it in the style of a Shakespeare play through a dialogue between two parties over the proof."

(Example LLM output / screenshot — insert image here)


Tutorial Example

Very Important

  • For the newcomer to ML, many basic concepts and much of the terminology can be introduced through a simple example: fitting a polynomial to a small synthetic data set (Bishop, 2006).
  • We are given a training set comprising NN observations of xx, written x1,x2,…,xNx_1, x_2, \ldots, x_N, together with corresponding observations of target values of tt, denoted t1,t2,…,tNt_1, t_2, \ldots, t_N.
  • Goal: predict the value of tt for some new value of xx.
  • The ability to make accurate predictions on previously unseen inputs is a key goal in ML and is known as generalization.

Tutorial Example: Synthetic data

  • N=10N = 10
  • Underlying function: sin⁡(2πx)\sin(2\pi x)
  • x∈[0,1]x \in [0,1]
  • By generating data this way, we capture an important property of many real-world data sets: they possess an underlying regularity, which we wish to learn, but individual observations are corrupted by random noise.

(Scatter plot of the 10 noisy samples around sin⁡(2πx)\sin(2\pi x) — insert image here)

dataset ={(x1,t1),(x2,t2),…(x10,t10)}=\{(x_1,t_1),(x_2,t_2),\dots(x_{10},t_{10})\} and we want to find the equation

  1. Random x∈[0,1]x\in [0,1]
  2. y=sin⁡(2πx)y=\sin(2\pi x)
  3. t=y+noiset=y+\text{noise}

Tutorial Example: Linear model

  • We fit the data using a polynomial function of the form:

y(x,w)=w0+w1x+w2x2+⋯+wMxM=∑j=0Mwjxj\boxed{y(x, \boldsymbol{w}) = w_0 + w_1 x + w_2 x^2 + \cdots + w_M x^M = \sum_{j=0}^{M} w_j x^j}

  • where MM is the order of the polynomial, and the polynomial coefficients are collectively denoted by the vector w\boldsymbol{w}.
    • w=[w1w2⋮wN]\boldsymbol{w} = \begin{bmatrix} w_1 \\ w_2 \\ \vdots \\ w_N \end{bmatrix}
  • Functions such as this polynomial, which are linear in the unknown parameters, have important properties as well as significant limitations, and are called linear models.

Analogy: "Linear in the parameters" doesn't mean the curve itself is a straight line — x2x^2, x3x^3, etc. can bend a lot. It means that if you double every weight wjw_j, the output for a fixed xx also scales predictably — the model is linear in terms of how the weights combine, even though it's nonlinear in xx.

Tutorial Example: Error function

  • The values of the coefficients are determined by fitting the polynomial to the training data.
  • This is done by minimizing an error function that measures the misfit between the function y(x,w)y(x, \boldsymbol{w}), for any given value of w\boldsymbol{w}, and the training data points.
  • Sum of the squares of the differences between the predictions y(xn,w)y(x_n, \boldsymbol{w}) for each data point xnx_n and the corresponding target value tnt_n:

E(w)=12∑n=1N{y(xn,w)−tn}2\boxed{E(\boldsymbol{w}) = \frac{1}{2}\sum_{n=1}^{N}\{y(x_n, \boldsymbol{w}) - t_n\}^2}

  • ทำไมเราต้องใส่ 12\frac{1}{2} factor ไว้ด้วย มัน helpful
  • When we want to find the minimum, we’ll find critical point (and it’ll cancel with ^2)

Tutorial Example: Model complexity

  • Poor-fitting (underfitting) vs. over-fitting.
  • The more flexible polynomial, with larger values of MM, becomes increasingly tuned to the random noise on the target values.


(Plots showing under-fit, good-fit, and over-fit polynomial curves for different MM — insert image here)

  • สังเกต M=3M=3 มันดูดีนะ แต่ว่าสีเขียวจริง ๆ มันก็ยังเป็น Sinusodal แต่ว่า สีแดงมันก็กราฟ x3x^3 ทั่วไปอะ ดังนั้นเขาถึงบอกไงว่า มัน good สำหรับ within range of data
  • Overfitting mean it does not fit, just overfit, error becomes zero
    • Error = blue dot and the red line
    • How to avoid the over-fitting, we need to test the model on unseen data.

Analogy: Underfitting is like memorizing only the general shape of a song and humming it roughly; overfitting is like memorizing every tiny background noise in one specific recording — it sounds perfect for that recording but fails on any other performance of the same song.

Tutorial Example: Model complexity (test set)

First way: split test, train set???

  • We can obtain quantitative insight into how generalization performance depends on MM by considering a separate test set, comprising 100 data points.

  • RMSE (root-mean-square error) allows us to compare different sizes of data sets on an equal footing, and the square root ensures RMSE is measured on the same scale (and in the same units) as the target variable.

  • ถ้าเราใช้อันด้านบน จำนวน data point เยอะ error ยิ่งเยอะ

  • เราอยากได้ error ที่ ไม่ขึ้นอยู่กับจำนวนของ data point อะ เก็ทป้ะ ใช้อันนี้ก็ดีกว่า

Tutorial Example: Model complexity (data set size)

Second way: Increase the number of training data

  • Examining the learned model's behavior as the size of the data set is varied: increasing the size of the data set reduces the over-fitting problem.

_(Two plots for M=9M = 9 with different training-set sizes, showing reduced over-fitting with more data — insert image here)

Tutorial Example: Regularization

Thrid way: Regularization!!

  • Regularization is a technique often used to control the over-fitting phenomenon. It involves adding a penalty term to the error function to discourage the coefficients from having large magnitudes:

E~(w)=12∑n=1N{y(xn,w)−tn}2+λ2∥w∥2\boxed{\widetilde{E}(\boldsymbol{w}) = \frac{1}{2}\sum_{n=1}^{N}\{y(x_n, \boldsymbol{w}) - t_n\}^2 + \frac{\lambda}{2}\lVert \boldsymbol{w} \rVert^2}

  • where ∥w∥2≡wTw=w02+w12+⋯+wM2\lVert \boldsymbol{w} \rVert^2 \equiv \boldsymbol{w}^{\mathsf{T}}\boldsymbol{w} = w_0^2 + w_1^2 + \cdots + w_M^2, and λ\lambda governs the relative importance of the penalty term compared to the sum-of-squares error term.

Analogy: Regularization is like a parent telling a student "keep your answer simple" — it discourages the model from using huge, wild coefficients just to force-fit every noisy wiggle in the data.

Tutorial Example: Regularization (large λ)

  • If we use too large a value for λ\lambda, we obtain a poor fit (the model becomes too constrained/simple — underfitting).

(Plots for M=9M=9 comparing "no regularization" vs. regularized fits — insert image here)

Tutorial Example: Regularization (choosing λ)

  • The impact of λ\lambda on the generalization error can be seen by plotting the RMSE for both training and test sets against ln⁡λ\ln \lambda (for M=9M = 9).

(RMSE vs. ln⁡λ\ln\lambda plot — insert image here)

Tutorial Example: Model selection

  • We need a way to determine suitable values for hyperparameters (such as MM and λ\lambda).
  • We take the available data and partition it into a training set, used to determine the coefficients w\boldsymbol{w}, and a separate validation set (also called a hold-out set or development set).
  • For some applications, the supply of data for training and testing will be limited. To build a good model, we should use as much of the available data as possible for training. However, if the validation set is too small, it will give a relatively noisy estimate of prediction performance. One solution is to use cross-validation.

(4-fold cross-validation diagram — insert image here)


4. Math Review (Part 1)

3 Important Tools

  • A key concept in pattern recognition is uncertainty, which arises from:
    • Measurement noise
    • Finite size of data sets
  • Three important tools:
    • Probability theory
    • Decision theory
    • Information theory
  • Combining them allows us to make optimal predictions given all the information available to us, even though that information may be incomplete or ambiguous.

Probability

Definition

  • The probability of an event is the fraction of times that event occurs out of the total number of trials, in the limit that the total number of trials goes to infinity.
  • Example: rolling a die repeatedly and noting the turned-up face values: 1, 6, 1, 5, 2, 4, 3, 3, …

Example: Apples and Oranges

  • We randomly pick one of two boxes (red or blue), and from that box, we randomly select an item of fruit; having observed which sort of fruit it is, we replace it in the box it came from.
  • We imagine repeating this process many times.
  • Suppose we pick the red box 40% of the time and the blue box 60% of the time, and when removing a fruit from a box, we are equally likely to select any piece of fruit in the box.

Example: Apples and Oranges (cont.)

  • Random variable BB = identity of the box that will be chosen. BB can take one of two values: red (rr) or blue (bb).
  • Random variable FF = identity of the fruit. FF can take one of two values: apple (aa) or orange (oo).
  • Find:
    • p(B=r)p(B = r)
    • p(B=b)p(B = b)
    • p(F=a∣B=r)p(F = a \mid B = r) — this is a conditional probability.

More General Example

  • Two random variables: X,YX, Y.
  • XX can take any of the values xix_i where i=1,…,Mi = 1, \ldots, M.
  • YY can take any of the values yjy_j where j=1,…,Lj = 1, \ldots, L.
  • Consider a total of NN trials in which we sample both XX and YY, and let the number of trials in which X=xiX = x_i and Y=yjY = y_j be nijn_{ij} (this defines the joint probability).
  • Let the number of trials in which X=xiX = x_i (irrespective of YY) be denoted cic_i.
  • Let the number of trials in which Y=yjY = y_j (irrespective of XX) be denoted rjr_j.

Sum Rule of Probability

  • The sum rule (marginal probability):

p(X=xi)=∑j=1Lp(X=xi,Y=yj)\boxed{p(X = x_i) = \sum_{j=1}^{L} p(X = x_i, Y = y_j)}

  • In more compact notation:

p(X)=∑Yp(X,Y)\boxed{p(X) = \sum_{Y} p(X, Y)}

  • This is sometimes called the marginal probability, because it's found by summing (marginalizing) over all values of YY.

Product Rule of Probability

  • The conditional probability of YY given XX:

p(Y=yj∣X=xi)=nijcip(Y = y_j \mid X = x_i) = \frac{n_{ij}}{c_i}

  • The product rule:

p(X=xi,Y=yj)=p(Y=yj∣X=xi),p(X=xi)\boxed{p(X = x_i, Y = y_j) = p(Y = y_j \mid X = x_i), p(X = x_i)}

  • In more compact notation:

p(X,Y)=p(Y∣X),p(X)\boxed{p(X, Y) = p(Y \mid X), p(X)}

Analogy: The sum rule is like asking "out of everyone in the building, how many are on the 3rd floor, regardless of which room?" (add up all rooms). The product rule is like asking "how many people are in Room 301?" — you take the fraction of the 3rd floor that's in Room 301, times the number of people on the 3rd floor.

Example: N = 60

  • N=60N = 60, XX takes 9 possible values, YY takes 2 possible values.

(Grid/table of joint counts nijn_{ij} over the 9×2 combinations, with row totals cic_i and column totals rjr_j — insert image here)

Example: Apples and Oranges (cont.)

  • p(B=r)=0.4p(B = r) = 0.4
  • p(B=b)=0.6p(B = b) = 0.6
  • p(F=a∣B=r)=14p(F = a \mid B = r) = \frac{1}{4}
  • p(F=o∣B=r)=34p(F = o \mid B = r) = \frac{3}{4}
  • p(F=a∣B=b)=34p(F = a \mid B = b) = \frac{3}{4}
  • p(F=o∣B=b)=14p(F = o \mid B = b) = \frac{1}{4}
  • Compute p(F=a)p(F = a) and p(F=o)p(F = o) (use the sum + product rule together).

Bayesian Reasoning

Independency & Bayes' Theorem

  • In probability theory, two events are statistically independent if the occurrence of one does not affect the probability of the occurrence of the other.
  • Two events AA and BB are independent if their joint probability equals the product of their individual probabilities:

P(A,B)=P(A),P(B)P(A, B) = P(A),P(B)

  • From the product rule:

P(A)=P(A,B)P(B)=P(A∣B)(when independent)P(A) = \frac{P(A,B)}{P(B)} = P(A \mid B) \quad \text{(when independent)} P(B)=P(A,B)P(A)=P(B∣A)(when independent)P(B) = \frac{P(A,B)}{P(A)} = P(B \mid A) \quad \text{(when independent)}

  • The conditional probability of AA given BB is:

P(A∣B)=P(A,B)P(B)P(A \mid B) = \frac{P(A,B)}{P(B)}

  • Bayes' theorem:

P(A∣B)=P(B∣A),P(A)P(B)\boxed{P(A \mid B) = \frac{P(B \mid A),P(A)}{P(B)}}

Dependence or Independence

  • For a standard 52-card deck, you randomly choose one card.
    • AA = the event that you get an Ace.
    • BB = the event that you get a Queen.
  • Quiz: Calculate P(Ace or Queen)P(\text{Ace or Queen}).
  • Quiz: Are events AA and BB dependent or independent?
  • Quiz: If a card (e.g., the 2) is lost from this deck, does it change the dependency/independency between AA and BB?

Boy or Girl

  • Mr. Jones has two children. The older child is a girl. What is the probability that both children are girls?
  • Mr. Smith has two children. At least one of them is a boy. What is the probability that both children are boys?

Analogy: These are classic conditional-probability "trick" puzzles — the key is being precise about what exactly you were told, since different phrasings of "one is a boy/girl" condition on different sample spaces and give different answers.

Monty Hall Problem

  • Suppose you're on a game show, given the choice of three doors: behind one is a car, behind the others, goats. You pick a door (No. 1); the host, who knows what's behind the doors, opens another door (No. 3), revealing a goat. He then asks, "Do you want to pick door No. 2?" Is it to your advantage to switch?

Example: Apples and Oranges (cont.) — Prior/Posterior

  • p(B=r)=0.4p(B = r) = 0.4 → prior probability
  • p(B=b)=0.6p(B = b) = 0.6
  • p(F=a∣B=r)=14p(F = a \mid B = r) = \frac{1}{4}
  • p(F=o∣B=r)=34p(F = o \mid B = r) = \frac{3}{4}
  • p(F=a∣B=b)=34p(F = a \mid B = b) = \frac{3}{4}
  • p(F=o∣B=b)=14p(F = o \mid B = b) = \frac{1}{4}
  • Compute p(B=r∣F=o)p(B = r \mid F = o) → posterior probability

Bayesian Reasoning

P(h∣e)=P(e∣h),P(h)P(e)\boxed{P(h \mid e) = \frac{P(e \mid h),P(h)}{P(e)}}

  • (Conditionalization) After applying Bayes' theorem to obtain P(h∣e)P(h \mid e), adopt that as your posterior degree of belief in hh, i.e., Bel(h)=P(h∣e)\text{Bel}(h) = P(h \mid e).

Analogy: Think of Bayesian reasoning as updating a rumor's credibility as new evidence (ee) comes in — you start with a "gut feeling" (prior P(h)P(h)), then adjust it based on how well the new evidence fits that hypothesis versus others.

Medical Screening Example

  • Suppose women attending a particular clinic show a long-term chance of 1 in 100 of having breast cancer.
  • The initial screening test has a false positive rate of 0.2 (20% of women without cancer test positive) and a false negative rate of 0.1 (10% of women with cancer test negative) — so the probability of a positive test given cancer is 90%.
  • Suppose you are such a woman who has just tested positive. What is the probability that you actually have cancer?

Analogy: This is the classic illustration of why "the test says positive" doesn't mean "you're probably sick" — when the disease is rare, even an accurate test produces far more false positives than true positives in raw numbers, so the posterior probability of cancer is much lower than intuition suggests.


Maximum Likelihood

Maximum Likelihood

  • Ten friends (A – J) and their attitudes toward pickled gherkins.
  • Question: What is the best estimate, from this data, of the frequency of the population who like pickled gherkins?
  • Intuitively, the correct answer feels like 4/10 or 40% (taking the average of all answers, Yes = 1, No = 0).
  • How do we know this is the correct answer?

(Table of 10 friends' yes/no answers — insert image here)

A's Proposal

  • A said: "We should give extra weighting to the answers of those who were asked first because they are the original."

B's Proposal

  • B said: "It is better to ask five people and ignore all the others." So she just looks at the answer of every second person.

C's Proposal

  • C said: "Let's just listen to the first person and accept what they say as true."

What is the unique best way of using data to make a measurement?

  • A's hypothesis: the probability that a person likes pickled gherkins is 715\frac{7}{15}.
  • B's hypothesis: 15\frac{1}{5} or 20%.
  • C's hypothesis: 1 or 100%.

Likelihood from A's Hypothesis

  • A's hypothesis: probability of liking pickled gherkins = 715\frac{7}{15}.
  • Combined likelihood of all answers:

(715)4×(815)6=0.00109≈1.09×10−3\left(\frac{7}{15}\right)^4 \times \left(\frac{8}{15}\right)^6 = 0.00109 \approx 1.09 \times 10^{-3}

Likelihood from B's Hypothesis

  • B's hypothesis: probability = 15\frac{1}{5}.
  • Combined likelihood of all answers = ? (exercise — apply the same method as A's hypothesis)

Likelihood from C's Hypothesis

  • C's hypothesis: probability = 11.
  • Combined likelihood of all answers = ? (exercise)

Likelihood from the Simple Average Model

  • The probability that a person likes pickled gherkins is 40%.
  • Combined likelihood of all answers:

0.44×0.66=0.00119\boxed{0.4^4 \times 0.6^6 = 0.00119}

  • This is the maximum likelihood estimate — of the models considered, the simple average (40%) gives the highest combined likelihood of producing the observed data.

Analogy: Maximum likelihood asks, "Out of all the possible 'stories' (hypotheses) I could tell about the world, which one makes the data I actually observed the least surprising?" The 40%-average story turns out to make the observed 4-yes/6-no split more plausible than the other proposals.


Expected Value

Expected Value

  • The expected value (mean, mean value, mathematical expectation) of a discrete random variable XX, with a finite number of finite outcomes x1,x2,…,xnx_1, x_2, \ldots, x_n occurring with probabilities p1,p2,…,pnp_1, p_2, \ldots, p_n respectively, is defined as:

E[X]=∑i=1nxipi,where ∑i=1npi=1\boxed{E[X] = \sum_{i=1}^{n} x_i p_i}, \qquad \text{where } \sum_{i=1}^{n} p_i = 1

Example: Roulette

  • The roulette game has a small ball and a wheel with 38 numbered pockets. As the wheel spins, the ball settles into one of the pockets.
  • Random variable XX represents the (monetary) outcome of a $1 bet on a single number.
  • If the bet wins (probability 138\frac{1}{38} in American roulette), the payoff is $35; otherwise, the player loses the bet.
  • Calculate the expected profit from a bet.

St. Petersburg Paradox

  • A casino offers a game of chance in which a fair coin is tossed at each stage. The initial stake starts at $2 and is doubled every time heads appears. The first time tails appears, the game ends, and the player wins whatever is in the pot.
  • Calculate the expected dollars a player gets.
  • Calculate the expected length of the game.

Analogy: This paradox shows that a game can have an infinite expected value, yet almost no rational person would pay a large amount to play it — a hint that expected value alone doesn't fully capture how people actually value risk (this is part of why utility theory was developed).

Two Envelopes Problem

  • You are given two indistinguishable envelopes, each containing money — one contains twice as much as the other. You pick one envelope and keep the money it contains. Before inspecting it, you're given the chance to switch envelopes. Should you switch?

Variance & Covariance Matrix

Variance

  • The variance of a random variable XX is the expected value of the squared deviation from the mean of XX:

σX2=E[(X−E[X])2]=E[X2]−(E[X])2\boxed{\sigma_X^2 = E\left[(X - E[X])^2\right] = E[X^2] - (E[X])^2}

Properties

  • E[c]=cE[c] = c, where cc is a constant.

  • E[cX]=cE[X]E[cX] = cE[X]

  • E[X±Y]=E[X]±E[Y]E[X \pm Y] = E[X] \pm E[Y]

  • Note: if E[X]=0E[X] = 0, then σX2=E[XX]\sigma_X^2 = E[XX].

Exercise

  • A fair six-sided die is tossed once. Let random variable XX denote the number showing on the top face. Compute the expected value of XX and the variance of XX.

Population Variance vs. Unbiased Sample Variance

  • Population variance of a finite population of size nn with values xix_i and mean μ\mu:

σX2=1n∑i=1n(xi−μ)2\boxed{\sigma_X^2 = \frac{1}{n}\sum_{i=1}^{n} (x_i - \mu)^2}

  • (Unbiased) sample variance of nn samples with values xix_i and sample mean xˉ\bar{x}:

σX2=1n−1∑i=1n(xi−xˉ)2\boxed{\sigma_X^2 = \frac{1}{n-1}\sum_{i=1}^{n} (x_i - \bar{x})^2}

Analogy: Dividing by n−1n-1 instead of nn is like giving yourself a small "penalty" for not knowing the _true_population mean — you estimated the mean from the same sample, which makes the data look slightly less spread out than it really is, so you correct for that by dividing by a smaller number.

Pseudo-variance is Biased

  • Simulation: repeatedly roll a die 100 times, record the face-up side, compute the average and variance. Repeat for 10,000 rounds. Compute the averages of the averages and variances.

  • Results:

    • mean(mean) = 3.5001
    • mean(var, n−1n-1 divisor) = 2.9168
    • mean(var, nn divisor) = 2.8876
  • This empirically demonstrates that dividing by nn (instead of n−1n-1) underestimates the true variance — i.e., it is a biased estimator, while the n−1n-1 version is unbiased.

Covariance

  • Covariance is a measure of the joint variability of two random variables:

σXY2=E[(X−E[X])(Y−E[Y])]=E[XY]−E[X]E[Y]\boxed{\sigma_{XY}^2 = E\big[(X - E[X])(Y - E[Y])\big] = E[XY] - E[X]E[Y]}

  • Note: σXX2=σX2\sigma_{XX}^2 = \sigma_X^2.
  • Note: if XX and YY are zero-mean, then σXY2=E[XY]\sigma_{XY}^2 = E[XY].

Example

  • Given the joint probability mass function f(x,y)f(x,y): f(1,1)=f(1,2)=f(2,2)=f(2,3)=0.25f(1,1) = f(1,2) = f(2,2) = f(2,3) = 0.25 and f(2,1)=f(1,3)=0f(2,1) = f(1,3) = 0, find σXY2\sigma_{XY}^2.

Covariance Matrix

  • Variance and covariance are often represented together in a covariance matrix CC, where entries CijC_{ij} are given by σXiXj2\sigma_{X_i X_j}^2.
  • The covariance matrix is symmetric.
  • Variances appear along the diagonal.
  • Covariances appear in the off-diagonal.

Analogy: Think of the covariance matrix as a "relationship report card" for a group of variables — the diagonal tells you how much each variable varies on its own, while the off-diagonal entries tell you how each pair of variables tends to move together (or in opposite directions).

Example: 5 observations, measuring 3 variables

  • X1=[4.0, 4.2, 3.9, 4.3, 4.1]X_1 = [4.0,\ 4.2,\ 3.9,\ 4.3,\ 4.1]
  • X2=[2.0, 2.1, 2.0, 2.1, 2.2]X_2 = [2.0,\ 2.1,\ 2.0,\ 2.1,\ 2.2]
  • X3=[0.60, 0.59, 0.58, 0.62, 0.63]X_3 = [0.60,\ 0.59,\ 0.58,\ 0.62,\ 0.63]
  • Find the covariance matrix.
  • (For MATLAB: use cov(X), where each row is an observation and each column is a variable.)