TAI BUI
Back to curriculum
LearnPython

Probability and Distributions

Probability is the only language a model has for saying 'I'm not sure.'

TIME: ~75 minutesPREREQUISITES: Phase 1, Lessons 01-04

Learning Objectives

  • Implement PMFs and PDFs from scratch for Bernoulli, categorical, Poisson, uniform, and normal distributions
  • Compute expected value, variance, and use the Central Limit Theorem to explain why Gaussians dominate
  • Build softmax and log-softmax functions with the numerical stability trick (subtract max logit)
  • Calculate cross-entropy loss from logits and connect it to negative log-likelihood

The Problem

A classifier outputs [0.03, 0.91, 0.06]. A language model picks its next token out of 50,000 candidates. A diffusion model paints an image by repeatedly sampling from a distribution it learned during training. Different tasks, same underlying move: probability in action.

That move never stops. A model's prediction is a probability distribution, its loss function is a measure of distance between that distribution and the true one, and every training step is just nudging one distribution to look more like the other. Skip probability and you can't read an ML paper, you can't debug a model that's gone wrong, and you definitely can't explain why your training loss just turned into NaN.

Warm-up0/3
1. A weather forecast says there's a 90% chance of rain tomorrow. In plain terms, what does that number represent?Warm-up
A forecast app showing a 90 percent filled bar next to a rain icon, labelled for tomorrow's date, with no further explanation of the number.
2. You flip a fair coin 10 times and get 8 heads. You then flip it 10,000 times. Which result would you expect to land closer to a 50/50 split?Warm-up
A bar chart of 10 coin flips giving 8 heads and 2 tails, next to a dashed placeholder box with a question mark standing in for 10,000 flips of the same coin.
3. In calculus, what does the definite integral of a function from a to b measure?Warm-up
A smooth curve f(x) with the region between two marked points a and b shaded, asking what the definite integral from a to b measures.

The Concept

Events, Sample Spaces, and Probability

The sample space S is the set of every possible outcome. An event is any subset of that space, and probability is the function that maps each event to a number between 0 and 1.

Coin flip:
  S = {H, T}
  P(H) = 0.5,  P(T) = 0.5

Single die roll:
  S = {1, 2, 3, 4, 5, 6}
  P(even) = P({2, 4, 6}) = 3/6 = 0.5

Three axioms define the entire subject:

  1. P(A) >= 0 for any event A
  2. P(S) = 1 (something always happens)
  3. P(A or B) = P(A) + P(B) when A and B cannot both occur

Bayes' theorem, expected value, every distribution in this lesson: all of it follows from these three rules.

Conditional Probability and Independence

P(A|B) is the probability of A, given that B already happened.

P(A|B) = P(A and B) / P(B)

Example: deck of cards
  P(King | Face card) = P(King and Face card) / P(Face card)
                      = (4/52) / (12/52)
                      = 4/12 = 1/3

Two events are independent exactly when knowing one tells you nothing about the other:

Independent:   P(A|B) = P(A)
Equivalent to: P(A and B) = P(A) * P(B)

Coin flips are independent of each other. Drawing cards without replacement is not.

Probability Mass Functions vs Probability Density Functions

A discrete random variable has a probability mass function (PMF): every outcome carries a specific probability you can read off directly.

PMF: P(X = k)

Fair die:
  P(X = 1) = 1/6
  P(X = 2) = 1/6
  ...
  P(X = 6) = 1/6

  Sum of all probabilities = 1

A continuous random variable has a probability density function (PDF) instead. The density at any single point isn't itself a probability; you only get a probability by integrating that density over an interval.

PDF: f(x)

P(a <= X <= b) = integral of f(x) from a to b

f(x) can be greater than 1 (density, not probability)
integral from -inf to +inf of f(x) dx = 1

The distinction matters in ML. Classification is a discrete choice, so its outputs are PMFs. Take a VAE (variational autoencoder, a generative model that learns a compressed representation of data): its latent space is continuous, so it works with PDFs.

Common Distributions

Bernoulli: one trial, two outcomes. This is the distribution binary classification runs on.

P(X = 1) = p
P(X = 0) = 1 - p
Mean = p,  Variance = p(1-p)

Categorical: one trial, k possible outcomes, exactly what softmax hands you for multi-class classification.

P(X = i) = p_i,  where sum of p_i = 1
Example: P(cat) = 0.7,  P(dog) = 0.2,  P(bird) = 0.1

