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,
The expression informs that belongs to ; already informs that does not belong to . Order and repetition do not change a set.
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 elements. Languages like Python reflect this difference: list maintains order and repetitions, while set eliminates duplicates.

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
The symbol “” means “such that”. This notation is useful when the set is too large or infinite. The empty set, denoted by or , has no element at all. Note: is different from 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:
- : natural numbers, used in counts and indexes;
- : integer numbers;
- : rational numbers, which can be written as , with and ;
- : real numbers, common in measurements, probabilities and model parameters.
There is an inclusion chain:
This means, for example, that every natural number is also integer and real. The irrational numbers, such as and , belong to .
1.1.3 Subsets and equality
We say is subset of , and we write , when every element of also belongs to . If and , then is a proper subset of , indicated by .
Two sets are the same when they have exactly the same elements. A common way to prove is to demonstrate the two inclusions: and . 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 and . The main operations are:
- union: gathers elements present in or in ;
- intersection: maintains elements present in and in ;
- difference: maintains elements of that do not belong to ;
- symmetric difference: maintains elements that belong to only one of the sets.
If , the sets are called disjoint sets . In a universe , the complement of is : everything that is in the universe considered but not in . 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.

Figure 1.2. Visual flow of filtering, combination and separation of data collections.
De Morgan’s laws relate operations and complements:
They appear in the simplification of Boolean conditions. Deny “ is in or ” is equivalent to stating that “ is not in and is not in ”.
1.1.5 Cardinality and the power set
The cardinality is the number of elements of a finite set. If , then . For finite sets,
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 parts contains all subsets. For ,
If then . Each element can be included or not in a subset, exactly as a bit can take over or . Therefore, subsets can be represented by bit masks: for , the 101 mask represents .
1.1.6 Cartesian product
The Cartesian product of and is the set of all possible ordered pairs:
If and , then
The order matters: in general, . If and are finite, . In Computing, Cartesian products model coordinates, combinations of parameters, composite states and lines produced by a CROSS JOIN. When , we use ; thus, represents the plane and represents the three-dimensional space.
Check your understanding
Consider , and . Calculate , , and in relation to . Then represent as a set in Python and test if
3belongs 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.

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 and be two sets. A function of in is a rule that associates to each element exactly one element.
In that rating:
- is the domain, i.e. the set of allowed inputs;
- is the counterdomain, the set in which we declare the outputs are;
- is a argument or a input;
- is the function value or the output corresponding to .
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 , we have .
In programming, the signature of a function expresses an idea similar to mathematical notation.
square : Real -> Real
corresponds to , . 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 is the set of outputs that the function actually produces:
Always worth , but inclusion can be strict.
The declared codomain is , but no negative number is produced.
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.
It has domain , because division by zero is not defined. , as a real function, has 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 seconds is
where For example, . 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:
| Entry | Output |
|---|---|
.png | image |
.qmd | Quarto document |
.py | Python 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
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
Each input determines a height point . 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 as 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
The argument is the pair. In general, machine learning models receive vectors
and produce a output. In binary classification, for example, one can have ; in classification with classes, a common output is a vector of probabilities.
1.2.5 Total and partial functions
By the adopted definition, needs to provide an output for all ; we say it is total in . 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,
where 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 .
- is injection moulder when different inputs produce different outputs:
- is overjet when every element of the counterdomain is hit:
- 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
composition of with is the function
First we apply and then we apply to the result. The order of the expression read, therefore, is from right to left.

