GNGiseldo Neo and Alana NeoBooks
Mathematical Foundations for Machine Learning2 / 8

Basic Concepts

1.1 Sets

Sets are a language to organize objects and reason about collections. In Computer Science, they appear when describing users of a system, possible states of a program, alphabet symbols, query results and examples of a data set. Understanding sets helps to transform phrases such as “select valid records” or “find elements present in both lists” in precise mathematical operations.

1.1.1 Elements, membership and representation

A set is a well-defined collection of objects, called elements. We write your elements in braces. For example,

A={2,4,6,8}. A = \{2,4,6,8\}.

The expression 4∈A4 \in A informs that 44 belongs to AA; 5∉A5 \notin A already informs that 55 does not belong to AA. Order and repetition do not change a set.

{1,2,3}={3,2,1}={1,1,2,3}. \{1,2,3\} = \{3,2,1\} = \{1,1,2,3\}.

This property distinguishes sets of structures such as lists and vectors. The [1, 1, 2] list has three positions and preserves the order; the corresponding set has only the {1,2}\{1,2\} elements. Languages like Python reflect this difference: list maintains order and repetitions, while set eliminates duplicates.

Collections of overlapping objects and regions illustrate the idea of shared sets and elements.

Figure 1.1. Collections of overlapping objects and regions illustrate the idea of shared sets and elements.

A set can also be described by a property. Instead of listing all even values, we write

P={x∈Z∣x is even}. P = \{x \in \mathbb{Z} \mid x \text{ is even}\}.

The symbol “∣\mid” means “such that”. This notation is useful when the set is too large or infinite. The empty set, denoted by ∅\varnothing or {}\{\}, has no element at all. Note: ∅\varnothing is different from {∅}\{\varnothing\} because the second set has an element — the empty set itself.

1.1.2 Numerical sets

Some sets appear repeatedly in mathematics applied to Computing:

  • N={0,1,2,3,…}\mathbb{N} = \{0,1,2,3,\ldots\}: natural numbers, used in counts and indexes;
  • Z={…,−2,−1,0,1,2,…}\mathbb{Z} = \{\ldots,-2,-1,0,1,2,\ldots\}: integer numbers;
  • Q\mathbb{Q}: rational numbers, which can be written as p/qp/q, with p,q∈Zp,q \in \mathbb{Z} and q≠0q \neq 0;
  • R\mathbb{R}: real numbers, common in measurements, probabilities and model parameters.

There is an inclusion chain:

N⊆Z⊆Q⊆R. \mathbb{N} \subseteq \mathbb{Z} \subseteq \mathbb{Q} \subseteq \mathbb{R}.

This means, for example, that every natural number is also integer and real. The irrational numbers, such as 2\sqrt{2} and π\pi, belong to R∖Q\mathbb{R} \setminus \mathbb{Q}.

1.1.3 Subsets and equality

We say AA is subset of BB, and we write A⊆BA \subseteq B, when every element of AA also belongs to BB. If A⊆BA \subseteq B and A≠BA \neq B, then AA is a proper subset of BB, indicated by A⊂BA \subset B.

Two sets are the same when they have exactly the same elements. A common way to prove A=BA=B is to demonstrate the two inclusions: A⊆BA \subseteq B and B⊆AB \subseteq A. This strategy, called double inclusion, is analogous to verifying two logical conditions rather than comparing only the appearance of representations.

1.1.4 Operations between sets

Consider A={1,2,3,4}A=\{1,2,3,4\} and B={3,4,5}B=\{3,4,5\}. The main operations are:

  • union: A∪B={1,2,3,4,5}A \cup B = \{1,2,3,4,5\} gathers elements present in AA or in BB;
  • intersection: A∩B={3,4}A \cap B = \{3,4\} maintains elements present in AA and in BB;
  • difference: A∖B={1,2}A \setminus B = \{1,2\} maintains elements of AA that do not belong to BB;
  • symmetric difference: A△B={1,2,5}A \triangle B = \{1,2,5\} maintains elements that belong to only one of the sets.

If A∩B=∅A \cap B=\varnothing, the sets are called disjoint sets . In a universe UU, the complement of AA is Ac=U∖AA^c=U\setminus A: everything that is in the universe considered but not in AA. The universe needs to be declared as the complement changes as the domain of the problem.

These operations correspond directly to computer tasks: remove duplicates, filter data, combine results and locate common items. In databases, UNION, INTERSECT and EXCEPT express equivalent ideas. In Python, for A and B sets, we can use A | B, A & B and A - B.

Visual flow of filtering, combination and separation of data collections.

Figure 1.2. Visual flow of filtering, combination and separation of data collections.

De Morgan’s laws relate operations and complements:

(A∪B)c=Ac∩Bc and (A∩B)c=Ac∪Bc. (A \cup B)^c = A^c \cap B^c \qquad\text{ and }\qquad (A \cap B)^c = A^c \cup B^c.

They appear in the simplification of Boolean conditions. Deny “xx is in AA or BB” is equivalent to stating that “xx is not in AA and is not in BB”.

1.1.5 Cardinality and the power set

The cardinality ∣A∣|A| is the number of elements of a finite set. If A={a,b,c}A=\{a,b,c\}, then ∣A∣=3|A|=3. For finite sets,

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

We subtracted the intersection because its elements were counted twice. This formula is the simplest case of the principle of inclusion-exclusion, used in count and combinatorial analysis.

The set of P(A)\mathcal{P}(A) parts contains all AA subsets. For A={0,1}A=\{0,1\},

P(A)={∅,{0},{1},{0,1}}. \mathcal{P}(A)=\{\varnothing,\{0\},\{1\},\{0,1\}\}.

If ∣A∣=n|A|=n then ∣P(A)∣=2n|\mathcal{P}(A)|=2^n. Each element can be included or not in a subset, exactly as a bit can take over 11 or 00. Therefore, subsets can be represented by bit masks: for A={a,b,c}A=\{a,b,c\}, the 101 mask represents {a,c}\{a,c\}.

1.1.6 Cartesian product

The Cartesian product of AA and BB is the set of all possible ordered pairs:

A×B={(a,b)∣a∈A and b∈B}. A \times B = \{(a,b) \mid a \in A \text{ and } b \in B\}.

If A={1,2}A=\{1,2\} and B={x,y}B=\{x,y\}, then

A×B={(1,x),(1,y),(2,x),(2,y)}. A \times B=\{(1,x),(1,y),(2,x),(2,y)\}.

The order matters: in general, (a,b)≠(b,a)(a,b)\neq(b,a). If AA and BB are finite, ∣A×B∣=∣A∣ ∣B∣|A\times B|=|A|\,|B|. In Computing, Cartesian products model coordinates, combinations of parameters, composite states and lines produced by a CROSS JOIN. When B=AB=A, we use A2A^2; thus, R2\mathbb{R}^2 represents the plane and R3\mathbb{R}^3 represents the three-dimensional space.

Check your understanding

Consider U={1,2,3,4,5,6}U=\{1,2,3,4,5,6\}, A={1,2,3,4}A=\{1,2,3,4\} and B={2,4,6}B=\{2,4,6\}. Calculate A∩BA\cap B, A∪BA\cup B, A∖BA\setminus B and BcB^c in relation to UU. Then represent A∩BA\cap B as a set in Python and test if 3 belongs to the result.

1.2 Functions

Functions are one of the fundamental languages of Mathematics and Computer Science. They appear when a program transforms an input into an output, when a database associates a key to a record, when a classifier assigns a label to an image, or when a neural network converts an attribute vector into probabilities. In all these cases there is the same idea: for each admissible input, there is a well-determined output.

A function seen as a deterministic machine: admissible inputs are processed and each produces a single output.

Figure 1.3. A function seen as a deterministic machine: admissible inputs are processed and each produces a single output.

1.2.1 Definition and notation

Let XX and YY be two sets. A ff function of XX in YY is a rule that associates to each x∈Xx \in X element exactly one y∈Yy \in Y element.

f ⁣:X→Y,x↦f(x). f \colon X \to Y, \qquad x \mapsto f(x).

In that rating:

  • XX is the domain, i.e. the set of allowed inputs;
  • YY is the counterdomain, the set in which we declare the outputs are;
  • xx is a argument or a input;
  • f(x)f(x) is the function value or the output corresponding to xx.

The word “exactly” is essential. A domain input cannot be left out and cannot have two different outputs either. Nothing prevents, however, that two distinct inputs produce the same output. For example, for f(x)=x2f(x)=x^2, we have f(2)=f(−2)=4f(2)=f(-2)=4.

In programming, the signature of a function expresses an idea similar to mathematical notation.

square : Real -> Real

corresponds to q ⁣:R→Rq \colon \mathbb{R} \to \mathbb{R}, q(x)=x2q(x)=x^2. The input type describes the expected domain while the return type describes the counterdomain. The analogy is not perfect: a mathematical function does not change state, does not perform input and output and always associates the same value to the same input. In computing, functions with these properties are often called pure functions.

Function is not just formula

A function can be described by a formula, a table, an algorithm or a verbal rule. What characterizes it is the unambiguous association between inputs and outputs, and not the form used to present it.

1.2.2 Domain, codomain and image

image of ff is the set of outputs that the function actually produces:

im⁡(f)={f(x)∣x∈X}. \operatorname{im}(f)=\{f(x) \mid x\in X\}.

Always worth im⁡(f)⊆Y\operatorname{im}(f)\subseteq Y, but inclusion can be strict.

q ⁣:R→R,q(x)=x2. q \colon \mathbb{R}\to\mathbb{R}, \qquad q(x)=x^2.

The declared codomain is R\mathbb{R}, but no negative number is produced.

im⁡(q)=[0,∞). \operatorname{im}(q)=[0,\infty).

This distinction matters in computing. One type of return can allow many values, although an implementation produces only part of them. It also matters to decide whether a function has inverse.

When a formula is presented without explicit domain, the largest subset of the real in which the expression makes sense is usually adopted.

r(x)=1x(x−3) r(x)=\frac{1}{x(x-3)}

It has R∖{0,3}\mathbb{R}\setminus\{0,3\} domain , because division by zero is not defined. s(x)=xs(x)=\sqrt{x}, as a real function, has [0,∞)[0,\infty) domain . In a program, trying to evaluate these expressions outside the domain can cause an exception, a special value like NaN or a result belonging to another numerical system, such as complexes.

1.2.3 Different ways to represent a function

The same function can be presented in various ways, each convenient for a type of problem.

Formula

A formula describes directly how to calculate the output. In the ideal free fall, starting from the rest, the distance traveled after tt seconds is

s(t)=12gt2,t≥0, s(t)=\frac{1}{2}gt^2, \qquad t\geq 0,

where g≈9,8 m/s2g\approx 9{,}8\,\mathrm{m/s^2} For example, s(2)=19,6 ms(2)=19{,}6\,\mathrm{m}. The formula makes evident the dependence between time and distance.

Table or dictionary

A function on a finite set can be stored as a table. A system can associate file extensions with the respective types:

EntryOutput
.pngimage
.qmdQuarto document
.pyPython code

This representation is similar to a dictionary or map in a programming language: a valid key determines a single value.

Algorithm

Some functions are more naturally described by an instruction sequence. The function that tells whether an integer is paired can be defined by

def eh_par(n: int) -> bool:
    return n % 2 == 0