Uniform: every outcome equally likely. The default for random initialization.

Discrete: P(X = k) = 1/n for k in {1, ..., n}
Continuous: f(x) = 1/(b-a) for x in [a, b]

Normal (Gaussian): the bell curve, set by two numbers, mean (mu) and variance (sigma^2).

f(x) = (1 / sqrt(2*pi*sigma^2)) * exp(-(x - mu)^2 / (2*sigma^2))

Standard normal: mu = 0, sigma = 1
  68% of data within 1 sigma
  95% within 2 sigma
  99.7% within 3 sigma

Poisson: counts of rare events over a fixed interval. This is the distribution behind event rates.

P(X = k) = (lambda^k * e^(-lambda)) / k!
Mean = lambda,  Variance = lambda

Expected Value and Variance

Expected value is the probability-weighted average outcome.

Discrete:   E[X] = sum of x_i * P(X = x_i)
Continuous: E[X] = integral of x * f(x) dx

Variance measures how spread out the outcomes are around that mean.

Var(X) = E[(X - E[X])^2] = E[X^2] - (E[X])^2
Standard deviation = sqrt(Var(X))

In ML, the loss function you're minimizing is an expected value: the average loss over the data distribution. Variance shows up as a stability signal instead. When your gradients have high variance, training gets noisy.

Joint and Marginal Distributions

A joint distribution, P(X, Y), describes two random variables at once.

Joint PMF example (X = weather, Y = umbrella):

Y=0 (no umbrella)Y=1 (umbrella)Marginal P(X)
X=0 (sun)0.400.10P(X=0) = 0.50
X=1 (rain)0.050.45P(X=1) = 0.50
Marginal P(Y)P(Y=0) = 0.45P(Y=1) = 0.551.00

The marginal distribution sums out the other variable:

P(X = x) = sum over all y of P(X = x, Y = y)

Those row and column totals in the table above are exactly the marginals.

Why the Normal Distribution Shows Up Everywhere

The Central Limit Theorem: the sum, or average, of many independent random variables converges to a normal distribution, no matter what distribution you started with.

Roll 1 die:  uniform distribution (flat)
Average of 2 dice:  triangular (peaked)
Average of 30 dice: nearly perfect bell curve

This works for ANY starting distribution.

That's why:

  • Measurement errors are approximately normal (many small independent sources)
  • Weight initializations in neural networks use normal distributions
  • Gradient noise in SGD (stochastic gradient descent) is approximately normal (sum of many sample gradients)
  • The normal distribution is the maximum entropy distribution for a given mean and variance

Log Probabilities

A log probability is log(P(x)): the same probability, just expressed on a log scale. Here's why that's worth doing. Raw probabilities break down numerically — multiply enough small ones together and the product underflows to zero:

P(sentence) = P(word1) * P(word2) * ... * P(word_n)
            = 0.01 * 0.003 * 0.02 * ...
            -> 0.0 (underflow after ~30 terms)

Taking the log turns that multiplication into addition, and addition doesn't underflow:

log P(sentence) = log P(word1) + log P(word2) + ... + log P(word_n)
                = -4.6 + -5.8 + -3.9 + ...
                -> finite number (no underflow)

Rules:

  • log(a * b) = log(a) + log(b)
  • log probabilities are always <= 0 (since 0 < P <= 1)
  • more negative means less likely
  • cross-entropy loss is the negative log probability of the correct class, also called the negative log-likelihood

Softmax as a Probability Distribution

A neural network's raw output is a set of scores called logits. Softmax is the function that turns those logits into a valid probability distribution:

softmax(z_i) = exp(z_i) / sum(exp(z_j) for all j)

Properties:
  - All outputs are in (0, 1)
  - All outputs sum to 1
  - Preserves relative ordering of inputs
  - exp() amplifies differences between logits

The softmax trick: subtract the max logit before you exponentiate, so nothing overflows.

z = [100, 101, 102]
exp(102) = overflow

z_shifted = z - max(z) = [-2, -1, 0]
exp(0) = 1  (safe)

Same result, no overflow.

Log-softmax fuses softmax and log into one numerically stable operation. PyTorch runs this internally for cross-entropy loss.

Sampling

Sampling is drawing random values from a distribution. In ML, it shows up constantly:

  • Dropout randomly samples which neurons to zero out
  • Data augmentation samples random transformations
  • Language models sample the next token from the predicted distribution
  • Diffusion models sample noise and progressively denoise

