Mathematical Foundations

I.7 · Mathematical Language

Is it in, or is it out?

Almost every definition in mathematics starts by saying which things belong. Learn to combine sets, to read the ends of an interval correctly, and to describe a rule between two collections as a set of pairs.

Try it: two sets inside a universe

Or start from

Show

A Venn diagram inside the universe U, the numbers 1 to 12, with two overlapping circles A and B. Only in A: 1, 2, 3. In both: 4, 5. Only in B: 6, 7. In neither: 8, 9, 10, 11, 12. Highlighted: union, {1, 2, 3, 4, 5, 6, 7}. The picture is schematic: the areas are not to scale.

Schematic: the areas are not to scale. The box is the universe U = {1, 2, …, 12}.

elements in A
5
elements in B
4
union
{1, 2, 3, 4, 5, 6, 7}
elements in the result
7

= exact (every statement about finite sets is exact)

A ∪ B = {1, 2, 3, 4, 5, 6, 7}: everything that is in A, in B, or in both. It has 7 elements.

Elements of A
Elements of B

Press the numbers to put them in A or in B, or choose a ready-made pair of sets. The picture is schematic: the areas are not to scale. Then choose an operation, and the elements it keeps are outlined in the picture and listed under it.

Try it before reading on. Press overlapping, then A ∩ B: the elements that are in both sets are picked out. Press A ∪ B and the picked-out elements become everything that is in at least one of them. Now press numbers to move elements around, and watch the lists under the picture change. By the end of the chapter you will be able to say what each operation keeps, to count a union without listing it, to tell exactly when two intervals join into one, and to say which of four properties a rule between two collections has.

Intuition: a set is a question with a yes-or-no answer

A set is a collection of things, called its elements, where the only question that matters is is this thing in the set, or not? Two consequences are worth stating at once, because they surprise people who think of a set as a list. The order does not matter: {1,2,3}\{1,2,3\} and {3,2,1}\{3,2,1\} are the same set. Repeats do not matter either: writing an element twice does not make it more present, so {1,2,2,3}={1,2,3}\{1,2,2,3\}=\{1,2,3\}.

Three kinds of set carry almost everything in this book:

  • Finite collections, such as the rows of a dataset, the digits {0,1,…,9}\{0,1,\dots,9\} or the set of labels a classifier can output. You can list them and count them.
  • Intervals of numbers, such as all the temperatures from 00 to 100100. You cannot list them, but you can say exactly where they start and stop, and whether the end itself belongs.
  • Sets of pairs, such as every pair (input, output) of a function, or every pair of items that are “similar”. These are called relations.

The same few ideas apply to all three. Combine two sets by asking for what is in either, in both, in the first but not the second, or in neither. Then ask which of those are the same set, and how many elements each has.

Intervals add one genuinely new difficulty: the end. The interval of numbers strictly between 00 and 11 and the interval of numbers from 00 to 11 including both ends are different sets, and the difference is a single point on each side. That single point decides whether two intervals that touch at 11 form one piece or two. Most mistakes with intervals are mistakes about the ends.

Definition

Sets and membership. We write x∈Ax\in A when xx is an element of AA and x∉Ax\notin A when it is not. A set is determined by its elements: A=BA=B exactly when every element of AA is in BB and every element of BB is in AA. The empty set ∅\varnothing has no elements. The number of elements of a finite set is its size, written ∣A∣\lvert A\rvert.

Subset. A⊆BA\subseteq B means every element of AA is in BB. It is a proper subset, A⊊BA\subsetneq B, if in addition BB has an element that AA lacks. The empty set is a subset of every set, because the sentence every element of ∅\varnothing is in BB has nothing to check, so it cannot fail. Every set is a subset of itself.

The universe. To talk about “everything that is not in AA” you must say everything in what. Fix a universe UU that contains all the elements you care about. Throughout the stages here, finite sets live in U={1,2,…,12}U=\{1,2,\dots,12\} and interval sets live in the real line R\mathbb{R}. A complement means nothing until the universe is named.

The operations. For two sets AA and BB inside a universe UU:

A∪B={ x:x∈A or x∈B }(union: at least one)A∩B={ x:x∈A and x∈B }(intersection: both)A∖B={ x:x∈A and x∉B }(difference: in A only)U∖A={ x∈U:x∉A }(complement of A in U)A△B=(A∖B)∪(B∖A)(symmetric difference: exactly one)\begin{aligned} A\cup B&=\{\,x : x\in A\ \text{or}\ x\in B\,\} &&\text{(union: at least one)}\\ A\cap B&=\{\,x : x\in A\ \text{and}\ x\in B\,\} &&\text{(intersection: both)}\\ A\setminus B&=\{\,x : x\in A\ \text{and}\ x\notin B\,\} &&\text{(difference: in }A\text{ only)}\\ U\setminus A&=\{\,x\in U : x\notin A\,\} &&\text{(complement of }A\text{ in }U\text{)}\\ A\mathbin{\triangle}B&=(A\setminus B)\cup(B\setminus A) &&\text{(symmetric difference: exactly one)} \end{aligned}

Here or is the inclusive or of mathematics: an element in both sets is in the union. Two sets are disjoint when A∩B=∅A\cap B=\varnothing.

Counting. Adding ∣A∣+∣B∣\lvert A\rvert+\lvert B\rvert counts every element of the overlap twice, once for each set. Subtract one copy of the overlap and the count is right. This is inclusion and exclusion:

∣A∪B∣=∣A∣+∣B∣−∣A∩B∣.\lvert A\cup B\rvert=\lvert A\rvert+\lvert B\rvert-\lvert A\cap B\rvert .

De Morgan’s laws. Complementing swaps or with and:

U∖(A∪B)=(U∖A)∩(U∖B),U∖(A∩B)=(U∖A)∪(U∖B).U\setminus(A\cup B)=(U\setminus A)\cap(U\setminus B),\qquad U\setminus(A\cap B)=(U\setminus A)\cup(U\setminus B).

In words: being outside the union means being outside AA and outside BB; being outside the intersection means being outside AA or outside BB. The stage at the top evaluates both sides for the sets you build, so you can watch them agree.

Intervals. For real numbers a≤ba\le b there are four intervals with ends aa and bb:

[a,b]={x:a≤x≤b},(a,b)={x:a<x<b},[a,b)={x:a≤x<b},(a,b]={x:a<x≤b}.[a,b]=\{x : a\le x\le b\},\quad (a,b)=\{x : a<x<b\},\quad [a,b)=\{x : a\le x<b\},\quad (a,b]=\{x : a<x\le b\}.

A square bracket means the end is included (closed); a round bracket means it is excluded (open). On a number line a closed end is drawn as a filled dot and an open end as a hollow ring. An interval can also run forever in one direction, as in [0,∞)[0,\infty) or (−∞,2)(-\infty,2); an infinite end is never included, because there is no number ∞\infty to include. If the left end is larger than the right end the set has no elements: it is the empty set. A single point is the closed interval [a,a]={a}[a,a]=\{a\}, while (a,a](a,a] and [a,a)[a,a) are empty.

Ordered pairs and products. An ordered pair (a,b)(a,b) remembers which element came first: (1,2)(1,2) and (2,1)(2,1) are different, and (1,1)(1,1) is allowed. The Cartesian product A×BA\times B is the set of all ordered pairs with first element from AA and second from BB. Its size is the product of the sizes, ∣A×B∣=∣A∣ ∣B∣\lvert A\times B\rvert=\lvert A\rvert\,\lvert B\rvert, because the two choices are independent.

Relations. A relation from AA to BB is any subset R⊆A×BR\subseteq A\times B. We write a R ba\,R\,b for (a,b)∈R(a,b)\in R. “Less than” on numbers is the relation {(a,b):a<b}\{(a,b):a<b\}; “divides” is {(a,b):b is a multiple of a}\{(a,b): b \text{ is a multiple of } a\}. A relation is nothing but its set of pairs.

Mechanics: how each piece behaves

Counting and combining finite sets

The hero stage and the full copy in Explore do the finite case. Two habits make the finite case quick:

  1. Draw the four regions. Two sets split the universe into four disjoint regions: in AA only, in both, in BB only, in neither. Every operation keeps a union of some of these regions: the union keeps the first three, the intersection keeps only both, the difference A∖BA\setminus B keeps only in AA only, and the complement U∖AU\setminus A keeps in BB only and in neither.
  2. Count by regions, not by lists. Inclusion and exclusion counts the union from three numbers. If you also know the size of the universe, the number of elements in neither set is ∣U∣−∣A∪B∣\lvert U\rvert-\lvert A\cup B\rvert.

Intervals: is the end in or out?

An interval is determined by four things: two ends and whether each is included. Choose them in the stage below, move the test point xx, and read whether xx belongs to each set. The result of an operation is always written in its simplest form: pieces that overlap or touch with the shared point included are merged into one, and an empty piece is dropped.

Intervals: is the end in or out?

Try these

Show

A number line from −6 to 6 with three rows. A is (0, 1). B is (1, 2). union is (0, 1) ∪ (1, 2). A filled dot marks an included end, a hollow dot an excluded end, and an arrow an end that never stops. The test point is 1.

interval A, typed as (0, 1)
(0, 1)
interval B, typed as (1, 2)
(1, 2)
union
(0, 1) ∪ (1, 2)
separate pieces in the result
2

= exact (every end is an exact decimal, never a rounded double)

A and B meet at 1, but that point belongs to neither (it is an open end of both), so it is missing: A ∪ B = (0, 1) ∪ (1, 2) has 2 pieces, with a one-point hole.

  • 1 ∉ A: it is the right end of (0, 1), and that end is open, so it is excluded.
  • 1 ∉ B: it is the left end of (1, 2), and that end is open, so it is excluded.
  • 1 ∉ A ∪ B: it is the right end of (0, 1), and that end is open, so it is excluded. The neighbouring piece (1, 2) is also open at 1, so 1 is a hole between them.
A=(0, 1),B=(1, 2)A=(0,\,1),\qquad B=(1,\,2)
(0, 1)∪(1, 2)=(0, 1)∪(1, 2)(0,\,1)\cup (1,\,2)=(0,\,1)\cup (1,\,2)
Interval A
Left end of A

from −5 to 5, up to 2 decimal places

Right end of A

from −5 to 5, up to 2 decimal places

Interval B
Left end of B

from −5 to 5, up to 2 decimal places

Right end of B

from −5 to 5, up to 2 decimal places

from −5 to 5, up to 2 decimal places

Choose the ends of two intervals and whether each end is included. The hollow ring is an excluded end, the filled dot an included one, and an arrow means the interval runs on without end. Move the test point x with the slider (it moves by 0.05) and read, for each set, whether x is in it and why.