Mathematically, she has the shape

par⁡ ⁣:Z→{false,true}. \operatorname{par}\colon\mathbb{Z}\to\{\text{false},\text{true}\}.

The code is an implementation of the mathematical rule. Different algorithms can implement the same function, with different time and memory costs.

Chart

For real functions of a real variable, the graph is the set

Gf={(x,f(x))∣x∈X}. G_f=\{(x,f(x))\mid x\in X\}.

Each xx input determines a height point f(x)f(x). The vertical straight test provides a visual check: if any vertical line intercepts the curve at more than one point, the drawn ratio does not represent yy as xx function .

A graph reveals trends, maximums, minimums and discontinuities, but a sampled figure does not replace the exact definition. In graphical computing, joining calculated points can hide oscillations or discontinuities between the samples.

1.2.4 Functions of various variables

Computer inputs are often vectors, not isolated numbers. A function that estimates the final note using proof and design can be written as

n ⁣:[0,10]2→[0,10],n(p,j)=0,6p+0,4j. n \colon [0,10]^2\to[0,10], \qquad n(p,j)=0{,}6p+0{,}4j.

The argument is the (p,j)(p,j) pair. In general, machine learning models receive vectors

x=(x1,x2,…,xd)∈Rd \mathbf{x}=(x_1,x_2,\ldots,x_d)\in\mathbb{R}^d

and produce a f(x)f(\mathbf{x}) output. In binary classification, for example, one can have f ⁣:Rd→{−1,+1}f\colon\mathbb{R}^d\to\{-1,+1\}; in classification with kk classes, a common output is a vector of kk probabilities.

1.2.5 Total and partial functions

By the adopted definition, f ⁣:X→Yf\colon X\to Y needs to provide an output for all x∈Xx\in X; we say it is total in XX. In computing, however, operations may fail or not finish. The search for a nonexistent key, the zero split or an algorithm that enters into infinite loop behave as partial functions.

There are two usual ways to model this fact. We can restrict the domain to valid entries or expand the counterdomain with a value that represents absence or error. For example,

buscar⁡ ⁣:K→V∪{⊥}, \operatorname{buscar}\colon K\to V\cup\{\bot\},

where ⊥\bot means “unfounded value”. Types like Option, Maybe and Result make this possibility explicit and help the compiler to require treatment of the exceptional case.

1.2.6 Important properties

Be f ⁣:X→Yf\colon X\to Y.

  • ff is injection moulder when different inputs produce different outputs: x1≠x2⟹f(x1)≠f(x2).x_1\neq x_2 \Longrightarrow f(x_1)\neq f(x_2).
  • ff is overjet when every element of the counterdomain is hit: im⁡(f)=Y.\operatorname{im}(f)=Y.
  • ff is bijetora when it is simultaneously injector and overjetor.

A common hash function illustrates the absence of injectivity: the set of possible inputs is usually much larger than the set of codes produced, so collisions are inevitable. On the other hand, a reversible encoding needs to preserve enough information so that different inputs do not confuse.

1.2.7 Composition of functions

Consider it compatible

f ⁣:X→Y and g ⁣:Y→Z. f\colon X\to Y \qquad\text{ and }\qquad g\colon Y\to Z.

composition of gg with ff is the function

g∘f ⁣:X→Z,(g∘f)(x)=g(f(x)). g\circ f\colon X\to Z, \qquad (g\circ f)(x)=g(f(x)).

First we apply ff and then we apply gg to the result. The order of the expression read, therefore, is from right to left.

The composition connects two transformations: the output of the first function becomes the input of the second.

Figure 1.4. The composition connects two transformations: the output of the first function becomes the input of the second.

For example, be f(x)=2x+1f(x)=2x+1 and g(y)=y2g(y)=y^2.

(g∘f)(x)=g(2x+1)=(2x+1)2, (g\circ f)(x)=g(2x+1)=(2x+1)^2,

while

(f∘g)(x)=f(x2)=2x2+1. (f\circ g)(x)=f(x^2)=2x^2+1.

In general, g∘f≠f∘gg\circ f\neq f\circ g. The composition also makes sense when the outputs of the first step are valid entries for the second. This verification corresponds, in programming, to the compatibility between types in a pipeline.

def normalizar(texto: str) -> str:
    return texto.strip().lower()

def comprimento(texto: str) -> int:
    return len(texto)

def tamanho_normalizado(texto: str) -> int:
    return comprimento(normalizar(texto))

In this example, normalizar produces a string, exactly the type accepted by comprimento. The tamanho_normalizado function implements the comprimento⁡∘normalizar⁡\operatorname{comprimento}\circ\operatorname{normalizar} composition.

The composition is associative: when the types are compatible,

h∘(g∘f)=(h∘g)∘f. h\circ(g\circ f)=(h\circ g)\circ f.

This property allows building complex systems from smaller modules, as occurs in compilers, data processing flows and layers of neural networks.

1.2.8 Identity function

For any XX set , the identity function is defined by

id⁡X ⁣:X→X,id⁡X(x)=x. \operatorname{id}_X\colon X\to X, \qquad \operatorname{id}_X(x)=x.

It does not modify the input and functions as a neutral element of the composition:

f∘id⁡X=f and id⁡Y∘f=f. f\circ\operatorname{id}_X=f \qquad\text{ and }\qquad \operatorname{id}_Y\circ f=f.

Although it seems trivial, identity is useful to express uniform interfaces, optional steps of pipelines and residual connections in neural networks.

1.2.9 Inverse function

A f ⁣:X→Yf\colon X\to Y function has an inverse f−1 ⁣:Y→Xf^{-1}\colon Y\to X when we can undo its action unambiguously:

f−1(f(x))=xfor all x∈X f^{-1}(f(x))=x \quad\text{for all }x\in X

e

f(f−1(y))=yfor all y∈Y. f(f^{-1}(y))=y \quad\text{for all }y\in Y.

This happens exactly when ff is bijetora. Injectivity ensures that the output identifies a single input; overjetivity ensures that every declared output can be reversed.

For example,

f ⁣:R→R,f(x)=2x+1 f\colon\mathbb{R}\to\mathbb{R}, \qquad f(x)=2x+1

To find the reverse, we write y=2x+1y=2x+1 and isolate xx:

x=y−12. x=\frac{y-1}{2}.

Soon,

f−1(y)=y−12. f^{-1}(y)=\frac{y-1}{2}.

We can check by composing the two functions:

f−1(f(x))=(2x+1)−12=x. f^{-1}(f(x))=\frac{(2x+1)-1}{2}=x.

q(x)=x2q(x)=x^2 is not an injector in R\mathbb{R}, because q(x)=q(−x)q(x)=q(-x). By restricting the domain to [0,∞)[0,\infty) and using the [0,∞)[0,\infty) counterdomain , we get a bijection whose reverse is q−1(y)=yq^{-1}(y)=\sqrt{y}. Therefore, invertibility does not depend only on the formula; it also depends on the domain and the counterdomain.

Geometrically, the ff and f−1f^{-1} graphs are each other’s reflexes in relation to the y=xy=x line. Computerly, inverting a transformation means recovering the input from output. Reversible encryption, lossless serialization and coordinate changes explore this idea; already compression with losses and hash functions discard information and therefore do not allow perfect inversion.

Don't confuse

f−1f^{-1} indicates the reverse function, while 1/f1/f indicates the reciprocal function, (1/f)(x)=1/f(x)(1/f)(x)=1/f(x). They are different concepts. For example, if f(x)=2xf(x)=2x, then f−1(x)=x/2f^{-1}(x)=x/2, but (1/f)(x)=1/(2x)(1/f)(x)=1/(2x).

1.2.10 Functions in machine learning

A predictive model is a parameterized function.

hw ⁣:X→Y, h_{\mathbf{w}}\colon X\to Y,

In which w\mathbf{w} represents the parameters learned from the data. During training, an algorithm modifies w\mathbf{w}; after training, the model receives an input and calculates an output.

A linear layer, for example, transforms a x∈Rd\mathbf{x}\in\mathbb{R}^d vector into

f(x)=Wx+b. f(\mathbf{x})=W\mathbf{x}+\mathbf{b}.

A neural network is obtained by the composition of several transformations.

h=f3∘f2∘f1. h=f_3\circ f_2\circ f_1.

The input passes first by f1f_1, then by f2f_2 and finally by f3f_3. Thus, domain, counterdomain, composition and image are not just abstractions: they describe directly how data travels through a computer system.

1.2.11 Practice exercises

  1. For f ⁣:Z→Zf\colon\mathbb{Z}\to\mathbb{Z}, f(n)=2n+1f(n)=2n+1, determine f(0)f(0), f(−3)f(-3) and the image of ff. Is the function superjet in the declared counterdomain?
  2. Explain why the relationship that associates a person with all your phone numbers is not, without an additional convention, a function with individual number codomain. How would you change the codomain?
  3. Be f(x)=x−1f(x)=x-1 and g(x)=3xg(x)=3x. Calculate (g∘f)(2)(g\circ f)(2) and (f∘g)(2)(f\circ g)(2).
  4. Determine a domain and a codomain for which f(x)=1/xf(x)=1/x is a bijetor and finds its reverse.
  5. Give an example of partial programming operation. Model it as a total function by adding an error value to the counterdomain.
  6. Consider a h ⁣:R784→R10h\colon\mathbb{R}^{784}\to\mathbb{R}^{10} model . Interpret input and output dimensions in the context of the 28×2828\times28 pixel classification of digit images.

1.3 Digits

Numbers are abstract objects; digits are symbols used to represent them. The number twelve, for example, can be written as 1212 in the decimal system, 11001100 in the binary system or C\mathrm{C} in the hexadecimal system. The three written represent the same amount, as the words “twelve” and “twelve” express the same idea in different languages.

For a computer science student, distinguishing the number of their representation is fundamental. Computers store bit sequences, but programs can display these sequences in decimal, hexadecimal, like characters, colors or instructions. The meaning depends on the chosen interpretation.

1.3.1 Positional numbering systems

A base numbering system bb uses different bb digits, with values between 00 and b−1b-1. The position of each digit determines by which power of the base it will be multiplied. For an entire sequence

(anan−1…a1a0)b, (a_na_{n-1}\ldots a_1a_0)_b,

Its value is

∑i=0naibi,0≤ai<b. \sum_{i=0}^{n}a_i b^i, \qquad 0\leq a_i<b.

The rightmost digit occupies the position 00 and has weight b0=1b^0=1. As we move to the left, the weights are multiplied successively by the base.

In a positional representation, each house has a weight; the houses on the left represent progressively larger clusters.

Figure 1.5. In a positional representation, each house has a weight; the houses on the left represent progressively larger clusters.

In the decimal system, the base is 1010 and the available digits are 0,1,…,90,1,\ldots,9.

(321)10=3⋅102+2⋅101+1⋅100. (321)_{10}=3\cdot10^2+2\cdot10^1+1\cdot10^0.

The parentheses and index explicitly indicate the basis. When there is no risk of ambiguity, we will omit the decimal index.

Zero plays two important roles: it can represent the null amount and also reserve a position. In 205205, zero informs that there are no dozens; without it, 2525 would represent another number.

A useful analogy

A hodometer is a positional counter. When a wheel completes all the symbols available, it returns to zero and produces a “go one” to the left wheel. On the basis of 1010, this occurs after ten states; on the basis of 22, after only two.

