Notes

Probability and Algebra

Probability

Deep Learning Book Chapter 3. wandb math4ml series. Tutoring and AI conversations.

Probability allows making uncertain statements and reasoning in its presence, and information theory allows quantifying uncertainty in a probability distribution.

1. Etymology

etymoline.com. Useful especially as a non-native English speaker.

  • probable, more than 50%
  • possible, non-0 %
  • chance, very likely, more than 50%
  • likely, same as probable and chance, more than 50%.
  • unlikely, possible in a negative way.
  • odds, same as probable, but in a negative way (?).
  • likelihood (likely + hood ~ state), same as probability.

Probability theory was made to reason under uncertainty. Frequentist and Bayesian: out of 100, 90 times it will be x, vs. we are 90% certain it is x. Bayesian deals with uncertainty, so I'm 0.7 sure that's it; frequentist says, if I do it 1000 times, it will happen 700 times. Both are computed the same way, but the meaning is a bit different.

2. Basics

2.1 Distributions

From all the possible values within a range or set of options, how likely is xx to show up?

  • Discrete, aka Probability Mass Functions, have a determined set of options.
  • Continuous, aka Probability Density Functions, have infinite possible values within a range. area/integral of P(x) = 1.
  • Uniform: for k possible states (continuous or discrete), each state is equally likely: 1/k.

2.2 Terminology

  • P(x)P(x) = probability of x

  • P(x,y)P(x, y) = probability of x and y at the same time (happening simultaneously)

  • P(x∣y)P(x | y) = conditional, probability of x ocurring, given that y already ocurred.

    • P(y∣x)=P(x,y)P(x)P(y \mid x) = \frac{P(x, y)}{P(x)}, where P(x)>=0P(x) >= 0
  • For P(x,y)P(x, y) and P(x∣y)P(x | y), xx and yy could be from the same distribution or different ones.

  • Marginal probability tells us that if we know P(x,y)P(x, y), we can find P(x)P(x) independently with the sum rule P(x, for every y).

  • The chain rule = the joint probability of multiple variables can be decomposed into conditionals Chain rule of conditional probabilities

  • Independence: x,yx, y are independent if P(x,y)=P(x)∗P(y)P(x,y) = P(x) * P(y)

  • Conditional Independence: x,yx, y are conditionally independent given z, if P(x,y∣z)=P(x∣z)⋅P(y∣z)P(x, y | z) = P(x | z) \cdot P(y | z)

  • Mode is the most likely value. Median: the value that gets to P(0.5), sorted by value (floats); there’s no median if options are strings.

  • Expectation: the average outcome you'd get if you repeated f(x)f(x) many times, weighted by how likely x is. E[X]=∑xP(x)⋅x\mathbb{E}[X] = \sum_x P(x) \cdot x. When f(x)=xf(x) = x = E[X]\mathbb{E}[X] = μμ, the mean, why???. If we say E[X2]\mathbb{E}[X^2] is just the expected value of f(x) = x^2.

  • ML Loss: E\mathbb{E} (Expectation) of the prediction error. Expected Loss=E(x,y)∼D[ℓ(f(x),y)]\text{Expected Loss} = \mathbb{E}_{(x,y) \sim \mathcal{D}}[\ell(f(x), y)]

  • Variance refers to how spread out the values of a distribution are around its mean (Expected value) = E[X]\mathbb{E}[X], so: Var(X)=E[(X−E[X])2]\text{Var}(X) = \mathbb{E}[(X - \mathbb{E}[X])^2] || where f(x)=(X−mean)2=E[f(x)]f(x) = (X - mean)^2 = E[f(x)]

  • Standard Deviation: deviation from the mean = (Var(X))\sqrt(Var(X)), basically variance in its original units. When talking data, we use std, when math, we use variance, because variance can be derived, stdstd, requires a \sqrt{}.

  • MSE (Mean Squared Error). MSE=E[(prediction−target)2]\text{MSE} = \mathbb{E}[(\text{prediction} - \text{target})^2]. Almost like the variance formula, but from the prediction, not from the mean (variance = mean squared distance)