Sampling from an arbitrary distribution isn't always trivial. It takes techniques like inverse transform sampling, rejection sampling, or the reparameterization trick VAEs rely on.

Check: The Concept0/34
1. Which of the following is one of the three axioms that define probability in this lesson?Define
A circle representing the sample space S of a die roll with all six outcomes marked, three of them (2, 4 and 6) shaded as the event A, asking which rule about P(S) and P(A) always holds.
2. What is the sample space of an experiment?Define
A box labelled flip a coin, the experiment, with an arrow to a highlighted set written S equals H, T, asking what this full set of outcomes is called.
3. Two events A and B are independent. According to this lesson, which equation must hold?Define
Two separate boxes, Flip 1 and Flip 2, each naming its own event as that flip landing heads, with a note that the two events are independent and a question asking which equation must hold.
4. What does P(A|B) mean?Define
Two overlapping circles A and B with P(A and B) = 0.08 and P(B) = 0.40 labelled, and a question mark next to P(A given B) equals question mark.
5. What does a probability mass function (PMF) give you?Define
Six equal-height bars for a fair die's faces 1 through 6, each marked 1/6, with a note that each outcome has its own exact probability read off directly.
6. For a continuous random variable, what does the PDF value f(x) at a single point represent?Define
An illustrative density curve whose peak rises above a dashed line marked f equals 1, asking what the curve's height at a single point represents.
Illustrative schematic, not a specific named distribution.
7. What is the expected value of a random variable?Define
A table of three payouts, 10, 50 and 100 dollars, with probabilities 0.50, 0.30 and 0.20, and a question mark asking for the expected value E of X.
8. Which formula correctly defines variance in terms of expected value, as given in this lesson?Define
Two bar charts of outcome probabilities, distribution A clustered at 4, 5 and 6 and distribution B spread across 0, 5 and 10, with a note that both share the same mean but spread differently.
9. Which two numbers fully specify a normal distribution?Define
A single symmetric bell-shaped curve with no axis values or parameters labelled, asking which two numbers fully specify a curve shaped like this.
10. What does the Central Limit Theorem state?Define
Three histograms side by side from real simulated dice rolls: one die giving a flat shape, the average of two dice giving a triangular shape, and the average of thirty dice giving a smooth bell shape.
Simulated with numpy, seed 42, 30,000 trials per panel.
11. What does a joint distribution P(X, Y) describe?Define
A blank 2 by 2 grid with row headers X equals x1, x2 and column headers Y equals y1, y2, every cell marked with a question mark, asking what P of X and Y describes.
12. In a joint distribution table for two variables X and Y, how do you compute the marginal distribution P(X = x)?Define
A joint table with cells 0.20, 0.30, 0.15 and 0.35 for X and Y, with the row marginals for X marked as question marks, asking how to compute the marginal from this table.
13. What is a log probability?Define
A probability of 0.2 feeding into a box labelled log of dot dot dot, with an arrow to a question mark, asking what the result of that step is called.
14. What does softmax do to a network's raw output scores?Define
A flow of three boxes: raw scores 1.0, 3.0, 0.5, then softmax of dot dot dot, then three question marks for the result, asking what softmax does to the raw scores.
15. What are logits?Define
A flow of three boxes, a highlighted box of raw numbers 2.1, -0.4 and 0.8 feeding into softmax and then into probabilities, with a question mark under the highlighted box asking what it is called.
16. According to the lesson, what is cross-entropy loss for the correct class also known as?Define
The formula cross-entropy loss equals negative log of q of the true class, with an arrow down to a question mark, asking what this same quantity is also known as.
17. What does sampling mean in this lesson?Define
A bar chart of weighted outcomes cat 0.7, dog 0.2 and bird 0.1, with an arrow to a circle marked with a question mark standing in for one drawn outcome.
18. What is the difference between a probability mass function (PMF) and a probability density function (PDF)?Explain
A bar chart of discrete outcomes 1, 2 and 3 with unmarked heights next to a smooth continuous curve, asking how describing probability differs between the two cases.
19. A continuous variable has density f(x) = 2.5 at some point x. Why is that not a problem?Explain
A flat block density that is 0 outside the interval 0 to 0.4 and a constant 2.5 inside it, with a dashed marker at x = 0.2 on top of the block, asking whether a density value of 2.5 is a problem.
20. Why is the gradient noise in SGD approximately normal?Explain
Five boxes g_1 through g_5 holding different per-example gradient values, with an arrow down through sum or average to a question mark, asking why the sum's noise ends up approximately bell-shaped.
Illustrative per-example gradient values.
21. Why does softmax subtract the maximum logit before exponentiating (the 'softmax trick')?Explain
The lesson's logits 100, 101 and 102 exponentiated directly in float32, with the last value not finite, next to the shifted logits -2, -1, 0 and a question mark asking why shifting helps and whether it changes the answer.
22. What does log-softmax combine, according to the lesson, and why does PyTorch use it internally for cross-entropy loss?Explain
Two pipelines from logits to log-probabilities: a two-step version through softmax then log, and a highlighted one-step log_softmax version, asking what the one-step version combines and why it is used.
23. Why do language models work with log probabilities instead of raw probabilities?Explain
The lesson's own sentence probability chain, 0.01 times 0.003 times 0.02 and so on, collapsing to exactly 0 after about 30 terms, with a question mark asking why a language model avoids this computation.
24. Cross-entropy loss for classification simplifies to -log(q(true_class)). What does this mean intuitively?Explain
A box showing a model's predicted probability of 0.9 for the true class, with an arrow to a question mark, asking what the formula negative log of q of the true class means about this prediction.
25. A model treats server errors as Poisson with lambda = 4 per hour. What are the mean and variance of the hourly count?Apply
A bar chart of Poisson probabilities for lambda equals 4, for counts 0 through 9, labelled server errors per hour, asking for the mean and variance of this count.
26. In the weather and umbrella table, what is P(umbrella | rain)?Apply
The lesson's weather and umbrella joint table with sun and rain rows and no-umbrella and umbrella columns filled in, and a question mark asking for the probability of umbrella given rain.
27. Training loss turns to NaN right after a batch containing a very large logit. Which cause is most likely?Analyze
A training loss curve dropping over four steps then hitting a dashed line marked NaN, next to a callout box noting that batch contained one logit of 812, asking what most likely caused the jump to NaN.
28. A pipeline computes -log(p) where the correct token's raw probability p is exactly 0. What happens?Analyze
A raw probability of exactly 0.0 feeding into negative log of p, with the result left as a question mark.
29. In the weather and umbrella table, which check shows X and Y are not independent?Analyze
The same weather and umbrella joint table, with sun and rain rows and no-umbrella and umbrella columns filled in, asking which check shows the two variables are not independent.
30. A teammate says the CLT makes any single measurement from a skewed source approximately normal. What is wrong?Analyze
A skewed histogram of a real exponential distribution with one single sampled value marked by a vertical line, next to a claim that this single draw will look approximately normal because of the Central Limit Theorem.
31. A scorer multiplies 500 per-token probabilities and gets 0.0 for many sequences, so it cannot rank them. What fixes this?Analyze
A chain of 500 multiplied probabilities collapsing to exactly 0, with a question mark asking what fixes the ranking problem.
32. A 3-class example has true class 0. Model A outputs [0.70, 0.20, 0.10] and model B outputs [0.34, 0.33, 0.33]. Which has the lower cross-entropy loss?Analyze
Two bar charts of predicted probabilities over three classes with the true class at index 0 highlighted: model A gives it 0.70, model B gives it 0.34, asking which model has the lower cross-entropy loss.
33. You must model how many support tickets arrive per hour, treating them as rare independent events over a fixed interval. Which distribution fits?Design
A one-hour timeline with several independent tick marks scattered along it, each representing one support ticket arriving at a random time, with no count or distribution named.
Simulated arrival times with numpy, seed 11.
34. A language model returns a distribution over 50,000 tokens at each step. How should you pick the next token so outputs vary while respecting the model's probabilities?Design
A bar chart over a few example tokens out of 50,000, with most of the probability mass on a handful of common words and a long unseen tail, asking how the next token should be picked.
Illustrative shape over an unspecified real vocabulary distribution.