Figure 1.4. The composition connects two transformations: the output of the first function becomes the input of the second.
For example, be and .
while
In general, . 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 composition.
The composition is associative: when the types are compatible,
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 set , the identity function is defined by
It does not modify the input and functions as a neutral element of the composition:
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 function has an inverse when we can undo its action unambiguously:
e
This happens exactly when is bijetora. Injectivity ensures that the output identifies a single input; overjetivity ensures that every declared output can be reversed.
For example,
To find the reverse, we write and isolate :
Soon,
We can check by composing the two functions:
is not an injector in , because . By restricting the domain to and using the counterdomain , we get a bijection whose reverse is . Therefore, invertibility does not depend only on the formula; it also depends on the domain and the counterdomain.
Geometrically, the and graphs are each other’s reflexes in relation to the 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
indicates the reverse function, while indicates the reciprocal function, . They are different concepts. For example, if , then , but .
1.2.10 Functions in machine learning
A predictive model is a parameterized function.
In which represents the parameters learned from the data. During training, an algorithm modifies ; after training, the model receives an input and calculates an output.
A linear layer, for example, transforms a vector into
A neural network is obtained by the composition of several transformations.
The input passes first by , then by and finally by . 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
- For , , determine , and the image of . Is the function superjet in the declared counterdomain?
- 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?
- Be and . Calculate and .
- Determine a domain and a codomain for which is a bijetor and finds its reverse.
- Give an example of partial programming operation. Model it as a total function by adding an error value to the counterdomain.
- Consider a model . Interpret input and output dimensions in the context of the 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 in the decimal system, in the binary system or 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 uses different digits, with values between and . The position of each digit determines by which power of the base it will be multiplied. For an entire sequence
Its value is
The rightmost digit occupies the position and has weight . As we move to the left, the weights are multiplied successively by the base.

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 and the available digits are .
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 , zero informs that there are no dozens; without it, 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 , this occurs after ten states; on the basis of , after only two.
1.3.2 Fractional part
Positions to the right of the separator represent negative power from the base. Based on ,
For example,
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 and uses only and digits. Each binary digit is called bit, * binary digit contraction*. The weights of the entire positions are
To convert a binary representation into decimal, we add the weights of the positions containing . For example,
Binary is appropriate for digital circuits because two distinguishable physical states can represent and : 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 and record the remains. The remains must be read from last division to first.
We convert :
| Division | Quot | Rest |
|---|---|---|
Reading the remains from the bottom up, we get
We can check it out: .
In Python, bin(45) returns the '0b101101'string. The 0b prefix informs that the representation is based on ; it is not part of the numbers.
1.3.5 Hexadecimal base
Long binary representations are hard to read. hexadecimal system, based on , offers compact writing and bit-lined. It uses the digits
where to represent the decimal values to . For example,
Like , each hexadecimal digit corresponds to exactly four bits:
| Binary | Hexadecimal | Decimal |
|---|---|---|
0000 | 0 | 0 |
0001 | 1 | 1 |
0010 | 2 | 2 |
0011 | 3 | 3 |
0100 | 4 | 4 |
0101 | 5 | 5 |
0110 | 6 | 6 |
0111 | 7 | 7 |
1000 | 8 | 8 |
1001 | 9 | 9 |
1010 | A | 10 |
1011 | B | 11 |
1100 | C | 12 |
1101 | D | 13 |
1110 | E | 14 |
1111 | F | 15 |

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:
The reverse process consists of replacing each hexadecimal digit with its four bits.
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 bits there are
A byte, therefore, admits patterns, from 00000000 to 11111111. If interpreted as integers without signal, these patterns represent the values from to .
In general, bits represent integers without signal in the range
The upper limit contains because one of the combinations is used to represent zero.
| Number of bits | Number of patterns | No signal interval |
|---|---|---|
| 4 | a | |
| 8 | a | |
| 16 | a | |
| 32 | a |
1.3.7 Signed integers and two’s complement
To represent negative numbers, modern computers usually use complement of two. With bits, the range becomes
In eight bits, this corresponds to up to . The leftmost bit has weight , while the others maintain positive weights. For example,
A practical way to get representation is to invert all bits of representation and add . In eight bits:
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, produces
00000000if 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 weights.
Not every decimal fraction has finite binary representation. The decimal number , 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 . 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:
ANDpreserves a position only when the two bits are ;ORproduces when at least one of the bits is ;XORproduces when bits are different;NOTreverses each bit;- offsets move bits to the left or right.
For example,
Moving a non-negative integer a left position corresponds, when there is no overflow, to multiply it by . Moving to the right corresponds to an entire division by . 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:
- Enter the base when it is not evident: , and are different numbers.
- Check the range allowed by the type before performing operations.
- Do not compare floating point numbers expecting exact equality; use a proper tolerance.
- Differentiate numerical text value. The
"10"string has two characters; the10integer is a numeric value. - Use hexadecimal to inspect bit groups, but convert each digit carefully.
1.3.13 Practice exercises
- Expand as a sum of powers.
- Convert to decimal and confirm the result by adding the weights of the positions.
- Convert to binary by the successive division method.
- Convert to hexadecimal and to binary.
- What’s the largest integer without representative signal with bits? How many different patterns are there?
- Determine the integer range with two-complement signal for bits.
- Interpret
01000001as an unsigned integer and search which ASCII character has this code. - Explain, with your words, why cannot be represented exactly by a finite binary number.
- Calculate
10110100 AND 11110000and 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 . 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.

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:

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:

After training, the model is used to calculate predictions:

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.
- Entries: objects on which we want to make a decision. We represent the set of possible entries by .
- Outputs: answers we wish to produce. The possible output set is denoted by .
- Data: examples observed, often pairs with and .
- Model: a function, also called hypothesis, used to produce predictions.
- Quality criterion: a measure that quantifies how much 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 examples is
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 input space is formed by possible messages, and the output space is
where we can convene for spam and 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
A set of previously labeled messages forms the training data. The algorithm adjusts a classifier. For a new message, we calculate 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 helps to identify the type of task.
- In classification, the output belongs to a finite set of categories. Examples:
spamornã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 ;
- 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
The values of and 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 prediction with the correct response, we use a loss function. In regression, a simple choice is squared error:
The average error in the sample is then
Training can be seen as looking for a hypothesis with a small value of . 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:
- What decision or prediction do we want to produce?
- What is an entry and what information will be available at the time of the forecast?
- What’s the exit space?
- Where will the examples come from and how will they be labelled?
- How will we measure an error and what types of errors are more serious?
- How do we check performance on unseen data?
- 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
- Compare conventional programming and machine learning using as an example the detection of spam messages.
- For a system that estimates the delivery time of an order, identify , , possible features and the type of task.
- Explain the difference between training and inference.
- Give an example of a model that memorizes the training data, but does not generalize.
- Propose a task for which an explicit rule is better than machine learning and justify.
- In a computer-assisted diagnosis, quote two types of error with different consequences.
- 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.

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:
The term “supervised” does not necessarily mean that a person follows each stage of training. It means that there is a target associated with each entry . 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 function that approximates the observed relationship. There are two central subtypes:
- classification, when contains discrete categories such as
spamandnão spam; - regression, when is numerical, such as price, temperature or duration.
For example, to classify emails, a sample may contain attribute vectors and their labels:
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:
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:
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
with a larger set without labels
The method tries to take advantage of the 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 , it observes a state , chooses a action, receives a reward and arrives at a new state:
The goal is not simply to predict a label, but to learn a policy that chooses actions capable of maximizing the accumulated reward over time.

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
| Paradigma | Training information | Typical objective | Example |
|---|---|---|---|
| Supervised | pairs | predict for new entry | sort spam |
| Not supervised | entries | find structure | group clients |
| Self-supervised | targets derived from data | learn representations | predict next token |
| Semisupervised | few labels and many entries | improve forecast with unlabeled data | classify medical images |
| By reinforcement | states, actions and rewards | maximize accumulated return | learn 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:
- Is there a known correct exit for each example? The problem can be supervised.
- Are there many data but few labels? Consider semi-supervised or self-supervised learning.
- Do we want to explore the data structure without predicting a known target? This is an unsupervised task.
- 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
- Rate as supervised, unsupervised or reinforced: predict the price of a house; group news by subject; learn to control a robot for rewards.
- Explain why predicting the next token is called self-supervised learning.
- 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.
- Give an example of the dilemma between exploration and out-of-game exploitation.
- Explain the difference between online learning and a service available on the internet.
- Propose a task that combines self-supervised pre-training and supervised adjustment.
- 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.

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 ;
- what response will be used as target ;
- 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:
If the objective is to indicate presence or absence of a condition, we can use
The training examples would be clinical records whose diagnosis was established by a reference procedure. The model would learn a function or preferably an estimated probability
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 terms, the coordinate records how many times the term appears:
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
but the decision to grant credit does not need to coincide directly with . 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:
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 pixels can be transformed into a vector with intensities:
The label belongs to the set
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:
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:
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
| Application | Entry | Target | Task | Relevant risk |
|---|---|---|---|---|
| Assisted diagnosis | clinical data | present or absent condition | classification | false negative and positive |
| Spam filter | content and metadata | spam or no spam | classification | block legitimate message |
| Credit | features and contract | default or injury | classification or regression | bias and past selective decisions |
| Sports | performance measurements | future result | classification or regression | target misrepresenting the goal |
| Numbers | pixels | class from to | multiclass classification | visual variation and ambiguity |
| Demand | historical and context | future quantity | regression | excessive 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:
- determine the population on which the system will be used;
- establish how inputs and labels will be measured;
- document missing data and exclusion criteria;
- separate examples of training, validation and testing;
- choose metrics before observing the final result;
- check performance by relevant groups and conditions;
- 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
- For a system that predicts student evasion, set entry, target and type of task. Name a possible data leak.
- Explain why “past call” and “sport quality” are not necessarily the same target.
- In a spam filter, compare the consequences of false positive and false negative.
- Turn the binary default prediction into a regression problem and explain the meaning of output.
- To predict demand, propose a situation where underestimating is more expensive than overestimating.
- Choose a table application and propose two complementary metrics to evaluate it.
- Create a new supervised example and describe , , 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.

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 contains all objects that can be displayed to the model. Depending on the application, a element can be a number, a vector, an image, a sequence of tokens or a more complex structure.
The output space contains the possible answers. Some examples are:
for binary classification,
for classification with classes, and
for regression. The choice of and 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 over :
Here, and in capitals represent random variables; and represent observed values. The distribution describes both which inputs are frequent and how outputs relate to them.
In an ideal deterministic problem, there may be a target function
such as 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
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 . It observes a finite sample of pairs:
We often assume that these pairs are independent and identically distributed, abbreviated by i.i.d.:
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 pairs, and not only the entries, when the problem is supervised. In unsupervised learning, on the other hand, we observed only .
1.17.4 Class of hypotheses
A hypothesis is a candidate function that transforms entries into predictions:
We use because the format of the forecast may differ from the final target. In binary classification, for example, the target may belong to , while the model produces a probability in that will then be converted into class.
The hypothesis class is the set of functions among which the algorithm can choose:
represents the parameters of the model. For related functions,
We have . In a neural network, gathers all the weight matrices and bias vectors.
The choice of 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:
The first argument is the prediction ; the second is the target . In regression, a common choice is squared loss:
In the classification, the zero-one loss only registers if there was correctness:
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:
This amount is called empirical risk, error within the sample or training error. The accent on remembers that it is an estimate built from a finite sample.
An algorithm to minimize empirical risk seeks
The symbol returns the argument that minimizes the expression — in this case a function — and not the smallest value of the expression.
1.17.7 Learning algorithm
Formally, a learning algorithm transforms a sample into a hypothesis:
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 :
is called expected risk, true risk or error out of sample. As 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:
A model that memorizes the sample may have very small and still have large . 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 :
controls the balance between adjusting the data and prefer a simpler solution. In a linear model, 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
And we tried to get closer. . In the probabilistic case, we model
For regression with squared loss, the function that minimizes the expected risk is the conditional mean:
For binary classification, we can estimate
and choose the class when exceeds a threshold. The threshold does not need to be 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:
The sample contains measurements
We choose the class of related functions
And the squared loss.
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
| Symbol | Meaning |
|---|---|
| input space | |
| exit space or targets | |
| pair generator distribution | |
| finite training sample | |
| hypothesis class | |
| a candidate hypothesis or model | |
| parameters that determine a hypothesis | |
| loss in an example | |
| empirical risk calculated in the sample | |
| expected risk under distribution | |
| algorithm that transforms data into hypothesis |
1.17.13 Practice exercises
- For spam classification, identify , , , a class and a possible loss function.
- Explain why usually has domain, not .
- What is the difference between and ?
- Give an example where i.i.d. hypothesis is unreasonable.
- A model has a training error equal to zero. Does that prove that its expected risk is zero? Justify.
- Explain the role of in a regularized goal.
- In the example of runtime, propose a class of hypotheses suitable for an algorithm whose cost increases as .
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 , and the sample , 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 clinical features and represent a person by
Coordinates may include age, laboratory measurements, and symptom indicators.
with for present condition and for absent.
obtained from records for which there is a reference diagnosis.
Instead of directly producing a class, a hypothesis can estimate
interpreted as positive class probability. A decision rule converts this score into class:
The threshold should reflect the costs of false negatives and false positives. A weighted loss can assign cost to the first and to the second.
Is there still a question about : 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
and we use a representation function
The coordinate can record the count or frequency of a term.
The labelled sample is
A simple class of hypotheses is formed by linear classifiers:
is worth when the condition is true and otherwise. Each weight measures how the corresponding term influences the score.
The 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:
To predict default on a given horizon,
e
If we want a probability of default, we use hypotheses. The decision to grant credit may consider the expected cost:
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.
while the system will be applied to . 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,
If the target is “convoked or not summoned”, then 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:
In that case we have regression and we can use absolute loss,
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 pixels in gray tones can be vectorized:
The target is one among ten classes:
The sample is
A hypothesis can produce a probability vector
In this case, is the simplex of probabilities, while is the set of classes. The predicted class is . 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:
The temporal sample is
The indexes remember that the examples are not necessarily independent. A linear class can serve as a starting point:
Since the actual output cannot be negative, we can restrict the forecast using or choose a family of models with non-negative outputs.
1.18.7 Comparative view
| Problem | Prediction | Critical observation | ||
|---|---|---|---|---|
| Diagnosis | clinical features | probability in | error costs differ | |
| Spam | sparse textual vectors | class or probability | vocabulary changes with time | |
| Credit | financial features | probability | observed data are selective | |
| Sports | performance measurements | real class or value | depends on the target | label may not represent merit |
| Numbers | ten classes | ten probability vector | visual variation | |
| Demand | historical and context | real value | temporal dependence |
The table shows that writing is only the beginning. It is necessary to explain the meaning of the coordinates, the origin of , the population represented by and the cost encoded by .
1.18.8 Dimension and geometry
When , we can draw each example as a point in the plane. In three dimensions there is still a direct view. For , the geometric interpretation remains valid, although we cannot literally draw the entire space.
An email represented by terms is a point in . 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 and , 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:
- : What entries are allowed and how are they represented?
- : What is the observed target?
- : What object does the model really produce?
- : how was the sample collected and labeled?
- : Which population or future process do we want to represent?
- : What functions can the algorithm choose?
- : Which errors receive the highest penalty?
- : how will a hypothesis be chosen?
- 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
- Formalize a school drop forecast system specifying , , , and a loss.
- In digit recognition, why can and be different sets?
- Explain the selection bias present in historical credit data.
- Write a linear hypothesis for spam with three features and interpret each weight.
- Propose two different targets for sports analysis and tell us what kind of task each produces.
- For demand, explain why a time division is preferable to shuffle all examples.
- Choose one of the cases and describe a change in that could degrade the model after implantation.
1.19 Score
Many classifiers start by calculating a numerical score. The input is an attribute vector
and each coordinate receives a weight that expresses its contribution to the decision.
is the vector of weights and 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:
This function can also be written as
1.19.1 Weights and features
The sign of a weight indicates the direction of its influence, keeping the other features fixed:
- : increase increases score;
- : increase decreases score;
- : the attribute does not directly affect the score.
The magnitude indicates the sensitivity of the score to the coordinate, but its interpretation depends on the scale. A weight of applied to a variable measured in thousands can contribute more than a weight applied to a ratio between and . Therefore, comparing weights is only informative when we know the units or standardize the features.
The term moves the decision border. We can interpret the rule using a threshold:
The two forms are equivalent when .
1.19.2 Numerical example
Consider three fictitious profiles described by two already normalized features:
- : technical performance measurement;
- : consistency measurement.
We’ll use the score.
Weights show that in this specific rule, an additional unit of consistency contributes , while a technical performance unit contributes .
| Profile | score | Class | ||
|---|---|---|---|---|
| A | 4 | 5 | ||
| B | 7 | 2 | ||
| C | 4 | 2 |
The calculation is deterministic: fixed and , 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:
In two dimensions, this boundary is a straight line. In three dimensions, it is a plane. In dimensions, it is a hyperplane. On one side are the points with positive score; on the other, the points with negative score.