3. Normalization

“Normalized” means that the data has been transformed to fit a structure/constraint, where constraints could be anything, for example: sum(x)=1sum(x)=1 | [0,1][0,1] | µ=0,std=1µ=0, std=1 | Vnorm=1Vnorm=1 | max=1max=1

There are 2 Types of normalization:

3.1. Probability normalization

Discrete distributions require the sum of the probabilities of their possible states to be 1. It can be done via P(x)=s(x)∑xs(x)P(x) = \frac{s(x)}{\sum_x s(x)}, softmax as well: pi=exi∑jexjp_i = \frac{e^{x_i}}{\sum_j e^{x_j}}

  • Softmax has some interesting properties, such as 1) it’s shift-invariant: if you have 2,1,1 and you add 10, 12, 11, 11, softmax will be the same, but 2) if you scale it to x10 = 20, 10, 10, softmax will be much more confident
  • Why softmax? 1) negative scores handled well, 2) smooth and easy to differentiate, 3) it pairs with CrossEntropyLoss by canceling log with the exponential, making a simple gradient.

3.2. Scale normalization

To center, scale, or fix to a range. For example:

  • L2 norm = xnorm=x∥x∥2=x∑xi2x_{\text{norm}} = \frac{x}{\|x\|_2} = \frac{x}{\sqrt{\sum x_i^2}}, magnitude = 1.
  • LayerNorm(x)=x−μσ=zscore=Standardization\text{LayerNorm}(x) = \frac{x - \mu}{\sigma} = z_{score} = Standardization , mean becomes 0 and std 1.
  • asks “How many standard deviations away is this value from the mean?” zscorez_{score}
  • Subtracting the mean centers the data at 0, and dividing by stdstd scales the spread to 1.
  • An example
    • after X−µX-µ = X=[−10,−5,0,5,10]X = [-10, -5, 0, 5, 10] = deviations from the mean
    • std = avg of x2\sqrt{\text{avg of } x^2} = 7.07
    • X’=[−107.07,−57.07,0,57.07,107.07]≈[−1.41,−0.71,0,0.71,1.41]X’ = \left[-\frac{10}{7.07}, -\frac{5}{7.07}, 0, \frac{5}{7.07}, \frac{10}{7.07}\right] \approx [-1.41, -0.71, 0, 0.71, 1.41]
    • average squared distance from 0 now is 1 = which is the definition of std = 1
    • Output unit = standard deviations.
  • RMSNorm\text{RMSNorm} normalizes using only the root mean square of the input, not centering; basically, rescaling does most of the work, and centering is unneeded, making it cheaper to compute and almost equal functionality/stabilization wise.
    • RMSNorm(x)=xRMS(x)+ϵ⋅γ\text{RMSNorm}(x) = \frac{x}{\text{RMS}(x) + \epsilon} \cdot \gamma, where RMS(x)=1d∑i=1dxi2\text{RMS}(x) = \sqrt{\frac{1}{d} \sum_{i=1}^d x_i^2}, pretty much each value squared / d, mean, then sqrt. γ\gamma is learned ϵ\epsilon is num stability
    • scales the inputs by RMS(x)+ϵRMS(x) + \epsilon to have sort of constant magnitude without centering to the mean (subtracting) as LayerNorm\text{LayerNorm} does
    • Relationship to L2 Norm\text{L2 Norm} = ∥x∥2=∑i=1nxi2\|x\|_2 = \sqrt{\sum_{i=1}^n x_i^2} = total magnitude of the vector
    • RMS\text{RMS} = average magnitude of the vector per dimension, L2 norm/n\text{L2 norm} / \sqrt{n}