Build It

Step 1: Probability basics

python
import math
import random
 
def factorial(n):
    result = 1
    for i in range(2, n + 1):
        result *= i
    return result
 
def combinations(n, k):
    return factorial(n) // (factorial(k) * factorial(n - k))
 
def conditional_probability(p_a_and_b, p_b):
    return p_a_and_b / p_b
 
p_king_given_face = conditional_probability(4/52, 12/52)
print(f"P(King | Face card) = {p_king_given_face:.4f}")

Step 2: PMF and PDF from scratch

python
def bernoulli_pmf(k, p):
    return p if k == 1 else (1 - p)
 
def categorical_pmf(k, probs):
    return probs[k]
 
def poisson_pmf(k, lam):
    return (lam ** k) * math.exp(-lam) / factorial(k)
 
def uniform_pdf(x, a, b):
    if a <= x <= b:
        return 1.0 / (b - a)
    return 0.0
 
def normal_pdf(x, mu, sigma):
    coeff = 1.0 / (sigma * math.sqrt(2 * math.pi))
    exponent = -0.5 * ((x - mu) / sigma) ** 2
    return coeff * math.exp(exponent)

Step 3: Expected value and variance

python
def expected_value(values, probabilities):
    return sum(v * p for v, p in zip(values, probabilities))
 