1.3.2 Fractional part

Positions to the right of the separator represent negative power from the base. Based on bb,

(anan−1…a0,a−1a−2…)b=∑i=−mnaibi. (a_na_{n-1}\ldots a_0,a_{-1}a_{-2}\ldots)_b =\sum_{i=-m}^{n}a_i b^i.

For example,

(321,34)10=3⋅102+2⋅101+1⋅100+3⋅10−1+4⋅10−2. (321,34)_{10} =3\cdot10^2+2\cdot10^1+1\cdot10^0 +3\cdot10^{-1}+4\cdot10^{-2}.

In Brazilian notation we use comma as decimal separator. Programming languages usually require point, as in 321.34.

1.3.3 Binary base

The binary system is based on 22 and uses only 00 and 11 digits. Each binary digit is called bit, * binary digit contraction*. The weights of the entire positions are

…,25,24,23,22,21,20=…,32,16,8,4,2,1. \ldots,2^5,2^4,2^3,2^2,2^1,2^0 =\ldots,32,16,8,4,2,1.

To convert a binary representation into decimal, we add the weights of the positions containing 11. For example,

(1101)2=1⋅23+1⋅22+0⋅21+1⋅20=8+4+0+1=(13)10. (1101)_2 =1\cdot2^3+1\cdot2^2+0\cdot2^1+1\cdot2^0 =8+4+0+1 =(13)_{10}.

Binary is appropriate for digital circuits because two distinguishable physical states can represent 00 and 11: low and high voltage, open and closed key or absence of charge. This does not mean that the computer “understands” binary numbers; it just means that we agree to interpret physical states in this way.

1.3.4 Conversion from decimal to binary

To convert a non-negative decimal integer into binary, we can divide it repeatedly by 22 and record the remains. The remains must be read from last division to first.

We convert (45)10(45)_{10}:

DivisionQuotRest
45÷245\div2222211
22÷222\div2111100
11÷211\div25511
5÷25\div22211
2÷22\div21100
1÷21\div20011

Reading the remains from the bottom up, we get

(45)10=(101101)2. (45)_{10}=(101101)_2.

We can check it out: 32+8+4+1=4532+8+4+1=45.

In Python, bin(45) returns the '0b101101'string. The 0b prefix informs that the representation is based on 22; it is not part of the numbers.

1.3.5 Hexadecimal base

Long binary representations are hard to read. hexadecimal system, based on 1616, offers compact writing and bit-lined. It uses the digits

0,1,…,9,A,B,C,D,E,F, 0,1,\ldots,9,\mathrm{A},\mathrm{B},\mathrm{C},\mathrm{D},\mathrm{E},\mathrm{F},

where A\mathrm{A} to F\mathrm{F} represent the decimal values 1010 to 1515. For example,

(A02F)16=10⋅163+0⋅162+2⋅161+15⋅160=(41007)10. (\mathrm{A02F})_{16} =10\cdot16^3+0\cdot16^2+2\cdot16^1+15\cdot16^0 =(41007)_{10}.

Like 16=2416=2^4, each hexadecimal digit corresponds to exactly four bits:

BinaryHexadecimalDecimal
000000
000111
001022
001133
010044
010155
011066
011177
100088
100199
1010A10
1011B11
1100C12
1101D13
1110E14
1111F15

One byte contains eight bits and can be separated into two groups of four; each group corresponds to a hexadecimal digit.

Figure 1.6. One byte contains eight bits and can be separated into two groups of four; each group corresponds to a hexadecimal digit.

To convert binary to hexadecimal, we group the bits four by four, starting from the right. If necessary, we complete the left group with zeros:

(10110110)2=(1011  0110)2=(B6)16. (10110110)_2=(1011\;0110)_2=(\mathrm{B6})_{16}.

The reverse process consists of replacing each hexadecimal digit with its four bits.

(3A)16=(0011  1010)2. (\mathrm{3A})_{16}=(0011\;1010)_2.

In programs, the 0x prefix usually indicates hexadecimal: 0x3A. Memory addresses, bit masks, color codes and debugging tools often use this base.

1.3.6 Bits, nibbles, bytes and capacity

A four-bit group is informally called nibble. An eight-bit group is a byte. With nn bits there are

2n 2^n

A byte, therefore, admits 28=2562^8=256 patterns, from 00000000 to 11111111. If interpreted as integers without signal, these patterns represent the values from 00 to 255255.

In general, nn bits represent integers without signal in the range

0≤x≤2n−1. 0\leq x\leq2^n-1.

The upper limit contains −1-1 because one of the 2n2^n combinations is used to represent zero.

Number of bitsNumber of patternsNo signal interval
4161600 a 1515
825625600 a 255255
1665 53665\,53600 a 65 53565\,535
324 294 967 2964\,294\,967\,29600 a 4 294 967 2954\,294\,967\,295

1.3.7 Signed integers and two’s complement

To represent negative numbers, modern computers usually use complement of two. With nn bits, the range becomes

−2n−1≤x≤2n−1−1. -2^{n-1}\leq x\leq2^{n-1}-1.

In eight bits, this corresponds to −128-128 up to 127127. The leftmost bit has weight −2n−1-2^{n-1}, while the others maintain positive weights. For example,

(11111101)2=−27+26+25+24+23+22+0⋅21+20=−3. (11111101)_2 =-2^7+2^6+2^5+2^4+2^3+2^2+0\cdot2^1+2^0 =-3.

A practical way to get −x-x representation is to invert all bits of xx representation and add 11. In eight bits:

3=00000011⟶11111100⟶11111101=−3. 3=00000011 \longrightarrow11111100 \longrightarrow11111101=-3.

In the intermediate step, all the bits were inverted; in the final step, we added 1.

Overflow

A fixed amount of bits has finite capacity. In an integer without an eight-bit signal, 255+1255+1 produces 00000000 if the calculation discards the final transport. This return to the beginning is called overflow and can cause serious errors when not predicted.

1.3.8 Binary fractions and inaccurate representation

The positions to the right of the binary separator have 2−1,2−2,2−3,…2^{-1},2^{-2},2^{-3},\ldots weights.

(10,101)2=1⋅21+0⋅20+1⋅2−1+0⋅2−2+1⋅2−3=(2,625)10. (10,101)_2 =1\cdot2^1+0\cdot2^0+1\cdot2^{-1} +0\cdot2^{-2}+1\cdot2^{-3} =(2,625)_{10}.

Not every decimal fraction has finite binary representation. The decimal number 0,10,1, for example, becomes an infinite binary expansion. As memory is finite, the computer stores an approximation. This explains why, in many languages,

0.1 + 0.2 == 0.3

results in False.

Floating point numbers are usually stored in a form analogous to scientific notation, with signal, meaning and exponent. The IEEE 754 standard specifies widely used formats. For financial calculations, in which pennies need to be exact, it may be better to use integers or appropriate decimal types.

1.3.9 Bits have no isolated meaning

The 01000001 sequence can be interpreted in various ways. As an unsigned integer, it is worth 6565. According to the ASCII encoding, it represents the A character. It can also be part of an instruction, a pixel or a floating point number. The bits are the same; the type and the context determine the interpretation.

This observation connects numbering systems to a central computing theme: data needs a coding convention. A file does not contain “an image” or “a text” intrinsically; it contains bytes interpreted according to a format.

1.3.10 Bitwise operations

Programming languages offer operations that act directly on bits:

  • AND preserves a position only when the two bits are 11;
  • OR produces 11 when at least one of the bits is 11;
  • XOR produces 11 when bits are different;
  • NOT reverses each bit;
  • offsets move bits to the left or right.

For example,

10102  AND⁡  11002=10002. 1010_2\;\operatorname{AND}\;1100_2=1000_2.

Moving a non-negative integer a left position corresponds, when there is no overflow, to multiply it by 22. Moving to the right corresponds to an entire division by 22. These operations appear in permission masks, communication protocols, compression and low-level programming.

1.3.11 Python Example

The following code shows different representations of the same integer:

n = 45

print(bin(n))  # 0b101101
print(oct(n))  # 0o55
print(hex(n))  # 0x2d
print(int("101101", 2))  # 45
print(f"{n:08b}")        # 00101101

bin, oct and hex return text. The value stored in n is not “decimal” or “is hexadecimal”; these bases relate to the chosen way to write or display the value.

1.3.12 Strategies to Avoid Mistakes

When working with numerical representations, it is appropriate to follow some practices:

  1. Enter the base when it is not evident: (101)2(101)_2, (101)10(101)_{10} and (101)16(101)_{16} are different numbers.
  2. Check the range allowed by the type before performing operations.
  3. Do not compare floating point numbers expecting exact equality; use a proper tolerance.
  4. Differentiate numerical text value. The "10" string has two characters; the 10 integer is a numeric value.
  5. Use hexadecimal to inspect bit groups, but convert each digit carefully.

1.3.13 Practice exercises

  1. Expand (5072)10(5072)_{10} as a sum of 1010 powers.
  2. Convert (101011)2(101011)_2 to decimal and confirm the result by adding the weights of the positions.
  3. Convert (73)10(73)_{10} to binary by the successive division method.
  4. Convert (11011110)2(11011110)_2 to hexadecimal and (7A)16(\mathrm{7A})_{16} to binary.
  5. What’s the largest integer without representative signal with 1212 bits? How many different patterns are there?
  6. Determine the integer range with two-complement signal for 1616 bits.
  7. Interpret 01000001 as an unsigned integer and search which ASCII character has this code.
  8. Explain, with your words, why 0,10,1 cannot be represented exactly by a finite binary number.
  9. Calculate 10110100 AND 11110000 and explain how this operation can serve to select the four most significant bits of a byte.

1.4 What Is a Learning Problem?

Programming a computer means specifying a procedure capable of transforming inputs into outputs. In many problems, we know this procedure well. To calculate the area of a circle, for example, we provide the computer with the formula A(r)=πr2A(r)=\pi r^2. To sort a list, we implement a sorting algorithm. The rules are written by a person and executed by the machine.

There are, however, tasks for which it is difficult to formulate all the rules explicitly. How to write a complete list of instructions to recognize a face, detect an attempted fraud or estimate the price of a residence? A person performs some of these tasks by experience, but may not be able to describe each decision as a rigid sequence of conditions. In such cases, we can provide examples and make an algorithm adjust a function that reproduces, as well as possible, the observed patterns.

This process is called machine learning. The computer does not learn in the same sense as a person, nor does it necessarily discover a true law of nature. It executes an optimization algorithm that chooses, within a family of possible functions, the one that achieves a good performance according to a mathematical criterion.

In conventional programming, rules guide data processing; in machine learning, examples are used to adjust a model that will make predictions about new inputs.

Figure 1.7. In conventional programming, rules guide data processing; in machine learning, examples are used to adjust a model that will make predictions about new inputs.

1.5 Conventional programming and machine learning

In conventional programming, data and rules are provided to the computer, which calculates an output:

Diagram

A program that calculates the due tax is a typical example. The tax rates and conditions are known, coded and applied to the taxpayer’s data. If the legislation changes, someone should change the program rules.

In supervised learning, the training data already include examples of intended inputs and outputs. An algorithm uses these pairs to produce a model:

Diagram

After training, the model is used to calculate predictions:

Diagram