4. More Definitions

  • Covariance refers to how 2 random variables vary together,
    • Cov(X,Y)=E[(X−E[X])⋅(Y−E[Y])]=∑x,yP(x,y)⋅(x−E[X])⋅(y−E[Y])\text{Cov}(X, Y) = \mathbb{E}[(X - \mathbb{E}[X]) \cdot (Y - \mathbb{E}[Y])] = \sum_{x,y} P(x, y) \cdot (x - \mathbb{E}[X]) \cdot (y - \mathbb{E}[Y])
    • Var(X)=Cov(X,X)\text{Var}(X) = \text{Cov}(X, X) = check out the 2^2 in VarVar formula
    • using joint probability P(x,y)P(x,y) as the weighting factor.
    • average product of deviations.
    • vary together? (x−E[x])(x- E[x]) is positive, means x tends to be above it's mean
    • Interpreting results
      • +, + = + → move same direction
      • -, - = + → move same direction
      • -, + = - → move opposite directions
      • magnitude = higher, lower, means stronger linear relationship, but depends on variables’ scale anyways
        • cause of this, correlation seems better to use.
      • units = P(x)unit x P(y)unit, e.g. score x hours studied. or $*h
  • Correlation = “Standardized Covariance” = how strongly 2 variables change, independent of scale [−1,1][-1, 1]
    • Corr(X,Y)=Cov(X,Y)σX⋅σY\text{Corr}(X, Y) = \frac{\text{Cov}(X, Y)}{\sigma_X \cdot \sigma_Y}
    • Corr(X,Y)=E[(X−μXσX)(Y−μYσY)]\text{Corr}(X, Y) = \mathbb{E}\left[\left(\frac{X - \mu_X}{\sigma_X}\right)\left(\frac{Y - \mu_Y}{\sigma_Y}\right)\right]
    • seem a lot like Z-score of x * Z-score of y
    • just covariance, divided by std of x,yx,y, the division causes:
      • removes units in Covariance of e.g. $⋅h\text{\textdollar} \cdot h, unitless
      • normalizes to standard deviations
      • [−1,1][-1, 1], closer to +1, high correlation; closer to -1, negative correlation, 0, no correlation
    • read Corr(X,Y)=0.8\text{Corr}(X, Y) = 0.8
      • In std terms: when X is 1 std above its mean, Y on avg is 0.8 std above its mean, or 2=1.6, or below=below
      • but also unitless, correlation of x, y is of 0.8
  • Causation = if I do x, will y happen; not enough to see with data. Correlation != causation. The fact that 2 things move together doesn't mean 1 causes the other. P(Y∣do(X))P(Y \mid \textbf{do}(X)) do: intervening, not just observing
  • Sparsity = most of the probability mass is in a small number of outcomes; the rest around 0
    • e.g. P(x)=[0.001,0.002,0.995,0.001,0.001]P(x) = [0.001, 0.002, 0.995, 0.001, 0.001]
    • in contrast to Dense: probabilities evenly spread: P=[0.33,0.33,0.33]P = [0.33, 0.33, 0.33]
    • Low entropy (low avg expected surprise) = high sparsity
    • Not usually seen as a measurement, but:
      • Sparsity(p)=1−H(p)Hmax\text{Sparsity}(p) = 1 - \frac{H(p)}{H_{\text{max}}}
      • where Hmax=log⁡nH_{\text{max}} = \log n, for a uniform distribution
      • lol, this is just a normalized measure around smth, in this case, compared to max entropy.
    • softmax makes distributions sparse

5. ML Probability

5.1 Expectation → Surprise → Entropy → Cross-Entropy → KL divergence