def variance(values, probabilities):
    mu = expected_value(values, probabilities)
    return sum(p * (v - mu) ** 2 for v, p in zip(values, probabilities))
 
die_values = [1, 2, 3, 4, 5, 6]
die_probs = [1/6] * 6
mu = expected_value(die_values, die_probs)
var = variance(die_values, die_probs)
print(f"Die: E[X] = {mu:.4f}, Var(X) = {var:.4f}, SD = {var**0.5:.4f}")

Step 4: Sampling from distributions

python
def sample_bernoulli(p, n=1):
    return [1 if random.random() < p else 0 for _ in range(n)]
 
def sample_categorical(probs, n=1):
    cumulative = []
    total = 0
    for p in probs:
        total += p
        cumulative.append(total)
    samples = []
    for _ in range(n):
        r = random.random()
        for i, c in enumerate(cumulative):
            if r <= c:
                samples.append(i)
                break
    return samples
 
def sample_normal_box_muller(mu, sigma, n=1):
    samples = []
    for _ in range(n):
        u1 = random.random()
        u2 = random.random()
        z = math.sqrt(-2 * math.log(u1)) * math.cos(2 * math.pi * u2)
        samples.append(mu + sigma * z)
    return samples

Step 5: Softmax and log probabilities

python
def softmax(logits):
    max_logit = max(logits)
    shifted = [z - max_logit for z in logits]
    exps = [math.exp(z) for z in shifted]
    total = sum(exps)
    return [e / total for e in exps]
 
def log_softmax(logits):
    max_logit = max(logits)
    shifted = [z - max_logit for z in logits]
    log_sum_exp = max_logit + math.log(sum(math.exp(z) for z in shifted))
    return [z - log_sum_exp for z in logits]
 
def cross_entropy_loss(logits, target_index):
    log_probs = log_softmax(logits)
    return -log_probs[target_index]

Step 6: Central Limit Theorem demonstration

python
def demonstrate_clt(dist_fn, n_samples, n_averages):
    averages = []
    for _ in range(n_averages):
        samples = [dist_fn() for _ in range(n_samples)]
        averages.append(sum(samples) / len(samples))
    return averages

Step 7: Visualization

python
import matplotlib.pyplot as plt
 
xs = [mu + sigma * (i - 500) / 100 for i in range(1001)]
ys = [normal_pdf(x, mu, sigma) for x, mu, sigma in ...]
plt.plot(xs, ys)

The full implementation, with every visualization, lives in code/probability.py.

Check: Build It0/7
1. What does the Build It code print for conditional_probability(4/52, 12/52) with four decimals?Apply
The Build It function call conditional_probability with 4 over 52 and 12 over 52, asking for the result to four decimal places.
2. What does the die example print for E[X] and Var(X)?Apply
The Build It die example with values 1 through 6 and equal probabilities of 1/6 each, asking for E of X and the variance of X.
3. What does uniform_pdf(0.1, 0.0, 0.5) return?Apply
A raised block from 0.0 to 0.5 for a uniform density with its height marked as unknown, next to the function call uniform_pdf of 0.1, 0.0 and 0.5 left unanswered.
4. In sample_categorical with probs [0.5, 0.3, 0.2], which index is appended when random.random() returns 0.65?Apply
A cumulative bar for probabilities 0.5, 0.3 and 0.2 split into segments labelled 0, 1 and 2, with a marker at r equals 0.65, asking which index gets appended.
5. What does the Build It softmax return for logits [100, 101, 102]?Apply
The logits 100, 101 and 102 with softmax of z left as three question marks.
6. What does cross_entropy_loss([0.0, 0.0, 0.0, 0.0], 2) return?Apply
Four equal logits, all 0.0, with target index 2, asking for the cross-entropy loss.
7. You build a 1,000-class classifier whose logits can be large. Which loss pipeline is safest?Design
An abbreviated list of 1000 logits, l_1 through l_1000, with a question asking for the safest way to compute the loss.