It is important to separate these two phases. Training means to choose or adjust the model using known data. Infer or predict means to apply the model already trained to a new input. Training can require millions of examples and large computational capacity; an individual inference can be much cheaper.

1.6 Elements of a learning problem

A supervised learning problem can be initially described by five components.

  1. Entries: objects on which we want to make a decision. We represent the set of possible entries by XX.
  2. Outputs: answers we wish to produce. The possible output set is denoted by YY.
  3. Data: examples observed, often pairs (xi,yi)(x_i,y_i) with xi∈Xx_i\in X and yi∈Yy_i\in Y.
  4. Model: a h ⁣:X→Yh\colon X\to Y function, also called hypothesis, used to produce predictions.
  5. Quality criterion: a measure that quantifies how much hh predictions differ from the observed responses.

The learning algorithm receives the data and looks for a hypothesis that has a small error. In compact notation, a supervised sample with NN examples is

D={(x1,y1),(x2,y2),…,(xN,yN)}. D=\{(x_1,y_1),(x_2,y_2),\ldots,(x_N,y_N)\}.

The goal is not just to memorize these pairs. We want the function learned to produce good answers for entries that were not in the sample. This capacity is called generalization.

Learning is not memorizing

A model that corrects all training examples can still fail in the face of new data. The success of a learning system is measured mainly by the performance outside the sample used to adjust it.

1.7 An example: spam filtering

Consider the problem of classifying messages as spam or não spam. The XX input space is formed by possible messages, and the output space is

Y={0,1}, Y=\{0,1\},

where we can convene 11 for spam and 00 for não spam.

The computer does not directly manipulate the linguistic meaning of a message. First, we need to transform it into numerical features, such as number of links, frequency of certain words, subject size or sender identity. This transformation produces a vector

x=(x1,x2,…,xd)∈Rd. \mathbf{x}=(x_1,x_2,\ldots,x_d)\in\mathbb{R}^d.

A set of previously labeled messages forms the training data. The algorithm adjusts a h ⁣:Rd→{0,1}h\colon\mathbb{R}^d\to\{0,1\} classifier. For a new message, we calculate h(x)h(\mathbf{x}) and use the result as a preview.

Even in this simple example, important decisions arise:

  • do labeled emails adequately represent future messages?
  • Are the labels correct?
  • what features should be extracted?
  • What kind of function will be used as hypothesis?
  • What is the cost of blocking a legitimate message compared to missing a spam?

These questions show that machine learning is not just about running an algorithm. It is necessary to formulate the problem, obtain adequate data, choose representations and evaluate risks.

1.8 Output types

The nature of YY helps to identify the type of task.

  • In classification, the output belongs to a finite set of categories. Examples: spam or não spam; plant species; figure present in an image.
  • In regression, the output is numerical. Examples: price of a house, future temperature or time required to complete a task.
  • In ranking, the goal is to sort items by relevance, as results of a search.
  • In the generation, the output can be a complex sequence, such as text, audio, image or code.

The same context can give rise to different formulations. To analyze credit risk, we can predict pagará or não pagará (classification), estimate the probability of payment (probabilistic regression) or order clients from the minor to the highest risk (ranking).

1.9 Where do the examples come from?

Data does not appear ready and neutral. They are collected by sensors, forms, system records, experiments or people responsible for labeling examples. Each collection mechanism introduces choices and possible errors.

A sample can be biased when it represents some groups or situations better than others. Historical data can also preserve unfair past decisions. In addition, the environment can change: fraud patterns, spam language and user preferences do not remain constant forever.

Therefore, the origin of the data should be documented. We should ask who or what remained outside, how the labels were defined, what measurement errors exist and whether the intended use is compatible with the consent and privacy of the people involved.

1.10 Hypothesis, parameters and algorithm

Three close concepts need to be distinguished:

  • the hypothesis is a candidate function h ⁣:X→Yh\colon X\to Y;
  • parameters are internal values that determine a specific hypothesis;
  • the learning algorithm is the procedure that chooses the parameters from the data.

For example, a linear function can be written as

hw,b(x)=wTx+b. h_{\mathbf{w},b}(\mathbf{x})=\mathbf{w}^{\mathsf{T}}\mathbf{x}+b.

The values of w\mathbf{w} and bb are parameters. The set of all the functions obtained by varying these parameters is a family of hypotheses. A training algorithm looks for values that reduce error in the available examples.

In a neural network, there are many parameters organized into matrices and vectors. Although the architecture is specified by the programmer, the values of these parameters are adjusted during training.

1.11 Error and training goal

To compare a h(xi)h(x_i) prediction with the correct yiy_i response, we use a loss function. In regression, a simple choice is squared error:

ℓ(h(xi),yi)=(h(xi)−yi)2. \ell(h(x_i),y_i)=(h(x_i)-y_i)^2.

The average error in the sample is then

ED(h)=1N∑i=1Nℓ(h(xi),yi). E_D(h)=\frac{1}{N}\sum_{i=1}^{N}\ell(h(x_i),y_i).

Training can be seen as looking for a hypothesis with a small value of ED(h)E_D(h). However, minimizing only the training error can favor models that memorize accidental details. Later we will discuss separation between training and testing, regularization and generalization limits.

1.12 When to use machine learning?

Machine learning tends to be useful when there are representative data, a measurable goal and a relationship between inputs and outputs that can be explored. It is also important that the desired pattern is relatively stable and that errors can be monitored.

Not every problem needs learning. An explicit rule is usually preferable when it is known, short, reliable and easy to maintain. It makes no sense to train a model to convert degrees Celsius into Fahrenheit or to check if an integer is paired. In such cases, the deterministic solution is more transparent and accurate.

We should also be cautious when there is little data, when the cost of an error is too high or when there is no responsible way to evaluate the system. In medical, legal, financial or security applications, predictions need rigorous validation, human supervision and analysis of consequences.

1.13 A guide to formulating the problem

Before choosing an algorithm, it is useful to answer the following questions:

  1. What decision or prediction do we want to produce?
  2. What is an entry and what information will be available at the time of the forecast?
  3. What’s the exit space?
  4. Where will the examples come from and how will they be labelled?
  5. How will we measure an error and what types of errors are more serious?
  6. How do we check performance on unseen data?
  7. How will the system be monitored after entering use?

This script avoids a common error: start with the model before clearly defining the problem. A technically sophisticated system does not compensate for a misconceived question or inadequate data.

1.14 Practice exercises

  1. Compare conventional programming and machine learning using as an example the detection of spam messages.
  2. For a system that estimates the delivery time of an order, identify XX, YY, possible features and the type of task.
  3. Explain the difference between training and inference.
  4. Give an example of a model that memorizes the training data, but does not generalize.
  5. Propose a task for which an explicit rule is better than machine learning and justify.
  6. In a computer-assisted diagnosis, quote two types of error with different consequences.
  7. Explain the difference between hypothesis, parameters and learning algorithm in the case of a linear function.

1.15 Categories of Learning

Learning problems can be organized according to the type of information available during training and the way in which the system receives feedback on its decisions.This classification guides the preparation of the data, the choice of algorithms and the way to evaluate the results.

Categories are not absolutely isolated boxes. A real system can combine several of them: a model can be pre-trained in a self-supervised way, refined with labeled examples and then adjusted with human feedback by reinforcement. Still, understanding paradigms separately provides a useful vocabulary to design solutions.

Three paradigms: examples labeled in supervised learning, discovery of structure in the unsupervised and interaction with rewards in learning for reinforcement.

Figure 1.8. Three paradigms: examples labeled in supervised learning, discovery of structure in the unsupervised and interaction with rewards in learning for reinforcement.

1.15.1 Specify rules or learn from data?

Before comparing the categories, it is appropriate to distinguish two ways to build a system. In direct specification, the programmer explicitly determines the rules. To check if a password has at least twelve characters, just write a condition. The rule is known, verifiable and does not need to be estimated.

In machine learning, the programmer specifies the representation of the data, the model family, the error measure and the training procedure. The internal decisions of the model are adjusted using examples. Therefore, the system does not eliminate the human specification; it moves part of it from the final rules to the process by which the parametric rules will be adjusted.

Consider coin identification by diameter and mass. If the manufacturer provides accurate and stable intervals for each currency, we can code these limits directly. If measurements vary by wear, sensor noise or manufacturing differences, we can collect examples and adjust decision boundaries. The choice between rules and learning depends on the available knowledge, variability of the problem and cost of errors.

A Practical Distinguishment

Rules defined before observing examples are a specification. Parameters adjusted from examples are learning. In practice, systems often combine both: rules ensure mandatory restrictions, while models deal with patterns difficult to describe.

1.15.2 Supervised Learning

In supervised learning, each training example contains a desired input and output:

D={(xi,yi)}i=1N. D=\{(x_i,y_i)\}_{i=1}^{N}.

The term “supervised” does not necessarily mean that a person follows each stage of training. It means that there is a target yiy_i associated with each entry xix_i. This target may have been provided by experts, produced by sensors, extracted from historical records or calculated by another process.

The algorithm looks for a h ⁣:X→Yh\colon X\to Y function that approximates the observed relationship. There are two central subtypes:

  • classification, when YY contains discrete categories such as spam and não spam;
  • regression, when YY is numerical, such as price, temperature or duration.

For example, to classify emails, a sample may contain attribute vectors and their labels:

(xi,yi),xi∈Rd,yi∈{0,1}. (\mathbf{x}_i,y_i), \qquad \mathbf{x}_i\in\mathbb{R}^d, \quad y_i\in\{0,1\}.

The training uses the labels to calculate the error and correct the model. Then, the classifier receives an unlabeled message and estimates its class.

Examples of supervised applications include character recognition, default prediction, assisted diagnosis, object detection and demand estimation.

Quality of labels

Labels are measurements and may contain errors. Two experts may disagree about a diagnosis; users may mark legitimate messages like spam; historical records may reflect biased decisions. A model does not have direct access to “truth”: it learns from the targets provided.

data leakage can also occur when an attribute contains, directly or indirectly, information that would only be available after the response we want to predict. A hospital risk model should not use a procedure performed after diagnosis as input to predict this same diagnosis.

1.15.3 Unsupervised learning

In unsupervised learning, the sample contains entries without an explicit target output:

D={xi}i=1N. D=\{x_i\}_{i=1}^{N}.

The objective is to find structure in the data: groups, directions of greater variation, compact representations or atypical examples. Since there are no correct labels available during training, the evaluation requires different criteria from those used in supervised classification.

The most common tasks include:

  • clustering (clustering): gather similar examples;
  • dimensionality reduction: represent the data using less variables;
  • anomaly detection: locate observations that differ from the predominant pattern;
  • density estimate: model more and less likely regions of data space.

In the example of coins, we can represent each coin by mass and diameter. A cluster algorithm can separate points concentrations without knowing the monetary values. However, the groups found do not automatically follow the names “ten cents” or “one real”. Moreover, depending on the distance measurement and algorithm, the clusters may reflect size, material, conservation status or simply noise.

Groupings are not hidden truths

An unsupervised algorithm finds structure according to mathematical hypotheses chosen by us. Changing the scale of features, the notion of similarity or the number of groups can completely change the result.

1.15.4 Self-supervised learning

In the self-supervised learning, targets are built from the data itself, without the need for manual labeling for each example. We hide or transform part of the input and train the model to recover it.

