Linear Hypotheses
Linear models are among the most important tools of machine learning. They are mathematically simple, efficient and interpretable, but also serve as a basic block for more flexible models A unit of a neural network, for example, begins by calculating the same weighted sum we will study in this chapter.
The term linear does not mean that the final output needs to be a straight one. It means that the model starts by combining the input features with a linear score. For an example , we set
where is the weights and is the bias (bias) or intercept. Each weight expressed as a variation in the attribute corresponding changes the score, keeping the other features fixed.
Weight does not imply causality
A positive weight indicates a positive association within the model; it does not prove that the attribute causes the result. Observational data may contain spurious correlations, omitted variables and selection biases.
4.1 Overview of linear models
4.1.1 A common structure for three tasks
After calculating , we apply a output function:
The choice of adapts the same linear structure to different types of problem:
| Task | Output space | Transformation | Interpretation |
|---|---|---|---|
| binary classification | choose one of two classes | ||
| linear regression | provides for a quantity | ||
| logistic regression | estimates a probability |

Figure 4.1. The same linear score can feed three different output functions.
Consider a bank that represents each customer for income, debt, time employment history and payment history. Different questions:
- classification: should the application be approved?
- regression: which credit limit is appropriate?
- probability: what is the estimated probability of default?
The type of the target variable determines the appropriate model and error function. It makes no sense, for example, to interpret a regression directly linear as probability, because its output may be less than zero or Bigger than one.
4.1.2 Matrix notation and bias co-ordinate
We can incorporate into the weight vector by adding a coordinate input constant:
So (4.1) takes the compact form
The superscript indicates transposition. If the two vectors are treated as columns, is a row and the matrix product produces scalar
This “ trick ” simplifies formulas and implementations: the algorithm can update bias and weights with a single vector operation. however, it is important to remember that an example with features becomes represented by coordinates.
For a sample with examples, we organize entries in the lines of design matrix
The vector contains the scores at once examples. This formulation is central in numerical libraries, because replaces explicit links with optimized matrix operations.
4.1.3 Learning means choosing the weights
Whatever.
a labeled sample. For each vector , the model produces predictions . A loss function measures the cost of each prediction, and error empirical is usually the average
The learning algorithm seeks weights that reduce this error:
The three methods of this chapter differ in two main points: output function and loss used in optimization. Perceptron updates the weights when you find an example misclassified; linear regression minimizes squared error; and logistic regression minimizes a probabilistic loss.
4.1.4 Score geometry
The set of points with zero score,
is a hyperplane. In two dimensions it is a straight; in three, a plane. The vector is perpendicular to this hyperplane, while bias controls its displacement in relation to origin. The score sign indicates which side of the border the point is from. regression, the score itself represents the expected height.
This geometric interpretation also reveals a limitation: without transform features, a single linear frontier cannot separate patterns such as XOR. Later, features transformations and neural networks will allow to build nonlinear borders from linear components.
4.1.5 Feature scaling
The weights depend on the units adopted. If income is in pennies and age in years, the first coordinated may have magnitude millions of times greater. This can make optimization unstable and makes it difficult to compare weights. A common practice is to standardize each numerical attribute:
where and are calculated ** only in the set of training**. Using validation statistics or testing would introduce data leak.
4.1.6 What we’ll study
In the next sections, the same sequence will be repeated for each model:
- define the class of hypotheses;
- choose an error function;
- derive or present the optimization algorithm;
- implement the method computationally;
- discuss convergence, limitations and proper use.
In the end, it will be possible to recognize that Perceptron, linear regression and logistic regression are not isolated techniques. the same idea: ** combine features linearly and adapt output to type of question we wish to answer**.
4.2 Perceptron (or Linear Discriminant)
Perceptron is an algorithm for binary classification. It receives examples described by numerical vectors and learn a linear boundary which seeks to separate two classes. Although simple, the method introduces ideas that reappear in neural networks: weighted sum, function of iterative activation and updating of weights from errors.
Consider again the credit analysis. Each client is represented by features such as income, debt and employment time, and the historical label informs whether there has been payment () or default (). calculates a score
and compares this score with zero:
Adopting an explicit rule for the case of equality prevents stay undefined in the implementation. It would be possible, as long as it was used consistently.
4.2.1 Score Interpretation
The value contains more information than the final label. determines the class and its module indicates the algebraic distance to the threshold. Each component contributes to :
- if , higher values of raise the score;
- if , higher values of reduce the score;
- if , the attribute does not participate in the current decision.
This reading requires attention to the scale, a small weight associated with a attribute measured in thousands can have greater impact than a large weight associated with an attribute between zero and one. Therefore, the contribution is usually more informative than the isolated weight.
4.2.2 Geometric interpretation
The decision border contains the zero score points:
This set is a hyperplane perpendicular to the vector . positive scores stay in a semispace, and negative scores, The other one.

Figure 4.2. The Perceptron boundary separates the two semispaces; the weight vector is perpendicular to it.
In two dimensions, with and , we can write to border as a straight line:
Therefore, is the slope and is the vertical intercept. Change the direction of turns the border; change moves it without change your orientation.
4.2.3 What the algorithm learns
Given a sample
the objective, when the data are linearly separable, is to find the and such that
Why does this single inequality represent the two classes? , it requires positive score. If , multiply by reverses the signal and requires negative punctuation.
is called functional margin of the example: it is positive when the classification is correct and not positive when there is error or tie.
Perceptron doesn’t calculate the boundary in a single formula. the examples and, whenever you encounter an error, moves the parameters in the direction that favors the correct label. The following subsections will formalize the class of hypotheses, error and this update rule.
Fundamental hypothesis
The classic Perceptron converges on a finite number of updates only when the data is linearly separable. contradictory labels or an essentially nonlinear border, it The * Pocket* variant will treat this case.
4.2.4 Examples of application
- Spam filter: word frequencies form the input vector, and the score sign decides between spam and legitimate message.
- Quality control: measures of a part feed a decision between approved and defective.
- Assisted diagnosis: clinical features produce a screening binary, which should be evaluated with attention to false positive costs and false negatives.
In such examples, the automated decision should not be confused with a absolute truth. The model reproduces patterns present in the sample and can inherit your errors and biases. In high impact applications, metrics by sub-group, human review and data documentation are parts of the system, not optional details.
4.2.5 Hypothesis
A hypothesis is a classification rule obtained by fixing the model parameters. To avoid ambiguity between features originals and the constant coordinate, we will use a til in the representation homogeneous:
The product scale between two vectors column is
So,
This writing incorporates the bias in the same operation used for the others weights. It also avoids a common error of orientation: if and are size column vectors , so is sized and represents a scalar. would be a matrix , not the desired scalar product.
With the convention that draws receive the label, we define
Perceptron’s hypothesis class in is, then,
Note the difference between three objects:
- is the class of all borders Linears allowed;
- is a particular hypothesis, determined by a parameter vector;
- is the final hypothesis chosen by algorithm a from the data.
4.2.6 Equivalence of parameterisations
Some texts write the score as and call Others write and call bias. two forms are equivalent: just swap for . In this chapter, we will adopt the second convention to maintain compatibility with the usual regression notation and neural networks.
For example, in two dimensions,
has homogeneous vector . , we have and
So . For , the score is and the forecast is .
4.2.7 Positive scale invariance
If , the and vectors define exactly the same classification, as
So there are infinite vectors of parameters that represent the same Cross by a negative number, however, changes the sides and reverses all labels. This redundancy explains why the size gross does not alone determine the decision border.
4.2.8 Representation of a sample
If the homogeneous examples are stored on the lines of , all scores can be calculated by
The component application to component generates In NumPy, this idea essentially corresponds to the scores = X_tilde @ w_tilde, a matrix operation that will also guide the implementation of the algorithm.
Dimension test
Before implementing a formula, note the dimensions: é e é ; So the product is , a score for example.
4.2.9 Error
To evaluate a classification hypothesis, the most direct measurement is: Count how many predictions disagree with the labels. loss zero–one loss of an example is
where is worth when the proposition is true and when it is false. The total number of errors in the sample is
and the error rate within the sample is
The count and rate contain the same information when is fixed. is generally preferable because it remains between zero and one and allows compare samples of different sizes.
4.2.10 Error written with labels
As and belong to , their difference is zero in a hit and on an error.
The factor is indispensable: without it, each error would be counted as four. Therefore, an equivalent form of (4.6) is
This equivalence depends specifically on the encoding . With labels , the square of the difference is already worth a the mistakes.
4.2.11 Margin and condition of error
For Perceptron, it is more convenient to express the error before applying the signal function. Set the functional margin of the example by
With the convention adopted for draws, an example is certainly correctly classified when . When , it is in the wrong side of the border. In , the zero-one loss depends on the label and the tiebreaker rule. The classic algorithm adopts a more conservative and requests an update to any margin not positive:

Figure 4.3. The conservative update criterion changes abruptly when the margin crosses zero.
The module does not change this criterion: a correct rating by margin and another by margin receive zero loss. behavior is suitable for measuring accuracy, but provides little information for optimization.
4.2.12 Why not directly minimize zero-one loss?
The (4.7) step function is discontinuous at zero and constant at almost all other points. it exists and is not defined in the jump. gradient do not receive a useful direction to move the weights.
Perceptron bypasses this problem with a simple operating rule: selects an example with and adjusts the weights to increase your margin. This rule will be derived in the next subsection. Other models replace zero-one loss with continuous functions such as logistic loss or hinge loss.
4.2.13 Separability and minimum value
If there is for which for all , the sample is linearly separable and the minimum error rate is zero. the Perceptron convergence theorem ensures that the algorithm finds a finite number of updates solution.
If the data is not separable, then no class hypothesis reaches zero error. Classic Perceptron can visit different weight vectors That doesn’t mean everyone’s equally good: Some make fewer mistakes than others. The * Pocket* variant will store in “bag” the best vector observed during execution.
Training error is not generalization error
Even when , it is still necessary to evaluate the hypothesis in data not used in the adjustment. sample by chance, especially when there are few examples or many features.
4.2.14 Accuracy and asymmetric costs
Accuracy is , but it does not always summarize the objective of In medical diagnosis, no longer detecting a disease may be more serious than generating a false alarm; in spam filters, block a legitimate message can have high cost. In these cases, besides the rate of error, the matrix of confusion, precision, recall and a cost function consistent with the problem.
Quick check
Consider true labels and predictions . There are two errors in four examples, therefore , and accuracy is . By quadratic formula, the sum of the squares is ; By dividing by , we get again.
4.2.15 Algorithm
The Perceptron algorithm builds the parameters by local corrections. We start with a vector, often . In iteration , we chose an example whose margin is not positive:
Then we update.
in which is the learning rate. In the classic Perceptron, is sufficient; leaving the explicit parameter helps to interpret the size of the step and approximates the notation used in other methods.
4.2.16 Why does the update point to the right side?
If , we add to the weights, increasing the punctuation of this example. If , subtract , reducing your score. In both cases, the new margin is
We use . Like and , the margin of the selected example always It’s going up.