Use It

With NumPy and SciPy, everything above collapses to one-liners:

python
import numpy as np
from scipy import stats
 
normal = stats.norm(loc=0, scale=1)
samples = normal.rvs(size=10000)
print(f"Mean: {np.mean(samples):.4f}, Std: {np.std(samples):.4f}")
print(f"P(X < 1.96) = {normal.cdf(1.96):.4f}")
 
logits = np.array([2.0, 1.0, 0.1])
from scipy.special import softmax, log_softmax
probs = softmax(logits)
log_probs = log_softmax(logits)
print(f"Softmax: {probs}")
print(f"Log-softmax: {log_probs}")

You built all of this by hand first. Now you know exactly what the library call is doing underneath.

Author's Note

The first time I watched a model's loss jump to nan mid-training, I assumed I'd broken something in the architecture. I hadn't. Somewhere in that batch, softmax had exponentiated a large logit into infinity, or a log() call had been handed a probability of exactly zero, and the whole computation graph poisoned itself from that point on. Every fix for this traces straight back to this lesson: shift the logits down before exponentiating, do your arithmetic in log space instead of raw probabilities, never let anything touch log(0) unguarded. None of it is exotic math. It's the boring numerical hygiene that keeps a training run from quietly going wrong for three hours before you notice the loss curve went flat. Learn the shift-and-log trick once, here, and you'll spot this bug on sight for the rest of your career.

Exercises

  1. Implement inverse transform sampling for the exponential distribution. Verify by sampling 10,000 values and comparing the histogram to the true PDF.

  2. Build a joint distribution table for two loaded dice. Compute the marginal distributions and check whether the dice are independent.

  3. Compute the cross-entropy loss for a 5-class classifier that outputs logits [2.0, 0.5, -1.0, 3.0, 0.1] when the correct class is index 3. Then verify your answer with PyTorch's nn.CrossEntropyLoss.

  4. Write a function that takes a list of log probabilities and returns the most likely sequence, the total log probability, and the equivalent raw probability. Test it with a sentence of 50 words where each word has probability 0.01.

Key Terms

TermWhat people sayWhat it actually means
Sample space"All the possibilities"The set S of every possible outcome of an experiment
PMF"The probability function"A function that gives the exact probability of each discrete outcome, summing to 1
PDF"The probability curve"A density function for continuous variables. Integrate it over an interval to get probability
Conditional probability"Probability given something"P(A|B) = P(A and B) / P(B). The foundation of Bayesian thinking and Bayes' theorem
Independence"They don't affect each other"P(A and B) = P(A) * P(B). Knowing one event tells you nothing about the other
Expected value"The average"The probability-weighted sum of all outcomes. The loss function is an expected value
Variance"How spread out"The expected squared deviation from the mean. High variance = noisy, unstable estimates
Normal distribution"The bell curve"f(x) = (1/sqrt(2pisigma^2)) * exp(-(x-mu)^2/(2*sigma^2)). Appears everywhere due to the CLT
Central Limit Theorem"Averages become normal"The mean of many independent samples converges to a normal distribution regardless of the source
Joint distribution"Two variables together"P(X, Y) describes the probability of every combination of X and Y outcomes
Marginal distribution"Sum out the other variable"P(X) = sum_y P(X, Y). Recovers one variable's distribution from the joint
Log probability"Log of the probability"log P(x). Turns products into sums, preventing numerical underflow in long sequences
Softmax"Turn scores into probabilities"softmax(z_i) = exp(z_i) / sum(exp(z_j)). Maps real-valued logits to a valid probability distribution
Cross-entropy"The loss function"-sum(p_true * log(p_predicted)), the negative log-likelihood of the correct class. Measures how different two distributions are. Lower is better
Logits"Raw model outputs"Unnormalized scores before softmax. Named after the logistic function
Sampling"Drawing random values"Generating values according to a probability distribution. How models generate output

Further Reading

Code

Ships With