Figure 1.11. A linear score divides the feature space into two regions by means of a decision line.
The vector is perpendicular to the hyperplane and points to the side where the score increases. If we multiply and by the same positive number, the boundary and the classes do not change, although the scores are scaled.
In the example,
can be isolated as
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 standard, we obtain the signed distance from the point to the hyperplane:
The signal informs the border side; the module provides the perpendicular distance. In the example,
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
can take any real value and does not need to be between and . To get a quantity interpretable as probability, we can apply a logistic function:
This transformation preserves the order of scores: if , then . However, interpreting 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
We want to choose and to produce good predictions. A correct classification condition is
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 matrix containing examples on the lines, all scores are
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
- Calculate the score of the three profiles using and determine their classes.
- Rewrite the rule in form.
- For and , calculate and the signed distance from to the border.
- Explain why multiplying and by does not change the classes, but changes the scores.
- Give an example of a set of points in that is not linearly separable.
- What is the difference between a score, a class and a calibrated probability?
- 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.
-
If and , what is the set?
-
A function is injected when:
- every element of has exactly one pre-image.
- distinct elements of always produce different images.
- its image is necessarily equal to .
- its domain contains only real numbers.
-
For a function to have an inverse , it must be:
- constant.
- just injective.
- bijective.
- just superfluous.
-
What is the binary representation of the decimal number ?
-
A byte contains:
- 2 bits.
- 4 bits.
- 8 bits.
- 16 bits.
-
In addition to two with 8 bits, the integer range representable is:
- from to .
- from to .
- from to .
- from to .
-
In a supervised problem, the training set contains:
- only entries without any output information.
- pairs of input and target output.
- only rules written by a programmer.
- only future actions and rewards.
-
What alternative describes a regression task?
- Decide if a message is spam.
- Group customers without prior labels.
- Predict monthly energy consumption in kWh.
- Recognizing which digit appears in an image.
-
In the linear score, the vector determines mainly:
- the direction of the decision-making border.
- the number of examples of the sample.
- the numerical base used by the computer.
- the exact probability of any class.
-
Obtain zero error in training data necessarily means that:
- the model will have zero error in production.
- the problem is not supervised.
- the hypothesis adjusted the sample, but still needs to have its generalization evaluated.
- all the weights of the model are equal to zero.
Answer key with explanations
- b. The intersection contains only the elements present in the two sets; in this case, only .
- b. Injectivity prevents two distinct entries from being associated with Same exit.
- c. The inverse defined across the counterdomain requires injection and overjetivity, that is, bijectivity.
- c. , so its bits are .
- c. By definition, a byte has 8 bits.
- b. With bits in addition to two, the range is .
- b. Supervised learning uses examples in which the target output Follow the entrance.
- c. Consumption is a continuous numerical quantity; alternatives to and from they are classifications, and b is grouping.
- a. is normal to hyperplane and therefore controls its orientation; controls displacement.
- c. Training error measures adjustment to the observed examples, does not warrant performance in new data.