The presets are the cases that cause trouble. Read them in turn:

  • (0,1)∪(1,2)(0,1)\cup(1,2): the point 11 is in neither interval, so the union is two pieces with a one-point hole. The number line shows the hole.
  • [0,1]∪(1,2)[0,1]\cup(1,2): now 11 belongs to the first interval. The pieces meet at an included point, and the union is the single interval [0,2)[0,2).
  • [0,1]∩[1,2][0,1]\cap[1,2]: the intervals share exactly the point 11. The intersection is the one-element set {1}\{1\}, not the empty set.
  • [0,1)∩[1,2][0,1)\cap[1,2]: the first interval stops just short of 11 and the second starts at 11. Nothing is shared, and the intersection is empty.
  • R∖{1}\mathbb{R}\setminus\{1\}: removing a single point from the line leaves two rays, (−∞,1)∪(1,∞)(-\infty,1)\cup(1,\infty).
  • [0,5]∖(2,3)[0,5]\setminus(2,3) shows that a difference can split an interval in two: [0,2]∪[3,5][0,2]\cup[3,5], with the open piece (2,3)(2,3) cut out of the middle and both of its ends kept.

The general rule is short. Two intervals [ ⋅ ,p][\,\cdot\,,p] and [q, ⋅ ][q,\,\cdot\,] with the same touching value p=qp=q make one piece if the shared point is included in at least one of them, and two pieces if it is excluded from both. The table of four cases is:

left interval endsright interval startsunion
open, p)p)open, (p(ptwo pieces, hole at pp
closed, p]p]open, (p(pone piece
open, p)p)closed, [p[pone piece
closed, p]p]closed, [p[pone piece (they share pp)

The complement of an interval turns every included end into an excluded one and the other way round: R∖(−1,3]=(−∞,−1]∪(3,∞)\mathbb{R}\setminus(-1,3]=(-\infty,-1]\cup(3,\infty). The complement of the whole line is the empty set and the complement of the empty set is the whole line.

Ordered pairs and products

Choose the elements of AA and BB below. The two tables list the pairs of A×BA\times B and of B×AB\times A. A pair shown with a dashed outline is in one table and not in the other.

Ordered pairs: A × B and B × A

Or start from

Elements of A
Elements of B
A × B: first coordinate from A
34
1(1,3) (only in this product)(1,4) (only in this product)
2(2,3) (only in this product)(2,4) (only in this product)
3(3,3)(3,4) (only in this product)
B × A: first coordinate from B
123
3(3,1) (only in this product)(3,2) (only in this product)(3,3)
4(4,1) (only in this product)(4,2) (only in this product)(4,3) (only in this product)

A is {1, 2, 3} and B is {3, 4}. A times B has 6 ordered pairs; B times A has 6 ordered pairs.

|A × B| = 6 = |A| · |B| = 3 · 2. A × B and B × A are different sets: (1, 3) is in A × B, but it is not in B × A, because that would need 1 to be in B and 3 to be in A. Order matters in a pair.

elements in A
3
elements in B
2
ordered pairs in A × B
6

= exact

∣A×B∣=6and∣A∣⋅∣B∣=3⋅2=6\lvert A\times B\rvert=6\quad\text{and}\quad \lvert A\rvert\cdot\lvert B\rvert=3\cdot 2=6
A={1,2,3},B={3,4}A=\{1,2,3\},\qquad B=\{3,4\}

Press the numbers to put them in A or in B. Each table lists the ordered pairs: the first coordinate labels the rows and the second labels the columns. A dashed outline marks a pair that is in one product and not in the other.

Try the presets. For A={1,2,3}A=\{1,2,3\} and B={3,4}B=\{3,4\} there are 3⋅2=63\cdot2=6 pairs. The pair (1,3)(1,3) is in A×BA\times B but its reverse (3,1)(3,1) is not in the same table, so A×B≠B×AA\times B\ne B\times A. They are equal exactly when A=BA=B or when one of the sets is empty (both products are then empty). When A=BA=B the table is symmetric.

Relations and their four properties

A relation on a set SS is a subset of S×SS\times S. Four properties tell relations apart. For all elements aa, bb, cc of SS:

  • reflexive: a R aa\,R\,a for every aa (every element is related to itself);
  • symmetric: a R ba\,R\,b implies b R ab\,R\,a;
  • antisymmetric: if a R ba\,R\,b and b R ab\,R\,a, then a=ba=b;
  • transitive: if a R ba\,R\,b and b R cb\,R\,c, then a R ca\,R\,c.

A property fails because of a witness: a specific pair or triple that breaks it. A property that holds has no witness. The stage finds and outlines the witness for you. The words symmetric and antisymmetric are not opposites: the equality relation is both, “less than” is antisymmetric and not symmetric, and a relation can be neither.

A relation that is reflexive, symmetric and transitive is an equivalence relation. It does what equality does: it splits the set into classes, groups of elements that are all related to one another and to nothing outside the group. “Same parity” on whole numbers is one: the classes are the odd numbers and the even numbers. A relation that is reflexive, antisymmetric and transitive is a partial order; “at most” and “divides” are examples.

A relation R⊆A×BR\subseteq A\times B is a function from AA to BB when every element of AA is related to exactly one element of BB. A relation fails to be a function in two ways: some aa has no partner (nothing is assigned) or some aa has more than one (the value is ambiguous). Many different aa may share the same bb; that does not stop it being a function.

Relations: a set of pairs

Fill the grid with the rule

Rows: elements a of A. Columns: elements b of B. A filled cell means a is related to b.
1234
1
2
3
4

A grid with the 4 elements of A as rows and the 4 elements of B as columns. {(1, 2), (1, 3), (2, 3), (1, 4), (2, 4), (3, 4)} are related, 6 of 16 pairs.

all ordered pairs
16
pairs in the relation
6
the relation as a set of pairs
{(1, 2), (1, 3), (2, 3), (1, 4), (2, 4), (3, 4)}

= exact

R has 6 pairs out of 16. It is not an equivalence relation: it is not reflexive and not symmetric.

What kind of relation is it?

  • a R a for every a. Fails: 1 is not related to itself, (1, 1) is missing.
  • a R b implies b R a. Fails: (1, 2) is in R but (2, 1) is not.
  • a R b and b R a imply a = b. Holds: no two different elements are related both ways.
  • a R b and b R c imply a R c. Holds: whenever a is related to b and b to c, a is related to c.
  • EquivalenceIt is not an equivalence relation: it is not reflexive and not symmetric.
  • FunctionNo: 1 is related to 3 elements of B (2, 3, 4), so R does not assign it a single value.
Elements in A
Elements in B

Press a cell to add or remove a pair: rows are elements of A and columns are elements of B. Or fill the grid with a rule. Press the name of a property to outline the pairs that prove or break it. Change the sizes of A and B to see which properties apply: reflexive, symmetric, antisymmetric and transitive are about a relation on ONE set, so they need the two sets to have the same size.

Work through these in the stage:

  • less than, the relation a<ba<b: not reflexive (the pair (1,1)(1,1) is missing), not symmetric, but antisymmetric and transitive. The antisymmetry holds vacuously: no pair (a,b)(a,b) and (b,a)(b,a) are both present, so the condition never applies.
  • a divides b on {1,2,3,4}\{1,2,3,4\}: look at the four properties yourself, and find the pair that decides symmetry. Then press the property name to outline it.
  • same parity: reflexive, symmetric, transitive, so an equivalence relation with two classes.
  • nothing (no pairs): symmetric, antisymmetric and transitive, all by emptiness, but not reflexive.

Worked examples

Four computations, each shown step by step with every set and every count taken from the same model as the stages. Step forward and back with the buttons; going back selects an earlier step, and nothing is undone.

Worked examples, step by step

Choose an example

A=(0, 1),B=(1, 2)A=(0,\,1),\qquad B=(1,\,2)

Two open intervals. Open means the end is NOT included: A has every number strictly between 0 and 1, B every number strictly between 1 and 2.

Choose an example and step through the work. The first is a union with a hole, the second a count by inclusion and exclusion, the third a check of De Morgan's law, and the last a check that same parity is an equivalence relation.

Executable reference code

Run the Python examples below to follow the calculations step by step. The comments record what each line returns.

First the finite case, using Python’s built-in set: union |, intersection &, difference -, symmetric difference ^, the subset tests, De Morgan against an explicit universe, and ordered pairs from itertools.product. Notice that Python has no built-in complement: you must subtract from a universe you name.

code/python/sets_finite.pysets, De Morgan, products and relations
from itertools import product

# A universe is a choice, not a given: a complement means nothing until you say "relative to U".
U = set(range(1, 13))  # {1, 2, ..., 12}
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7}

union = A | B  # {1, 2, 3, 4, 5, 6, 7}
intersection = A & B  # {4, 5}
a_minus_b = A - B  # {1, 2, 3}
symmetric = A ^ B  # {1, 2, 3, 6, 7}: in exactly one of the two
complement_a = U - A  # {6, ..., 12}: always U minus the set

# Inclusion-exclusion: counting A and B separately counts A ∩ B twice.
inclusion_exclusion = len(union) == len(A) + len(B) - len(intersection)  # True

# De Morgan: complementing swaps union and intersection.
de_morgan_union = (U - (A | B)) == (U - A) & (U - B)  # True
de_morgan_intersection = (U - (A & B)) == (U - A) | (U - B)  # True

# Subset tests: A <= B means every element of A is in B; < means proper subset.
a_in_b = A <= B  # False (1 is not in B)
small_in_a = {2, 3} <= A  # True
empty_is_subset = set() <= A  # True: the empty set is a subset of every set

# Ordered pairs: (1, 2) and (2, 1) are different elements of a product.
X = {1, 2, 3}
Y = {3, 4}
pairs = set(product(X, Y))  # 3 * 2 = 6 ordered pairs
pairs_swapped = set(product(Y, X))
product_size_ok = len(pairs) == len(X) * len(Y)  # True
commutes = pairs == pairs_swapped  # False: X x Y is not Y x X unless X = Y or one is empty

# A relation on S is just a subset of S x S. Its properties are statements about that subset.
S = {1, 2, 3, 4}
less_than = {(a, b) for a, b in product(S, S) if a < b}
reflexive = all((a, a) in less_than for a in S)  # False: 1 < 1 is false
transitive = all((a, c) in less_than for (a, b) in less_than for (b2, c) in less_than if b == b2)  # True
same_parity = {(a, b) for a, b in product(S, S) if (a - b) % 2 == 0}
symmetric_parity = all((b, a) in same_parity for (a, b) in same_parity)  # True
classes = {frozenset(b for b in S if (a, b) in same_parity) for a in S}  # {frozenset({1, 3}), frozenset({2, 4})}

print(union, intersection, a_minus_b, symmetric, complement_a, inclusion_exclusion, de_morgan_union, de_morgan_intersection)
print(a_in_b, small_in_a, empty_is_subset, product_size_ok, commutes, reflexive, transitive, symmetric_parity, classes)

Then intervals. Python has no interval type, so the file builds one from Fraction, which represents numbers like 0.1 exactly. It shows why a closed end must be tested on the exact number, when two intervals join, and the three empty cases from the Definition section.

code/python/sets_intervals.pyopen and closed ends with exact numbers
from dataclasses import dataclass
from fractions import Fraction

# Closed endpoints are tests like x >= a. With doubles, 0.1 + 0.2 is not 0.3, so a closed test can fail by one rounding error.
double_sum = 0.1 + 0.2  # 0.30000000000000004
float_test = 0.3 <= double_sum <= 0.3  # False: the point 0.3 "missed" its own closed interval

# Fraction('0.1') reads the TEXT and gives exactly 1/10. Fraction(0.1) would read the double, which is not 1/10.
tenth, fifth = Fraction("0.1"), Fraction("0.2")
exact_test = Fraction("0.3") <= tenth + fifth <= Fraction("0.3")  # True


@dataclass(frozen=True)
class Interval:
    """The set of x with lo <= x <= hi, each end open or closed. An infinite end is None and is always open."""

    lo: Fraction | None
    hi: Fraction | None
    lo_closed: bool = True
    hi_closed: bool = True

    def contains(self, x: Fraction) -> bool:
        above = self.lo is None or (x >= self.lo if self.lo_closed else x > self.lo)
        below = self.hi is None or (x <= self.hi if self.hi_closed else x < self.hi)
        return above and below

    def is_empty(self) -> bool:
        if self.lo is None or self.hi is None:
            return False
        return self.lo > self.hi or (self.lo == self.hi and not (self.lo_closed and self.hi_closed))


def touch_and_merge(left: Interval, right: Interval) -> bool:
    """Do two intervals with left.hi == right.lo form ONE interval? Only if the shared point belongs to at least one."""
    return left.hi == right.lo and (left.hi_closed or right.lo_closed)


a = Interval(Fraction(0), Fraction(1), True, False)  # [0, 1)
b = Interval(Fraction(1), Fraction(2), False, True)  # (1, 2]
c = Interval(Fraction(1), Fraction(2), True, True)  # [1, 2]

joined_ab = touch_and_merge(a, b)  # False: 1 belongs to neither, so [0,1) ∪ (1,2] is two pieces
joined_ac = touch_and_merge(a, c)  # True:  [0,1) ∪ [1,2] = [0,2]
one_in_union = a.contains(Fraction(1)) or b.contains(Fraction(1))  # False
reversed_is_empty = Interval(Fraction(3), Fraction(1)).is_empty()  # True: left end greater than right end
point_is_not_empty = Interval(Fraction(1), Fraction(1)).is_empty()  # False: [1, 1] = {1}
open_point_is_empty = Interval(Fraction(1), Fraction(1), False, True).is_empty()  # True: (1, 1] has nothing in it

print(double_sum, float_test, exact_test, joined_ab, joined_ac, one_in_union, reversed_is_empty, point_is_not_empty, open_point_is_empty)

Finally the form the same ideas take on data: a split of row numbers into training, validation and test sets that must be disjoint, a Boolean mask as the indicator of a set, clipping to a closed interval, and a grid of combinations.

code/python/sets_numpy_masks.pydisjoint splits, masks, clipping and products with NumPy
import numpy as np

# Rows of a dataset are indexed 0..9. A split into train / validation / test is three SETS of indices that must be disjoint.
rows = np.arange(10)
rng = np.random.default_rng(0)
order = rng.permutation(rows)  # a shuffle of the indices
train, val, test = order[:6], order[6:8], order[8:]

disjoint = (
    np.intersect1d(train, val).size == 0
    and np.intersect1d(train, test).size == 0
    and np.intersect1d(val, test).size == 0
)  # True: no row appears in two splits (an overlap is "leakage")
covers = np.array_equal(np.union1d(np.union1d(train, val), test), rows)  # True: together they are the whole universe

# Membership as a Boolean mask: np.isin(x, S) is the indicator 1[x in S], one entry per row.
mask_train = np.isin(rows, train)  # array of True/False
indicator = mask_train.astype(int)  # 0/1 values: 1 where the row is in the training set
count_matches = int(indicator.sum()) == train.size  # True: summing the indicator counts the members

# Complement relative to the universe is the mask negation.
not_train = ~mask_train
complement_ok = np.array_equal(rows[not_train], np.union1d(val, test))  # True

# Clipping to a CLOSED interval [lo, hi]: values outside are moved onto the nearest endpoint, so the result is always in [lo, hi].
x = np.array([-3.0, 0.0, 0.5, 1.0, 4.0])
clipped = np.clip(x, 0.0, 1.0)  # [0.  0.  0.5 1.  1. ]
inside = bool(np.all((clipped >= 0.0) & (clipped <= 1.0)))  # True

# Cartesian product of two small feature value sets: every combination, as a grid of pairs.
first, second = np.meshgrid([0, 1, 2], [10, 20], indexing="ij")
grid = np.stack([first.ravel(), second.ravel()], axis=1)  # 3 * 2 = 6 rows (a, b), a from the first set, b from the second
grid_size_ok = grid.shape == (3 * 2, 2)  # True

print(disjoint, covers, count_matches, complement_ok, clipped, inside, grid_size_ok)

Explore: change the sets

This is the finite stage with everything visible: the lists, the true-or-false facts about the pair, and the identities with your numbers in them. These questions have definite answers; check them against the stage.

Build two sets and combine them

Or start from

Show

A Venn diagram inside the universe U, the numbers 1 to 12, with two overlapping circles A and B. Only in A: 1, 2, 3. In both: 4, 5. Only in B: 6, 7. In neither: 8, 9, 10, 11, 12. Highlighted: union, {1, 2, 3, 4, 5, 6, 7}. The picture is schematic: the areas are not to scale.

Schematic: the areas are not to scale. The box is the universe U = {1, 2, …, 12}.

elements in A
5
elements in B
4
union
{1, 2, 3, 4, 5, 6, 7}
elements in the result
7

= exact (every statement about finite sets is exact)

A ∪ B = {1, 2, 3, 4, 5, 6, 7}: everything that is in A, in B, or in both. It has 7 elements.

Elements of A
Elements of B
  • A ⊆ B is false: 1 is in A but not in B.
  • B ⊆ A is false: 6 is in B but not in A.
  • A = B is false: neither contains the other.
  • A ∩ B = ∅ is false: 2 elements in common: {4, 5}.
∣A∪B∣=7and∣A∣+∣B∣−∣A∩B∣=5+4−2=7\lvert A\cup B\rvert=7\quad\text{and}\quad \lvert A\rvert+\lvert B\rvert-\lvert A\cap B\rvert=5+4-2=7
U∖(A∪B)={8,9,10,11,12}and(U∖A)∩(U∖B)={8,9,10,11,12}U\setminus(A\cup B)=\{8,9,10,11,12\}\quad\text{and}\quad (U\setminus A)\cap(U\setminus B)=\{8,9,10,11,12\}
U∖(A∩B)={1,2,3,6,7,8,9,10,11,12}and(U∖A)∪(U∖B)={1,2,3,6,7,8,9,10,11,12}U\setminus(A\cap B)=\{1,2,3,6,7,8,9,10,11,12\}\quad\text{and}\quad (U\setminus A)\cup(U\setminus B)=\{1,2,3,6,7,8,9,10,11,12\}

The full finite stage. Press numbers to build A and B, choose an operation, and read the facts about the pair: whether one set is inside the other, whether they are equal or disjoint, and whether inclusion and exclusion and De Morgan's laws hold.
  • Make AA the odd numbers from 11 to 1111 and BB the even numbers from 22 to 1212 (the disjoint preset). What is ∣A∪B∣\lvert A\cup B\rvert, and why does inclusion and exclusion collapse to a plain sum?
  • Make A={2,3}A=\{2,3\} and B={1,2,3,4}B=\{1,2,3,4\} (the A inside B preset). What is A∩BA\cap B? What is A∪BA\cup B? What is A∖BA\setminus B, and what is B∖AB\setminus A?
  • Press A empty. Which operation gives the whole universe? Is AA a subset of BB, and is it a proper subset?
  • Choose A={1,2,3,4}A=\{1,2,3,4\} and B={3,4,5,6}B=\{3,4,5,6\} and the operation U∖AU\setminus A. Count the elements. Then find, using the facts list, the two sides of De Morgan’s first law and check them against each other.
  • Build two sets of your own where A⊆BA\subseteq B and B⊆AB\subseteq A are both true. What must be true of AA and BB?

Common mistakes

Numerical considerations

Sets and intervals are exact: an element is in or it is not. Numbers on a computer are not. The decimal 0.10.1 cannot be stored exactly in a double, and a closed end that is a decimal fraction can then miss itself.

Every interval value in this chapter is an exact decimal with at most two places, so the stage can say that an end is in or out with no doubt, and it writes ==. The same stage would be wrong to use for a computed double. A second place where a set meets a number: the empty set from reversed ends is not an error. The interval from 33 to 11 is empty because no xx satisfies 3≤x≤13\le x\le 1; code that sorts the ends silently, or clips them, answers a different question than the one that was asked. The stage reports that case with its reason instead of repairing it.

Finally, a finite set of floating-point numbers can contain two values that look the same when rounded for display and still compare different. Set membership uses exact equality, so 0.1 + 0.2 and 0.3 are two different elements of a Python set. When elements are measurements, round them to a stated precision first, or compare with a tolerance and use a structure that expects it.

Connections to engineering and machine learning

  • Train, validation and test splits are disjoint sets. A split of the row numbers UU into three sets must satisfy train∩val=∅\text{train}\cap\text{val}=\varnothing, and the same for each other pair, and their union must be UU. If a row is in both train and test, the reported test score is optimistic: this is leakage. Counting the distinct rows is inclusion and exclusion: if 600600, 200200 and 200200 ids are listed and exactly 5050 of them appear in both train and test, only 950950 different rows were used.
  • An indicator is a set written as a column. The indicator of AA is the function that is 11 on AA and 00 elsewhere. In NumPy, np.isin(rows, A) gives the Boolean mask, and summing the mask counts ∣A∣\lvert A\rvert. The complement is the mask’s negation, the intersection is & and the union is |, which is why set algebra and mask algebra are the same algebra.
  • Clipping is intersection with a closed interval. np.clip(x, lo, hi) moves every value outside [lo,hi][lo,hi] onto the nearest end, so the result lies in the closed interval. The ends are included, and the choice of a closed interval matters: a clipped value of exactly lolo is a legal output.
  • Feature spaces are products. A model that takes a colour from {red,green,blue}\{\text{red},\text{green},\text{blue}\} and a size from {S,M,L}\{S,M,L\} has 3⋅3=93\cdot3=9 combinations: the Cartesian product. A grid search over two hyperparameters is a product of two sets, and the cost is the product of the sizes, which is why adding one more parameter can multiply a run time rather than add to it.
  • Equivalence relations are clustering. Grouping items into classes where being in the same class is reflexive, symmetric and transitive is a partition of the data. Duplicate detection is the same idea; if “is a near-duplicate of” is only close and not transitive, chaining gives classes you did not intend.
  • A function is a relation with one output per input. A deterministic model is a function from inputs to outputs; a lookup table with two different outputs for the same key is a relation that is not a function, and the code that reads it must say which to use.

Exercises

Answer each question and press Check. A wrong answer tells you which mistake it looks like. After one attempt you may open a worked solution.

calculation

Counting a union

A class has 20 students in the chess club (set A) and 15 in the debate club (set B). Exactly 6 students are in both clubs. How many students are in at least one of the two clubs?

explanation

Which union is one interval?

Which of these unions is exactly the single interval [0, 2], with no number missing?

Choose one answer

explanation

The complement of a half-open interval

Take the interval [2, 5) of real numbers: 2 is included and 5 is excluded. What is its complement in the real line ℝ?

Choose one answer

calculation

Counting ordered pairs

A has 4 elements and B has 3 elements. How many ordered pairs are in A × B? Then, if C has 5 elements, how many ordered pairs are in C × C?

explanation

When is A × B the same as B × A?

A and B are sets of numbers. When is A × B = B × A?

Choose one answer

explanation

Divisibility as a relation

On the set {1, 2, 3, 4, 5, 6}, say that a is related to b when a divides b (b is a multiple of a). Which description is correct?

Choose one answer

explanation

Being close is not an equivalence

On {1, 2, 3, 4, 5}, say that a is related to b when |a − b| ≤ 1 (they differ by at most 1). Which statement is true?

Choose one answer

calculation

How many pairs?

Write down the relation "a < b" on the set {1, 2, 3, 4, 5, 6}: all ordered pairs (a, b) with a less than b. How many pairs are in it?

calculation

Outside both sets

In the universe U = {1, 2, …, 12}, let A = {1, 2, 3, 4, 5, 6} and B = {5, 6, 7, 8, 9}. How many elements of U are in neither A nor B? (That is the complement of A ∪ B, or by De Morgan the intersection of the two complements.)

prediction

Leakage between data splits

A machine-learning pipeline reports three lists of row ids: 800 in the training set, 100 in validation and 100 in test (1,000 ids in all). A check finds that exactly 30 ids appear in BOTH the training list and the test list, and no other overlaps. How many different rows were actually used?

Summary and checkpoints

  • A set is determined by its elements: order and repeats do not matter. The union keeps what is in at least one set, the intersection what is in both, the difference what is in the first only, and a complement needs a named universe.
  • Counting a union: ∣A∪B∣=∣A∣+∣B∣−∣A∩B∣\lvert A\cup B\rvert=\lvert A\rvert+\lvert B\rvert-\lvert A\cap B\rvert. De Morgan: the complement of a union is the intersection of the complements, and the complement of an intersection is the union of the complements.
  • An interval end is in (closed, filled dot) or out (open, hollow ring). Two touching intervals join into one piece exactly when the shared point is in at least one; [a,a][a,a] is one point, and reversed ends or (a,a)(a,a) give the empty set. The complement of an interval flips every end.
  • Ordered pairs keep their order. ∣A×B∣=∣A∣ ∣B∣\lvert A\times B\rvert=\lvert A\rvert\,\lvert B\rvert, and A×B=B×AA\times B=B\times A only if A=BA=B or one set is empty.
  • A relation is a set of pairs. Reflexive, symmetric, antisymmetric and transitive are four separate properties, each with a witness when it fails. Reflexive, symmetric and transitive together make an equivalence relation, which splits a set into classes; a function is a relation with exactly one partner for each input.
  • On a computer, exact membership needs exact numbers: 0.1 + 0.2 is not 0.3.

Checkpoints. You can move on when you can, without the stage:

  1. Say what A∪BA\cup B, A∩BA\cap B, A∖BA\setminus B and U∖AU\setminus A each keep, and count a union from three sizes.
  2. Decide whether [0,1)∪[1,2][0,1)\cup[1,2] is one interval, and whether [0,1)∩[1,2][0,1)\cap[1,2] is empty.
  3. Write the complement of [0,4)[0,4) and of {1}\{1\} in R\mathbb{R}.
  4. List A×BA\times B for two small sets and say why B×AB\times A is different.
  5. Give a relation that is symmetric but not transitive, and one that is an equivalence relation, with its classes.

The map of the book

97 of 97 chapters written · eight Parts

demo Foundation demo Try the live vector example Open as a page

Part I

Mathematical Language

The notation and mental objects everything else uses.

9 of 9 chapters written

  1. I.1 Scalars, quantities, units, powers and roots available
  2. I.2 Coordinates and points available
  3. I.3 Vectors: components, magnitude, and direction reference chapter available
  4. I.4 Algebraic expressions, equations and inequalities available
  5. I.5 Functions as input → transformation → output available
  6. I.6 Essential function families available
  7. I.7 Sets, intervals, and relations available
  8. I.8 Indexed quantities and summation available
  9. I.9 The notation map for ML available

Part II

Linear Algebra

Matrices as transformations: the strongest foundation in the book.

19 of 19 chapters written

  1. II.1 Vector addition and subtraction available
  2. II.2 Scalar multiplication and vector scaling available
  3. II.3 Norms, magnitude, and normalization available
  4. II.4 Dot product, angle, and orthogonality available
  5. II.5 Projection and distance to a direction available
  6. II.6 Linear combinations and span available
  7. II.7 Linear independence, basis, and coordinates available
  8. II.8 Matrices as linear transformations available
  9. II.9 Matrix × vector available
  10. II.10 Matrix × matrix as composition available
  11. II.11 Transpose and orthogonality available
  12. II.12 Determinant: orientation and area/volume scaling available
  13. II.13 Linear systems as intersecting constraints available
  14. II.14 Gaussian elimination and row operations available
  15. II.15 Rank and invertibility available
  16. II.16 Inverse matrices available
  17. II.17 Eigenvalues and eigenvectors available
  18. II.18 Orthogonal bases and least-squares geometry available
  19. II.19 Singular Value Decomposition available

Part III

Calculus

Change, local approximation, and sensitivity made visible.

15 of 15 chapters written

  1. III.1 Limits through approach available
  2. III.2 Continuity and local behavior available
  3. III.3 Derivative as secant → tangent available
  4. III.4 Derivative as rate of change and local linear model available
  5. III.5 Derivative rules available
  6. III.6 Chain rule available
  7. III.7 Multivariable functions and partial derivatives available
  8. III.8 Gradient and directional derivatives available
  9. III.9 Jacobian available
  10. III.10 Computational graphs and automatic differentiation available
  11. III.11 Hessian and curvature available
  12. III.12 Integrals as accumulation available
  13. III.13 Fundamental derivative/integral connection available
  14. III.14 Numerical differentiation available
  15. III.15 Numerical integration available

Part IV

Probability

Uncertainty through sample spaces, evidence, and repetition.

16 of 16 chapters written

  1. IV.1 Random experiments, outcomes, and sample spaces available
  2. IV.2 Events and probability mass available
  3. IV.3 Counting and finite probability where needed available
  4. IV.4 Conditional probability as restricted sample space available
  5. IV.5 Independence available
  6. IV.6 Bayes' theorem as probability-mass update available
  7. IV.7 Random variables available
  8. IV.8 PMF, PDF, and CDF available
  9. IV.9 Bernoulli and Binomial distributions available
  10. IV.10 Uniform and Gaussian distributions available
  11. IV.11 Expectation available
  12. IV.12 Variance and standard deviation available
  13. IV.13 Joint, marginal, and conditional distributions available
  14. IV.14 Covariance and correlation available
  15. IV.15 Law of Large Numbers available
  16. IV.16 Central Limit Theorem available

Part V

Statistics

From observed data to estimates, intervals, and likelihood.

10 of 10 chapters written

  1. V.1 Data summaries: mean, median, mode available
  2. V.2 Spread: variance, standard deviation, robust interpretation available
  3. V.3 Population, sample, and sampling variability available
  4. V.4 Estimators and estimation available
  5. V.5 Confidence intervals through repeated sampling available
  6. V.6 Covariance matrices and multivariate spread available
  7. V.7 Regression fundamentals available
  8. V.8 Likelihood available
  9. V.9 Maximum Likelihood Estimation available
  10. V.10 Maximum A Posteriori estimation available

Part VI

Optimization

Learning as repeated parameter updates governed by an objective.

10 of 10 chapters written

  1. VI.1 Objective functions and optimization landscapes available
  2. VI.2 Local vs global optima and stationary points available
  3. VI.3 Convexity available
  4. VI.4 Gradient descent flagship chapter available
  5. VI.5 Learning rate and convergence behavior available
  6. VI.6 Momentum available
  7. VI.7 Stochastic and mini-batch gradient descent available
  8. VI.8 Adam intuition available
  9. VI.9 Constraints and projected/penalized intuition available
  10. VI.10 Numerical stopping and optimization diagnostics available

Part VII

Information Theory

Logarithms, entropy, and the loss behind token prediction.

8 of 8 chapters written

  1. VII.1 Logarithms and log probabilities in computation available
  2. VII.2 Self-information available
  3. VII.3 Entropy available
  4. VII.4 Cross entropy and negative log-likelihood available
  5. VII.5 KL divergence available
  6. VII.6 Logits and softmax available
  7. VII.7 Numerical stability: log-sum-exp and stable softmax available
  8. VII.8 From token logits to language-model loss available

Part VIII

Numerical Computing

Why equivalent expressions behave differently on real machines.

10 of 10 chapters written

  1. VIII.1 Floating-point representation available
  2. VIII.2 Rounding and representation error available
  3. VIII.3 Error propagation and conditioning available
  4. VIII.4 Catastrophic cancellation available
  5. VIII.5 Overflow and underflow available
  6. VIII.6 Stable algorithms available
  7. VIII.7 Numerical linear algebra realities available
  8. VIII.8 Sparse matrices and sparse structure available
  9. VIII.9 Vectorized computation available
  10. VIII.10 Reproducibility, random seeds, and nondeterminism available