In language models, a common task is to predict the next token:

(w1,w2,…,wt)⟼wt+1. (w_1,w_2,\ldots,w_t) \longmapsto w_{t+1}.

The text provides both input and target. In computer view, we can hide regions from an image and ask the model to reconstruct the missing content. These tasks allow you to learn general representations using large volumes of data not manually labeled.

Although targets are automatically generated, training remains mathematically similar to supervised: there is an expected response and a loss function. The difference lies at the origin of supervision.

1.15.5 Semi-supervised learning

Labeling data can be expensive while collecting unlabeled entries can be easy. semisupervised learning combines a small labeled set

DL={(xi,yi)} D_L=\{(x_i,y_i)\}

with a larger set without labels

DU={xj}. D_U=\{x_j\}.

The method tries to take advantage of the DUD_U structure to improve the prediction, without automatically treating all prediction of the model itself as truth. Strategies include pseudo-rotles, consistency regularization and propagation of labels in graphs.

This approach is useful in medical images, audio and documents, in which experts can label only a fraction of the material available.

1.15.6 Reinforcement learning

In booster learning, a agent repeatedly interacts with a environment. At every moment tt, it observes a sts_t state , chooses a ata_t action, receives a rt+1r_{t+1} reward and arrives at a new st+1s_{t+1} state:

st→ at (rt+1,st+1). s_t \xrightarrow{\ a_t\ } (r_{t+1},s_{t+1}).

The goal is not simply to predict a label, but to learn a policy π\pi that chooses actions capable of maximizing the accumulated reward over time.

Diagram

An immediate reward may not reveal the quality of an action. In a chess game, sacrificing a piece reduces the material advantage at that time, but may contribute to the victory many bids later. That is the problem of credit time assignment: determine which previous decisions were responsible for the future result.

Exploitation and exploitation

The agent faces a dilemma:

  • take advantage of (* explosion*) actions that already look good;
  • explore less known actions that can reveal better strategies.

If you just take advantage of the current knowledge, you can remain stuck to a median strategy. If you explore all the time, you stop using what you have learned. Reinforcement algorithms balance these behaviors in different ways.

Applications include robotic control, games, resource allocation, and sequential recommendation systems. The paradigm requires care: a poorly defined reward can induce behaviors that maximize formal scoring without fulfilling human intent.

1.15.7 Online and Batch Learning

Another distinction concerns the time when the data arrive.

In batch learning (* batch*), the model is trained using a previously assembled set. New data only influences the system in a later training. In online learning, the parameters are updated as observations arrive.

Online learning is useful for continuous flows and changing environments, but requires mechanisms against noise, attacks and forgetfulness of previous patterns. “On-line” in this context does not necessarily mean connected to the internet; it means incremental update.

1.15.8 Comparison between paradigms

ParadigmaTraining informationTypical objectiveExample
Supervised(x,y)(x,y) pairspredict yy for new entrysort spam
Not supervisedxx entriesfind structuregroup clients
Self-supervisedtargets derived from datalearn representationspredict next token
Semisupervisedfew labels and many entriesimprove forecast with unlabeled dataclassify medical images
By reinforcementstates, actions and rewardsmaximize accumulated returnlearn a game strategy

This table describes the source of the learning signal, not the specific algorithm. Neural networks, for example, can be used in all these paradigms.

1.15.9 How to choose the category?

The choice begins with the information available and the question we wish to answer:

  1. Is there a known correct exit for each example? The problem can be supervised.
  2. Are there many data but few labels? Consider semi-supervised or self-supervised learning.
  3. Do we want to explore the data structure without predicting a known target? This is an unsupervised task.
  4. Do decisions change future states and return occurs over time? The reinforcement paradigm may be appropriate.

We should not choose a category just because it is in evidence. If there is an exact rule, it may be more appropriate than any learned model. If there is no data capable of measuring the goal, changing the algorithm does not solve the incomplete formulation.

1.15.10 Practice exercises

  1. Rate as supervised, unsupervised or reinforced: predict the price of a house; group news by subject; learn to control a robot for rewards.
  2. Explain why predicting the next token is called self-supervised learning.
  3. A group separated customers by region, but the team expected groups for purchasing behavior. Is the result “wrong”? Discuss the role of features and the similarity metric.
  4. Give an example of the dilemma between exploration and out-of-game exploitation.
  5. Explain the difference between online learning and a service available on the internet.
  6. Propose a task that combines self-supervised pre-training and supervised adjustment.
  7. For coin identification, describe a solution by rules and a solution learned. Under what conditions would you choose each one?

1.16 Examples of Supervised Learning

Supervised learning appears in very different contexts, but all share the same structure: we have entries accompanied by known answers and we want to build a function that produces adequate responses to new inputs. The application domain changes; the mathematical formulation remains similar.

Different domains can use the same supervised pattern: examples accompanied by targets train a model that will make predictions for new entries.

Figure 1.9. Different domains can use the same supervised pattern: examples accompanied by targets train a model that will make predictions for new entries.

To analyze an application, it is not enough to say that “we will use artificial intelligence.” We need to clearly identify:

  • which object constitutes an entry xx;
  • what response will be used as target yy;
  • whether the task is classification or regression;
  • how the examples will be collected;
  • which metric translates the desired quality;
  • what are the consequences of each type of error.

The following case studies apply this script.

1.16.1 Assisted diagnosis

Consider a system that helps health professionals identify a disease. An entry can combine age, symptoms, laboratory results and measurements obtained by equipment:

x=(x1,x2,…,xd)∈X. \mathbf{x}=(x_1,x_2,\ldots,x_d)\in X.

If the objective is to indicate presence or absence of a condition, we can use

Y={0,1}. Y=\{0,1\}.

The training examples would be clinical records whose diagnosis was established by a reference procedure. The model would learn a h ⁣:X→{0,1}h\colon X\to\{0,1\} function or preferably an estimated probability

h(x)≈P(Y=1∣X=x). h(\mathbf{x})\approx P(Y=1\mid X=\mathbf{x}).

In this domain, two errors deserve distinct attention. A false negative occurs when a sick person is classified as healthy; a false positive occurs when a healthy person is signaled as sick. The relative importance depends on the condition, treatment and use of the system. Therefore, only the total percentage of correct answers can be insufficient.

It is also necessary to separate causality correlation. A model may find that a certain procedure is associated with the disease because the procedure is usually requested after doctors already suspect the diagnosis. Using this variable can produce good retrospective result, but not a valid tool for early detection.

Support is not an automatic decision

In clinical applications, the model should be validated in the population and in the context of use. A statistical prediction does not replace professional evaluation, safety protocols or institutional responsibility.

1.16.2 Filtering unwanted messages

In the filtering of emails, the original input is a message and the target indicates spam or não spam. To process the text, we extract features such as frequency of terms, sender, number of links and header characteristics.

A simple representation is the count vector. Chosen a vocabulary with dd terms, the xjx_j coordinate records how many times the term jj appears:

x∈Nd,y∈{0,1}. \mathbf{x}\in\mathbb{N}^d, \qquad y\in\{0,1\}.

The classifier is trained with previously labeled messages. However, patterns change: malicious senders adapt their writing to avoid filters, while legitimate messages start using expressions previously associated with spam. This phenomenon is an example of distribution change.

The choice of the metric should reflect the user experience. Blocking a legitimate email may be more serious than letting an advertisement reach the inbox. Therefore, accuracy, recall and false positive rate should be examined separately.

1.16.3 Credit risk assessment

In a credit analysis, entry may contain income, monthly commitment, payment history and contract characteristics. There are several possible questions, and each one defines a different problem:

  • predict whether there will be default: binary classification;
  • estimate the probability of default: probabilistic regression;
  • estimate expected injury: regression;
  • sort out bids by risk: ranking.

For classification, we can write

h ⁣:X→{0,1}, h\colon X\to\{0,1\},

but the decision to grant credit does not need to coincide directly with h(x)h(\mathbf{x}). A later policy may consider estimated probability, requested value, guarantees and regulatory limits.

Historical data requires careful analysis. We observe payment only for people who have received credit in the past. We do not know directly what would have happened to rejected proposals. In addition, previous decisions may contain discrimination. A model that mimics these data can reproduce or expand inequalities.

1.16.4 Prediction of sports performance

In sports, entries can gather speed, distance traveled, accuracy, injury history and match statistics. The target must be defined in a measurable way. “Being summoned to the selection” is a possible label, but mix performance with tactical decisions, availability, position and choices of the technical commission.

A more specific formulation could predict the amount of successful actions in a future match:

h ⁣:Rd→R≥0. h\colon\mathbb{R}^d\to\mathbb{R}_{\geq0}.

Another could estimate the probability of injury in a given interval. In both cases, it is important to avoid information after the event and respect the privacy of athletes.

The example shows that the available target does not always coincide with the quality we really want to measure. Learning to reproduce past summons does not necessarily mean learning “sporting merit”.

1.16.5 Image recognition

Consider the classification of manuscript digit images. A gray tones image with 28×2828\times28 pixels can be transformed into a vector with 784784 intensities:

x∈[0,1]784. \mathbf{x}\in[0,1]^{784}.

The label belongs to the set

Y={0,1,2,…,9}. Y=\{0,1,2,\ldots,9\}.

The model can produce ten scores, one for each class. After a normalization, these scores can be interpreted as estimated probabilities. The predicted class is often the highest value:

y^=argmax⁡k∈Y  hk(x). \widehat{y}=\underset{k\in Y}{\operatorname{argmax}}\;h_k(\mathbf{x}).

Even here there are difficulties: handwritings vary, some images are ambiguous and training data may not represent future devices or populations.

1.16.6 Demand forecast

A company may want to estimate how many units of a product will be requested next week. Possible entries include previous sales, price, promotions, holidays, region and availability in stock. Exit is a numerical amount:

h ⁣:X→R≥0. h\colon X\to\mathbb{R}_{\geq0}.

This is a regression problem. Errors up and down may have different costs: overestimating generates still stock; underestimating causes product failure. An asymmetric loss function may represent this difference better than the usual squared error.

Time series require a time-respecting training and test division. Training with future data to assess past predictions would cause leakage and produce an unrealistic estimate of performance.

1.16.7 Comparing examples

ApplicationEntryTargetTaskRelevant risk
Assisted diagnosisclinical datapresent or absent conditionclassificationfalse negative and positive
Spam filtercontent and metadataspam or no spamclassificationblock legitimate message
Creditfeatures and contractdefault or injuryclassification or regressionbias and past selective decisions
Sportsperformance measurementsfuture resultclassification or regressiontarget misrepresenting the goal
Numberspixelsclass from 00 to 99multiclass classificationvisual variation and ambiguity
Demandhistorical and contextfuture quantityregressionexcessive or insufficient stock

The table shows that the same technique may appear in different domains, but the risks and criteria of success are not interchangeable. An accuracy considered adequate in content recommendation may be unacceptable in a medical screening.

1.16.8 From Question to Dataset

After setting input and target, we need to build a sample. A careful procedure includes:

  1. determine the population on which the system will be used;
  2. establish how inputs and labels will be measured;
  3. document missing data and exclusion criteria;
  4. separate examples of training, validation and testing;
  5. choose metrics before observing the final result;
  6. check performance by relevant groups and conditions;
  7. plan monitoring after deployment.