Surprise tells us how unexpected an event is; the more unlikely, the more surprising. Very much 1/P(x)1/P(x), but because of logs shape, we do log⁡(1P(x))=−log⁡P(x)\log\left(\frac{1}{P(x)}\right) = -\log P(x). If P(x)=0.9P(x) = 0.9, sampling and fixing is very little surprising −log⁡(0.9)≈0.045-\log(0.9) \approx 0.045.

  • Entropy just asks: what’s the Expected Surprise of the distribution H(X)=−∑xP(x)log⁡P(x)H(X) = -\sum_x P(x) \log P(x).
  • Cross-Entropy asks: if you have a model QQ, that is trying to predict PP, what’s the Expected Surprise of QQ when predicting? H(p,q)=∑xp(x)⋅(−log⁡q(x))H(p, q) = \sum_x p(x) \cdot (-\log q(x))
    • QQ itself has Entropy, but that’s uncertainty in its own predictions, not yet reality playing out.
    • PP aka reality, also has entropy, as reality can also have uncertainty)
    • Example: if P(2)=0.9P(2) = 0.9, in reality, 2 happens often = it wouldn’t be surprising to get it. Our model says that Q(2)=0.1Q(2) = 0.1, very unlikely; thus, the surprise is large. p(x)∗surprise(q(x))p(x) * surprise(q(x)) = 0.9 x 1.0 = 0.9 (high Cross-Entropy)
  • Cross-entropy Loss = In ML, our correct distribution is generally a one-hot vector [1,0,0][1,0,0]. It means we will be summing p(x)∗−log(q(x))p(x) * -log(q(x)) , but most items we’ll be multiplying by 0 cause, p(x)=0p(x)=0, except for the label p(x)=1p(x)=1 . The formula then becomes 1∗−log(q(x))1 * -log(q(x)), where qq is our model, and x is the probability of the correct label.
    • Wrong + confident = high penalty.
    • Wrong + uncertain = low penalty.
    • Right + confident = reward (low loss).
    • Surprise has these 3 properties; thus, you minimize expected surprise.
  • KL Divergence = if we say Entropy is the expected surprise in reality, and cross-entropy is our model’s expected surprise, DKL(p∥q)=H(p,q)−H(p)D_{\text{KL}}(p \| q) = H(p, q) - H(p), KL Divergence is the extra expected surprise in our system, expected bits of information wasted per prediction.
  • Perplexity = 2 ^ Cross-Entropy in bits; it tells us how many options our model QQ is weighting as equally likely.

5.2 Logs and bits

When we talk about loglog we could have different bases, base2base_2 baseebase_e, etc… It matters in meaning, not in results. Base 2 refers to information theory (measures information in bits). Base e refers to nats (a measurement of …), and ML uses nats because derivatives are nicer.

Regarding information theory (base 2), a great way to think about it is “How many yes/no questions you need to guess something.” For example, to guess a number from 1-8 you need 3 questions, 3 bits; you’d ask 1) “Is it greater than 4?” 2) “ Is it greater than 2, 3) “ Answer. log⁡2(8)=3bits\log_2(8) = 3 \quad \text{bits}

Why do we use logslogs in ML?

  1. It allows for addition instead of multiplication because logs give you the exponents, and you add exponents (that’s why you can sum), and this is needed because multiplications of small numbers will end up collapsing to very unsmooth 0.0000x numbers.
  2. Sums are easy to differentiate compared to long products (stability).
  3. loglog is monotonic; maximizing the log probability finds the same answer as maximizing the probability.
  4. Why negative? The log of probabilities is negative, so we multiply by −1-1to flip the value positive and push it down; ML is about minimization.

5.3 Cross-Entropy Loss == Negative Log Likelihood