Figure 4.4. An update increases the margin of the example that caused the correction.
This warranty is local: the update can reduce the margin of others examples and even make a proper prediction before become incorrect. convergence theorem does not state that the number of errors decreases with each step; states that, under separability, this process of corrections does not It can go on forever.
4.2.17 Updating bias and weights separately
Like and , (4.9) equals
This form is useful when implementation stores separate bias. the features are transformed or standardised, the constant coordinate It should not be normalized with them.
4.2.18 Pseudocode
input: sample D, rate η > 0, time limit
initialize w and b
for each season:
_Other Organiser
for each (x_n, y_n) in D:
margin ← y_n (wT x_n + b)
if margin ≤ 0:
w ← w + η y_n x_n
b ← b + η y_n
_Refreshes number ←_of_updates number + 1
if_of_updates = 0:
close: all examples have positive margins
Return w and b
A season is a complete passage through the sample. updates provides a more reliable stop criterion than check if the vector has changed “little”: in Perceptron, no updates during an era means that all the examples have been classified correctly according to the criteria adopted.
4.2.19 Order of examples
The solution found is not unique and may depend on the order in which the examples are presented. In practical implementations, it is common shuffle the sample every season. This avoids artificial patterns in the data order and can accelerate convergence, although it does not alter the mathematical hypothesis of separability.
There are two frequent selection variants:
- online or stochastic: updates immediately when finding each error;
- by chosen error: locates some incorrect example, update and Reboot the search.
Both follow the same fundamental rule. natural for data received in flow.
4.2.20 Learning rate and initialization
For separable data and constant positive rate, change or to initialization scale often changes the numerical representative, But not the essence of the search for a frontier. extremes can cause floating point problems. Initializing at zero is valid for a single Perceptron, unlike neural networks with several symmetric units.
Always impose an execution limit
If the sample is not separable, the criterion “stops when there is no errors” may never be satisfied. A robust implementation receives a maximum number of times or updates and records the best solution observed.
4.2.21 Convergence is not generalization
When the algorithm ends with zero errors, all we know is that it’s found a border consistent with the sample. Performance in new examples depends on the representativeness of the data and the complexity of the class. convergence is a property of the optimization procedure; generalization is a statistical property evaluated outside the set of training.
4.2.22 Code
An implementation should make explicit decisions that pseudocode mathematicians usually omit: data format, criterion for draws, time limit, shuffle and information returned to the user. The code below uses NumPy and stores bias separately from the weights.
from dataclasses import dataclass
import numpy as np
@dataclass
class ResultadoPerceptron:
pesos: np.ndarray
vies: float
epocas: int
atualizacoes: int
convergiu: bool
erros_por_epoca: list[int]
def treinar_perceptron(
X,
y,
*,
taxa=1.0,
max_epocas=1_000,
embaralhar=True,
semente=0,
):
"""Treina um classificador Perceptron binário.
X deve ter forma (n_exemplos, n_atributos) e y deve conter
somente os rótulos -1 e +1.
"""
X = np.asarray(X, dtype=float)
y = np.asarray(y, dtype=int)
if X.ndim != 2:
raise ValueError("X deve ser uma matriz bidimensional")
if y.ndim != 1 or len(y) != len(X):
raise ValueError("y deve ter um rótulo para cada linha de X")
if not np.all(np.isin(y, (-1, 1))):
raise ValueError("os rótulos devem pertencer a {-1, +1}")
if taxa <= 0 or max_epocas <= 0:
raise ValueError("taxa e max_epocas devem ser positivos")
rng = np.random.default_rng(semente)
pesos = np.zeros(X.shape[1], dtype=float)
vies = 0.0
atualizacoes = 0
erros_por_epoca = []
for epoca in range(1, max_epocas + 1):
indices = np.arange(len(X))
if embaralhar:
rng.shuffle(indices)
erros = 0
for i in indices:
margem = y[i] * (X[i] @ pesos + vies)
if margem <= 0:
pesos += taxa * y[i] * X[i]
vies += taxa * y[i]
erros += 1
atualizacoes += 1
erros_por_epoca.append(erros)
if erros == 0:
return ResultadoPerceptron(
pesos, vies, epoca, atualizacoes, True,
erros_por_epoca
)
return ResultadoPerceptron(
pesos, vies, max_epocas, atualizacoes, False,
erros_por_epoca
)
Using named arguments after * reduces mistakes like changing the rate learning by the number of seasons. The seed makes shuffle reproducible, something important in experiments and purification.
4.2.23 Prediction
Training and prediction should be separate functions. This allows you to apply the same parameters to training, validation and testing sets.
def prever_perceptron(X, pesos, vies):
X = np.asarray(X, dtype=float)
pontuacoes = X @ pesos + vies
# Same chapter convention: tie receives +1.
return np.where(pontuacoes >= 0, 1, -1)
def taxa_de_erro(y_real, y_predito):
y_real = np.asarray(y_real)
y_predito = np.asarray(y_predito)
return np.mean(y_real != y_predito)
4.2.24 Reproducible example
X = np.array([
[-2.0, 4.0],
[ 4.0, 1.0],
[ 1.0, 6.0],
[ 2.0, 4.0],
[ 6.0, 2.0],
])
y = np.array([-1, -1, 1, 1, 1])
resultado = treinar_perceptron(
X,
y,
taxa=1.0,
max_epocas=1_000,
embaralhar=True,
semente=42,
)
predicoes = prever_perceptron(
X, resultado.pesos, resultado.vies
)
print("pesos:", resultado.pesos)
print("viés:", resultado.vies)
print("convergiu:", resultado.convergiu)
print("erro de treino:", taxa_de_erro(y, predicoes))
If resultado.convergiu is false, the last one should not be interpreted vector as necessarily the best. It is only the state in the instant The section on the algorithm * Pocket* will show you how to save the smallest error parameters.
4.2.25 Two-dimensional view
When there are exactly two features and , the border can be drawn as :
import matplotlib.pyplot as plt
def desenhar_fronteira_2d(X, y, pesos, vies):
fig, ax = plt.subplots()
positivos = y == 1
ax.scatter(
X[positivos, 0], X[positivos, 1],
marker="o", label="+1"
)
ax.scatter(
X[~positivos, 0], X[~positivos, 1],
marker="x", label="-1"
)
limite_x = np.array(ax.get_xlim())
if not np.isclose(pesos[1], 0.0):
limite_y = -(pesos[0] * limite_x + vies) / pesos[1]
ax.plot(limite_x, limite_y, label="fronteira")
else:
ax.axvline(-vies / pesos[0], label="fronteira")
ax.set_xlabel("atributo 1")
ax.set_ylabel("atributo 2")
ax.legend()
return fig, ax
desenhar_fronteira_2d(
X, y, resultado.pesos, resultado.vies
)
plt.show()
The pesos[1] == 0 case deserves its own treatment, because the border is vertical and the slope formula would divide by zero.
Avoid leakage in preprocessing
If the features are standardized, mean adjustment and deviations only in the Training data. Then apply the same transformation to the data from validation, testing and production.
Questions to try
- Perform training with different seeds. Final weights are The predictions in the sample are the same?
- Remove
max_epocasfrom a naive implementation and insert two identical examples with opposite labels. What happens? - Compare the
erros_por_epocahistory with the calculated error rate after each period. Why the number of updates during a Doesn’t season have to be equal to the error of parameters at the end of it?
4.2.26 Example in two steps
We’ll follow up on a case small enough to check each account. Consider the two-dimensional points
In the homogeneous representation,
Choose as Start Status . The first coordinate is bias; both remaining are the features weights. The initial border satisfies
I mean, .
Step 1: Find error
The initial scores are
The point is positive and received positive score, so it is The point is negative, but it also received a positive score. Your margin confirms the error:
Step 2: Update and Verify
With rate , we use to update:
The new border is
Now, the scores are
Therefore, receives and receives . A single update was Enough to separate the sample.

Figure 4.5. The correction caused by q transforms the horizontal border into a straight line that separates the two points.
We can directly check the identity of the margin improvement. ,
which matches with .
Why does the title say two steps?
The two steps are to diagnose the incorrect example and apply the There’s only one way. a weight update. Distinguish iteration, update and season avoids confusion when analyzing the execution time.
Extension exercise
Redo accounts starting with and going through first and then . Register, after each update, the scores, the margins and the boundary equation.
4.2.27 Execution Time
There are two different costs to consider: the cost of a operation and the number of operations until convergence.
For an example with features, calculate costs . A passage by examples costs ; therefore, run eras has cost and requires memory for the parameters, besides the memory used to store or transmit the data.
This calculation does not inform how much is worth. Perceptron convergence theorem provides a bound for the number update, based on sample geometry.
4.2.28 Radius and margin
We’ll use the homogeneous vectors to include bias. Suppose there is a unit vector , with , that separate the sample with margin :
Set also the radius
As is unitary, is the distance signed from point to hyperplane . The margin is the smallest distance signed after fixing the side with ; is the nearest point that limits the clearance of the separation.

Figure 4.6. The margin is determined by the closest examples to the border.
To a border in non-standard form , the geometric distance of a point is
The denominator is , not . This formula stems from the projection on the normal direction . Remembering the product climb,
where is the angle between vectors.
4.2.29 Convergence theorem
Perceptron convergence theorem
Consider , rate and a sample that satisfies (4.11) and (4.12). Perceptron commits maximum
updates before finding a correct separation.
The bound depends on the ratio . A large margin facilitates the problem; examples with very large standards increase the bound. helps to understand why scaling features can improve the Numerical behavior.
4.2.30 Proof sketch
After updates, each caused by , we have
Projecting the accumulated vector over the direction of the solution,
By Cauchy-Schwarz and ,
Now we limit the growth of the standard. How an update occurs when ,
Adding updates,
The argument shows a contrast: alignment with the solution grows linearly in , while the norm grows at most as . If updates continued beyond bound, both inequalities would be incompatible.
4.2.31 What the bound doesn’t say
- It limits updates, not necessarily epochs. An era may contain none, one or several updates.
- It is a worst case bound; real execution can end much earlier.
- It requires separability with positive margin. Separate, there’s no guarantee of termination.
- She doesn’t claim that the Perceptron finds the border of maximum margin. Methods such as support vector machines pursue this goal of explicit form.
- It is not a guarantee of generalization; it only proves convergence in the training set.
4.2.32 Relationship with the total cost
In online mode, each example costs and the theorem limits the amount of corrections to . However, find a time without errors still requires checking the examples. For an implementation by times, the most transparent measure remains
recording separately and the total number of updates. distinction avoids interpreting the theoretical bound as if it were directly the program clock time.
Exercises
- What happens to bound if all input vectors are multiplied by a positive constant ? Consider also how The margin changes.
- Show which step of the demonstration the separability is used.
- One execution made 80 updates in 12 seasons. Which of these numbers can be directly compared with ?
4.2.33 Animation
An animation helps undo a misleading interpretation: Perceptron does not move the border continuously towards an ideal line. error, it jumps into a new parameter vector. to translate and even incorrectly reclassify a point that was Correct.
In order to monitor the process, each table shall show at least:
- points and their true labels;
- the current border ;
- the example that led to the update;
- the number of the time and update;
- the error rate or number of errors of the current parameters.
4.2.34 Registering frames
The generator below is a compact version of the training. It produces a status after each correction, without storing all frames At the same time.
import numpy as np
def quadros_perceptron(X, y, max_epocas=100):
X = np.asarray(X, dtype=float)
y = np.asarray(y, dtype=int)
w = np.zeros(X.shape[1])
b = 0.0
atualizacao = 0
# Initial table.
yield {
"epoca": 0,
"atualizacao": 0,
"indice": None,
"w": w.copy(),
"b": b,
}
for epoca in range(1, max_epocas + 1):
houve_atualizacao = False
for i, (x_i, y_i) in enumerate(zip(X, y)):
if y_i * (w @ x_i + b) <= 0:
w += y_i * x_i
b += y_i
atualizacao += 1
houve_atualizacao = True
yield {
"epoca": epoca,
"atualizacao": atualizacao,
"indice": i,
"w": w.copy(),
"b": b,
}
if not houve_atualizacao:
return
The copy() method is important. Without it, all the dictionaries could refer to the same changeable vector and appear to contain only the final state. This is a frequent error when registering numerical history in Python.
4.2.35 Building animation
For two-dimensional data, we can turn the states into one. animation with matplotlib.animation.FuncAnimation:
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
def animar_perceptron(X, y, max_epocas=100, intervalo=700):
estados = list(quadros_perceptron(X, y, max_epocas))
fig, ax = plt.subplots()
positivos = y == 1
ax.scatter(X[positivos, 0], X[positivos, 1], label="+1")
ax.scatter(
X[~positivos, 0], X[~positivos, 1],
marker="x", label="-1"
)
destaque = ax.scatter([], [], s=180, facecolors="none",
edgecolors="black")
fronteira, = ax.plot([], [], color="black")
titulo = ax.set_title("")
ax.legend()
xmin, xmax = ax.get_xlim()
ymin, ymax = ax.get_ylim()
eixo_x = np.array([xmin, xmax])
def atualizar(estado):
w, b = estado["w"], estado["b"]
if not np.isclose(w[1], 0.0):
eixo_y = -(w[0] * eixo_x + b) / w[1]
fronteira.set_data(eixo_x, eixo_y)
elif not np.isclose(w[0], 0.0):
x_vertical = -b / w[0]
fronteira.set_data([x_vertical, x_vertical], [ymin, ymax])
else:
fronteira.set_data([], [])
i = estado["indice"]
destaque.set_offsets(
np.empty((0, 2)) if i is None else X[[i]]
)
titulo.set_text(
f"época {estado['epoca']} · "
f"atualização {estado['atualizacao']}"
)
return fronteira, destaque, titulo
animacao = FuncAnimation(
fig,
atualizar,
frames=estados,
interval=intervalo,
repeat=False,
)
return fig, animacao
In a notebook, the result can be displayed as HTML:
from IPython.display import HTML
fig, animacao = animar_perceptron(X, y)
plt.close(fig)
HTML(animacao.to_jshtml())
To save in GIF or video, Matplotlib needs a writer compatible installed in the environment. The to_jshtml() display prevents this dependence and is usually enough for didactic experiments.
4.2.36 What to Watch
When performing the animation, answer:
- Does every update reduce the total number of errors?
- Is the highlighted example correct immediately after your update?
- How many updates do you have in each season?
- Does the final frontier change when the order of examples changes?
- Does behavior become more stable after standardizing the features?
Animation is not proof
Visualization produces intuition and helps debug an implementation, but shows only one sample and one order of presentation. convergence comes from the mathematical argument of the previous section.
4.2.37 The Pocket Algorithm (= pocket)
The classic Perceptron is designed to find a separation perfect. When the sample is not linearly separable, its updates continue, and the last vector visited may be worse than vectors found previously. Pocket algorithm adds memory to the process: it keeps in the “bag” the parameters with the lowest error observed until then.
This modification is useful when there is measurement noise, incorrect labels, contradictory examples or a true nonlinear border. cases, requiring is impossible or undesirable.
Current and saved state
Pocket maintains two distinct vectors:
- , which continues to receive updates Perceptron;
- , which represents the smallest error of training found until that moment.
After each update of the current state, we calculated
If the new error is smaller than the saved error, we copy the parameters to the pocket. As the best state is replaced only by another better, your sequence of errors is monotonically non-growing, even if the state Oscile current.