This process is a central part of supervised learning. A large set of data does not automatically correct bad labels, biased sampling or a poorly defined question.

1.16.9 Practice exercises

  1. For a system that predicts student evasion, set entry, target and type of task. Name a possible data leak.
  2. Explain why “past call” and “sport quality” are not necessarily the same target.
  3. In a spam filter, compare the consequences of false positive and false negative.
  4. Turn the binary default prediction into a regression problem and explain the meaning of output.
  5. To predict demand, propose a situation where underestimating is more expensive than overestimating.
  6. Choose a table application and propose two complementary metrics to evaluate it.
  7. Create a new supervised example and describe XX, YY, the origin of the labels and an ethical or operational risk.

1.17 Formalization

So far we describe learning intuitively. Now we will gather its components into a single notation. Formalization helps answer precise questions: what the algorithm receives, what it chooses, what amount it seeks to minimize, and in what sense we expect the result to work for future data.

A distribution generates a finite sample; the algorithm selects a hypothesis in a family of models, and the hypothesis is evaluated in new examples.

Figure 1.10. A distribution generates a finite sample; the algorithm selects a hypothesis in a family of models, and the hypothesis is evaluated in new examples.

1.17.1 Input space and output space

The input space XX contains all objects that can be displayed to the model. Depending on the application, a x∈Xx\in X element can be a number, a vector, an image, a sequence of tokens or a more complex structure.

The output space YY contains the possible answers. Some examples are:

Y={0,1} Y=\{0,1\}

for binary classification,

Y={1,2,…,K} Y=\{1,2,\ldots,K\}

for classification with KK classes, and

Y=R Y=\mathbb{R}

for regression. The choice of XX and YY is part of the formulation of the problem. To say only “predict credit” is insufficient: we need to decide which information forms the input and whether the output will be a class, a probability or a monetary value.

1.17.2 Data-generating process

We assume that input-output pairs are produced by some unknown process. We represent this process by a joint distribution PP over X×YX\times Y:

(X,Y)∼P. (X,Y)\sim P.

Here, XX and YY in capitals represent random variables; xx and yy represent observed values. The PP distribution describes both which inputs are frequent and how outputs relate to them.

In an ideal deterministic problem, there may be a target function

f ⁣:X→Y f\colon X\to Y

such as y=f(x)y=f(x) for every example. However, real problems often contain noise, factors not observed or genuinely uncertain responses. In this case, a single input may be associated with different outputs with certain probabilities. The appropriate description is conditional distribution

P(Y=y∣X=x). P(Y=y\mid X=x).

For example, two people with the same registered features may present different clinical results because the input vector does not contain all the biologically relevant information.

The target function is a conceptual model

Speaking in a target function that “always hits” can be useful in noise-free problems, but should not be taken as a general rule. In probabilistic contexts, the ideal target can be a probability, a conditional average or a decision that minimizes an expected cost.

1.17.3 Training sample

The algorithm does not know PP. It observes a finite sample of NN pairs:

D=((x1,y1),(x2,y2),…,(xN,yN)). D=\bigl((x_1,y_1),(x_2,y_2),\ldots,(x_N,y_N)\bigr).

We often assume that these pairs are independent and identically distributed, abbreviated by i.i.d.:

(xi,yi)∼i.i.d.P. (x_i,y_i)\overset{\text{i.i.d.}}{\sim}P.

This hypothesis states that each example was obtained by the same process and that the observation of one example does not change the others. It simplifies the theory, but is not always realistic. Time data, people from the same family, consecutive frames of a video or multiple measurements of the same patient can be dependent.

The sample should contain the (xi,yi)(x_i,y_i) pairs, and not only the xix_i entries, when the problem is supervised. In unsupervised learning, on the other hand, we observed only (x1,…,xN)(x_1,\ldots,x_N).

1.17.4 Class of hypotheses

A hypothesis is a candidate function that transforms entries into predictions:

h ⁣:X→Y^. h\colon X\to\widehat{Y}.

We use Y^\widehat{Y} because the format of the forecast may differ from the final target. In binary classification, for example, the target may belong to {0,1}\{0,1\}, while the model produces a probability in [0,1][0,1] that will then be converted into class.

The hypothesis class H\mathcal{H} is the set of functions among which the algorithm can choose:

H={hθ∣θ∈Θ}. \mathcal{H}=\{h_\theta\mid\theta\in\Theta\}.

θ\theta represents the parameters of the model. For related functions,

hw,b(x)=wTx+b, h_{\mathbf{w},b}(\mathbf{x})=\mathbf{w}^{\mathsf T}\mathbf{x}+b,

We have θ=(w,b)\theta=(\mathbf{w},b). In a neural network, θ\theta gathers all the weight matrices and bias vectors.

The choice of H\mathcal{H} imposes a inductive bias: limits the patterns that the method can represent and indicates which solutions it considers plausible. Without some restriction, finite data does not determine how the model should act in points not yet observed.

1.17.5 Loss function

A loss function measures the quality of a forecast for a single example:

ℓ ⁣:Y^×Y→[0,∞). \ell\colon\widehat{Y}\times Y\to[0,\infty).

The first argument is the prediction h(x)h(x); the second is the target yy. In regression, a common choice is squared loss:

ℓ(h(x),y)=(h(x)−y)2. \ell(h(x),y)=(h(x)-y)^2.

In the classification, the zero-one loss only registers if there was correctness:

ℓ0/1(h(x),y)={0,h(x)=y,1,h(x)≠y. \ell_{0/1}(h(x),y) = \begin{cases} 0, & h(x)=y,\\ 1, & h(x)\neq y. \end{cases}

Loss is not synonymous with distance between entries. It compares a predicted output with a observed output. In addition, different losses express different priorities. If a false negative costs more than a false positive, the function can assign distinct penalties to these events.

1.17.6 Empirical risk

As we know only the sample, we calculated the mean loss in the observed data:

R^D(h)=1N∑i=1Nℓ(h(xi),yi). \widehat{R}_D(h) =\frac{1}{N}\sum_{i=1}^{N}\ell(h(x_i),y_i).

This amount is called empirical risk, error within the sample or training error. The accent on R^\widehat{R} remembers that it is an estimate built from a finite sample.

An algorithm to minimize empirical risk seeks

h^∈argmin⁡h∈H  R^D(h). \widehat{h} \in \underset{h\in\mathcal{H}}{\operatorname{argmin}} \;\widehat{R}_D(h).

The argmin⁡\operatorname{argmin} symbol returns the argument that minimizes the expression — in this case a hh function — and not the smallest value of the expression.

1.17.7 Learning algorithm

Formally, a learning algorithm AA transforms a sample into a hypothesis:

A ⁣:(X×Y)N→H,D↦A(D)=h^. A\colon (X\times Y)^N\to\mathcal{H}, \qquad D\mapsto A(D)=\widehat{h}.

The algorithm can use gradient descent, algebraic solution, combinatorial search, or other procedure. The hypothesis class and algorithm are not the same. Two algorithms can search for functions in the same class and produce different results because of startup, approximations, or stopping criteria.

In pseudocode, the general flow is:

input: sample D and hypothesis class H
initialize the model parameters
repeat:
    calculate forecasts in the examples
    evaluate the mean loss
    update parameters to reduce loss
up to the stop criterion
output: trained hypothesis h

Not every algorithm literally follows this iterative cycle, but the description shows the role of each component.

1.17.8 Expected risk and generalization

What we really want to minimize is not only the error in known examples, but the average error in new pairs generated by PP:

R(h)=E(X,Y)∼P[ℓ(h(X),Y)]. R(h) =\mathbb{E}_{(X,Y)\sim P} \bigl[\ell(h(X),Y)\bigr].

R(h)R(h) is called expected risk, true risk or error out of sample. As PP is unknown, we cannot calculate it exactly. We use validation and testing data to estimate it.

The generalization gap compares the expected risk with the empirical:

R(h)−R^D(h). R(h)-\widehat{R}_D(h).

A model that memorizes the sample may have very small R^D(h)\widehat{R}_D(h) and still have large R(h)R(h) . The learning theory investigates conditions under which empirical risk provides reliable information about the expected risk.

1.17.9 Regularization

To discourage excessively complex solutions, we can add a regularization term Ω(h)\Omega(h):

h^∈argmin⁡h∈H[R^D(h)+λΩ(h)]. \widehat{h} \in \underset{h\in\mathcal{H}}{\operatorname{argmin}} \left[ \widehat{R}_D(h)+\lambda\Omega(h) \right].

λ≥0\lambda\geq0 controls the balance between adjusting the data and prefer a simpler solution. In a linear model, Ω(h)\Omega(h) can penalize large-magnitude weights. Regularization can also be implemented by early stop, increased data or restrictions on architecture.

1.17.10 deterministic case and probabilistic case

In the deterministic case, we suppose

Y=f(X), Y=f(X),

And we tried to get closer. ff. In the probabilistic case, we model

P(Y∣X=x). P(Y\mid X=x).

For regression with squared loss, the function that minimizes the expected risk is the conditional mean:

h∗(x)=E[Y∣X=x]. h^*(x)=\mathbb{E}[Y\mid X=x].

For binary classification, we can estimate

η(x)=P(Y=1∣X=x) \eta(x)=P(Y=1\mid X=x)

and choose the class 11 when η(x)\eta(x) exceeds a threshold. The threshold does not need to be 0,50{,}5 when the costs of errors are different.

This perspective is more precise than to imagine that all observed frequency is a fixed property of the input. The sample provides limited evidence about a distribution; the model uses hypotheses and regularities to generalize beyond recorded occurrences.

1.17.11 Full example

Consider a regression that estimates the execution time of a program from the input size:

X=R>0,Y=R>0. X=\mathbb{R}_{>0}, \qquad Y=\mathbb{R}_{>0}.

The sample contains measurements

D={(ni,ti)}i=1N. D=\{(n_i,t_i)\}_{i=1}^{N}.

We choose the class of related functions

H={ha,b(n)=an+b∣a,b∈R} \mathcal{H}=\{h_{a,b}(n)=an+b\mid a,b\in\mathbb{R}\}

And the squared loss.

(a^,b^)∈argmin⁡a,b1N∑i=1N(ani+b−ti)2. (\widehat{a},\widehat{b}) \in \underset{a,b}{\operatorname{argmin}} \frac{1}{N}\sum_{i=1}^{N} \bigl(an_i+b-t_i\bigr)^2.

The trained hypothesis can predict times for unmeasured sizes. However, if the actual algorithm has quadratic behavior or if the machine used in production is different, the linear class or training distribution may be inadequate.

1.17.12 Notation map

SymbolMeaning
XXinput space
YYexit space or targets
PP(X,Y)(X,Y) pair generator distribution
DDfinite training sample
H\mathcal{H}hypothesis class
hha candidate hypothesis or model
θ\thetaparameters that determine a hypothesis
ℓ\ellloss in an example
R^D\widehat{R}_Dempirical risk calculated in the sample
RRexpected risk under distribution PP
AAalgorithm that transforms data into hypothesis

1.17.13 Practice exercises

  1. For spam classification, identify XX, YY, DD, a H\mathcal{H} class and a possible loss function.
  2. Explain why ℓ\ell usually has Y^×Y\widehat{Y}\times Y domain, not X×XX\times X.
  3. What is the difference between min⁡hR^D(h)\min_h\widehat{R}_D(h) and argmin⁡hR^D(h)\operatorname{argmin}_h\widehat{R}_D(h)?
  4. Give an example where i.i.d. hypothesis is unreasonable.
  5. A model has a training error equal to zero. Does that prove that its expected risk is zero? Justify.
  6. Explain the role of λ\lambda in a regularized goal.
  7. In the example of runtime, propose a class of hypotheses suitable for an algorithm whose cost increases as n2n^2.

1.18 Formalization of Examples

The abstract notation of the previous section becomes clearer when we apply it to concrete problems. In each example we need to define not only XX, YY and the sample DD, but also the representation of objects, the class of hypotheses, the loss and the distribution in which the system will be used.

A formalization is a modeling choice. The same verbal problem can originate different mathematical models. “Evaluing a credit application”, for example, may mean predicting default, estimating loss or ordering proposals for risk. Each interpretation changes the output space and the loss function.

1.18.1 Assisted diagnosis as binary classification

Suppose we want to estimate the presence of a specific condition. We chose dd clinical features and represent a person by

x=(x1,x2,…,xd)∈X⊆Rd. \mathbf{x}=(x_1,x_2,\ldots,x_d)\in X\subseteq\mathbb{R}^d.

Coordinates may include age, laboratory measurements, and symptom indicators.

Y={0,1}, Y=\{0,1\},

with y=1y=1 for present condition and y=0y=0 for absent.

Dclin={(xi,yi)}i=1N, D_{\text{clin}} =\{(\mathbf{x}_i,y_i)\}_{i=1}^{N},

obtained from records for which there is a reference diagnosis.

Instead of directly producing a class, a hypothesis can estimate

hθ(x)∈[0,1], h_\theta(\mathbf{x})\in[0,1],

interpreted as positive class probability. A decision rule converts this score into class:

y^={1,hθ(x)≥τ,0,hθ(x)<τ. \widehat{y} = \begin{cases} 1, & h_\theta(\mathbf{x})\geq\tau,\\ 0, & h_\theta(\mathbf{x})<\tau. \end{cases}

The τ\tau threshold should reflect the costs of false negatives and false positives. A weighted loss can assign cost cFNc_{FN} to the first and cFPc_{FP} to the second.

Is there still a question about PP: does the training population correspond to the future population? A model trained in a single hospital may not generalize for other equipment, protocols or demographic profiles.

1.18.2 Spam as text classification

A message is a textual object, but many algorithms receive numerical vectors. We set a vocabulary

V={w1,w2,…,wd} V=\{w_1,w_2,\ldots,w_d\}

and we use a representation function

ϕ ⁣:messages→Rd. \phi\colon\text{messages}\to\mathbb{R}^d.

The ϕ(m)\phi(m) coordinate can record the count or frequency of a term.

X=ϕ(messages)⊆Rd,Y={0,1}. X=\phi(\text{messages})\subseteq\mathbb{R}^d, \qquad Y=\{0,1\}.

The labelled sample is

Dspam={(ϕ(mi),yi)}i=1N. D_{\text{spam}} =\{(\phi(m_i),y_i)\}_{i=1}^{N}.

A simple class of hypotheses is formed by linear classifiers:

H={hw,b(x)=1[wTx+b≥0]}. \mathcal{H} =\left\{ h_{\mathbf{w},b}(\mathbf{x}) =\mathbb{1}[\mathbf{w}^{\mathsf T}\mathbf{x}+b\geq0] \right\}.

1[C]\mathbb{1}[C] is worth 11 when the CC condition is true and 00 otherwise. Each weight wjw_j measures how the corresponding term influences the score.

The dd dimension can be very large, as a vocabulary contains thousands of terms. However, each message uses only a small fraction of them; its vectors are sparse. Sparse data structures store only non-null coordinates and save memory.

1.18.3 Credit risk: class or probability

We represent a proposal by an attribute vector:

x=(income,debt,term,…)∈X⊆Rd. \mathbf{x} =(\text{income},\text{debt},\text{term},\ldots) \in X\subseteq\mathbb{R}^d.

To predict default on a given horizon,

Y={0,1} Y=\{0,1\}

e

Dcredit={(xi,yi)}i=1N. D_{\text{credit}} =\{(\mathbf{x}_i,y_i)\}_{i=1}^{N}.

If we want a probability of default, we use h ⁣:X→[0,1]h\colon X\to[0,1] hypotheses. The decision to grant credit may consider the expected cost:

custo⁡(x)=h(x)Cdefault+(1−h(x))Ccurrent. \operatorname{custo}(\mathbf{x}) =h(\mathbf{x})C_{\text{default}} +(1-h(\mathbf{x}))C_{\text{current}}.

This separation is important: prediction estimates a result; decision combines forecast with costs, rules and restrictions.

The historical sample has a selection bias: we generally observe default only for approved proposals.

P(X,Y∣credit approved), P(X,Y\mid\text{credit approved}),

while the system will be applied to P(X,Y∣nova proposta)P(X,Y\mid\text{nova proposta}). Ignore this difference compromises the validity of the evaluation.

1.18.4 Sports performance: choosing a measurable target

Consider it a vector of the characteristics of an athlete,

x=(speed,precision,strength,…)∈Rd. \mathbf{x} =(\text{speed},\text{precision},\text{strength},\ldots) \in\mathbb{R}^d.

If the target is “convoked or not summoned”, then Y={0,1}Y=\{0,1\} and we can train with past decisions. However, this label represents choices of technical commissions, not objective physical property.

An alternative is to predict a future statistic, as a number of successful actions per departure:

Y=R≥0. Y=\mathbb{R}_{\geq0}.

In that case we have regression and we can use absolute loss,

ℓ(h(x),y)=∣h(x)−y∣, \ell(h(\mathbf{x}),y)=|h(\mathbf{x})-y|,

which proportionally penalizes the magnitude of error and is less sensitive to extreme values than squared loss.

We also need to respect the temporal order. Features of a later season cannot be used to predict a previous result. A naive random division can place measurements of the same athlete and period both in training and in testing, overestimating generalization.

1.18.5 Digit recognition

An image with 28×2828\times28 pixels in gray tones can be vectorized:

X=[0,1]784. X=[0,1]^{784}.

The target is one among ten classes:

Y={0,1,2,…,9}. Y=\{0,1,2,\ldots,9\}.

The sample is

Ddigits={(xi,yi)}i=1N. D_{\text{digits}} =\{(\mathbf{x}_i,y_i)\}_{i=1}^{N}.

A hypothesis can produce a probability vector

h(x)=(p0,p1,…,p9),pk≥0,∑k=09pk=1. h(\mathbf{x}) =(p_0,p_1,\ldots,p_9), \qquad p_k\geq0, \quad \sum_{k=0}^{9}p_k=1.

In this case, Y^\widehat{Y} is the simplex of probabilities, while YY is the set of classes. The predicted class is argmax⁡kpk\operatorname{argmax}_k p_k. This distinction explains why prediction and target do not always belong to the same set.

1.18.6 Demand forecast as regression

To predict the demand for a product the following week, entry may gather recent sales, price, promotion and calendar:

xt∈X⊆Rd,yt∈Y=R≥0. \mathbf{x}_t\in X\subseteq\mathbb{R}^d, \qquad y_t\in Y=\mathbb{R}_{\geq0}.

The temporal sample is

Ddemand={(xt,yt)}t=1T. D_{\text{demand}} =\{(\mathbf{x}_t,y_t)\}_{t=1}^{T}.

The tt indexes remember that the examples are not necessarily independent. A linear class can serve as a starting point:

hw,b(x)=wTx+b. h_{\mathbf{w},b}(\mathbf{x}) =\mathbf{w}^{\mathsf T}\mathbf{x}+b.

Since the actual output cannot be negative, we can restrict the forecast using max⁡{0,h(x)}\max\{0,h(\mathbf{x})\} or choose a family of models with non-negative outputs.

1.18.7 Comparative view

ProblemXXYYPrediction Y^\widehat{Y}Critical observation
Diagnosisclinical features{0,1}\{0,1\}probability in [0,1][0,1]error costs differ
Spamsparse textual vectors{0,1}\{0,1\}class or probabilityvocabulary changes with time
Creditfinancial features{0,1}\{0,1\}probabilityobserved data are selective
Sportsperformance measurementsreal class or valuedepends on the targetlabel may not represent merit
Numbers[0,1]784[0,1]^{784}ten classesten probability vectorvisual variation
Demandhistorical and contextR≥0\mathbb{R}_{\geq0}real valuetemporal dependence

The table shows that writing X=RdX=\mathbb{R}^d is only the beginning. It is necessary to explain the meaning of the coordinates, the origin of YY, the population represented by PP and the cost encoded by ℓ\ell.

1.18.8 Dimension and geometry

When X⊆R2X\subseteq\mathbb{R}^2, we can draw each example as a point in the plane. In three dimensions there is still a direct view. For d>3d>3, the geometric interpretation remains valid, although we cannot literally draw the entire space.

An email represented by 50 00050\,000 terms is a point in R50 000\mathbb{R}^{50\,000}. The high dimension does not prevent the use of concepts such as distance, internal product, hyperplane and decision region. Much of machine learning consists in extending geometric intuition to these spaces.

However, features at different scales can distort geometry. If income is measured in thousands and a proportion varies between 00 and 11, distances and internal products can be dominated by income. Normalization and standardization are important stages of representation.

1.18.9 Checklist of formalization

Before we train a model, we should be able to fill in:

  1. XX: What entries are allowed and how are they represented?
  2. YY: What is the observed target?
  3. Y^\widehat{Y}: What object does the model really produce?
  4. DD: how was the sample collected and labeled?
  5. PP: Which population or future process do we want to represent?
  6. H\mathcal{H}: What functions can the algorithm choose?
  7. ℓ\ell: Which errors receive the highest penalty?
  8. AA: how will a hypothesis be chosen?
  9. evaluation: how will we estimate performance outside the sample?

If any item cannot be answered, the problem is not yet sufficiently defined for the choice of an algorithm to be the main concern.

1.18.10 Practice exercises

  1. Formalize a school drop forecast system specifying XX, YY, DD, Y^\widehat{Y} and a loss.
  2. In digit recognition, why can YY and Y^\widehat{Y} be different sets?
  3. Explain the selection bias present in historical credit data.
  4. Write a linear hypothesis for spam with three features and interpret each weight.
  5. Propose two different targets for sports analysis and tell us what kind of task each produces.
  6. For demand, explain why a time division is preferable to shuffle all examples.
  7. Choose one of the cases and describe a change in PP that could degrade the model after implantation.

1.19 Score

Many classifiers start by calculating a numerical score. The input is an attribute vector

x=(x1,x2,…,xd)∈Rd, \mathbf{x}=(x_1,x_2,\ldots,x_d)\in\mathbb{R}^d,

and each coordinate receives a weight that expresses its contribution to the decision.

s(x)=wTx+b=w1x1+w2x2+⋯+wdxd+b. s(\mathbf{x}) =\mathbf{w}^{\mathsf T}\mathbf{x}+b =w_1x_1+w_2x_2+\cdots+w_dx_d+b.

w=(w1,…,wd)\mathbf{w}=(w_1,\ldots,w_d) is the vector of weights and bb is the bias (bias). The name “viles” here designates a parameter of the model and should not be confused with statistical bias or discrimination in the data.

A simple binary rule assigns the positive class when the score is not negative:

hw,b(x)={+1,s(x)≥0,−1,s(x)<0. h_{\mathbf{w},b}(\mathbf{x}) = \begin{cases} +1, & s(\mathbf{x})\geq0,\\ -1, & s(\mathbf{x})<0. \end{cases}

This function can also be written as

hw,b(x)=sign⁡(wTx+b). h_{\mathbf{w},b}(\mathbf{x}) =\operatorname{sign}(\mathbf{w}^{\mathsf T}\mathbf{x}+b).

1.19.1 Weights and features

The sign of a weight indicates the direction of its influence, keeping the other features fixed:

  • wj>0w_j>0: increase xjx_j increases score;
  • wj<0w_j<0: increase xjx_j decreases score;
  • wj=0w_j=0: the attribute does not directly affect the score.

The ∣wj∣|w_j| magnitude indicates the sensitivity of the score to the xjx_j coordinate, but its interpretation depends on the scale. A weight of 0,10{,}1 applied to a variable measured in thousands can contribute more than a weight 1010 applied to a ratio between 00 and 11. Therefore, comparing weights is only informative when we know the units or standardize the features.

The term bb moves the decision border. We can interpret the rule using a τ\tau threshold:

wTx≥τ. \mathbf{w}^{\mathsf T}\mathbf{x}\geq\tau.

The two forms are equivalent when b=−τb=-\tau.

1.19.2 Numerical example

Consider three fictitious profiles described by two already normalized features:

  • x1x_1: technical performance measurement;
  • x2x_2: consistency measurement.

We’ll use the score.

s(x)=0,6x1+0,8x2−5. s(\mathbf{x})=0{,}6x_1+0{,}8x_2-5.

Weights show that in this specific rule, an additional unit of consistency contributes 0,80{,}8, while a technical performance unit contributes 0,60{,}6.

Profilex1x_1x2x_2s(x)s(\mathbf{x}) scoreClass
A450,6(4)+0,8(5)−5=1,40{,}6(4)+0{,}8(5)-5=1{,}4+1+1
B720,6(7)+0,8(2)−5=0,80{,}6(7)+0{,}8(2)-5=0{,}8+1+1
C420,6(4)+0,8(2)−5=−1,00{,}6(4)+0{,}8(2)-5=-1{,}0−1-1

The calculation is deterministic: fixed w\mathbf{w} and bb, any vector receives a score and a class. The learning consists of choosing these parameters from the examples, and not calculating the sum after the parameters are already known.

1.19.3 Geometric interpretation

The points for which the score is exactly zero form the decision border:

wTx+b=0. \mathbf{w}^{\mathsf T}\mathbf{x}+b=0.

In two dimensions, this boundary is a straight line. In three dimensions, it is a plane. In dd dimensions, it is a hyperplane. On one side are the points with positive score; on the other, the points with negative score.

A linear score divides the feature space into two regions by means of a decision line.

Figure 1.11. A linear score divides the feature space into two regions by means of a decision line.

The vector w\mathbf{w} is perpendicular to the hyperplane and points to the side where the score increases. If we multiply w\mathbf{w} and bb by the same positive number, the boundary and the classes do not change, although the scores are scaled.

In the example,

0,6x1+0,8x2−5=0 0{,}6x_1+0{,}8x_2-5=0

can be isolated as

x2=6,25−0,75x1. x_2=6{,}25-0{,}75x_1.

This equation allows you to draw the line and visually verify the region of each profile.

1.19.4 Signed distance to the border

The gross score depends on the scale of the weights. By dividing it by the w\mathbf{w} standard, we obtain the signed distance from the point to the hyperplane:

d(x)=wTx+b∥w∥2. d(\mathbf{x}) =\frac{\mathbf{w}^{\mathsf T}\mathbf{x}+b}{\|\mathbf{w}\|_2}.

The signal informs the border side; the module provides the perpendicular distance. In the example,

∥w∥2=0,62+0,82=1, \|\mathbf{w}\|_2 =\sqrt{0{,}6^2+0{,}8^2}=1,

therefore the score coincides numerically with the signed distance.

Border points are more sensitive to small changes in features or parameters. However, a large distance is not automatically a high probability; it only expresses geometric separation in the linear model.

1.19.5 Score is not probability

s(x)s(\mathbf{x}) can take any real value and does not need to be between 00 and 11. To get a quantity interpretable as probability, we can apply a logistic function:

p(x)=σ(s(x))=11+e−s(x). p(\mathbf{x}) =\sigma(s(\mathbf{x})) =\frac{1}{1+e^{-s(\mathbf{x})}}.

This transformation preserves the order of scores: if s(xa)>s(xb)s(\mathbf{x}_a)>s(\mathbf{x}_b), then p(xa)>p(xb)p(\mathbf{x}_a)>p(\mathbf{x}_b). However, interpreting pp as a reliable probability requires appropriate training and calibration.

A score can also be used only for rank elements. A search engine, for example, orders documents by relevance without necessarily converting each value into a class.

1.19.6 Learning the Weights

Given a sample

D={(xi,yi)}i=1N,yi∈{−1,+1}, D=\{(\mathbf{x}_i,y_i)\}_{i=1}^{N}, \qquad y_i\in\{-1,+1\},

We want to choose w\mathbf{w} and bb to produce good predictions. A correct classification condition is

yi(wTxi+b)>0. y_i(\mathbf{w}^{\mathsf T}\mathbf{x}_i+b)>0.

When data is linearly separable , there is at least one hyperplane that correctly classifies all training examples. This does not guarantee that the same border will perform well in future data, nor that all real sets are separable.

The perceptron, studied below, adjusts weights when you find an example incorrectly classified. Logistic regression uses a different loss and produces scores transformed by the logistic function. Support vector machines seek a border with wide margin. These methods share the linear structure, but have different training objectives.

1.19.7 Code of a linear score

A direct Python implementation is:

def pontuacao(x, w, b):
    return sum(x_j * w_j for x_j, w_j in zip(x, w)) + b


def classificar(x, w, b):
    return 1 if pontuacao(x, w, b) >= 0 else -1


w = [0.6, 0.8]
b = -5.0

print(classificar([4, 5], w, b))  # 1
print(classificar([4, 2], w, b))  # -1

In numerical libraries, the internal product is usually vectorized. For a X∈RN×dX\in\mathbb{R}^{N\times d} matrix containing NN examples on the lines, all scores are

s=Xw+b1. \mathbf{s}=X\mathbf{w}+b\mathbf{1}.

This way avoids an explicit loop for example and takes advantage of efficient linear algebra implementations.

1.19.8 Limitations and care

A linear boundary is simple and interpretable, but does not represent any pattern. If the positive class forms a circle surrounded by the negative class, no line will separate the groups perfectly into the original space. We can then create new features, apply a transformation, or choose a nonlinear hypothesis class.

In addition, a learned weight represents an association within the data and model; it does not prove causality. Sensitive features or variables that function as substitutes can produce unfair decisions. In applications that affect people, it is necessary to evaluate performance between groups, document limitations and allow proper review.

Separating the sample is not enough

Finding weights that perfectly classify training examples demonstrates adjustment to the sample, not generalization.The frontier needs to be evaluated in independent and representative data of the population of use.

1.19.9 Practice exercises

  1. Calculate the score of the three profiles using s(x)=x1+x2−6s(\mathbf{x})=x_1+x_2-6 and determine their classes.
  2. Rewrite the 2x1−3x2≥42x_1-3x_2\geq4 rule in wTx+b≥0\mathbf{w}^{\mathsf T}\mathbf{x}+b\geq0 form.
  3. For w=(3,4)\mathbf{w}=(3,4) and b=−10b=-10, calculate ∥w∥2\|\mathbf{w}\|_2 and the signed distance from (2,2)(2,2) to the border.
  4. Explain why multiplying w\mathbf{w} and bb by 55 does not change the classes, but changes the scores.
  5. Give an example of a set of points in R2\mathbb{R}^2 that is not linearly separable.
  6. What is the difference between a score, a class and a calibrated probability?
  7. Implement the vectorized version of the score for several examples using a numerical library.

1.20 Multiple choice exercises

The following questions take up the main concepts of the chapter. Please tick only one alternative. Try to justify your choice before consulting the feedback.

  1. If A={1,2,3}A=\{1,2,3\} and B={3,4}B=\{3,4\}, what is the A∩BA\cap B set?

    1. {1,2,4}\{1,2,4\}
    2. {3}\{3\}
    3. {1,2,3,4}\{1,2,3,4\}
    4. ∅\varnothing
  2. A f:A→Bf:A\to B function is injected when:

    1. every element of BB has exactly one pre-image.
    2. distinct elements of AA always produce different images.
    3. its image is necessarily equal to AA.
    4. its domain contains only real numbers.
  3. For a f:A→Bf:A\to B function to have an inverse f−1:B→Af^{-1}:B\to A, it must be:

    1. constant.
    2. just injective.
    3. bijective.
    4. just superfluous.
  4. What is the binary representation of the decimal number 1313?

    1. 101121011_2
    2. 110021100_2
    3. 110121101_2
    4. 111021110_2
  5. A byte contains:

    1. 2 bits.
    2. 4 bits.
    3. 8 bits.
    4. 16 bits.
  6. In addition to two with 8 bits, the integer range representable is:

    1. from −127-127 to 127127.
    2. from −128-128 to 127127.
    3. from −128-128 to 128128.
    4. from 00 to 255255.
  7. In a supervised problem, the training set contains:

    1. only entries without any output information.
    2. pairs of input and target output.
    3. only rules written by a programmer.
    4. only future actions and rewards.
  8. What alternative describes a regression task?

    1. Decide if a message is spam.
    2. Group customers without prior labels.
    3. Predict monthly energy consumption in kWh.
    4. Recognizing which digit appears in an image.
  9. In the linear s(x)=wTx+bs(\mathbf{x})=\mathbf{w}^{\mathsf T}\mathbf{x}+b score, the vector w\mathbf{w} determines mainly:

    1. the direction of the decision-making border.
    2. the number of examples of the sample.
    3. the numerical base used by the computer.
    4. the exact probability of any class.
  10. Obtain zero error in training data necessarily means that:

    1. the model will have zero error in production.
    2. the problem is not supervised.
    3. the hypothesis adjusted the sample, but still needs to have its generalization evaluated.
    4. all the weights of the model are equal to zero.

Answer key with explanations

  1. b. The intersection contains only the elements present in the two sets; in this case, only 33.
  2. b. Injectivity prevents two distinct entries from being associated with Same exit.
  3. c. The inverse defined across the counterdomain requires injection and overjetivity, that is, bijectivity.
  4. c. 13=8+4+113=8+4+1, so its bits are 110121101_2.
  5. c. By definition, a byte has 8 bits.
  6. b. With nn bits in addition to two, the range is [−2n−1,2n−1−1][-2^{n-1},2^{n-1}-1].
  7. b. Supervised learning uses examples in which the target output Follow the entrance.
  8. c. Consumption is a continuous numerical quantity; alternatives to and from they are classifications, and b is grouping.
  9. a. w\mathbf{w} is normal to hyperplane and therefore controls its orientation; bb controls displacement.
  10. c. Training error measures adjustment to the observed examples, does not warrant performance in new data.