Same formula, P(x | θ), read two ways:

  • Probability: θ (model) fixed, vary x. How likely is the data (where data is the real-world observations)? P(x∣θ)P(x \mid \theta)
  • Likelihood: x (data) fixed, vary θ. How well does each model explain it? L(θ)=P(x∣θ)L(\theta) = P(x \mid \theta)
    • Not a distribution over θ (doesn't sum to 1); only meaningful when comparing θs.
  • Log likelihood: many data points multiply; log turns the product into a sum, easy to differentiate. log⁡L(θ)=∑ilog⁡P(xi∣θ)\log L(\theta) = \sum_i \log P(x_i \mid \theta)
  • MLE: pick the θ that makes the data most likely. θ∗=arg⁡max⁡θlog⁡L(θ)\theta^* = \arg\max_\theta \log L(\theta)
  • NLL: flip the sign so we can minimize, and average. NLL=−1N∑ilog⁡P(xi∣θ)\text{NLL} = -\frac{1}{N}\sum_i \log P(x_i \mid \theta) = Cross-Entropy Loss = minimizing expected surprise.

Example: 10 flips, 7 heads. θ = 0.7 explains the data better than θ = 0.5, so MLE picks θ = 0.7.

5.4 Accuracy and Recall

Actually spam Actually not spam
Flagged as spam True Positive (TP), caught it False Positive (FP), false alarm
Not flagged False Negative (FN), missed it True Negative (TN), correctly ignored

Accuracy = (TP+TN)/everything(TP + TN) / \text{everything}. “How often was I right overall?”

Recall = TP/(TP+FN)TP / (TP + FN). “Of the real spam, how much did I catch?”

Specificity = TN/(TN+FP)TN / (TN + FP). Inverse of Recall. “How many did I correctly leave alone?”

Precision = TP/(TP+FP)TP / (TP + FP). “Of what I flagged, how much was real?”

F1 = 2⋅P⋅R/(P+R)2 \cdot P \cdot R / (P + R). “Am I good at both precision and recall?”

Algebraic Relationships

ConceptIdentity / meaningExponentials and powerabFor a positive integer b:multiply a by itself b times.Negative powersa−n=1anFor a positive integer n:start at 1 and divide by a, n times.Inversea−1=1aRoots and fractional powersan=a1/nSquare roota=a1/2Reciprocal of a power1ab=a−bReciprocal of square root1a=a−1/2Definition of a logarithmlog⁡b(a)=x  ⟺  bx=aNatural logarithmln⁡(x)=log⁡e(x)Exponential-log cancelln⁡(ex)=x,eln⁡(x)=xExponentials and logs undo each other.Exponential-log exampleeln⁡(4x2)=4x2Log of a powerlog⁡b(an)=n⋅log⁡b(a)Power of log baseblog⁡b(x)=xProduct to sum in logslog⁡(ab)=log⁡a+log⁡bDivision to subtractionlog⁡(a/b)=log⁡a−log⁡bDerivative of expddxex=exDerivative of logddxln⁡(x)=1x\begin{array}{|l|l|} \hline \textbf{Concept} & \textbf{Identity / meaning} \\ \hline \text{Exponentials and power} & \begin{array}{l}a^b \\ \text{For a positive integer }b\text{:} \\ \text{multiply }a\text{ by itself }b\text{ times.}\end{array} \\[6pt] \hline \text{Negative powers} & \begin{array}{l}a^{-n} = \frac{1}{a^n} \\ \text{For a positive integer }n\text{:} \\ \text{start at 1 and divide by }a\text{, }n\text{ times.}\end{array} \\[6pt] \hline \text{Inverse} & a^{-1} = \frac{1}{a} \\[6pt] \hline \text{Roots and fractional powers} & \sqrt[n]{a} = a^{1/n} \\[6pt] \hline \text{Square root} & \sqrt{a} = a^{1/2} \\[6pt] \hline \text{Reciprocal of a power} & \frac{1}{a^b} = a^{-b} \\[6pt] \hline \text{Reciprocal of square root} & \frac{1}{\sqrt{a}} = a^{-1/2} \\[6pt] \hline \text{Definition of a logarithm} & \log_b(a) = x \iff b^x = a \\[6pt] \hline \text{Natural logarithm} & \ln(x) = \log_e(x) \\[6pt] \hline \text{Exponential-log cancel} & \begin{array}{l}\ln(e^x) = x, e^{\ln(x)} = x \\ \text{Exponentials and logs undo each other.}\end{array} \\[6pt] \hline \text{Exponential-log example} & e^{\ln(4x^2)} = 4x^2 \\[6pt] \hline \text{Log of a power} & \log_b(a^n) = n \cdot \log_b(a) \\[6pt] \hline \text{Power of log base} & b^{\log_b(x)} = x \\[6pt] \hline \text{Product to sum in logs} & \log(ab) = \log a + \log b \\[6pt] \hline \text{Division to subtraction} & \log(a/b) = \log a - \log b \\[6pt] \hline \text{Derivative of exp} & \frac{d}{dx} e^x = e^x \\[6pt] \hline \text{Derivative of log} & \frac{d}{dx} \ln(x) = \frac{1}{x} \\[6pt] \hline \end{array}