Figure 4.7. The current state may worsen, while the smallest error saved by Pocket never increases.
It is indispensable to copy the vector. In Python, the assignment melhor_w = w can only create another reference for the same array; future updates would also change the contents of the pocket.
Pseudocode
initialize w_current
w_best ← copy of w_current
best_error ←_of_training error(w_better)
repeat until you reach the update limit:
choose an example with non-positive margin
if none exists:
close: error zero has been reached
apply a Perceptron update to w_current
current_error ←_de_training error(w_current)
if current_error < best_error:
w_best ← copy of w_current
error_better ← current_error
Return w_better
An update limit is part of the specification, not just a accidental protection: in non-separable data, there is no instant natural in which the Perceptron necessarily stops.
Implementation
import numpy as np
def erro_classificacao(X, y, w, b):
predicoes = np.where(X @ w + b >= 0, 1, -1)
return np.mean(predicoes != y)
def treinar_pocket(
X,
y,
*,
max_atualizacoes=10_000,
taxa=1.0,
semente=0,
):
X = np.asarray(X, dtype=float)
y = np.asarray(y, dtype=int)
rng = np.random.default_rng(semente)
w = np.zeros(X.shape[1])
b = 0.0
melhor_w = w.copy()
melhor_b = b
melhor_erro = erro_classificacao(X, y, w, b)
for atualizacao in range(1, max_atualizacoes + 1):
margens = y * (X @ w + b)
candidatos = np.flatnonzero(margens <= 0)
if len(candidatos) == 0:
return melhor_w, melhor_b, melhor_erro, atualizacao - 1
i = rng.choice(candidatos)
w += taxa * y[i] * X[i]
b += taxa * y[i]
erro_atual = erro_classificacao(X, y, w, b)
if erro_atual < melhor_erro:
melhor_w = w.copy()
melhor_b = b
melhor_erro = erro_atual
return melhor_w, melhor_b, melhor_erro, max_atualizacoes
This version randomly chooses a problematic example. Using a Seed allows you to reproduce the trajectory. In case of a tie in the error, we could keep the older vector, prefer the higher average margin or use a validation criterion; the decision must be documented.
Computation cost
An update costs , but recalculate the error on all examples cost . If this evaluation occurs after each of the updates, the cost is . Therefore implementations for bases large can evaluate the pocket at every certain number of steps or keep These optimizations change the frequency with which Good states can be registered.
What Pocket guarantees — and what it does not guarantee
The algorithm returns a ** solution no worse than any state it have saved** according to the criteria used. However:
- it does not guarantee finding the global minimum of zero-one loss;
- more iterations expand the search, but do not establish when the great was found;
- choosing by the training error does not guarantee the slightest error outside the sample;
- repeatedly test on test set to decide the pocket cause data leak.
If we want to choose the number of updates or unmatch templates based on external performance, we should use a validation set and reserve the test for the final evaluation.
Perceptron versus Pocket
| Aspect | Classic Perceptron | |
|---|---|---|
| status returned | last state | best observed state |
| separateable | converge to zero error | can also achieve zero error |
| non-separable | can oscillate | returns a found approach |
| extra memory | for additional copy | |
| error assessment | is not required at every step | usually costs |
| guarantee of great global | no | no |
The pocket preserves, but does not optimize alone
The merit of Pocket is not to lose a good solution during a trajectory The final quality still depends on the states exploited by the Perceptron, update budget and order of examples.
4.2.38 Review
Perceptron brings together in a single example several fundamental ideas of machine learning. Data provides labeled examples; a class of hypotheses delimits the permitted borders; an error measure assesses predictions; and an algorithm adjusts parameters based on examples in that the current hypothesis fails.
Section Map
| Element | Perceptron formulation |
|---|---|
| entry | |
| label | |
| score | |
| hypothesis | |
| border | |
| functional margin | |
| update condition | |
| update | , |
| empirical error | mean |
| convergence hypothesis | linearly separable sample |
| update bound |
The vector is perpendicular to the border, while controls its offset. Adding a constant coordinate allows you to write both as a single homogeneous vector .
The flow of training
- Initialize the parameters.
- Calculate the margin of an example.
- If the margin is not positive, update in the direction .
- Repeat until you complete a time without updates or reach the limit of execution.
- Evaluate the resulting hypothesis in data that did not participate in the adjustment.
For separable data, Perceptron ends with zero training error. For non-separable data, the current state can oscillate; Pocket preserves the state of least error found during a finite execution.
Four conclusions that are not valid
- An update does not need to reduce the total sample error.
- Converging does not mean finding the border of greater margin.
- Zero training error does not imply zero test error.
- A large module weight does not prove that the attribute is causally important.
Conceptual issues
- What is the difference between zero-one loss and the update criterion based on non-positive margin?
- Why correctly represents the two classes in a single inequality?
- What happens geometrically when we change only ? And when Do we alter the direction of ?
- Why the
melhor_w = wassignment can invalidate an implementation Pocket in NumPy? - On what hypothesis does the convergence theorem depend? Give an example of sample that violates this hypothesis.
- Does the number of errors necessarily decrease after each update? Justify with the local nature of the rule.
Application problems
- An update. For , , , and , calculate the margin. Determine if there is update and, if any, get the new parameters.
- Border. Write the line equation defined by and . Identify slope and intercept.
- XOR. Represent the four binary points , labeling the odd parity as positive. Explain geometrically why a single straight line does not separate classes.
- Complexity. A base has examples and features. How many weight-attribute products are needed, approximately, for ten complete seasons?
- Cota. If and , calculate the bound for updates. Explain why the value does not predict exactly the time observed.
Brief answers to the conference
- In the first problem, the score is , the margin is and there is no update.
- The straight line is , or .
- In XOR, equal classes occupy opposite vertices; any line leaves at least one vertex on the incompatible side.
- Ten seasons require approximately multiplications, plus sums and others Costs.
- The bound is updates and represents a worst case under the theorem’s hypotheses.
With this consolidated vocabulary, we can move from binary decision to binary decision. the prediction of real values. Linear regression will keep the score , but will replace the signal function and the rule of update by a distinguishable error function.
4.3 Linear Regression
The classification answers categorical questions such as “approve or reject?” Many systems, however, need to predict a quantity: the energy consumption in the next hour, the execution time of a programme, the price of a property or the credit limit appropriate to a customer. linear regression is the simplest model for this type of output.
In a regression problem, each example is a pair
where contains the features and is the target value observed. sample is
The model assigns to each input a real forecast
The “hat” symbol distinguishes the forecast from the observed value . Difference
is the residual example of . Positive residual means the model predicted below the observed value; negative residual means that predicted above.

Figure 4.8. Regression chooses a straight line that approximates the observed values; the traced segments are residuals.
4.3.1 From lines to hyperplanes
With a single attribute, (4.15) describes a straight line:
The weight is the slope: increase in a unit changes the forecast in units. The bias is the prediction when , although this interpretation is only relevant if zero makes sense in the field.
With two features, the forecast graph is a plan; with features, It’s a dimension hyperplane. directly when is large, but algebra remains the same.
4.3.2 An example: runtime
Suppose we want to predict the time of an algorithm from the size input and a density measure. A possible model is
For and , the forecast is
If the observed time is seconds, the residual is second. A single difference does not determine the quality of the model; we need to summarize the residuals of the entire sample.
4.3.3 What does “best-fit line” mean?
In general, no line goes through all the points. We need to define how compare positive and negative errors and penalize large deviations. Classical linear regression chooses the parameters that minimize the sum or the average square waste:
The square prevents cancellation between signals and heavily penalizes errors It also produces a differentiable and convex function of the parameters, allowing to obtain a global solution by linear algebra or by iterative methods.
Linear in parameters
A regression may include transformed features and continue linear parameters. For example, is curved in , but it is linear in the vector when we use features.
4.3.4 Prediction, association and causality
A positive coefficient indicates that, within the model and keeping others constant features, higher values of that attribute are associated This shows no causality. use useful correlations to predict even when not identifying the process that generates the result.
In credit, health or public policy decisions, this distinction is critical: historical data may reflect inequalities, human decisions Predictive performance should be analyzed. along with data origin, metrics per subgroup and consequences of the use of the model.
4.3.5 Assumptions and initial limits
Linear regression is an appropriate approach when a combination linear captures relevant part of the signal. Common problems include:
- nonlinearity: waste exhibits a systematic pattern;
- atypical values: the square gives high influence to large errors;
- extrapolation: predictions away from the observed range can be implausible;
- multicollinearity: almost redundant features make coefficients unstable;
- distribution change: relationships learned in the past may not persist in production.
The next subsections formalize the hypothesis class, the error function and the two main paths to calculate the parameters: solution algebraic for least squares and iterative optimization.
4.3.6 Hypothesis
In this subsection, hypothesis means a candidate function within the model class. It should not be confused with statistical hypotheses about noise, independence or variance that can be used to make Inference on the coefficients.
For features, the linear regression class with intercept is
Each choice of defines a different hypothesis. learning will select one of them using the sample.
4.3.7 Homogeneous representation
As in the Perceptron, we can introduce
and write
The order of the product is only a convention when both represent vectors and the result is scalar. To maintain consistency with the matrix of the project, we will treat each homogeneous example as a line vector. in abstract notation corresponds to a line multiplied by the column vector of parameters in the implementation.
More precisely, if is defined as column vector, we use ; if it is stored as line, transposition is already implicit. dimensions, do not decorate the position of a superscript.
4.3.8 From the individual hypothesis to the design matrix
We organize the examples in the lines of the design matrix:
The target vector is
and the forecast vector of a hypothesis is
The dimensions confirm the operation:
Each line of multiplication reproduces .
4.3.9 Residual vector
Gathering the waste from all the examples,
The least square regression will choose to make the small standard. Geometrically, it measures deviations in the direction of the output axis , not the smallest perpendicular distance between each this distinction is important: the usual linear regression assumes that the features are given and the error is associated with the variable of exit.
4.3.10 The role of each coefficient
Stop
the coefficient is the variation in the prediction caused by increasing the in a drive keeping the other features constant. Your units are
If is measured in real and in square meters, for example, is measured in real per square meter. Standardizing features changes to numerical scale of coefficients, but no need to change predictions after the correct inverse transformation.
Intercept should not be removed automatically
Force forces the hyperplane to pass through the source. justifiable when problem theory requires zero output for input zero. Otherwise, the restriction may introduce systematic bias in the waste.
4.3.11 Linearity and Feature engineering
The class can be enriched by replacing with a vector of features :
With , we get a quadratic polynomial regression. binary indicators, we can represent categories; with products , we can represent interactions. parameters , although the relation to the original input can be curved.
This flexibility has cost: adding many features increases the model capacity, memory consumption and the risk of overfit. Transformations should be defined using only available information at the moment of the forecast.
Computing verification of shapes
import numpy as np
X = np.array([
[100.0, 0.2],
[250.0, 0.7],
[400.0, 0.9],
])
y = np.array([1.8, 5.2, 7.1])
X_tilde = np.column_stack([np.ones(len(X)), X])
w_tilde = np.array([0.4, 0.015, 1.8])
y_predito = X_tilde @ w_tilde
residuos = y - y_predito
print(X_tilde.shape) # (3, 3)
print(w_tilde.shape) # (3,)
print(y_predito.shape) # (3,)
In NumPy, an array with shape == (3,) is not explicitly line or column. The operator @ applies the appropriate rules, but when combining more complex matrices, declare ways how (3, 1) can make the I think it’s a clearer intention.
4.3.12 Error
The error function transforms a residual vector into a single number. classical linear regression, we used the mean squared error (* mean Squared error*, MSE:
The word “medium” corresponds to factor . There is no integral on the finite sample; there is an empirical average of individual losses.
The square plays three roles:
- makes all terms non-negative, preventing cancellation between positive and negative waste;
- penalises large wastes more intensely;
- produces a smooth and convex function of the parameters.
4.3.13 Sum, mean and root of squared error
sum of waste squares is
How and does not depend on parameters, SSE and MSE have exactly the same minimizers. values, however, are not interchangeable when reporting results.
The root of the MSE is
MSE has units, while RMSE has the same target units. If the target is measured in seconds, for example, the RMSE is also expressed in seconds and it’s usually easier to interpret.
4.3.14 Matrix form
By (4.19),
The Euclidean Standard Satisfys
Thus, (4.20) can be written in a compact way:
Expanding the product,
This is a quadratic function of . Its Hessian matrix is proportional to , which is positive Semi-defined. So every local minimum is global. The uniqueness will depend the post of the design matrix, subject of the subsection on the algorithm.
4.3.15 MSE versus MAE
Another common measure is the mean absolute error (* absolute error*, MAE:

Figure 4.9. Squared loss assigns increasing influence to large-module waste.
| Property | MSE/RMSE | M.E. |
|---|---|---|
| loss growth | quadratic | linear |
| sensitivity to atypical values | larger | minor |
| 0-differentiability | Yeah. | no |
| associated central estimate | conditional average | conditional median |
| reported unit | MSE: square; RMSE: original | original |
No metrics are universally superior. The choice should reflect the actual cost of errors. If double error should cost four times more, the square is coherent; if the cost grows approximately linearly, the MAE can best represent the application.
4.3.16 Effect of an atypical value
Consider waste.
while
The last example answers by of the sum quadratic. This may be desirable when big mistakes are really severe, or harmful when the point results from measurement failure. Atypical values should be investigated, not removed automatically.
4.3.17 Coefficient of determination
A complementary metric is
where is the average of the targets of the evaluated set. numerator is the model error and the denominator is the predictor error constant .
- indicates perfect predictions in that set;
- indicates performance equal to the mean predictor;
- means that the model is worse than this reference predictor.
Therefore, is not a percentage of correct predictions and does not need to be between zero and one in test data.
4.3.18 Correct assessment
Training metrics measure adjustment, not generalization. MSE, RMSE, MAE and should also be calculated on data not used in training. When comparing models, use the same partition and the same preprocessing.
Do not choose the metric after seeing the result
Selecting the metric that makes a model look better introduces bias in the evaluation. In advance define the main measure on the basis of the cost of application and use secondary metrics for diagnosis.
Computational verification
import numpy as np
y = np.array([3.0, 5.0, 7.0, 20.0])
y_predito = np.array([2.0, 6.0, 5.0, 10.0])
residuos = y - y_predito
mse = np.mean(residuos ** 2)
rmse = np.sqrt(mse)
mae = np.mean(np.abs(residuos))
print(f"MSE = {mse:.2f}")
print(f"RMSE = {rmse:.2f}")
print(f"MAE = {mae:.2f}")
In the next step, we will minimize (4.21) to obtain the regression coefficients.
4.3.19 Algorithm
Training linear regression means solving the minimal problem square
We write because the result is the set of parameters that reach the lowest value. When the solution is unique, we can treat it as a single vector .
The factor does not change the minimizer, so leads can working with the sum of squares. It remains important when comparing the error value between samples of different sizes.
4.3.20 Solution Overview
Under conditions which ensure the inversibility of , the solution can be written as
This expression is called solution normal equations. It will be obtained in two ways:
- geometrically: is the projection orthogonal over the space generated by the columns of ;
- by differentiation: at least, the error gradient relative to parameters are zero.
The two arguments produce the same condition:
This equation says that the residual vector is orthogonal to each column of the design matrix. In particular, when there is a column of one for the intercept, the sum of training waste is zero, except for effects of numerical rounding.
4.3.21 Math formula versus numerical algorithm
It is tempting to directly implement the reverse of . In numerical software, this rarely is the best option. Forming the product can worsen the conditioning, and calculating an explicit inverse performs work It’s unnecessary.
Usual strategies include:
- solve the linear system of normal equations without forming the inverse;
- use QR factoration, usually more stable;
- use singular value decomposition (SVD), which also treats disabled and produces pseudo-inverse;
- apply downward gradient or stochastic methods when matrix It’s too big for the direct solution.
Thus, “linear regression has closed formula” does not mean that all implementation should calculate this formula literally.
4.3.22 When is the solution unique?
If columns of are linearly independent, So…
and is defined positive and Invertible. In this case, the minimizer is unique.
If there is a redundant column, more features than independent information or categories coded redundantly, the matrix may have put There are still least square predictions, but several coefficients vectors can produce the same adjustment. Moore–Penrose selects, among them, the lowest standard solution.
Never use reverse as a test of existence
If
inv(X.T @ X)fails, this does not mean that regression cannot be adjusted. Use a least square solver such asnumpy.linalg.lstsq, which deals with rectangular matrices and informs the Estimated rank.
4.3.23 Complexity in general
For examples and parameters, storing the dense matrix costs . A direct solution per QR typically costs when plus of auxiliary memory. In problems with many examples or many sparse features, iterative methods can be more suitable.
It is also necessary to consider conditioning. Features in scales very different or almost collinear can make the coefficients extremely sensitive to small disturbances, even when the calculation ends without error.
4.3.24 Transposition and dimensions
For , the transposed exchanges rows for columns. No our problem,
Therefore, normal equations form a square system with unknown. Annotating these dimensions is a simple error check code guidance and demonstrations.
The following two subsections first develop the interpretation by projection and then derivation by gradient.
Projection Approach
The interpretation by projection occurs in , the space that has a coordinate for each example. The target vector
for each choice of parameters, the vector of the vector is a point in this space. predictions is . Which forecast vectors are possible?
The space column
Write the design matrix in terms of your columns:
So…
Therefore, the set of all possible predictions is the space generated by the columns of :
Even if the model has few parameters, each forecast on the whole sample is a vector with components. of the original figure in the attribute space and the column space used in this derivation are different objects.
The optimal prediction is a projection
Minimize
means find the point more near . This point is orthogonal projection .

Figure 4.10. The target vector is decomposed in the prediction, which belongs to the column space, and the orthogonal residual.
The Great Residual
is perpendicular to every vector of the column space. In particular, it is perpendicular to each column of :
By replacing the residual definition,
and we get the normal equations
Why does orthogonality guarantee the minimum?
Consider any other parameter vector . Your residual is
The first term is perpendicular to the column space, and the second belongs By Pythagoras’ theorem,
Therefore, no other possible prediction is closer to . equality can occur for only if , that is, if the matrix has a non-trivial core And the parameters aren’t unique.
Full post case
If the columns of are linearly independent, is invertible. Isolating parameters in (4.26),
The projection matrix over the column space is, in this case,
Because . She’s satisfied.
symmetry and idempotence properties characteristic of a projection orthogonal.
Deficient position and pseudo-inverse
Having does not guarantee column independence. Two features can be duplicated or one can be combination of the others. is not invertible, we use Moore’s pseudo-inverse–Penrose:
In this case, should not be automatically defined by , because this expression requires precisely the inversibility. general is built, for example, by SVD and returns the solution of minimums squares with lower Euclidean standard.
Numerical example
Consider a attribute, targets and intercept:
Normal equations produce
The residual vector is
We can verify orthogonality with the two columns:
The first result says that the waste adds up to zero; the second, that it does not residual component remains in the direction of the attribute .
Useful diagnosis
In a regression with intercept adjusted by least squares, a sum training waste very different from zero may indicate error of implementation, lack of intercept column or much numerical accuracy Bad.
Derivation Approach
The same solution can be obtained by treating the MSE as a function The starting point is:
Before using matrix notation, we derive each coordinate. visible the origin of all factors and signs.
Coordinate derivation
For the parameter , the string rule provides
If we set , gather all derivatives Partial produces
The dimensions are consistent: is and the residual vector is , therefore the gradient has components.
Derivative by quadratic form
We can also expand the MSE:
We use identities.
and the fact that a scalar is equal to its transposition. symmetric ,
Since is symmetrical, we arrived again to (4.27).
First-order condition
At any non-restricted differenceable minimum, the gradient shall be zero. equalizing (4.27) to zero,
or
It’s exactly the normal equations obtained by the projection. is invertible,
If it is not invertible, the gradient equality still characterizes the minimizers, but we cannot isolate a single solution by means of the On the contrary.
Why is a stationary point a global minimum?
Zeroing the gradient alone is not enough for any function: points stationary can also be maximum or saddles. Here, the Hessian is
For any vector,
Therefore, Hessiana is positive semi-defined and is convex. normal equations is a global minimum. has full columns, inequality is strict for , the Hessian is positive defined and the minimum is unique.
The gradient as sum of contributions
The formula
it shows that each example contributes to its residual multiplied by features. A large error exerts greater influence; features of great scale can also produce large components in the gradient. a practical reason to standardize inputs before using methods Iteratives.
If we don’t want to solve the system directly, we can use
the gradient descending. Unlike Perceptron, the update Now it is explicitly derived from a smooth error function.
Verification in the case of a straight line
For ,
The two first-order equations are:
The first states that waste adds up to zero; the second states that waste are orthogonal to the vector of the values. verifications made in the projection example.
Two languages for the same fact
In geometric language, the residual is orthogonal to the column space. calculation language, gradient is zero. As gradient is , the statements are equivalent.
Exercises
- Derive (4.27) using convention . What changes?
- Show that is always symmetrical.
- Explain why disabled station produces a direction with Zero curvature in (4.28).
4.3.25 Computing
In implementation, the goal is to find that minimizes . The mathematical form of equations normal is useful for the theory, but the explicit calculation
It’s not the recommended numerical strategy.
First, we don’t need the reverse matrix: We just need to solve a system for a vector. raises squared, approximately, the condition number of the matrix, expanding errors of the matrix and the rounding.
Recommended NumPy Implementation
numpy.linalg.lstsq directly solves the least square problem, usually by SVD-based methods. It accepts rectangular matrices and also works when the columns are not independent.
from dataclasses import dataclass
import numpy as np
@dataclass
class ModeloLinear:
coeficientes: np.ndarray
intercepto: float
posto: int
valores_singulares: np.ndarray
def ajustar_regressao_linear(X, y):
X = np.asarray(X, dtype=float)
y = np.asarray(y, dtype=float)
if X.ndim != 2:
raise ValueError("X deve ter forma (n_exemplos, n_atributos)")
if y.ndim != 1 or len(y) != len(X):
raise ValueError("y deve ter um valor para cada linha de X")
if not np.all(np.isfinite(X)) or not np.all(np.isfinite(y)):
raise ValueError("X e y devem conter somente valores finitos")
X_tilde = np.column_stack([np.ones(len(X)), X])
w_tilde, _, posto, singulares = np.linalg.lstsq(
X_tilde, y, rcond=None
)
return ModeloLinear(
coeficientes=w_tilde[1:],
intercepto=float(w_tilde[0]),
posto=int(posto),
valores_singulares=singulares,
)
def prever_regressao(modelo, X):
X = np.asarray(X, dtype=float)
return X @ modelo.coeficientes + modelo.intercepto
The second value returned by lstsq contains sums of waste only in certain shape and post configurations; therefore, it is clearer to calculate the metrics explicitly from the forecasts.
def metricas_regressao(y, y_predito):
y = np.asarray(y, dtype=float)
y_predito = np.asarray(y_predito, dtype=float)
residuos = y - y_predito
mse = np.mean(residuos**2)
rmse = np.sqrt(mse)
mae = np.mean(np.abs(residuos))
denominador = np.sum((y - np.mean(y))**2)
r2 = np.nan if denominador == 0 else (
1 - np.sum(residuos**2) / denominador
)
return {"mse": mse, "rmse": rmse, "mae": mae, "r2": r2}
When all targets are equal, the denominator is zero; return NaN makes it explicit that the metric is not defined in this sample.
Full example
X_treino = np.array([
[50.0, 0.10],
[90.0, 0.25],
[140.0, 0.40],
[200.0, 0.65],
[280.0, 0.80],
])
y_treino = np.array([1.1, 1.8, 2.9, 4.1, 5.4])
modelo = ajustar_regressao_linear(X_treino, y_treino)
predicoes = prever_regressao(modelo, X_treino)
print("intercepto:", modelo.intercepto)
print("coeficientes:", modelo.coeficientes)
print("posto:", modelo.posto)
print(metricas_regressao(y_treino, predicoes))
With two features and intercept, we expect to post . A smaller value indicates linear dependence detected numerically. automatically useless predictions, but prevents interpreting the coefficients as a single solution.
Understanding QR Factoring
If has full column rank and its reduced QR is
So…
with and superior triangular. Replacing in condition of least squares, the solution satisfies
We solved (4.29) by retroactive replacement, without calculate . In NumPy:
Q, R = np.linalg.qr(X_tilde, mode="reduced")
w_tilde = np.linalg.solve(R, Q.T @ y)
QR is more stable than solving normal equations and usually is a good one. option for dense arrays with full post. Mature libraries use Householder transformations or equivalent techniques; implement Gram–Schmidt classic as production solver is unadvisable for its sensitivity to rounding.
SVD, pseudo-inverse and rank
Decomposition in singular values writes
Very small singular values reveal almost redundant directions. The pseudoverse is
where reverses only the singular values treated as not No, no, no.
The tolerance used to consider a null singular value is a decision The rcond argument of lstsq controls that decision; None uses the appropriate library pattern.
Conditioning
The condition number in standard 2 is, for full rank,
The bigger , the more sensitive the solution gets to small Troubles. We can estimate it by
condicao = np.linalg.cond(X_tilde)
print("número de condição:", condicao)
A high value does not have a universal threshold of “failure”; its gravity depends on numerical accuracy and application. Standardization can reduce scale differences, but does not remove structural redundancy. Regularization, such as ridge regression, can stabilize coefficients to the take a little bias.
Which method to choose?
| Situation | Typical strategy |
|---|---|
| moderate dense matrix | lstsq or QR |
| disabled or almost disabled | SVD/pseudoinverse |
| many examples and few features | Specialised QR or solver |
| very large or in-flow data | stochastic gradient or iterative methods |
| sparse matrix | routines suitable for sparse matrices |
| need for stabilization | ridge regularization |
Training, validation and testing
Adjust the coefficients only in training. Use validation to choose changes, regularization or other hyperparameters and test for the final evaluation. If there is standardization, average adjustment and deviation in training and reuse these values in the other sets.
Avoid inv(X.T@X) @X.T@y
In addition to failing in a deficient position, this expression forms a matrix with worse conditioning and calculates an unnecessary inverse.
np.linalg.lstsq(X, y, rcond=None)or an appropriate solver to data structure.
Checks after adjustment
- Compare the returned post with the number of parameters.
- Examine singular values and condition number.
- Check residuals and metrics in training and validation.
- Inspect waste patterns according to predictions and features.
- Confirm that the same preprocessing will be applied in production.
4.3.26 Summary
Linear regression learns a real output function
minimizing the average of the waste squares. Although the model is simple, his study gathered matrix representation, orthogonal projection, multivariable calculation and numerical stability.
Conceptual map
| Element | Expression |
|---|---|
| design matrix | |
| parameters | |
| forecasts | |
| waste | |
| objective | |
| gradient | |
| Great condition | |
| normal equations | |
| general solution of lower standard |
The condition has two readings equivalent:
- geometry: prediction is the projection of in column space and the waste is perpendicular to that space;
- calculation: the MSE gradient is zero at least.
Recommended Flow of Implementation
- Separate training, validation and testing.
- Adjust attribute transformations only in training.
- Add the intercept or configure the library to estimate it.
- Solve least squares with
lstsq, QR, SVD or appropriate method for data structure. - Examine rank, singular values and conditioning.
- Calculate MSE or RMSE and complementary metrics in data not used in adjustment.
- Analyze residuals and check patterns, atypical values and change of distribution.
The solution is not just a formula
Calculate explicitly is unnecessary and can be unstable. The pseudoverse is a mathematical concept; in code, use a reliable numerical solver.
What each metric responds
- MSE: what is the mean squared loss?
- RMSE: what is the typical scale of error with quadratic penalty, in the target units?
- MAE: What is the average error module with linear influence?
- : as the model improves compared to the constant predictor of Average on that set?
Training results respond on adjustment; validation results and test provide evidence of generalization. None of these metrics, by themselves only, establishes causality or safety of application.
Common Errors
- forget the intercept column;
- transpose the design matrix and exchange examples for features;
- use the reverse formula without checking rank;
- interpret coefficients without considering units and correlation between features;
- calculate pre-processing with test data;
- extrapolate far beyond the observed region;
- report only and hide the waste scale.
Conceptual issues
- Why do SSE and MSE have the same minimizer?
- Why is the optimal residual orthogonal to the columns of the design matrix?
- Having more examples than parameters ensures unique solution? Justify.
- Why can forming worsen conditioning?
- In what sense is a regression with attribute still linear?
- How can a model present negative in the test set?
Exercises
- Stop e , check by multiplication the equations normal using .
- Build a design matrix with two identical columns. Calculate your put and explain why the coefficients are not unique.
- Compare
np.linalg.lstsqwith the explicit solution of normal equations in a matrix whose columns are almost collinear. - Adjust a straight line to a sample, add an extremely target value distant and observe how coefficients, RMSE and MAE change.
- Examine a graph of waste against predictions. that a nonlinear relationship remains without modeling?
Domain criteria
When completing this section, the student must be able to:
- Mount , , and with correct dimensions;
- derive normal equations by projection and gradient;
- explain rank, pseudo-inverse and uniqueness;
- choose an appropriate numerical routine without calculating an inverse explicit;
- evaluate the model outside the sample and interpret its residuals.
4.3.27 Animation
An animation can simultaneously show two views of the same process:
- in the data space, the line changes as and are updated;
- in the space of the parameters, the point runs through the surface of the MSE towards the minimum.
For a regression with one attribute, the MSE is a quadratic function of two parameters. Their level curves are ellipses when the solution is unique.

Figure 4.11. The downward gradient crosses MSE level curves towards the minimum.
Very elongated ellipses indicate different scales or strong correlation between the directions of the parameters. In this scenario, a rate of learning High can make the trajectory oscillate from side to side of the valley.
Registering trajectory
The following code adjusts a line by descending gradient and holds a copy of the parameters at each step.
import numpy as np
def trajetoria_gradiente(X, y, taxa=0.05, passos=100):
X = np.asarray(X, dtype=float).reshape(-1)
y = np.asarray(y, dtype=float)
b, w = 0.0, 0.0
historico = []
for passo in range(passos + 1):
predicoes = b + w * X
residuos = predicoes - y
mse = np.mean(residuos**2)
historico.append((passo, b, w, mse))
grad_b = 2 * np.mean(residuos)
grad_w = 2 * np.mean(residuos * X)
b -= taxa * grad_b
w -= taxa * grad_w
return historico
We use residuos = predicoes - y, so the gradient appears with positive signal before subtraction, if we defined waste as , the intermediate formula signal would change, but the Final update would be equivalent.
♪ Cheering up the straight ♪
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
def animar_ajuste_linear(X, y, taxa=0.05, passos=100):
X = np.asarray(X, dtype=float).reshape(-1)
y = np.asarray(y, dtype=float)
historico = trajetoria_gradiente(X, y, taxa, passos)
fig, (ax_dados, ax_erro) = plt.subplots(1, 2, figsize=(10, 4))
ax_dados.scatter(X, y, label="observações")
eixo_x = np.linspace(X.min(), X.max(), 100)
reta, = ax_dados.plot([], [], label="modelo")
ax_dados.set_xlim(X.min(), X.max())
margem_y = 0.1 * max(np.ptp(y), 1.0)
ax_dados.set_ylim(y.min() - margem_y, y.max() + margem_y)
ax_dados.legend()
passos_hist = [estado[0] for estado in historico]
erros_hist = [estado[3] for estado in historico]
ax_erro.plot(passos_hist, erros_hist, color="lightgray")
ponto_erro, = ax_erro.plot([], [], "o")
ax_erro.set_xlabel("passo")
ax_erro.set_ylabel("MSE")
titulo = fig.suptitle("")
def atualizar(estado):
passo, b, w, mse = estado
reta.set_data(eixo_x, b + w * eixo_x)
ponto_erro.set_data([passo], [mse])
titulo.set_text(
f"passo={passo} · b={b:.3f} · w={w:.3f} · MSE={mse:.4f}"
)
return reta, ponto_erro, titulo
animacao = FuncAnimation(
fig,
atualizar,
frames=historico,
interval=100,
repeat=False,
)
return fig, animacao
On a notebook:
from IPython.display import HTML
X = np.array([0.0, 1.0, 2.0, 3.0, 4.0])
y = np.array([1.1, 2.8, 5.2, 6.9, 9.2])
fig, animacao = animar_ajuste_linear(
X, y, taxa=0.03, passos=100
)
plt.close(fig)
HTML(animacao.to_jshtml())
Guided experiments
- Increase the learning rate gradually. At what value does the MSE leave to decrease in a stable way?
- Multiply by without changing the rate. Explain the change using the gradient expression.
- Standardize and repeat the experiment. Compare trajectory.
- Add an atypical value to . Note how the optimal line changes.
- Compare the final parameters to the
np.linalg.lstsqresult.
Direct solution does not travel through animation
QR or SVD calculates the solution by linear algebra operations and does not generate of course a sequence of intermediate lines. belongs to the descending gradient, an alternative algorithm for the same quadratic objective.
4.4 Logistic regression
Logistic regression is a model of ** probability classification binary**. Although the name contains “regression”, the observed target belongs two classes. We’ll use the encoding
in which represents the event of interest and , its complement. Examples include default or payment, fraud or transaction legitimate, failure or operation and presence or absence of a condition clinic.
The goal is not just to return a class. We want to model
the conditional probability of the positive event given the features. the classes are complementary,
4.4.1 Why isn’t linear regression enough?
We could encode the labels as zero and one and adjust for least squares. linear probability model, has important limitations:
- the output may be less than zero or greater than one;
- the effect of a variation in the score remains constant, even in the close to probabilistic extremes;
- the variance of a binary variable depends on its probability;
- SEM does not directly correspond to the likelihood of an observation Bernoulli.
Logistic regression maintains linear score
but apply a transformation that takes any real number to the range :

Figure 4.12. Logistic regression separates the probability estimate from the decision made with a threshold.
4.4.2 Probability is not a decision
After estimating , an application can convert it into class using a threshold:
The value is common but not mandatory. If you stop detecting A fraud costs a lot more than investigating a false alarm, a threshold The model estimates probabilities; decision combines these odds with costs and restrictions.
As and sigmoid is increasing, the threshold produces the border
the same geometric shape as the Perceptron. The difference is at the output and in the training: Perceptron provides a signal and uses error corrections; logistic regression provides a continuous value and optimizes a loss Probabilistic.
4.4.3 Conditional interpretation
There is no deterministic label for each entry than the model You need to find out. different results. Uncertainty is represented by a distribution Bernoulli:
That means…
By observing many similar cases with , we expect a close proportion of of positive results, not the certainty of that each case will be positive.
4.4.4 Example of reading
Consider a server failure template:
For temperature and load ,
e
This number is a conditional estimate to the attribute vector and to the adjusted model. It is not a frequency observed directly for that individual server.
4.4.5 Three levels that should not be confused
| Quantity | Domain | Meaning |
|---|---|---|
| score | linear evidence before transformation | |
| probability | estimate of | |
| decision | action after applying a threshold |
A good accuracy does not guarantee reliable probabilities. correspond to positive results in only of cases, the model is poorly calibrated, although many classes are correct. Calibration and discrimination are different properties.
Probability of the model is not scientific certainty
The output depends on the data, features, population and assumptions of the model. Change of distribution, poorly represented groups and omitted variables In high-impact applications, evaluate calibration and errors by subgroup and define human supervision.
4.4.6 Section script
In the next subsections, we will study:
- the logistic function and its relationship with chances and log-odds;
- the probabilistic hypothesis class;
- the loss of Bernoulli-derived cross-entropy;
- gradient, Hessian and optimization methods;
- numerically stable implementation and evaluation.
4.4.7 Logistic function
We need to turn a score into a The logistic function, also called sigmoid, is
Your domain is the whole real line and your image is the open range . It never produces exactly zero or one for a real argument finite, but approaching these values when tends to or .

Figure 4.13. The sigmoid converts a real score into probability and satura near the extremes.
Fundamental properties
The sigmoid satisfies
It is strictly growing. Its derivative has a special form convenient:
Like , the derivative is positive. Its maximum value is , reached on In the tails, the derivative approaches zero: we say that function satura.
For small variations close to zero,
Far from the center, the same score variation causes a minor change in probability.
Log chances and chances
If an event has probability , its chances (* odds*) are
Probability , for example, corresponds to chances : we read “four to one” in favor of the event. corresponds to chances .
The logarithm of chances is the function logit:
Applying it to the sigmoid,
Therefore, sigmoid and logit are inverse functions:
In logistic regression, the linear amount is not the probability, but the logarithm of the chances:
Interpretation of a coefficient
Keeping the other features fixed, increase in a sum unit to log-odds. Exposing, the chances are multiplied by :
If , an additional drive doubles the chances. This does not means double the probability. If it goes from to chances , double the odds produces , which corresponds to probability , not .
Relationship with Bernoulli distribution
A Bernoulli variable with parameter satisfies
Set the natural parameter
Like , we can rewrite the probability mass:
That’s Bernoulli’s exponential family form. logistics models the natural parameter by . This link explains why the logistic function and the loss of cross-entropy appears together; they are not just convenient graphic choices.
Logistic function, probit and hyperbolic tangent
Model probit replaces sigmoid with distribution function normal accumulated . Both produce curves in S and often generate similar adjustments after a change of scale, but correspond the different connection functions.
The hyperbolic tangent satisfies
and has image. It is common as a network activation function neural, but does not directly represent a probability Bernoulli without additional transformation.
Logistics is not logarithmic
The name “ Logistic regression” comes from the logistic function. Logarithm appears because the model makes the log-odds linear in features.
Intercept and reference probability
In the homogeneous vector,
we have . When all features Originals are worth zero,
so that represents the reference log-odds. features can make this reference more interpretable.
Numerically stable computing
The direct formula can cause overflow when calculating for Very negative . A branch implementation prevents exponentials giants:
import numpy as np
def sigmoide_estavel(z):
z = np.asarray(z, dtype=float)
saida = np.empty_like(z)
positivos = z >= 0
saida[positivos] = 1 / (1 + np.exp(-z[positivos]))
exp_z = np.exp(z[~positivos])
saida[~positivos] = exp_z / (1 + exp_z)
return saida
For logistical losses, libraries use identities like logaddexp and logsumexp, avoiding first calculating rounded probabilities to Zero or one.
Exercises
- Demonstrate identity (4.32).
- Convert , and probabilities into odds and log-odds.
- If , by what factor the chances change when increases Three units?
- Show algebraically that the inverse of logit function is sigmoid.
- Explain why a fixed change in log-odds does not correspond to a fixed change in probability.
4.4.8 Hypothesis
The logistic regression hypothesis class is:
Each hypothesis associates to an input an estimated probability:
Since is binary,
This function is a conditional probability, not a density of continuous variable. For , we use a mass function of probability Bernoulli:
4.4.9 Homogeneous and matrix representation
With
We write
For a whole sample,
in which the sigmoid component is applied to the component. : there is a score and a probability for Every example.
4.4.10 Label encoding
encoding is convenient for Bernoulli and entropy crossover. If data uses , we can convert by
The two conventions are valid, but their loss formulas differ. Mixing them quietly is a common source of signal errors.
4.4.11 Probability surfaces
All points with the same probability satisfy
Applying logit function,
Therefore, the surfaces of constant probability are hyperplanes For , the right side is zero and we get the border
For a general threshold , the decision border is
Change threshold moves border parallel; no need train again the model just to test another decision policy.
4.4.12 Interpretation of parameters
The model assumes linearity in log-odds:
Each represents the change in log-odds to an additional unit of , keeping other features constant. The factor is the corresponding odds ratio.
This interpretation depends on the model specification. If a relationship is curve, omit nonlinear terms can make the coefficient misleading. two features are strongly correlated, the phrase “keeping the other constants” may describe a rare or impossible comparison in data.
4.4.13 Feature engineering
As in linear regression, we can use a map of characteristics:
With , the boundary in original space can be curved, although log-odds remain linear in the parameters. This increases the capacity and should be accompanied by validation and many Sometimes, regularization.
4.4.14 What the hypothesis assumes — and what it does not assume
Logistic regression does not require features to follow distribution The central specification is that conditional log-odds are modeled by the chosen combination of characteristics. traditional statistics, other conditions may be necessary; for prediction, mainly evaluated performance, calibration and stability outside from the sample.
Perfect separation
If a linear combination perfectly separates the classes, the Unsettled likelihood may continue to improve as the the coefficients standard tends to infinity. extreme and there is no usual finite estimate of maximum likelihood. Regularization or specific methods deal with this case.
4.4.15 Vectorized example
import numpy as np
X = np.array([
[70.0, 0.40],
[85.0, 0.75],
[60.0, 0.25],
])
w = np.array([0.03, 1.20])
b = -4.0
z = X @ w + b
p = 1 / (1 + np.exp(-z))
classes = (p >= 0.5).astype(int)
print("pontuações:", z)
print("probabilidades:", p)
print("classes:", classes)
The p vector is the probabilistic output of the hypothesis; classes depends on the chosen threshold and belongs to the decision layer.
Questions
- Derive (4.39) to .
- Convert a base labeled to .
- Explain why all constant probability surfaces are parallel in the model without nonlinear transformations.
- Give a map that allows a circular border in two dimensions.
4.4.16 Error
The sample does not contain true probabilities; it contains achievements binary. To relate these observations to the parameters, we used the Bernoulli model and the maximum likelihood principle.
If
the probability assigned to the label is
Assuming that observations are conditionally independent given the features, the likelihood of the sample is
This expression is a function of the parameters for the data set. is not the probability that the parameters are true.
From product to sum
Products of many small probabilities can suffer underflow Numerical. As the logarithm is increasing, maximizing is equivalent to maximize log-likeness:
Learning algorithms usually minimize a loss. negative:
This function is called binary cross-entropy, log-loss or logistics loss.

Figure 4.14. Cross-entropy strongly penalizes confident probabilities attributed to the wrong class.
For , the individual loss is ; for , it is . A correct and confident forecast gets close loss of Zero. Wrong and confident prediction gets very big loss.
Shape with labels
If we use and the score , the probability of the label observed is
So, the individual loss is
The average error becomes
The forms (4.41) and (4.42) are equivalent after converting labels. is called softplus.
Relation with margin
In encoding, the margin is
The loss is decreasing in the margin:
- large and positive margin: correct classification and close loss of zero;
- zero margin: probability and loss ;
- negative margin: wrong classification, with loss growing to measure that the error becomes more confident.
Unlike zero-one loss, the logistic loss is smooth and provides a useful gradient in almost all situations.
Why not just use accuracy?
Acuracia considers only the side of the threshold. and for a positive case are both correct, but the second assigns more probability to the observed result. distinguishes these situations and is a own score rule: in expectation, is minimized when reporting the true probability.
This does not eliminate the need for decision metrics. Log-loss evaluates probabilistic quality; precision, recall and costs assess what It happens after applying a threshold.
Stable Computing
Calculate first and then log(p) can produce log(0) by rounding. With labels , use np.logaddexp(0, -t * z), which calculates the softplus stable mode:
import numpy as np
def perda_logistica_pm1(X, t, w, b):
z = X @ w + b
perdas = np.logaddexp(0.0, -t * z)
return np.mean(perdas)
With labels, a stable shape directly in * logs* is
def entropia_cruzada_logits(X, y, w, b):
z = X @ w + b
perdas = np.logaddexp(0.0, z) - y * z
return np.mean(perdas)
Regularization
It is common to add a penalty to the weights:
The intercept is normally not penalized. extreme coefficients, help in perfect separation and control overfit. The value must be chosen by validation, not by test set.
Log-loss has no upper limit
An almost zero probability for an event that occurs produces a lot of loss great. This is intentional: the model is responsible for trust It also makes it essential to investigate incorrect labels and use numerically stable operations.
Example
For a positive case with ,
If the model assigns to the same result,
The second forecast is not only incorrect according to a threshold ; It’s incorrect with high confidence.
Exercises
- Derive (4.41) from (4.40).
- Show that .
- Calculate the log-ins for and forecasts and .
- Explain why maximizing likelihood is tantamount to minimizing negative log-likeness.
- Compare logistic loss and zero-one loss on margins .
4.4.17 Algorithm
Training logistic regression means finding parameters that minimise cross-entropy, or equivalently maximize cross-entropy Bernoulli likelihood. For labels the problem is
In linear regression, zeroing the gradient produced a linear system with Here, the odds depend not linearly of the parameters. The first order condition forms a nonlinear system and, in general, needs to be solved iteratively.
Gradient and Hessian in an early view
Gathering the probabilities in vector , the gradient is
The gradient points in the direction of greater local growth. The loss, we move in the opposite direction, .
The Hessian is
where
For any vector,
because the diagonal elements of are non-negative. Convex: there are no bad least places. That does not mean that all execution is trivial; conditioning, step choice and separation Perfect still matters.
Three strategies
The following subsections have related methods:
| Method | Information used | Cost per iteration | Feature |
|---|---|---|---|
| downward gradient | first derivative | usually | simple and scalable |
| Newton/IRLS | gradient and Hessian | includes system in variable | few iterations close to minimum |
| maximum slope with step search | gradient and adaptive choice of | multiple loss assessments | reduces the risk of inadequate step |
On very large bases, the gradient can be estimated with minilots. moderate dimension, Newton or quasi-Newton methods, such as BFGS and L-BFGS, They usually converge on fewer iterations.
Regularization
With penalty , we minimize
usually excluding the intercept. The gradient gains the term and Hessiana wins in the penalized coordinates. In addition to controlling overfit, this term improves conditioning and produces finite solution in many cases of perfect separation.
Structure of an iteration
Regardless of the method, a typical cycle contains:
- calculate the * logs* ;
- calculate probabilities or equivalent quantities in a stable manner;
- evaluate loss and gradient;
- determine a direction ;
- choose a step size ;
- update ;
- check stop criteria.
For descending gradient, .
but an implementation solves the linear system without calculating the inverse.
Stopping criteria
A single criterion can be misleading. Robust implementations combine:
- gradient standard below a tolerance;
- relative variation in small loss;
- relative variation of small parameters;
- maximum number of iterations;
- detection of non-finite values;
- validation performance for early stop, where appropriate.
Loss must be monitored precisely enough. may be irrelevant for a loss of and important for a loss of ; therefore, relative tolerances are useful.
Initialization and scale
Starting at zero is valid for an isolated logistic regression: there is no symmetry between several units that needs to be broken. are very unbalanced, a useful intercept boot is
with initially zero weights, since . This starts with the prevalence of the positive class.
Standardizing features improves conditioning and makes a single rate of more reasonable learning for all coordinates. standardization should be estimated only in training.
Numerical convergence does not guarantee a good model
An optimiser can perfectly minimize loss of training and even generalize poorly, be uncalibrated or show unequal performance between groups. Optimization solves the parameters of the specified objective; evaluation verifies whether this objective serves the application.
Basic diagnostics
During training, register at least:
- loss of training and validation;
- gradient standard;
- the standard of parameters;
- step size;
- number of iterations and reason for the stop.
Continuous growth of parameter standard with decreasing loss may Indicate perfect separation without regularization. Loss NaN or infinite usually indicates unstable operations or excessive step.
Gradient
For a function to scale , the gradient gathers Partial derivatives:
We’ll adopt gradients as column vectors. unit direction is
By Cauchy–Schwarz, this value is maximum when points in the direction of gradient. Therefore, is the direction of highest local slope.
Derivation with labels
For an example, set
and use stable loss in logits
Since the derivative of softplus is sigmoid,
Besides,
By the rule of jail,
Calculating the average and gathering the examples in the design matrix,
The formula has a simple interpretation: measures error Probabilistic of each example, and multiplication by distributes these errors between the parameters of according to the features values.
Derivation with labels
For , the loss is
Its derivative is
Note the exponent in the denominator. When the margin is large and positive, the contribution tends to zero; when it is negative, the contribution It’s approaching .
Batch update
The descending gradient in batch uses all examples:
With regularization , we added to the coordinates of the pesos, leaving the intercept without penalty.
A very small step converges slowly. A very large step can make the loss oscillate or increase despite convexity. describes the shape of the goal, does not automatically correct a rate of inadequate learning.
Stochastic gradient and minilots
The full gradient costs per iteration. For large bases, we can estimate it using a subset:
- SGD: ; cheap and noisy updates;
- minilot: ; takes advantage of vectorization and reduces variance;
- complete batch: ; deterministic direction.
In minilot training, we shuffle the examples every time and We usually reduce the learning rate over time. makes the loss oscillate, so a single increase between steps does not imply failure.
Stable implementation
import number as np
def loss_e_gradiente_logistico(X, y, w, b, lambda_l2=0.0):
z = X @ w + b
# Loss directly on logits: softplus(z) - y*z.
losses = np.logaddexp(0.0, z) - y * z
loss = np.mean(loss) + 0.5 * lambda_l2 * (w@w)
# Sigmoid stable.
p = np.empty_like(z)
positive = z >= 0
p[positive] = 1 / (1 + np.exp(-z[positive]))
exp_z = np.exp(z[~positive])
p[~positives] = exp_z / (1 + exp_z)
error = p -y
grad_w = X.T@error/len(X) + lambda_l2 *w
grad_b = np.mean(error)
return loss, grad_w, grad_b
An implementation of the training can use:
def adjust_by_gradient(
X,
y,
*,
rate=0.1,
max_iter=10_000,
tolerance=1e-7,
lambda_l2=0.0,
):
X = np.asarray(X, dtype=float)
y = np.asarray(y, dtype=float)
w = np.zeros(X.shape[1])
b = 0.0
historic = []
for iteration in range(1, max_iter + 1):
loss, grad_w, grad_b = loss_e_gradiente_logistico(
X, y, w, b, lambda_l2
)
standard_grad = np.sqrt(grad_w@grad_w + grad_b**2)
historic.append(loss)
if not np.isfinite(loss):
raid FloatingPointError("loss is no longer finite")
If standard_grad <= tolerance:
return w, b, historic, True
w -= rate * grad_w
b -= rate * grad_b
return w, b, historic, False
The Boolean return prevents iterations from reaching the limit Confused with convergence.
Check for finite differences
Before we rely on a manually implemented derivative, we can compare it with a numerical approach:
def gradient_numeric(function, w, epsilon=1e-6):
approximation = np.zeros_like(w)
for j in range(len(w)):
offset = np.zeros_like(w)
displacement[j] = epsilon
approximation[j] = (
function(w + offset)
- function(w - offset)
) / (2 * epsilon)
return approach
Finite differences also have rounding and truncation error, but are excellent for detecting exchanged signals, missing factors and errors for transposition into small examples.
Convergence and uniqueness
The loss is convex, but the minimum is not necessarily unique without Additional conditions. Redundant columns produce flat directions. In perfectly separable and unregulated data, the minimal can be approximate while the standard of parameters differs, without a minimizer finite.
With positive regularization in the relevant directions, the objective becomes more strongly convex and the numerical behavior improves.
Monitor more than the loss
Record gradient standard, validation loss and parameter standard. A loss that changes little can indicate convergence, too small a rate or numerical saturation; the other signs help distinguish the cases.
Exercises
- Derive (4.46) by the chain rule.
- Convert (4.48) to encoding.
- Implement finite difference verification for and .
- Compare full batch and minilots in the same sample, using the same number of seasons.
- Explain why standardizing features allows you to use a common rate with More security.
Newton’s Method
The gradient uses the local slope, but ignores how this slope changes. in each direction. Newton’s method adds curvature information contained in the Hessian.
From quadratic approach to step
Close to a point , the second-order Taylor expansion is
where . To minimize this quadratic approach in with respect to , we zeroed its gradient:
Newton’s direction resolves, therefore,
and the update is
with in pure Newton. In code, we solved (4.50); We didn’t calculate explicitly.
In a dimension, this expression reduces the
which is Newton’s method applied to the equation .
Gradient and Logistic Hessian
For the homogeneous matrix , we have
e
where
The matrix assigns greater weight to the examples whose probability is close to and weight lower than those that are saturated close to zero or one. If there is regularization , we add to penalized coordinates from Hessiana and to the gradient.
Relationship with reweighted least squares
Newton’s equation can be rewritten as a problem of least squares iteratively reweighted (IRLS). Work response
Next vector solves
The normal equations of (4.52) are
which are equivalent to Newton’s step. The name “repondered” comes from the fact that change with each iteration as the odds change.
In practice, it is not necessary to form as a matrix . If , multiply by equals multiplying each line or component by the corresponding element of .
Implementation with broken Newton
The code below gathers intercept and weights in a homogeneous vector, including regularization only in weights and uses backtracking to avoid steps to increase the loss.
import number as np
def loss_logistica_logits(X, y, w, lambda_l2=0.0):
z = X @ w
loss_data = np.mean(np.logaddexp(0.0, z) - y * z)
return loss_data + 0.5 * lambda_l2 * (w[1:] @w[1:])
def adjust_logistica_newton(
X,
y,
*,
lambda_l2=1e-6,
max_iter=100,
tolerance=1e-8,
):
X = np.asarray(X, dtype=float)
y = np.asarray(y, dtype=float)
Xh = np.column_stack([np.ones(len(X)), X])
w = np.zeros(Xh.shape[1])
penalty = np.diag([0.0] + [lambda_l2] * X.shape[1])
historic = []
for iteration in range(1, max_iter + 1):
Z = Xh @w
p = np.empty_like(z)
positive = z >= 0
p[positive] = 1 / (1 + np.exp(-z[positive]))
exp_z = np.exp(z[~positive])
p[~positives] = exp_z / (1 + exp_z)
g = Xh.T @ (p - y) / len(Xh) + penalty @w
s = p * (1 - p)
H = Xh.T @ (s[:, None] * Xh) / len(Xh) + penalty
standard_grad = np.linalg.norm(g)
current_loss =_logistica_logits(
Xh, y, w, lambda_l2
)
historic.append(current_loss)
If standard_grad <= tolerance:
return w, historical, True
try:
direction = np.linalg.solve(H, -g)
Except np.linalg.LinAlgError:
direction = np.linalg.lstsq(H, -g, rcond=None)[0]
# Backtracking: Take a step that reduces loss.
step = 1.0
derivative_directional = g @direction
while step > 1e-12:
candidate = w + step * direction
loss_new = loss_logistica_logits(
Xh, y, candidate, lambda_l2
)
if loss_new <= (
current_loss + 1e-4 *step *derived_directional
):
break
step *= 0.5
else:
return w, historical, False
w = candidate
return w, historical, False
The condition used in backtracking is a form of Armijo’s condition. requires sufficient reduction, not just any tiny decrease.
Why add dampening?
Far from minimal, the quadratic approach can be bad. Almost unique can also produce a huge step. There are three mechanisms common:
- use by linear search;
- add to the Hessian, as in reliable region methods;
- use statistical regularization, which also improves conditioning.
Newton with linear search preserves local speed without assuming that all Unitary step be safe.
Computation cost
If is the number of parameters, calculate gradient and dense Hessian costs approximately , and solving the system costs . Hessian’s memory is .
The descending gradient avoids Hessian and costs approximately Iteration . Newton usually uses fewer iterations, but each is more expensive. For many parameters, near-Newton methods like L-BFGS They approach the curvature without storing the complete Hessian.
Newton, Fisher scoring and IRLS
In generalized linear models, Fisher scoring replaces the Hessian observed by the Fisher information expected. Bernoulli logistics with canonical connection, the relevant matrices coincide in the usual form, and the algorithm is often described as much as Newton-Raphson as much as IRLS.
Local Convergence
Close to a strict minimum, with Hessian not singular and regularity enough, Newton can present quadratic convergence: the error is approximately squared of one iteration to the next. This is a local property. It does not guarantee a startup Arbitrary always accept unitary steps nor solves perfect separation.
Saturated probabilities require care
When is numerically zero or one, can be Make it zero and Hessiana loses information on that observation. Regularization, stable calculus and damping help; cutting Undocumented odds can mask the problem.
Checks
- Confirm that for a descent direction.
- Check that the loss accepted by backtracking does not increase.
- Monitor the condition number.
- Compare the result with a library optimizer.
- Test a perfectly separable base with and without regularization.
Exercises
- Derive Hessiana from (4.47).
- Show the equivalence between (4.50) and (4.52).
- Explain why we should not explicitly form .
- Compare costs of a Newton iteration and gradient to e .
- Modify the code to penalize the intercept as well and discuss why That’s not the usual convention.
Maximum Decline Method
The maximum slope method, or descending gradient, chooses in each Iteration the opposite direction to the gradient. For a unitary direction , the directional derivative is
For the inequality of Cauchy–Schwarz,
The lowest value occurs in
Thus, in Euclidean geometry of parameters, the negative gradient is the fastest local fall direction. The usual update absorbs the normalization in the learning rate:
The gradient points perpendicular to the level curves. curves are very elongated, the trajectory can cross repeatedly the valley and form a zigzag.

Figure 4.15. The maximum slope crosses the level curves in the local perpendicular direction, and may oscillate in elongated valleys.
“More steep” depends on scale
If we replace an attribute measured in meters with the same attribute in mm, the predictive function may represent the same relationship, but the parameter space geometry changes. Consequently, direction Euclidean maximum slope also changes. Standardization and preconditioning reduces this problem.
Newton can be interpreted as a gradient step corrected by curvature:
Instead of treating all directions with the same scale, the Hessian rescales the gradient according to the local curvature.
How to choose the size of the step?
There are three common approaches:
- fixed rate: simple but requires adjustment;
- decay schedule: reduces along the iterations;
- linear search: chooses a step that produces enough reduction.
For unregulated logistic regression, Hessiana satisfies
Yeah. . Therefore, Lipschitz’s lowest constant satisfies
With penalty intensity , we add approximately at the bound in the penalized directions. provides a conservative choice for monotonic reduction in the convex and smooth problem.
Calculate exactly can be expensive; linear search or estimates are practical alternatives.
Linear search by backtracking
If and , Armijo’s condition accepts when
Like , the right side requires a reduction proportional to step and inclination.
def passo_backtracking(
perda,
w,
gradiente,
*,
passo_inicial=1.0,
contracao=0.5,
armijo=1e-4,
):
direcao = -gradiente
valor = perda(w)
derivada_direcional = gradiente @ direcao
passo = passo_inicial
while passo > 1e-12:
candidato = w + passo * direcao
if perda(candidato) <= (
valor + armijo * passo * derivada_direcional
):
return passo
passo *= contracao
raise RuntimeError("a busca linear não encontrou um passo")
The search begins with a candidate step and reduces it geometrically. performs extra reviews of the loss, but avoids choosing a previously Adequate rate for the entire trajectory.
Full algorithm
start w
repeat:
calculate loss E(w) and gradient g
if
η choice by fixed rate, schedule or linear search
w ← w − ηg
until it reaches the iteration limit
For minilots, the linear search is less direct because the estimated loss is noisy. In this case, rate schedules and adaptive optimizers are more Common.
Convergence
Convexity ensures that a finite stationary point is global, but not ensures uniqueness and existence of finite separation minimizer Perfect. Under softness and an appropriate step, the downward gradient converges. For strongly convex functions, as often occurs with regularization and proper position, convergence can be linear depending on the number of iterations.
The term “linear” here describes the geometric convergence rate of error, not the fact that the model uses a linear score.
Maximum slope versus Newton
| Aspect | Maximum slope | Newton. |
|---|---|---|
| derivatives | gradient | gradient and Hessian |
| additional memory | for dense Hessian | |
| typical cost per iteration | ||
| sensitivity to scale | high | smaller, by the correction of curvature |
| use with minilots | natural | less common in exact form |
| speed near the great | slower | potentially quadratic |
Local descent, global goal
The direction is defined by a local approach. Convexity is the which allows to relate this local movement to the global minimum, since that the size of the step and the other conditions are adequate.
Exercises
- Use Cauchy–Schwarz to demonstrate maximum slope direction.
- Show that .
- Explain how multiplying an attribute by changes the path the downward gradient.
- Implement (4.54) and register how many step reductions they occur by iteration.
- Compare a fixed rate, backtracking and Newton on the same sample.
4.4.18 Computing
This section transforms previous leads into a computational flow The goal is not only to obtain a vector of weights, but to produce a reproducible artifact that preserves preprocessing, parameters, convergence threshold and information.
We will compare two didactic implementations:
- Newton cushioned, suitable for dense bases of moderate size;
- gradient descending, simple and adaptable to large volumes of data and minilots.
In real applications, consolidated libraries offer methods quasi-Newton, regularization, class weighting and verifications Additional numericals. Implement from scratch is useful to understand the algorithm, not to automatically replace these libraries.
Data contract
We’ll adopt
Each line of is an example; each column is an attribute. Before adjustment, we checked:
- the same number of lines in and inputs in ;
- finite values only;
- exactly two labels, coded as zero and one;
- the presence of sufficient examples for the planned evaluation.
Missing values require explicit policy. Remove lines, filling in values or creating indicators of absence are decisions of modeling and should be adjusted only with the training data.
Division and pre-processing
For classification, the division should preserve approximately the proportion The correct flow is:
raw data
??? training → adjust imputation/standardization → adjust model
?? validation → apply training transformations → choose hyperparameters
Standardization is particularly useful for regularization and gradient The intercept is not standardized or normally penalized.
Exits from a training
A routine should return more than the coefficients. A minimum result may be represented by:
from dataclasses import dataclass
import numpy as np
@dataclass
class ResultadoLogistico:
pesos: np.ndarray
intercepto: float
convergiu: bool
iteracoes: int
motivo_parada: str
perdas: list[float]
normas_gradiente: list[float]
The reason for the stop differs convergence, limit of iterations, search Linear unsuccessful and numerical problem. Silence this difference can lead a system to publish incompletely adjusted parameters.
Prediction API
We should separate score, probability, and class:
def pontuacao(X, pesos, intercepto):
return np.asarray(X, dtype=float) @ pesos + intercepto
def probabilidade_positiva(X, pesos, intercepto):
z = pontuacao(X, pesos, intercepto)
p = np.empty_like(z)
positivos = z >= 0
p[positivos] = 1 / (1 + np.exp(-z[positivos]))
exp_z = np.exp(z[~positivos])
p[~positivos] = exp_z / (1 + exp_z)
return p
def prever_classe(X, pesos, intercepto, limiar=0.5):
if not 0 < limiar < 1:
raise ValueError("o limiar deve estar entre zero e um")
return (
probabilidade_positiva(X, pesos, intercepto) >= limiar
).astype(int)
This separation prevents a threshold change from being confused with new training and allows to evaluate calibration using the probabilities.
Complementary metrics
Log-loss evaluates probabilities. After choosing a threshold, the matrix of confusion allows you to calculate accuracy and recall:
When a denominator is zero, implementation must define the behavior rather than quietly producing a deceptive value. unbalanced bases, isolated accuracy can hide complete failure in the rare class.
We should also inspect:
- log them into training, validation and testing;
- ROC curve or precision–recall, as per application;
- calibration of probabilities;
- metrics per relevant subgroup;
- stability under temporal or operational change.
Reproducibility
Register data version, division, seed, transformations, intensity for regularization, algorithm, tolerances and iteration limit. deterministic methods in batch presented here, the seed may affect data division, even when it does not affect optimization.
Test set does not choose algorithm
Compare Newton, gradient, regularization or thresholds repeatedly in test transforms this set into validation. Choose settings in validation and use the test only for the final estimate.
By Newton’s Method
The correct computational form of Newton’s step is
where and are the gradient and the Hessian in the current state. Note the negative sign: adding would generally move to the Wrong direction.
Pseudocode
input: X, y, λ, tolerances and iteration limit
add the intercept column to X
start w
for t = 0, 1, ...:
z ← Xw
p ← sigmoid_stable(z)
g ← XT(p − y)/N + gradient_of_penality
H ← XT diag(p(1−p)) X/N + Hessiana_da_penality
if
Return convergence
solve H d = −g
choice η by backtracking
w ← w + ηd
if the relative change in loss is small:
Return convergence
_Other Organiser
The intercept corresponds to the first coordinate. penalize it, we use a diagonal matrix of regularization whose first element is zero.
Initialization
The null vector is a valid and deterministic choice. At this point, all The odds are worth . When the positive class is rare, we can initialize only the intercept with the smoothed prevalence:
where and are class counts and avoids Logarithm of zero, weights start at zero.
Random booting is not required to break symmetry into a only logistic regression and difficult to reproduce results without offering Auto benefit.
System solution
Never form . Solve
direction = np.linalg.solve(H, -gradiente)
When the matrix is defined positive symmetrical, a Cholesky factoration is appropriate. If the system is unique or almost unique, check rank, scale, separation and regularization; silently resort to pseudoverse can hide a modeling problem.
The system can also be solved without materializing the Hessian in big problems, using Hessian-vector products and methods like conjugate gradients.
Combined criteria
Robust implementation can declare convergence when at least one of these conditions, properly escalated, is satisfied:
The maximum limit remains mandatory. A loss “sufficiently small” is not a good universal criterion: with noise, the great can be away from zero; in perfect separation, chasing loss almost zero can make the coefficients diverge.
Numerical example
Consider a single attribute:
X = np.array([[-2.0], [-1.0], [0.5], [1.0], [2.0])
y = np.array([0.0, 0.0, 0.0, 1.0, 1.0])
With in weights and zero boot, Newton produces a sequence as:
| iteration | loss penalised | gradient standard |
|---|---|---|
| 0 | ||
| 1 | lower value | lower standard |
| 2 | refined approach | close to zero |
The exact values depend on the normalization of the penalty and the rule of step. The important property is that every step accepted by backtracking reduces objective function.
We can check the final solution by three conditions:
z = Xh @w_final
p = 1 / (1 + np.exp(-z))
gradient = Xh.T @ (p - y) / len(Xh) + penalty @w_final
assert np.linalg.norm(gradiente) < 1e-6
assert all(
current <= previous + 1e-12
is previous, current in zip(losses, losses[1:])
)
assert np.all(np.isfinite(w_final))
Fault diagnosis
| Symptoms | Probable cause | Action |
|---|---|---|
| unique system | redundant columns or saturated weights | check rank and regularize |
| loss increases | inadequate unit step or gradient error | use backtracking and check derivatives |
| coefficients grow nonstop | Perfect separation | regularize and monitor standard |
| non-finite loss value | exponential or unstable logarithm | work directly with logits |
| slow convergence | poor conditioning | standardize and review features |
| validation worsen | overfit | regularization and selection by validation |
Cost and choice of method
Newton is attractive when the number of parameters is moderate and the matrix fits comfortably in memory. If is large, store and factoring a dense Hessian can dominate the cost. L-BFGS, stochastic gradient or truncated Newton may be better.
Compare with a reference implementation
In tests, compare probabilities, loss and gradient with a library consolidated using the same regularization and intercept convention. Coefficients may differ if libraries normalize the penalty of Different ways.
Exercises
- Correct the pseudocode if the objective function is the sum, not the average, the losses.
- Implement the three relative stopping criteria.
- Force two identical columns and observe the system without regularisation.
- Compare null initialization and intercepted by prevalence.
- Register accepted step, condition of the Hessian and standard of weights in each iteration.
By the Maximum Decline Method
Batch implementation uses the complete gradient
where leaves the intercept without Penalty. Update is
We don’t have to normalize . , all steps would have length , discarding the information that the small gradient may indicate proximity of the The unstandardized version is the most common convention.
Pseudocode
input: X, y, λ, rate or linear search, tolerances, max_iter
add the intercept column
start w
for t = 0, 1, ...:
calculate loss E(w) and gradient g
record loss and
if
Return convergence
choice η
candidate ← w − ηg
if candidate is not finite:
Return numerical failure
update w
check relative variation and iteration limit
Return the last state with reason for stopping
Batch implementation
import number as np
def objective_e_gradiente(Xh, y, w, lambda_l2):
Z = Xh @w
loss = np.mean(np.logaddexp(0.0, z) - y * z)
loss += 0.5 * lambda_l2 * (w[1:] @w[1:])
p = np.empty_like(z)
positive = z >= 0
p[positive] = 1 / (1 + np.exp(-z[positive]))
exp_z = np.exp(z[~positive])
p[~positives] = exp_z / (1 + exp_z)
gradient = Xh.T @ (p - y) / len(Xh)
gradient[1:] += lambda_l2 * w[1:]
return loss, gradient
def adjust_logistica_gradiente(
X,
y,
*,
lambda_l2=1e-4,
rate=0.1,
max_iter=10_000,
tolerance_grad=1e-7,
tolerance_loss=1e-10,
):
X = np.asarray(X, dtype=float)
y = np.asarray(y, dtype=float)
Xh = np.column_stack([np.ones(len(X)), X])
w = np.zeros(Xh.shape[1])
losses = []
standards = []
_Previous loss = None
for iteration in range(1, max_iter + 1):
loss, gradient = objective_e_gradient(
Xh, y, w, lambda_l2
)
standard = np.linalg.norm(gradiente)
losses.append(float(loss))
standards.append(float(standard))
if not np.isfinite(loss) or not np.all(
np.isfinite(gradient)
):
reason = "non-finite value"
break
If standard <= tolerance_grad:
reason = "Gradient standard"
return w, losses, standards, True, motive
if loss_anterior is not None:
change = abs(loss - previous_loss)
scale = max(1.0, abs(loss_anterior))
If variation/scale <= tolerance_loss:
reason = "relative change in loss"
return w, losses, standards, True, motive
w -= rate * gradient
loss_anterior = loss
else:
reason = "iteration limit"
return w, losses, standards, False, motive
This version uses fixed rate. It is suitable for study, but should check if the loss actually decreases. We can replace the line of update by Armijo search presented earlier.
Validation of entries
Before training, add checks:
def validate_classacao_binaria(X, y):
If X.ndim ! = 2:
raise ValueError("X must be two-dimensional")
if y.ndim != 1 or len(X) != len(y):
raise ValueError("y must have a label for example")
if len(X)==References==
raise ValueError("the sample cannot be empty")
if not np.all(np.isfinite(X)) or not np.all(np.isfinite(y)):
raise ValueError("data must be finite")
if not np.all(np.isin(y, (0, 1))):
raise ValueError("labels must belong to {0,1}")
A sample containing only one class can still be accepted mathematically, but requires careful interpretation and generally not allows for useful discriminative evaluation.
Reproducible example
X = np.array([
[-2.0, 0.2],
[-1.5, -0.4],
[-0.5, 0.3],
[ 0.4, -0.2],
[ 1.0, 0.5],
[ 1.8, -0.1],
])
y = np.array([0,0,0,0,1,1], dtype=float)
w_homogene, losses, standards, converged, reason = (
set_logistica_gradient(
X,
y,
lambda_l2=0.01,
rate=0.2,
max_iter=5_000,
)
)
intercept = w_homogeneo[0]
weights = w_homogeneo[1:]
probabilities = probability_positive(
X, pesos, intercept
)
print("converged:", converged, "-", motive)
print("initial/final loss:", losses[0], losses[-1])
print("probabilities:", probabilities)
Useful checks:
assert np.all(np.isfinite(w_homogene))
losses[-1] <= losses[0]
assert np.all((probabilities >= 0) & (probabilities <= 1))
Compare only the final loss with the initial is a weak condition: a execution can end better than started and still oscillate a lot. Fixed batch rate, inspect the entire sequence or use linear search.
Minilots
For minilots, select indexes, calculate the gradient only in the block and Update immediately:
ng = np.random.default_rng(42)
for epoch in range(max_epoca):
indices = ng.permutation(len(Xh))
is beginning in range(0, len(Xh), size_lot):
lot = index[start:start + size_lot]
_, gradient = objective_e_gradient(
Xh[lote], y[lote], w, lambda_l2
)
w -= rate * gradient
There is a subtlety in the regularization: if the batch function adds to full penalty in each minilot, the effective amount of the period of adjustment depends on the number of lots and the rate. Libraries carefully define normalization; when comparing implementations, check if has the same meaning.
Monitoring
A useful chart contains loss of training and validation per season. There are three typical patterns:
- both decrease: the adjustment still improves;
- training decreases and validation increases: possible overfit;
- both oscillate or differ: high rate, poorly scaled data or error of implementation.
Early stop chooses the state of lowest validation loss, no necessarily the last one. As in Pocket, you need to copy the parameters to keep the best state.
Choice of threshold
Log-loss training does not automatically determine the threshold of decision. After adjusting the model:
- manages probabilities in validation;
- assess threshold candidates according to the desired cost or metric;
- set the threshold;
- evaluate once in the test.
If the false positive cost is and the false negative cost is , under simple conditions and calibrated probabilities, the decision with lower cost predicts positive when
Costs, prevalence and real actions need to be defined with the The Commission shall adopt implementing acts.
Final comparison of methods
| Criteria | Newton’s dead | Batch Gradient |
|---|---|---|
| moderate parameters | generally efficient | works, with more iterations |
| many features | Hessian can be prohibitive | memory smaller |
| learning rate | search for still useful step | central choice |
| curvature | explicitly used | ignored |
| minilots | unnatural in the exact form | natural |
| implementation | more complex | simpler |
| essential diagnosis | condition of the Hessian | scale and rate |
Recapitulation of logistic regression
- The linear score models log-odds.
- The sigmoid converts scores into probability.
- Cross-entropy comes from the verisimilitude Bernoulli.
- The gradient is .
- The Hessian is .
- Regularization controls coefficients and improves conditioning.
- Probability, class and action are conceptually distinct outputs.
- Training convergence does not replace validation, calibration and analysis by subgroup.
From model to system
A classifier in production includes data, transformation, parameters, calibration, threshold, treatment of invalid inputs and monitoring. Saving only the weight vector does not preserve the complete behavior.
Integrator exercises
- Run Newton and gradient in the same division and compare losses, Iterations and time.
- Produce a separable sample and observe the coefficients without regularisation.
- Select a threshold that maximizes recall under minimal precision.
- Build a calibration diagram in ten probability ranges.
- Simulate test prevalence change and observe accuracy, accuracy, recall and calibration.
- Explain why choosing the threshold in the test invalidates your function of final evaluation.
4.5 Multiple choice exercises
Tick an alternative in each question and then check the justifications.
-
In the perceptron with labels , an example is correctly classified when:
- .
- .
- for any input.
- is necessarily positive.
-
When finding a poorly classified example, the basic perceptron update for weights:
- .
- .
- .
- .
-
The convergence theorem of the perceptron ensures ending in finite number of updates when the data is:
- linearly separable with positive margin.
- always not separate.
- produced by regression.
- standard, irrespective of the labels.
-
Pocket algorithm is useful mainly because:
- turns any problem into separable.
- keeps the best solution observed during execution.
- calculates perfectly calibrated probabilities.
- does not require a stop criterion.
-
In the linear regression by least squares, the orthogonality condition of the waste is:
- .
- .
- .
- .
-
Why
solveor a QR factoring is usually preferable to calculating explicitly ?- Because it avoids all multiplication.
- Because it tends to offer greater numerical stability.
- Because it eliminates data need.
- Because it always produces whole coefficients.
-
The determination coefficient compares the model error with:
- a reference predictor based on the mean output.
- the amount of classes.
- the highest singular value of .
- the zero-one classification error.
-
The logistic function turns a real score into a value in the range:
- .
- .
- .
- .
-
In binary logistic regression, choose a different decision threshold from :
- is impossible mathematically.
- may alter the compromise between false positives and false negatives.
- it modifies the weights already trained.
- makes all odds equal.
-
Compared to maximum slope, Newton’s method uses:
- only the sign of the labels.
- second-order information through Hessiana.
- a learning rate always equals zero.
- just one observation of the whole.
Answer key with explanations
- a. The positive product indicates that the score has the same signal as the label.
- b. The plot shifts the example score in the direction Correct.
- a. Separability with margin supports the bound of updates; this is not guarantee of generalization.
- b. In non-separable data, current weights may worsen; Pocket preserves the best configuration found.
- a. In normal equations, the residual is orthogonal to the column space of .
- b. Form the inverse and normal equations can zoom point errors Floating and worsening conditioning.
- a. measures the relative reduction of the sum of squares compared to the forecast constant by average.
- c. For every finite real input, the sigmoid produces strictly value between 0 and 1.
- b. The threshold converts probability into action and should reflect costs and application requirements.
- b. The Hessiana describes the local curvature and allows to build a step of Newton.