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

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 x=(x1,…,xd)∈Rdx=(x_1,\ldots,x_d)\in\mathbb R^d, we set

s(x)=b+w1x1+⋯+wdxd,(4.1) s(x)=b+w_1x_1+\cdots+w_dx_d, \tag{4.1}

where w1,…,wdw_1,\ldots,w_d is the weights and bb 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 s(x)s(x), we apply a h0h_0 output function:

hw(x)=h0 ⁣(s(x)). h_w(x)=h_0\!\left(s(x)\right).

The choice of h0h_0 adapts the same linear structure to different types of problem:

TaskOutput spaceTransformationInterpretation
binary classification{−1,+1}\{-1,+1\}h0(s)=sinal⁡(s)h_0(s)=\operatorname{sinal}(s)choose one of two classes
linear regressionR\mathbb Rh0(s)=sh_0(s)=sprovides for a quantity
logistic regression(0,1)(0,1)h0(s)=σ(s)=1/(1+e−s)h_0(s)=\sigma(s)=1/(1+e^{-s})estimates a probability

The same linear score can feed three different output functions.

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 bb into the weight vector by adding a coordinate input constant:

x~=(1,x1,…,xd),w~=(b,w1,…,wd). \widetilde{x}=(1,x_1,\ldots,x_d), \qquad \widetilde{w}=(b,w_1,\ldots,w_d).

So (4.1) takes the compact form

s(x)=w~Tx~. s(x)=\widetilde{w}^{\mathsf T}\widetilde{x}.

The T\mathsf T superscript indicates transposition. If the two vectors are treated as columns, w~T\widetilde{w}^{\mathsf T} is a row and the matrix product produces scalar

w~Tx~=b+w1x1+⋯+wdxd. \widetilde{w}^{\mathsf T}\widetilde{x} =b+w_1x_1+\cdots+w_dx_d.

This “ 11 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 dd features becomes represented by d+1d+1 coordinates.

For a sample with NN examples, we organize entries in the lines of design matrix

X=[1x11⋯x1d1x21⋯x2d⋮⋮⋱⋮1xN1⋯xNd]. X= \begin{bmatrix} 1 & x_{11} & \cdots & x_{1d}\\ 1 & x_{21} & \cdots & x_{2d}\\ \vdots & \vdots & \ddots & \vdots\\ 1 & x_{N1} & \cdots & x_{Nd} \end{bmatrix}.

The Xw~X\widetilde w vector contains the NN 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.

D={(x1,y1),…,(xN,yN)} D=\{(x_1,y_1),\ldots,(x_N,y_N)\}

a labeled sample. For each vector w~\widetilde w, the model produces hw~(xn)h_{\widetilde w}(x_n) predictions . A loss function ℓ(hw~(xn),yn)\ell(h_{\widetilde w}(x_n),y_n) measures the cost of each prediction, and error empirical is usually the average

Ein(w~)=1N∑n=1Nℓ ⁣(hw~(xn),yn). E_{\mathrm{in}}(\widetilde w) =\frac1N\sum_{n=1}^{N} \ell\!\left(h_{\widetilde w}(x_n),y_n\right).

The learning algorithm seeks weights that reduce this error:

w~∗∈arg min⁡w~Ein(w~). \widetilde w^{\ast} \in\operatorname*{arg\,min}_{\widetilde w} E_{\mathrm{in}}(\widetilde w).

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,

b+w1x1+⋯+wdxd=0, b+w_1x_1+\cdots+w_dx_d=0,

is a hyperplane. In two dimensions it is a straight; in three, a plane. The vector w=(w1,…,wd)w=(w_1,\ldots,w_d) 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:

xj′=xj−μjσj, x'_j=\frac{x_j-\mu_j}{\sigma_j},

where μj\mu_j and σj\sigma_j 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:

  1. define the class of hypotheses;
  2. choose an error function;
  3. derive or present the optimization algorithm;
  4. implement the method computationally;
  5. 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 (+1+1) or default (−1-1). calculates a score

s(x)=wTx+b s(x)=w^{\mathsf T}x+b

and compares this score with zero:

hw,b(x)={+1,wTx+b≥0,−1,wTx+b<0.(4.2) h_{w,b}(x)= \begin{cases} +1, & w^{\mathsf T}x+b\geq 0,\\ -1, & w^{\mathsf T}x+b<0. \end{cases} \tag{4.2}

Adopting an explicit rule for the case of equality prevents sinal⁡(0)\operatorname{sinal}(0) stay undefined in the implementation. It would be possible, as long as it was used consistently.

4.2.1 Score Interpretation

The s(x)s(x) 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 wjxjw_jx_j:

  • if wj>0w_j>0, higher values of xjx_j raise the score;
  • if wj<0w_j<0, higher values of xjx_j reduce the score;
  • if wj=0w_j=0, 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 wjxjw_jx_j is usually more informative than the isolated weight.

4.2.2 Geometric interpretation

The decision border contains the zero score points:

{x∈Rd:wTx+b=0}. \{x\in\mathbb R^d:w^{\mathsf T}x+b=0\}.

This set is a hyperplane perpendicular to the vector ww. positive scores stay in a semispace, and negative scores, The other one.

The Perceptron boundary separates the two semispaces; the weight vector is perpendicular to it.

Figure 4.2. The Perceptron boundary separates the two semispaces; the weight vector is perpendicular to it.

In two dimensions, with x=(x1,x2)x=(x_1,x_2) and w2≠0w_2\neq0, we can write to border as a straight line:

w1x1+w2x2+b=0⟺x2=−w1w2x1−bw2. w_1x_1+w_2x_2+b=0 \quad\Longleftrightarrow\quad x_2=-\frac{w_1}{w_2}x_1-\frac{b}{w_2}.

Therefore, −w1/w2-w_1/w_2 is the slope and −b/w2-b/w_2 is the vertical intercept. Change the direction of ww turns the border; change bb moves it without change your orientation.

4.2.3 What the algorithm learns

Given a sample

D={(x1,y1),…,(xN,yN)},yn∈{−1,+1}, D=\{(x_1,y_1),\ldots,(x_N,y_N)\}, \qquad y_n\in\{-1,+1\},

the objective, when the data are linearly separable, is to find the ww and bb such that

yn(wTxn+b)>0for all n.(4.3) y_n\bigl(w^{\mathsf T}x_n+b\bigr)>0 \qquad\text{for all }n. \tag{4.3}

Why does this single inequality represent the two classes? yn=+1y_n=+1, it requires positive score. If yn=−1y_n=-1, multiply by −1-1 reverses the signal and requires negative punctuation.

yn(wTxn+b) y_n\bigl(w^{\mathsf T}x_n+b\bigr)

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:

x=(x1,…,xd)⟼x~=(1,x1,…,xd), x=(x_1,\ldots,x_d) \quad\longmapsto\quad \widetilde{x}=(1,x_1,\ldots,x_d), (b,w1,…,wd)⟼w~=(b,w1,…,wd). (b,w_1,\ldots,w_d) \quad\longmapsto\quad \widetilde{w}=(b,w_1,\ldots,w_d).

The product scale between two vectors column u,v∈Rd+1u,v\in\mathbb R^{d+1} is

uTv=∑j=0dujvj. u^{\mathsf T}v=\sum_{j=0}^{d}u_jv_j.

So,

w~Tx~=b+w1x1+⋯+wdxd.(4.4) \widetilde{w}^{\mathsf T}\widetilde{x} =b+w_1x_1+\cdots+w_dx_d. \tag{4.4}

This writing incorporates the bias in the same operation used for the others weights. It also avoids a common error of orientation: if w~\widetilde w and x~\widetilde x are size column vectors (d+1)×1(d+1)\times1, so w~Tx~\widetilde w^{\mathsf T}\widetilde x is sized 1×11\times1 and represents a scalar. w~x~T\widetilde w\widetilde x^{\mathsf T} would be a matrix (d+1)×(d+1)(d+1)\times(d+1), not the desired scalar product.

With the convention that draws receive the +1+1 label, we define

sinal⁡+(z)={+1,z≥0,−1,z<0. \operatorname{sinal}_{+}(z)= \begin{cases} +1, & z\geq0,\\ -1, & z<0. \end{cases}

Perceptron’s hypothesis class in Rd\mathbb R^d is, then,

Hmathrmperc={hw~(x)=sinal⁡+ ⁣(w~Tx~):w~∈Rd+1}.(4.5) \mathcal H_{mathrm{perc}} =\left\{ h_{\widetilde w}(x) =\operatorname{sinal}_{+} \!\left(\widetilde w^{\mathsf T}\widetilde x\right) :\widetilde w\in\mathbb R^{d+1} \right\}. \tag{4.5}

Note the difference between three objects:

  • Hperc\mathcal H_{\mathrm{perc}} is the class of all borders Linears allowed;
  • hw~h_{\widetilde w} is a particular hypothesis, determined by a parameter vector;
  • g=hw~∗g=h_{\widetilde w^*} is the final hypothesis chosen by algorithm a from the data.

4.2.6 Equivalence of parameterisations

Some texts write the score as wTx−bw^{\mathsf T}x-b and call bb Others write wTx+bw^{\mathsf T}x+b and call bb bias. two forms are equivalent: just swap bb for −b-b. 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,

h(x)=sinal⁡+(2−3x1+x2) h(x)=\operatorname{sinal}_{+}(2-3x_1+x_2)

has homogeneous vector w~=(2,−3,1)\widetilde w=(2,-3,1). x=(1,4)x=(1,4), we have x~=(1,1,4)\widetilde x=(1,1,4) and

w~Tx~=2−3(1)+1(4)=3, \widetilde w^{\mathsf T}\widetilde x =2-3(1)+1(4)=3,

So h(x)=+1h(x)=+1. For x=(2,1)x=(2,1), the score is 2−3(2)+1=−32-3(2)+1=-3 and the forecast is −1-1.

4.2.7 Positive scale invariance

If c>0c>0, the w~\widetilde w and cw~c\widetilde w vectors define exactly the same classification, as

sinal⁡+ ⁣((cw~)Tx~)=sinal⁡+ ⁣(c w~Tx~). \operatorname{sinal}_{+} \!\left((c\widetilde w)^{\mathsf T}\widetilde x\right) = \operatorname{sinal}_{+} \!\left(c\,\widetilde w^{\mathsf T}\widetilde x\right).

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 w~\widetilde w 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 X~∈RN×(d+1)\widetilde X\in\mathbb R^{N\times(d+1)}, all scores can be calculated by

s=X~w~∈RN. s=\widetilde X\widetilde w\in\mathbb R^N.

The component application to sinal⁡+\operatorname{sinal}_{+} 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: X~\widetilde X é N×(d+1)N\times(d+1) e w~\widetilde w é (d+1)×1(d+1)\times1; So the product is N×1N\times1, 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

ℓ0-1(h(xn),yn)=1 ⁣[h(xn)≠yn], \ell_{0\text{-}1}(h(x_n),y_n) =\mathbb 1\!\left[h(x_n)\neq y_n\right],

where 1[Q]\mathbb 1[Q] is worth 11 when the QQ proposition is true and 00 when it is false. The total number of errors in the sample is

Nerro(h)=∑n=1N1 ⁣[h(xn)≠yn], N_{\mathrm{erro}}(h) =\sum_{n=1}^{N} \mathbb 1\!\left[h(x_n)\neq y_n\right],

and the error rate within the sample is

Ein(h)=1NNerro(h).(4.6) E_{\mathrm{in}}(h) =\frac{1}{N}N_{\mathrm{erro}}(h). \tag{4.6}

The count and rate contain the same information when NN 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 {−1,+1}\{-1,+1\} labels

As h(xn)h(x_n) and yny_n belong to {−1,+1}\{-1,+1\}, their difference is zero in a hit and ±2\pm2 on an error.

1 ⁣[h(xn)≠yn]=(h(xn)−yn)24. \mathbb 1\!\left[h(x_n)\neq y_n\right] =\frac{\left(h(x_n)-y_n\right)^2}{4}.

The 1/41/4 factor is indispensable: without it, each error would be counted as four. Therefore, an equivalent form of (4.6) is

Ein(h)=14N∑n=1N(h(xn)−yn)2. E_{\mathrm{in}}(h) =\frac{1}{4N}\sum_{n=1}^{N} \left(h(x_n)-y_n\right)^2.

This equivalence depends specifically on the encoding {−1,+1}\{-1,+1\}. With {0,1}\{0,1\} 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 nn by

mn=yn(wTxn+b). m_n=y_n\left(w^{\mathsf T}x_n+b\right).

With the convention adopted for draws, an example is certainly correctly classified when mn>0m_n>0. When mn<0m_n<0, it is in the wrong side of the border. In mn=0m_n=0, 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:

ℓperc(mn)=1[mn≤0].(4.7) \ell_{\mathrm{perc}}(m_n)=\mathbb 1[m_n\leq0]. \tag{4.7}

The conservative update criterion changes abruptly when the margin crosses zero.

Figure 4.3. The conservative update criterion changes abruptly when the margin crosses zero.

The mnm_n module does not change this criterion: a correct rating by 0,0010{,}001 margin and another by 100100 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 mn≤0m_n\leq0 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 (w,b)(w,b) for which mn>0m_n>0 for all nn, 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 Ein(h)=0E_{\mathrm{in}}(h)=0, 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 1−Ein(h)1-E_{\mathrm{in}}(h), 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 (+1,+1,−1,−1)(+1,+1,-1,-1) labels and predictions (+1,−1,−1,+1)(+1,-1,-1,+1). There are two errors in four examples, therefore Nerro=2N_{\mathrm{erro}}=2, Ein=0,5E_{\mathrm{in}}=0{,}5 and accuracy is 0,50{,}5. By quadratic formula, the sum of the squares is 0+4+0+4=80+4+0+4=8; By dividing by 4N=164N=16, we get 0,50{,}5 again.

4.2.15 Algorithm

The Perceptron algorithm builds the parameters by local corrections. We start with a vector, often w~(0)=0\widetilde w^{(0)}=0. In ttiteration , we chose an example (x~n,yn)(\widetilde x_n,y_n) whose margin is not positive:

yn(w~(t))Tx~n≤0.(4.8) y_n\left(\widetilde w^{(t)}\right)^{\mathsf T} \widetilde x_n\leq0. \tag{4.8}

Then we update.

w~(t+1)=w~(t)+ηynx~n,(4.9) \widetilde w^{(t+1)} =\widetilde w^{(t)}+\eta y_n\widetilde x_n, \tag{4.9}

in which η>0\eta>0 is the learning rate. In the classic Perceptron, η=1\eta=1 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 yn=+1y_n=+1, we add ηx~n\eta\widetilde x_n to the weights, increasing the punctuation of this example. If yn=−1y_n=-1, subtract ηx~n\eta\widetilde x_n, reducing your score. In both cases, the new margin is

mn(t+1)=yn(w~(t+1))Tx~n=yn(w~(t)+ηynx~n)Tx~n=mn(t)+ηyn2x~nTx~n=mn(t)+η∥x~n∥22.(4.10) \begin{aligned} m_n^{(t+1)} &=y_n\left(\widetilde w^{(t+1)}\right)^{\mathsf T}\widetilde x_n\\ &=y_n\left(\widetilde w^{(t)}+\eta y_n\widetilde x_n\right)^{\mathsf T} \widetilde x_n\\ &=m_n^{(t)}+\eta y_n^2\widetilde x_n^{\mathsf T}\widetilde x_n\\ &=m_n^{(t)}+\eta\|\widetilde x_n\|_2^2. \end{aligned} \tag{4.10}

We use yn2=1y_n^2=1. Like η>0\eta>0 and ∥x~n∥22>0\|\widetilde x_n\|_2^2>0, the margin of the selected example always It’s going up.

An update increases the margin of the example that caused the correction.

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 x~n=(1,xn)\widetilde x_n=(1,x_n) and w~=(b,w)\widetilde w=(b,w), (4.9) equals

b(t+1)=b(t)+ηyn,w(t+1)=w(t)+ηynxn. \begin{aligned} b^{(t+1)}&=b^{(t)}+\eta y_n,\\ w^{(t+1)}&=w^{(t)}+\eta y_nx_n. \end{aligned}

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 η\eta 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 w2≠0w_2\neq0, the border w1x1+w2x2+b=0w_1x_1+w_2x_2+b=0 can be drawn as x2=−(w1x1+b)/w2x_2=-(w_1x_1+b)/w_2:

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

  1. Perform training with different seeds. Final weights are The predictions in the sample are the same?
  2. Remove max_epocas from a naive implementation and insert two identical examples with opposite labels. What happens?
  3. Compare the erros_por_epoca history 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

p=(0,2),yp=+1, p=(0,2),\qquad y_p=+1, q=(1,1),yq=−1. q=(1,1),\qquad y_q=-1.

In the homogeneous representation,

p~=(1,0,2),q~=(1,1,1). \widetilde p=(1,0,2), \qquad \widetilde q=(1,1,1).

Choose as Start Status w~(0)=(0,0,2)\widetilde w^{(0)}=(0,0,2). The first coordinate is bias; both remaining are the features weights. The initial border satisfies

0+0x1+2x2=0, 0+0x_1+2x_2=0,

I mean, x2=0x_2=0.

Step 1: Find error

The initial scores are

(w~(0))Tp~=0+0(0)+2(2)=4, \left(\widetilde w^{(0)}\right)^{\mathsf T}\widetilde p =0+0(0)+2(2)=4, (w~(0))Tq~=0+0(1)+2(1)=2. \left(\widetilde w^{(0)}\right)^{\mathsf T}\widetilde q =0+0(1)+2(1)=2.

The pp point is positive and received positive score, so it is The qq point is negative, but it also received a positive score. Your margin confirms the error:

mq(0)=yq(w~(0))Tq~=(−1)(2)=−2<0. m_q^{(0)} =y_q\left(\widetilde w^{(0)}\right)^{\mathsf T}\widetilde q =(-1)(2)=-2<0.

Step 2: Update and Verify

With η=1\eta=1 rate , we use qq to update:

w~(1)=w~(0)+yqq~=(0,0,2)−(1,1,1)=(−1,−1,1). \begin{aligned} \widetilde w^{(1)} &=\widetilde w^{(0)}+y_q\widetilde q\\ &=(0,0,2)-(1,1,1)\\ &=(-1,-1,1). \end{aligned}

The new border is

−1−x1+x2=0⟺x2=x1+1. -1-x_1+x_2=0 \quad\Longleftrightarrow\quad x_2=x_1+1.

Now, the scores are

(w~(1))Tp~=−1−1(0)+1(2)=1, \left(\widetilde w^{(1)}\right)^{\mathsf T}\widetilde p =-1-1(0)+1(2)=1, (w~(1))Tq~=−1−1(1)+1(1)=−1. \left(\widetilde w^{(1)}\right)^{\mathsf T}\widetilde q =-1-1(1)+1(1)=-1.

Therefore, pp receives +1+1 and qq receives −1-1. A single update was Enough to separate the sample.

The correction caused by q transforms the horizontal border into a straight line that separates the two points.

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. ∥q~∥2=12+12+12=3\|\widetilde q\|^2=1^2+1^2+1^2=3,

mq(1)=mq(0)+∥q~∥2=−2+3=1, m_q^{(1)} =m_q^{(0)}+\|\widetilde q\|^2 =-2+3=1,

which matches with yq(w~(1))Tq~=(−1)(−1)=1y_q(\widetilde w^{(1)})^{\mathsf T}\widetilde q=(-1)(-1)=1.

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 w~(0)=(0,0,0)\widetilde w^{(0)}=(0,0,0) and going through first pp and then qq. 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 dd features, calculate wTx+bw^{\mathsf T}x+b costs O(d)O(d). A passage by NN examples costs O(Nd)O(Nd); therefore, run KK eras has cost O(KNd)O(KNd) and requires O(d)O(d) memory for the parameters, besides the memory used to store or transmit the data.

This calculation does not inform how much KK 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 x~n\widetilde x_n to include bias. Suppose there is a unit vector uu, with ∥u∥2=1\|u\|_2=1, that separate the sample with γ>0\gamma>0 margin :

ynuTx~n≥γfor all n.(4.11) y_nu^{\mathsf T}\widetilde x_n\geq\gamma \qquad\text{for all }n. \tag{4.11}

Set also the radius

R=max⁡1≤n≤N∥x~n∥2.(4.12) R=\max_{1\leq n\leq N}\|\widetilde x_n\|_2. \tag{4.12}

As uu is unitary, ∣uTx~∣|u^{\mathsf T}\widetilde x| is the distance signed from point to hyperplane uTx~=0u^{\mathsf T}\widetilde x=0. The margin γ\gamma is the smallest distance signed after fixing the side with yny_n; is the nearest point that limits the clearance of the separation.

The margin is determined by the closest examples to the border.

Figure 4.6. The margin is determined by the closest examples to the border.

To a border in non-standard form wTx+b=0w^{\mathsf T}x+b=0, the geometric distance of a xx point is

dist⁡(x,H)=∣wTx+b∣∥w∥2. \operatorname{dist}(x,H) =\frac{|w^{\mathsf T}x+b|}{\|w\|_2}.

The denominator is ∥w∥2\|w\|_2, not ∥w∥22\|w\|_2^2. This formula stems from the projection on the normal direction w/∥w∥2w/\|w\|_2. Remembering the product climb,

vTz=∥v∥2 ∥z∥2cos⁡θ, v^{\mathsf T}z=\|v\|_2\,\|z\|_2\cos\theta,

where θ\theta is the angle between vectors.

4.2.29 Convergence theorem

Perceptron convergence theorem

Consider w~(0)=0\widetilde w^{(0)}=0, η=1\eta=1 rate and a sample that satisfies (4.11) and (4.12). Perceptron commits maximum

T≤(Rγ)2 T\leq\left(\frac{R}{\gamma}\right)^2

updates before finding a correct separation.

The bound depends on the ratio R/γR/\gamma. 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 TT updates, each caused by (x~t,yt)(\widetilde x_t,y_t), we have

w~(T)=∑t=1Tytx~t. \widetilde w^{(T)} =\sum_{t=1}^{T}y_t\widetilde x_t.

Projecting the accumulated vector over the direction of the uu solution,

uTw~(T)=∑t=1TytuTx~t≥Tγ.(4.13) u^{\mathsf T}\widetilde w^{(T)} =\sum_{t=1}^{T}y_tu^{\mathsf T}\widetilde x_t \geq T\gamma. \tag{4.13}

By Cauchy-Schwarz and ∥u∥=1\|u\|=1,

uTw~(T)≤∥w~(T)∥2. u^{\mathsf T}\widetilde w^{(T)} \leq\|\widetilde w^{(T)}\|_2.

Now we limit the growth of the standard. How an update occurs when yt(w~(t))Tx~t≤0y_t(\widetilde w^{(t)})^{\mathsf T}\widetilde x_t\leq0,

∥w~(t+1)∥22=∥w~(t)+ytx~t∥22=∥w~(t)∥22+2yt(w~(t))Tx~t+∥x~t∥22≤∥w~(t)∥22+R2. \begin{aligned} \|\widetilde w^{(t+1)}\|_2^2 &=\|\widetilde w^{(t)}+y_t\widetilde x_t\|_2^2\\ &=\|\widetilde w^{(t)}\|_2^2 +2y_t(\widetilde w^{(t)})^{\mathsf T}\widetilde x_t +\|\widetilde x_t\|_2^2\\ &\leq\|\widetilde w^{(t)}\|_2^2+R^2. \end{aligned}

Adding TT updates,

∥w~(T)∥22≤TR2,∥w~(T)∥2≤TR.(4.14) \|\widetilde w^{(T)}\|_2^2\leq TR^2, \qquad \|\widetilde w^{(T)}\|_2\leq\sqrt{T}R. \tag{4.14}

Combining (4.13) and (4.14),

Tγ≤TR⟹T≤R2γ2. T\gamma\leq\sqrt{T}R \quad\Longrightarrow\quad T\leq\frac{R^2}{\gamma^2}.

The argument shows a contrast: alignment with the solution grows linearly in TT, while the norm grows at most as T\sqrt{T}. 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 O(d)O(d) and the theorem limits the amount of corrections to (R/γ)2(R/\gamma)^2. However, find a time without errors still requires checking the examples. For an implementation by times, the most transparent measure remains

O(KNd), O(KNd),

recording separately KK and the total number of updates. distinction avoids interpreting the theoretical bound as if it were directly the program clock time.

Exercises

  1. What happens to bound if all input vectors are multiplied by a positive constant cc? Consider also how The margin changes.
  2. Show which step of the demonstration the separability is used.
  3. One execution made 80 updates in 12 seasons. Which of these numbers can be directly compared with (R/γ)2(R/\gamma)^2?

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 wTx+b=0w^{\mathsf T}x+b=0;
  • 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:

  1. Does every update reduce the total number of errors?
  2. Is the highlighted example correct immediately after your update?
  3. How many updates do you have in each season?
  4. Does the final frontier change when the order of examples changes?
  5. 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 Ein=0E_{\mathrm{in}}=0 is impossible or undesirable.

Current and saved state

Pocket maintains two distinct vectors:

  • w~atual\widetilde w_{\mathrm{atual}}, which continues to receive updates Perceptron;
  • w~melhor\widetilde w_{\mathrm{melhor}}, which represents the smallest error of training found until that moment.

After each update of the current state, we calculated

Ein(w~)=1N∑n=1N1 ⁣[hw~(xn)≠yn]. E_{\mathrm{in}}(\widetilde w) =\frac1N\sum_{n=1}^{N} \mathbb 1\!\left[ h_{\widetilde w}(x_n)\neq y_n \right].

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.

The current state may worsen, while the smallest error saved by Pocket never increases.

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 O(d)O(d), but recalculate the error on all examples cost O(Nd)O(Nd). If this evaluation occurs after each of the TT updates, the cost is O(TNd)O(TNd). 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

AspectClassic PerceptronPocket
status returnedlast statebest observed state
separateableconverge to zero errorcan also achieve zero error
non-separablecan oscillatereturns a found approach
extra memoryO(d)O(d)O(d)O(d) for additional copy
error assessmentis not required at every stepusually costs O(Nd)O(Nd)
guarantee of great globalnono

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

ElementPerceptron formulation
entryx∈Rdx\in\mathbb R^d
labely∈{−1,+1}y\in\{-1,+1\}
scores(x)=wTx+bs(x)=w^{\mathsf T}x+b
hypothesish(x)=sinal⁡+(s(x))h(x)=\operatorname{sinal}_{+}(s(x))
borderwTx+b=0w^{\mathsf T}x+b=0
functional marginy(wTx+b)y(w^{\mathsf T}x+b)
update conditiony(wTx+b)≤0y(w^{\mathsf T}x+b)\leq0
updatew←w+ηyxw\leftarrow w+\eta yx, b←b+ηyb\leftarrow b+\eta y
empirical errormean 1[h(xn)≠yn]\mathbb 1[h(x_n)\neq y_n]
convergence hypothesislinearly separable sample
update boundT≤(R/γ)2T\leq(R/\gamma)^2

The vector ww is perpendicular to the border, while bb controls its offset. Adding a constant coordinate allows you to write both as a single homogeneous vector w~\widetilde w.

The flow of training

  1. Initialize the parameters.
  2. Calculate the margin of an example.
  3. If the margin is not positive, update in the direction yxy x.
  4. Repeat until you complete a time without updates or reach the limit of execution.
  5. 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

  1. What is the difference between zero-one loss and the update criterion based on non-positive margin?
  2. Why y(wTx+b)>0y(w^{\mathsf T}x+b)>0 correctly represents the two classes in a single inequality?
  3. What happens geometrically when we change only bb? And when Do we alter the direction of ww?
  4. Why the melhor_w = w assignment can invalidate an implementation Pocket in NumPy?
  5. On what hypothesis does the convergence theorem depend? Give an example of sample that violates this hypothesis.
  6. Does the number of errors necessarily decrease after each update? Justify with the local nature of the rule.

Application problems

  1. An update. For x=(2,−1)x=(2,-1), y=−1y=-1, w=(1,3)w=(1,3), b=0b=0 and η=0,5\eta=0{,}5, calculate the margin. Determine if there is update and, if any, get the new parameters.
  2. Border. Write the line equation defined by w=(2,−4)w=(2,-4) and b=8b=8. Identify slope and intercept.
  3. XOR. Represent the four binary points (0,0),(0,1),(1,0),(1,1)(0,0),(0,1),(1,0),(1,1), labeling the odd parity as positive. Explain geometrically why a single straight line does not separate classes.
  4. Complexity. A base has N=50 000N=50\,000 examples and d=200d=200 features. How many weight-attribute products are needed, approximately, for ten complete seasons?
  5. Cota. If R=5R=5 and γ=0,25\gamma=0{,}25, calculate the bound for updates. Explain why the value does not predict exactly the time observed.

Brief answers to the conference

  1. In the first problem, the score is −1-1, the margin is 11 and there is no update.
  2. The straight line is 2x1−4x2+8=02x_1-4x_2+8=0, or x2=0,5x1+2x_2=0{,}5x_1+2.
  3. In XOR, equal classes occupy opposite vertices; any line leaves at least one vertex on the incompatible side.
  4. Ten seasons require approximately 10⋅50 000⋅200=10810\cdot50\,000\cdot200=10^8 multiplications, plus sums and others Costs.
  5. The bound is (5/0,25)2=400(5/0{,}25)^2=400 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 wTx+bw^{\mathsf T}x+b, 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

(xn,yn),xn∈Rd,yn∈R, (x_n,y_n), \qquad x_n\in\mathbb R^d, \quad y_n\in\mathbb R,

where xnx_n contains the features and yny_n is the target value observed. sample is

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

The model assigns to each input a real forecast

y^=hw,b(x)=wTx+b.(4.15) \widehat y=h_{w,b}(x)=w^{\mathsf T}x+b. \tag{4.15}

The “hat” symbol distinguishes the y^\widehat y forecast from the observed value yy. Difference

en=yn−y^n e_n=y_n-\widehat y_n

is the residual example of nn. Positive residual means the model predicted below the observed value; negative residual means that predicted above.

Regression chooses a straight line that approximates the observed values; the traced segments are residuals.

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:

y^=b+wx. \widehat y=b+wx.

The weight ww is the slope: increase xx in a unit changes the forecast in ww units. The bb bias is the prediction when x=0x=0, although this interpretation is only relevant if zero makes sense in the field.

With two features, the forecast graph is a plan; with dd features, It’s a d+1d+1 dimension hyperplane. directly when dd 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 nn input and a rr density measure. A possible model is

t^=0,4+0,015n+1,8r. \widehat t=0{,}4+0{,}015n+1{,}8r.

For n=100n=100 and r=0,5r=0{,}5, the forecast is

t^=0,4+0,015(100)+1,8(0,5)=2,8. \widehat t=0{,}4+0{,}015(100)+1{,}8(0{,}5)=2{,}8.

If the observed time is 3,13{,}1 seconds, the residual is 3,1−2,8=0,33{,}1-2{,}8=0{,}3 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:

MSE⁡(w,b)=1N∑n=1N(yn−wTxn−b)2. \operatorname{MSE}(w,b) =\frac1N\sum_{n=1}^{N} \left(y_n-w^{\mathsf T}x_n-b\right)^2.

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, y^=w0+w1x+w2x2\widehat y=w_0+w_1x+w_2x^2 is curved in xx, but it is linear in the vector (w0,w1,w2)(w_0,w_1,w_2) when we use (1,x,x2)(1,x,x^2) 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 dd features, the linear regression class with intercept is

Hmathrmlin={hw,b:Rd→R  |  hw,b(x)=wTx+b,  w∈Rd,  b∈R}.(4.16) \mathcal H_{mathrm{lin}} =\left\{ h_{w,b}:\mathbb R^d\to\mathbb R \;\middle|\; h_{w,b}(x)=w^{\mathsf T}x+b, \;w\in\mathbb R^d, \;b\in\mathbb R \right\}. \tag{4.16}

Each choice of (w,b)(w,b) 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

x~=(1,x1,…,xd),w~=(b,w1,…,wd), \widetilde x=(1,x_1,\ldots,x_d), \qquad \widetilde w=(b,w_1,\ldots,w_d),

and write

hw~(x)=x~Tw~.(4.17) h_{\widetilde w}(x) =\widetilde x^{\mathsf T}\widetilde w. \tag{4.17}

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. x~Tw~\widetilde x^{\mathsf T}\widetilde w in abstract notation corresponds to a line multiplied by the column vector of parameters in the implementation.

More precisely, if x~\widetilde x is defined as column vector, we use x~Tw~\widetilde x^{\mathsf T}\widetilde w; 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 NN examples in the lines of the design matrix:

X~=[1x11x12⋯x1d1x21x22⋯x2d⋮⋮⋮⋱⋮1xN1xN2⋯xNd]∈RN×(d+1). \widetilde X= \begin{bmatrix} 1 & x_{11} & x_{12} & \cdots & x_{1d}\\ 1 & x_{21} & x_{22} & \cdots & x_{2d}\\ \vdots & \vdots & \vdots & \ddots & \vdots\\ 1 & x_{N1} & x_{N2} & \cdots & x_{Nd} \end{bmatrix} \in\mathbb R^{N\times(d+1)}.

The target vector is

y=[y1y2⋮yN]∈RN, y= \begin{bmatrix} y_1\\y_2\\\vdots\\y_N \end{bmatrix} \in\mathbb R^N,

and the forecast vector of a hypothesis is

y^=X~w~∈RN.(4.18) \widehat y =\widetilde X\widetilde w \in\mathbb R^N. \tag{4.18}

The dimensions confirm the operation:

X~⏟N×(d+1)w~⏟(d+1)×1=y^⏟N×1. \underbrace{\widetilde X}_{N\times(d+1)} \underbrace{\widetilde w}_{(d+1)\times1} = \underbrace{\widehat y}_{N\times1}.

Each line of multiplication reproduces y^n=b+w1xn1+⋯+wdxnd\widehat y_n=b+w_1x_{n1}+\cdots+w_dx_{nd}.

4.3.9 Residual vector

Gathering the waste from all the examples,

e=y−y^=y−X~w~.(4.19) e=y-\widehat y =y-\widetilde X\widetilde w. \tag{4.19}

The least square regression will choose w~\widetilde w to make the small ∥e∥2\|e\|_2 standard. Geometrically, it measures deviations in the direction of the output axis yy, 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

h(x)=b+w1x1+⋯+wdxd, h(x)=b+w_1x_1+\cdots+w_dx_d,

the wjw_j coefficient is the variation in the prediction caused by increasing the xjx_j in a drive keeping the other features constant. Your units are

[wj]=[y][xj]. [w_j]=\frac{[y]}{[x_j]}.

If yy is measured in real and xjx_j in square meters, for example, wjw_j 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 b=0b=0 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 xx with a vector of ϕ(x)\phi(x) features :

hw(x)=wTϕ(x). h_w(x)=w^{\mathsf T}\phi(x).

With ϕ(x)=(1,x,x2)\phi(x)=(1,x,x^2), we get a quadratic polynomial regression. binary indicators, we can represent categories; with products xixjx_ix_j, we can represent interactions. ww 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:

Ein(w~)=MSE⁡(w~)=1N∑n=1N(yn−x~nTw~)2.(4.20) E_{\mathrm{in}}(\widetilde w) =\operatorname{MSE}(\widetilde w) =\frac1N\sum_{n=1}^{N} \left(y_n-\widetilde x_n^{\mathsf T}\widetilde w\right)^2. \tag{4.20}

The word “medium” corresponds to factor 1/N1/N. 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

SSE⁡(w~)=∑n=1Nen2. \operatorname{SSE}(\widetilde w) =\sum_{n=1}^{N}e_n^2.

How MSE⁡=SSE⁡/N\operatorname{MSE}=\operatorname{SSE}/N and NN 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

RMSE⁡=1N∑n=1Nen2. \operatorname{RMSE} =\sqrt{\frac1N\sum_{n=1}^{N}e_n^2}.

MSE has y2y^2 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),

e=y−X~w~. e=y-\widetilde X\widetilde w.

The Euclidean Standard Satisfys

∥e∥22=eTe=∑n=1Nen2. \|e\|_2^2=e^{\mathsf T}e=\sum_{n=1}^{N}e_n^2.

Thus, (4.20) can be written in a compact way:

Ein(w~)=1N∥y−X~w~∥22.(4.21) E_{\mathrm{in}}(\widetilde w) =\frac1N \left\|y-\widetilde X\widetilde w\right\|_2^2. \tag{4.21}

Expanding the product,

Ein(w~)=1N(yTy−2w~TX~Ty+w~TX~TX~w~).(4.22) E_{\mathrm{in}}(\widetilde w) =\frac1N \left( y^{\mathsf T}y -2\widetilde w^{\mathsf T}\widetilde X^{\mathsf T}y +\widetilde w^{\mathsf T}\widetilde X^{\mathsf T} \widetilde X\widetilde w \right). \tag{4.22}

This is a quadratic function of w~\widetilde w. Its Hessian matrix is proportional to X~TX~\widetilde X^{\mathsf T}\widetilde X, 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:

MAE⁡=1N∑n=1N∣en∣. \operatorname{MAE} =\frac1N\sum_{n=1}^{N}|e_n|.

Squared loss assigns increasing influence to large-module waste.

Figure 4.9. Squared loss assigns increasing influence to large-module waste.

PropertyMSE/RMSEM.E.
loss growthquadraticlinear
sensitivity to atypical valueslargerminor
0-differentiabilityYeah.no
associated central estimateconditional averageconditional median
reported unitMSE: square; RMSE: originaloriginal

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 (1,−1,2,10)(1,-1,2,10) waste.

MAE⁡=1+1+2+104=3,5, \operatorname{MAE} =\frac{1+1+2+10}{4}=3{,}5,

while

MSE⁡=1+1+4+1004=26,5. \operatorname{MSE} =\frac{1+1+4+100}{4}=26{,}5.

The last example answers by 100/106≈94,3%100/106\approx94{,}3\% 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

R2=1−∑n(yn−y^n)2∑n(yn−y‾)2, R^2 =1- \frac{\sum_n(y_n-\widehat y_n)^2} {\sum_n(y_n-\overline y)^2},

where y‾\overline y is the average of the targets of the evaluated set. numerator is the model error and the denominator is the predictor error constant y‾\overline y.

  • R2=1R^2=1 indicates perfect predictions in that set;
  • R2=0R^2=0 indicates performance equal to the mean predictor;
  • R2<0R^2<0 means that the model is worse than this reference predictor.

Therefore, R2R^2 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 R2R^2 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

w~∗∈arg min⁡w~∈Rd+11N∥y−X~w~∥22.(4.23) \widetilde w^* \in\operatorname*{arg\,min}_{\widetilde w\in\mathbb R^{d+1}} \frac1N \left\|y-\widetilde X\widetilde w\right\|_2^2. \tag{4.23}

We write arg min⁡\operatorname*{arg\,min} 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 w~∗\widetilde w^*.

The 1/N1/N 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 X~TX~\widetilde X^{\mathsf T}\widetilde X, the solution can be written as

w~∗=(X~TX~)−1X~Ty.(4.24) \widetilde w^* =\left(\widetilde X^{\mathsf T}\widetilde X\right)^{-1} \widetilde X^{\mathsf T}y. \tag{4.24}

This expression is called solution normal equations. It will be obtained in two ways:

  1. geometrically: X~w~∗\widetilde X\widetilde w^* is the projection yy orthogonal over the space generated by the columns of X~\widetilde X;
  2. by differentiation: at least, the error gradient relative to parameters are zero.

The two arguments produce the same condition:

X~T(y−X~w~∗)=0.(4.25) \widetilde X^{\mathsf T} \left(y-\widetilde X\widetilde w^*\right)=0. \tag{4.25}

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 X~TX~\widetilde X^{\mathsf T}\widetilde X. 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 d+1d+1 columns of X~\widetilde X are linearly independent, So…

posto⁡(X~)=d+1 \operatorname{posto}(\widetilde X)=d+1

and X~TX~\widetilde X^{\mathsf T}\widetilde X 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 as numpy.linalg.lstsq, which deals with rectangular matrices and informs the Estimated rank.

4.3.23 Complexity in general

For NN examples and p=d+1p=d+1 parameters, storing the dense matrix costs O(Np)O(Np). A direct solution per QR typically costs O(Np2)O(Np^2) when N≥pN\geq p plus O(p2)O(p^2) 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 A∈Rm×nA\in\mathbb R^{m\times n}, the transposed AT∈Rn×mA^{\mathsf T}\in\mathbb R^{n\times m} exchanges rows for columns. No our problem,

X~TX~∈Rp×p,X~Ty∈Rp. \widetilde X^{\mathsf T}\widetilde X \in\mathbb R^{p\times p}, \qquad \widetilde X^{\mathsf T}y \in\mathbb R^p.

Therefore, normal equations form a square system with pp 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 RN\mathbb R^N, the space that has a coordinate for each example. The target vector

y=(y1,…,yN)T y=(y_1,\ldots,y_N)^{\mathsf T}

for each choice of parameters, the vector of the vector is a point in this space. predictions is X~w~\widetilde X\widetilde w. Which forecast vectors are possible?

The space column

Write the design matrix in terms of your columns:

X~=[∣∣∣c0c1⋯cd∣∣∣]. \widetilde X= \begin{bmatrix} \vert & \vert & & \vert\\ c_0 & c_1 & \cdots & c_d\\ \vert & \vert & & \vert \end{bmatrix}.

So…

X~w~=w0c0+w1c1+⋯+wdcd. \widetilde X\widetilde w =w_0c_0+w_1c_1+\cdots+w_dc_d.

Therefore, the set of all possible predictions is the space generated by the columns of X~\widetilde X:

Col⁡(X~)={X~w~:w~∈Rd+1}⊆RN. \operatorname{Col}(\widetilde X) =\{\widetilde X\widetilde w: \widetilde w\in\mathbb R^{d+1}\} \subseteq\mathbb R^N.

Even if the model has few parameters, each forecast on the whole sample is a vector with NN 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

∥y−X~w~∥2 \left\|y-\widetilde X\widetilde w\right\|_2

means find the Col⁡(X~)\operatorname{Col}(\widetilde X) point more near yy. This point is orthogonal projection y^=PwidetildeXy\widehat y=P_{widetilde X}y.

The target vector is decomposed in the prediction, which belongs to the column space, and the orthogonal residual.

Figure 4.10. The target vector is decomposed in the prediction, which belongs to the column space, and the orthogonal residual.

The Great Residual

e∗=y−y^=y−X~w~∗ e^*=y-\widehat y =y-\widetilde X\widetilde w^*

is perpendicular to every vector of the column space. In particular, it is perpendicular to each column of X~\widetilde X:

X~Te∗=0. \widetilde X^{\mathsf T}e^*=0.

By replacing the residual definition,

X~T(y−X~w~∗)=0, \widetilde X^{\mathsf T} \left(y-\widetilde X\widetilde w^*\right)=0,

and we get the normal equations

X~TX~w~∗=X~Ty.(4.26) \widetilde X^{\mathsf T}\widetilde X\widetilde w^* =\widetilde X^{\mathsf T}y. \tag{4.26}

Why does orthogonality guarantee the minimum?

Consider any other parameter vector w~=w~∗+Δ\widetilde w=\widetilde w^*+\Delta. Your residual is

y−X~w~=e∗−X~Δ. y-\widetilde X\widetilde w =e^*-\widetilde X\Delta.

The first term is perpendicular to the column space, and the second belongs By Pythagoras’ theorem,

∥e∗−X~Δ∥22=∥e∗∥22+∥X~Δ∥22≥∥e∗∥22. \left\|e^*-\widetilde X\Delta\right\|_2^2 =\|e^*\|_2^2+\|\widetilde X\Delta\|_2^2 \geq\|e^*\|_2^2.

Therefore, no other possible prediction is closer to yy. equality can occur for Δ≠0\Delta\neq0 only if X~Δ=0\widetilde X\Delta=0, that is, if the matrix has a non-trivial core And the parameters aren’t unique.

Full post case

If the columns of X~\widetilde X are linearly independent, X~TX~\widetilde X^{\mathsf T}\widetilde X is invertible. Isolating parameters in (4.26),

w~∗=(X~TX~)−1X~Ty. \widetilde w^* =\left(\widetilde X^{\mathsf T}\widetilde X\right)^{-1} \widetilde X^{\mathsf T}y.

The projection matrix over the column space is, in this case,

PwidetildeX=X~(X~TX~)−1X~T, P_{widetilde X} =\widetilde X \left(\widetilde X^{\mathsf T}\widetilde X\right)^{-1} \widetilde X^{\mathsf T},

Because y^=X~w~∗=PX~y\widehat y=\widetilde X\widetilde w^*=P_{\widetilde X}y. She’s satisfied.

PX~T=PX~,PX~2=PX~, P_{\widetilde X}^{\mathsf T}=P_{\widetilde X}, \qquad P_{\widetilde X}^2=P_{\widetilde X},

symmetry and idempotence properties characteristic of a projection orthogonal.

Deficient position and pseudo-inverse

Having N>d+1N>d+1 does not guarantee column independence. Two features can be duplicated or one can be combination of the others. X~TX~\widetilde X^{\mathsf T}\widetilde X is not invertible, we use Moore’s pseudo-inverse–Penrose:

w~∗=X~+y. \widetilde w^*=\widetilde X^+y.

In this case, X~+\widetilde X^+ should not be automatically defined by (X~TX~)−1X~T(\widetilde X^{\mathsf T}\widetilde X)^{-1}\widetilde X^{\mathsf T}, 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 x=(0,1,2)Tx=(0,1,2)^{\mathsf T} attribute, targets y=(1,2,2)Ty=(1,2,2)^{\mathsf T} and intercept:

X~=[101112]. \widetilde X= \begin{bmatrix} 1&0\\1&1\\1&2 \end{bmatrix}.

Normal equations produce

w~∗=[7/61/2],y^=[7/65/313/6]. \widetilde w^*= \begin{bmatrix}7/6\\1/2\end{bmatrix}, \qquad \widehat y= \begin{bmatrix}7/6\\5/3\\13/6\end{bmatrix}.

The residual vector is

e∗=y−y^=[−1/61/3−1/6]. e^*=y-\widehat y =\begin{bmatrix}-1/6\\1/3\\-1/6\end{bmatrix}.

We can verify orthogonality with the two columns:

[111]e∗=0,[012]e∗=0. \begin{bmatrix}1&1&1\end{bmatrix}e^*=0, \qquad \begin{bmatrix}0&1&2\end{bmatrix}e^*=0.

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 xx 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:

E(w~)=1N∑n=1N(yn−x~nTw~)2. E(\widetilde w) =\frac1N\sum_{n=1}^{N} \left(y_n-\widetilde x_n^{\mathsf T}\widetilde w\right)^2.

Before using matrix notation, we derive each coordinate. visible the origin of all factors and signs.

Coordinate derivation

For the wjw_j parameter , the string rule provides

∂E∂wj=1N∑n=1N2(yn−x~nTw~)∂∂wj(yn−x~nTw~)=−2N∑n=1Nx~nj(yn−x~nTw~). \begin{aligned} \frac{\partial E}{\partial w_j} &=\frac1N\sum_{n=1}^{N} 2\left(y_n-\widetilde x_n^{\mathsf T}\widetilde w\right) \frac{\partial}{\partial w_j} \left(y_n-\widetilde x_n^{\mathsf T}\widetilde w\right)\\ &=-\frac2N\sum_{n=1}^{N} \widetilde x_{nj} \left(y_n-\widetilde x_n^{\mathsf T}\widetilde w\right). \end{aligned}

If we set e=y−X~w~e=y-\widetilde X\widetilde w, gather all derivatives Partial produces

∇E(w~)=−2NX~Te=2NX~T(X~w~−y).(4.27) \nabla E(\widetilde w) =-\frac2N\widetilde X^{\mathsf T}e =\frac2N\widetilde X^{\mathsf T} \left(\widetilde X\widetilde w-y\right). \tag{4.27}

The dimensions are consistent: X~T\widetilde X^{\mathsf T} is (d+1)×N(d+1)\times N and the residual vector is N×1N\times1, therefore the gradient has d+1d+1 components.

Derivative by quadratic form

We can also expand the MSE:

E(w~)=1N(y−X~w~)T(y−X~w~)=1N(yTy−2w~TX~Ty+w~TX~TX~w~). \begin{aligned} E(\widetilde w) &=\frac1N \left(y-\widetilde X\widetilde w\right)^{\mathsf T} \left(y-\widetilde X\widetilde w\right)\\ &=\frac1N\left( y^{\mathsf T}y -2\widetilde w^{\mathsf T}\widetilde X^{\mathsf T}y +\widetilde w^{\mathsf T}\widetilde X^{\mathsf T} \widetilde X\widetilde w \right). \end{aligned}

We use identities.

(AB)T=BTAT,(AT)T=A, (AB)^{\mathsf T}=B^{\mathsf T}A^{\mathsf T}, \qquad (A^{\mathsf T})^{\mathsf T}=A,

and the fact that a scalar is equal to its transposition. symmetric AA,

∇w(wTAw)=2Aw. \nabla_w(w^{\mathsf T}Aw)=2Aw.

Since X~TX~\widetilde X^{\mathsf T}\widetilde X 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,

X~T(X~w~∗−y)=0, \widetilde X^{\mathsf T} \left(\widetilde X\widetilde w^*-y\right)=0,

or

X~TX~w~∗=X~Ty. \widetilde X^{\mathsf T}\widetilde X\widetilde w^* =\widetilde X^{\mathsf T}y.

It’s exactly the normal equations obtained by the projection. X~TX~\widetilde X^{\mathsf T}\widetilde X is invertible,

w~∗=(X~TX~)−1X~Ty. \widetilde w^* =\left(\widetilde X^{\mathsf T}\widetilde X\right)^{-1} \widetilde X^{\mathsf T}y.

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

∇2E(w~)=2NX~TX~.(4.28) \nabla^2E(\widetilde w) =\frac2N\widetilde X^{\mathsf T}\widetilde X. \tag{4.28}

For any vv vector,

vT∇2E(w~)v=2NvTX~TX~v=2N∥X~v∥22≥0. v^{\mathsf T}\nabla^2E(\widetilde w)v =\frac2N v^{\mathsf T}\widetilde X^{\mathsf T}\widetilde Xv =\frac2N\|\widetilde Xv\|_2^2 \geq0.

Therefore, Hessiana is positive semi-defined and EE is convex. normal equations is a global minimum. X~\widetilde X has full columns, inequality is strict for v≠0v\neq0, the Hessian is positive defined and the minimum is unique.

The gradient as sum of contributions

The formula

∇E(w~)=−2N∑n=1Nenx~n \nabla E(\widetilde w) =-\frac2N\sum_{n=1}^{N}e_n\widetilde x_n

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

w~(t+1)=w~(t)−η∇E(w~(t)), \widetilde w^{(t+1)} =\widetilde w^{(t)} -\eta\nabla E(\widetilde w^{(t)}),

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 y^n=b+wxn\widehat y_n=b+wx_n,

E(b,w)=1N∑n(yn−b−wxn)2. E(b,w)=\frac1N\sum_n(y_n-b-wx_n)^2.

The two first-order equations are:

∂E∂b=−2N∑n(yn−b−wxn)=0, \frac{\partial E}{\partial b} =-\frac2N\sum_n(y_n-b-wx_n)=0, ∂E∂w=−2N∑nxn(yn−b−wxn)=0. \frac{\partial E}{\partial w} =-\frac2N\sum_nx_n(y_n-b-wx_n)=0.

The first states that waste adds up to zero; the second states that waste are orthogonal to the vector of the xnx_n 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 −2X~Te/N-2\widetilde X^{\mathsf T}e/N, the statements are equivalent.

Exercises

  1. Derive (4.27) using convention E=∥X~w~−y∥2/(2N)E=\|\widetilde X\widetilde w-y\|^2/(2N). What changes?
  2. Show that X~TX~\widetilde X^{\mathsf T}\widetilde X is always symmetrical.
  3. Explain why disabled station produces a v≠0v\neq0 direction with Zero curvature in (4.28).

4.3.25 Computing

In implementation, the goal is to find w~\widetilde w that minimizes ∥X~w~−y∥2\|\widetilde X\widetilde w-y\|_2. The mathematical form of equations normal is useful for the theory, but the explicit calculation

(X~TX~)−1X~Ty \left(\widetilde X^{\mathsf T}\widetilde X\right)^{-1} \widetilde X^{\mathsf T}y

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. X~TX~\widetilde X^{\mathsf T}\widetilde X 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 R2R^2 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 33. A smaller value indicates linear dependence detected numerically. automatically useless predictions, but prevents interpreting the coefficients as a single solution.

Understanding QR Factoring

If X~\widetilde X has full column rank and its reduced QR is

X~=QR, \widetilde X=QR,

So…

Q∈RN×p,R∈Rp×p,QTQ=Ip, Q\in\mathbb R^{N\times p}, \qquad R\in\mathbb R^{p\times p}, \qquad Q^{\mathsf T}Q=I_p,

with p=d+1p=d+1 and RR superior triangular. Replacing in condition of least squares, the solution satisfies

Rw~=QTy.(4.29) R\widetilde w=Q^{\mathsf T}y. \tag{4.29}

We solved (4.29) by retroactive replacement, without calculate R−1R^{-1}. 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

X~=UΣVT. \widetilde X=U\Sigma V^{\mathsf T}.

Very small singular values reveal almost redundant directions. The pseudoverse is

X~+=VΣ+UT, \widetilde X^+ =V\Sigma^+U^{\mathsf T},

where Σ+\Sigma^+ reverses only the singular values treated as not No, no, no.

w~∗=X~+y. \widetilde w^*=\widetilde X^+y.

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,

κ2(X~)=σmax⁡σmin⁡. \kappa_2(\widetilde X) =\frac{\sigma_{\max}}{\sigma_{\min}}.

The bigger κ2\kappa_2, 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?

SituationTypical strategy
moderate dense matrixlstsq or QR
disabled or almost disabledSVD/pseudoinverse
many examples and few featuresSpecialised QR or solver
very large or in-flow datastochastic gradient or iterative methods
sparse matrixroutines suitable for sparse matrices
need for stabilizationridge 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

  1. Compare the returned post with the number of parameters.
  2. Examine singular values and condition number.
  3. Check residuals and metrics in training and validation.
  4. Inspect waste patterns according to predictions and features.
  5. Confirm that the same preprocessing will be applied in production.

4.3.26 Summary

Linear regression learns a real output function

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

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

ElementExpression
design matrixX~∈RN×(d+1)\widetilde X\in\mathbb R^{N\times(d+1)}
parametersw~=(b,w1,…,wd)T\widetilde w=(b,w_1,\ldots,w_d)^{\mathsf T}
forecastsy^=X~w~\widehat y=\widetilde X\widetilde w
wastee=y−y^e=y-\widehat y
objective∥e∥22/N\|e\|_2^2/N
gradient2X~T(X~w~−y)/N2\widetilde X^{\mathsf T}(\widetilde X\widetilde w-y)/N
Great conditionX~Te=0\widetilde X^{\mathsf T}e=0
normal equationsX~TX~w~=X~Ty\widetilde X^{\mathsf T}\widetilde X\widetilde w=\widetilde X^{\mathsf T}y
general solution of lower standardw~∗=X~+y\widetilde w^*=\widetilde X^+y

The X~Te=0\widetilde X^{\mathsf T}e=0 condition has two readings equivalent:

  • geometry: prediction is the projection of yy in column space and the waste is perpendicular to that space;
  • calculation: the MSE gradient is zero at least.
  1. Separate training, validation and testing.
  2. Adjust attribute transformations only in training.
  3. Add the intercept or configure the library to estimate it.
  4. Solve least squares with lstsq, QR, SVD or appropriate method for data structure.
  5. Examine rank, singular values and conditioning.
  6. Calculate MSE or RMSE and complementary metrics in data not used in adjustment.
  7. Analyze residuals and check patterns, atypical values and change of distribution.

The solution is not just a formula

Calculate explicitly (X~TX~)−1(\widetilde X^{\mathsf T}\widetilde X)^{-1} 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?
  • R2R^2: 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 R2R^2 and hide the waste scale.

Conceptual issues

  1. Why do SSE and MSE have the same minimizer?
  2. Why is the optimal residual orthogonal to the columns of the design matrix?
  3. Having more examples than parameters ensures unique solution? Justify.
  4. Why can forming XTXX^{\mathsf T}X worsen conditioning?
  5. In what sense is a regression with x2x^2 attribute still linear?
  6. How can a model present negative R2R^2 in the test set?

Exercises

  1. Stop X~=[101112]\widetilde X=\begin{bmatrix}1&0\\1&1\\1&2\end{bmatrix} e y=(1,2,2)Ty=(1,2,2)^{\mathsf T}, check by multiplication the equations normal using w~=(7/6,1/2)T\widetilde w=(7/6,1/2)^{\mathsf T}.
  2. Build a design matrix with two identical columns. Calculate your put and explain why the coefficients are not unique.
  3. Compare np.linalg.lstsq with the explicit solution of normal equations in a matrix whose columns are almost collinear.
  4. Adjust a straight line to a sample, add an extremely target value distant and observe how coefficients, RMSE and MAE change.
  5. 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 X~\widetilde X, yy, y^\widehat y and ee 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 bb and ww are updated;
  • in the space of the parameters, the (b,w)(b,w) 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.

The downward gradient crosses MSE level curves towards the minimum.

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 y−y^y-\widehat y, 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

  1. Increase the learning rate gradually. At what value does the MSE leave to decrease in a stable way?
  2. Multiply XX by 1 0001\,000 without changing the rate. Explain the change using the gradient expression.
  3. Standardize XX and repeat the experiment. Compare trajectory.
  4. Add an atypical value to yy. Note how the optimal line changes.
  5. Compare the final parameters to the np.linalg.lstsq result.

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

y∈{0,1}, y\in\{0,1\},

in which y=1y=1 represents the event of interest and y=0y=0, 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

p(x)=P(Y=1∣X=x), p(x)=P(Y=1\mid X=x),

the conditional probability of the positive event given the features. the classes are complementary,

P(Y=0∣X=x)=1−p(x). P(Y=0\mid X=x)=1-p(x).

4.4.1 Why isn’t linear regression enough?

We could encode the labels as zero and one and adjust wTx+bw^{\mathsf T}x+b 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

z=wTx+b, z=w^{\mathsf T}x+b,

but apply a transformation that takes any real number to the range (0,1)(0,1):

p(x)=σ(z)=11+e−z.(4.30) p(x)=\sigma(z)=\frac{1}{1+e^{-z}}. \tag{4.30}

Logistic regression separates the probability estimate from the decision made with a threshold.

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 p(x)p(x), an application can convert it into class using a τ\tau threshold:

y^={1,p(x)≥τ,0,p(x)<τ. \widehat y= \begin{cases} 1,&p(x)\geq\tau,\\ 0,&p(x)<\tau. \end{cases}

The τ=0,5\tau=0{,}5 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 σ(0)=0,5\sigma(0)=0{,}5 and sigmoid is increasing, the 0,50{,}5 threshold produces the border

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

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 xx than the model You need to find out. different results. Uncertainty is represented by a distribution Bernoulli:

Y∣X=x∼Bernoulli⁡(p(x)). Y\mid X=x\sim\operatorname{Bernoulli}(p(x)).

That means…

P(Y=y∣X=x)=p(x)y[1−p(x)]1−y,y∈{0,1}. P(Y=y\mid X=x) =p(x)^y[1-p(x)]^{1-y}, \qquad y\in\{0,1\}.

By observing many similar cases with p(x)=0,8p(x)=0{,}8, we expect a close proportion of 80%80\% of positive results, not the certainty of that each case will be positive.

4.4.4 Example of reading

Consider a server failure template:

z=−4+0,03 temperature+1,2 load. z=-4+0{,}03\,\text{temperature} +1{,}2\,\text{load}.

For temperature 8080 and load 0,750{,}75,

z=−4+0,03(80)+1,2(0,75)=−0,7, z=-4+0{,}03(80)+1{,}2(0{,}75)=-0{,}7,

e

p=σ(−0,7)≈0,332. p=\sigma(-0{,}7)\approx0{,}332.

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

QuantityDomainMeaning
zz scoreR\mathbb Rlinear evidence before transformation
probability p=σ(z)p=\sigma(z)(0,1)(0,1)estimate of P(Y=1∣X=x)P(Y=1\mid X=x)
decision y^\widehat y{0,1}\{0,1\}action after applying a threshold

A good accuracy does not guarantee reliable probabilities. 0,80{,}8 correspond to positive results in only 60%60\% 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:

  1. the logistic function and its relationship with chances and log-odds;
  2. the probabilistic hypothesis class;
  3. the loss of Bernoulli-derived cross-entropy;
  4. gradient, Hessian and optimization methods;
  5. numerically stable implementation and evaluation.

4.4.7 Logistic function

We need to turn a z∈Rz\in\mathbb R score into a The logistic function, also called sigmoid, is

σ(z)=11+e−z=ez1+ez.(4.31) \sigma(z) =\frac{1}{1+e^{-z}} =\frac{e^z}{1+e^z}. \tag{4.31}

Your domain is the whole real line and your image is the open range (0,1)(0,1). It never produces exactly zero or one for a real argument finite, but approaching these values when zz tends to −∞-\infty or +∞+\infty.

The sigmoid converts a real score into probability and satura near the extremes.

Figure 4.13. The sigmoid converts a real score into probability and satura near the extremes.

Fundamental properties

The sigmoid satisfies

σ(0)=12,σ(−z)=1−σ(z). \sigma(0)=\frac12, \qquad \sigma(-z)=1-\sigma(z).

It is strictly growing. Its derivative has a special form convenient:

σ′(z)=e−z(1+e−z)2=σ(z)[1−σ(z)].(4.32) \begin{aligned} \sigma'(z) &=\frac{e^{-z}}{(1+e^{-z})^2}\\ &=\sigma(z)[1-\sigma(z)]. \end{aligned} \tag{4.32}

Like 0<σ(z)<10<\sigma(z)<1, the derivative is positive. Its maximum value is 1/41/4, reached on z=0z=0 In the tails, the derivative approaches zero: we say that function satura.

For small Δz\Delta z variations close to zero,

Δp≈σ′(0)Δz=14Δz. \Delta p\approx\sigma'(0)\Delta z=\frac14\Delta z.

Far from the center, the same score variation causes a minor change in probability.

Log chances and chances

If an event has probability pp, its chances (* odds*) are

odds⁡(p)=p1−p. \operatorname{odds}(p)=\frac{p}{1-p}.

Probability p=0,8p=0{,}8, for example, corresponds to chances 0,8/0,2=40{,}8/0{,}2=4: we read “four to one” in favor of the event. 0,50{,}5 corresponds to chances 11.

The logarithm of chances is the function logit:

logit⁡(p)=ln⁡(p1−p).(4.33) \operatorname{logit}(p) =\ln\left(\frac{p}{1-p}\right). \tag{4.33}

Applying it to the sigmoid,

σ(z)1−σ(z)=ez⟹logit⁡(σ(z))=z. \frac{\sigma(z)}{1-\sigma(z)}=e^z \quad\Longrightarrow\quad \operatorname{logit}(\sigma(z))=z.

Therefore, sigmoid and logit are inverse functions:

p=σ(z)⟺z=ln⁡(p1−p). p=\sigma(z) \quad\Longleftrightarrow\quad z=\ln\left(\frac{p}{1-p}\right).

In logistic regression, the linear amount is not the probability, but the logarithm of the chances:

ln⁡(p(x)1−p(x))=wTx+b.(4.34) \ln\left(\frac{p(x)}{1-p(x)}\right) =w^{\mathsf T}x+b. \tag{4.34}

Interpretation of a coefficient

Keeping the other features fixed, increase xjx_j in a sum unit wjw_j to log-odds. Exposing, the chances are multiplied by ewje^{w_j}:

odds⁡(xj+1)odds⁡(xj)=ewj. \frac{\operatorname{odds}(x_j+1)} {\operatorname{odds}(x_j)}=e^{w_j}.

If wj=ln⁡2w_j=\ln2, an additional drive doubles the chances. This does not means double the probability. If it goes from 0,20{,}2 to chances 0,250{,}25, double the odds produces 0,50{,}5, which corresponds to probability 1/31/3, not 0,40{,}4.

Relationship with Bernoulli distribution

A Bernoulli variable with pp parameter satisfies

P(Y=y∣p)=py(1−p)1−y,y∈{0,1}. P(Y=y\mid p)=p^y(1-p)^{1-y}, \qquad y\in\{0,1\}.

Set the natural parameter

η=ln⁡(p1−p). \eta=\ln\left(\frac{p}{1-p}\right).

Like p=σ(η)p=\sigma(\eta), we can rewrite the probability mass:

P(Y=y∣η)=exp⁡[yη−ln⁡(1+eη)].(4.35) P(Y=y\mid\eta) =\exp\left[y\eta-\ln(1+e^\eta)\right]. \tag{4.35}

That’s Bernoulli’s exponential family form. logistics models the natural parameter by η=wTx+b\eta=w^{\mathsf T}x+b. 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 Φ(z)\Phi(z). 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

tanh⁡(z)=2σ(2z)−1 \tanh(z)=2\sigma(2z)-1

and has (−1,1)(-1,1) 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,

x~=(1,x1,…,xd),w~=(b,w1,…,wd), \widetilde x=(1,x_1,\ldots,x_d), \qquad \widetilde w=(b,w_1,\ldots,w_d),

we have z=w~Tx~z=\widetilde w^{\mathsf T}\widetilde x. When all features Originals are worth zero,

p0=σ(b), p_0=\sigma(b),

so that bb represents the reference log-odds. features can make this reference more interpretable.

Numerically stable computing

The direct formula can cause overflow when calculating e−ze^{-z} for Very negativezz . 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

  1. Demonstrate identity (4.32).
  2. Convert 0,10{,}1, 0,50{,}5 and 0,90{,}9 probabilities into odds and log-odds.
  3. If wj=0,4w_j=0{,}4, by what factor the chances change when xjx_j increases Three units?
  4. Show algebraically that the inverse of logit function is sigmoid.
  5. 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:

Hlog={hw,b(x)=σ(wTx+b):w∈Rd, b∈R}.(4.36) \mathcal H_{\mathrm{log}} =\left\{ h_{w,b}(x)=\sigma(w^{\mathsf T}x+b) :w\in\mathbb R^d,\ b\in\mathbb R \right\}. \tag{4.36}

Each hypothesis associates to an input an estimated probability:

hw,b(x)=P^(Y=1∣X=x). h_{w,b}(x) =\widehat P(Y=1\mid X=x).

Since YY is binary,

P^(Y=0∣X=x)=1−hw,b(x). \widehat P(Y=0\mid X=x)=1-h_{w,b}(x).

This function is a conditional probability, not a density of continuous variable. For Y∈{0,1}Y\in\{0,1\}, we use a mass function of probability Bernoulli:

P^(Y=y∣X=x)=h(x)y[1−h(x)]1−y.(4.37) \widehat P(Y=y\mid X=x) =h(x)^y[1-h(x)]^{1-y}. \tag{4.37}

4.4.9 Homogeneous and matrix representation

With

x~=(1,x1,…,xd),w~=(b,w1,…,wd), \widetilde x=(1,x_1,\ldots,x_d), \qquad \widetilde w=(b,w_1,\ldots,w_d),

We write

hw~(x)=σ(w~Tx~). h_{\widetilde w}(x) =\sigma(\widetilde w^{\mathsf T}\widetilde x).

For a whole sample,

z=X~w~,p^=σ(z),(4.38) z=\widetilde X\widetilde w, \qquad \widehat p=\sigma(z), \tag{4.38}

in which the sigmoid component is applied to the component. z,p^∈RNz,\widehat p\in\mathbb R^N: there is a score and a probability for Every example.

4.4.10 Label encoding

{0,1}\{0,1\} encoding is convenient for Bernoulli and entropy crossover. If data uses {−1,+1}\{-1,+1\}, we can convert by

y01=y±1+12,y±1=2y01−1. y_{01}=\frac{y_{\pm1}+1}{2}, \qquad y_{\pm1}=2y_{01}-1.

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 c∈(0,1)c\in(0,1) satisfy

σ(wTx+b)=c. \sigma(w^{\mathsf T}x+b)=c.

Applying logit function,

wTx+b=ln⁡(c1−c). w^{\mathsf T}x+b =\ln\left(\frac{c}{1-c}\right).

Therefore, the surfaces of constant probability are hyperplanes For c=0,5c=0{,}5, the right side is zero and we get the border

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

For a general threshold τ\tau, the decision border is

wTx+b=logit⁡(τ).(4.39) w^{\mathsf T}x+b =\operatorname{logit}(\tau). \tag{4.39}

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:

logit⁡(h(x))=b+w1x1+⋯+wdxd. \operatorname{logit}(h(x)) =b+w_1x_1+\cdots+w_dx_d.

Each wjw_j represents the change in log-odds to an additional unit of xjx_j, keeping other features constant. The ewje^{w_j} 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:

hw(x)=σ ⁣(wTϕ(x)). h_w(x)=\sigma\!\left(w^{\mathsf T}\phi(x)\right).

With ϕ(x)=(1,x1,x2,x1x2,x12)\phi(x)=(1,x_1,x_2,x_1x_2,x_1^2), 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

  1. Derive (4.39) to τ=0,8\tau=0{,}8.
  2. Convert a base labeled {−1,+1}\{-1,+1\} to {0,1}\{0,1\}.
  3. Explain why all constant probability surfaces are parallel in the model without nonlinear transformations.
  4. Give a ϕ(x)\phi(x) 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

pn=σ(x~nTw~), p_n=\sigma(\widetilde x_n^{\mathsf T}\widetilde w),

the probability assigned to the yn∈{0,1}y_n\in\{0,1\} label is

P(Yn=yn∣xn,w~)=pnyn(1−pn)1−yn. P(Y_n=y_n\mid x_n,\widetilde w) =p_n^{y_n}(1-p_n)^{1-y_n}.

Assuming that observations are conditionally independent given the features, the likelihood of the sample is

L(w~)=∏n=1Npnyn(1−pn)1−yn.(4.40) L(\widetilde w) =\prod_{n=1}^{N} p_n^{y_n}(1-p_n)^{1-y_n}. \tag{4.40}

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 LL is equivalent to maximize log-likeness:

ℓ(w~)=ln⁡L(w~)=∑n=1N[ynln⁡pn+(1−yn)ln⁡(1−pn)]. \ell(\widetilde w) =\ln L(\widetilde w) =\sum_{n=1}^{N} \left[ y_n\ln p_n+(1-y_n)\ln(1-p_n) \right].

Learning algorithms usually minimize a loss. negative:

Ein(w~)=−1N∑n=1N[ynln⁡pn+(1−yn)ln⁡(1−pn)].(4.41) E_{\mathrm{in}}(\widetilde w) =-\frac1N\sum_{n=1}^{N} \left[ y_n\ln p_n+(1-y_n)\ln(1-p_n) \right]. \tag{4.41}

This function is called binary cross-entropy, log-loss or logistics loss.

Cross-entropy strongly penalizes confident probabilities attributed to the wrong class.

Figure 4.14. Cross-entropy strongly penalizes confident probabilities attributed to the wrong class.

For y=1y=1, the individual loss is −ln⁡p-\ln p; for y=0y=0, it is −ln⁡(1−p)-\ln(1-p). A correct and confident forecast gets close loss of Zero. Wrong and confident prediction gets very big loss.

Shape with labels {−1,+1}\{-1,+1\}

If we use tn∈{−1,+1}t_n\in\{-1,+1\} and the score zn=x~nTw~z_n=\widetilde x_n^{\mathsf T}\widetilde w, the probability of the label observed is

P(Tn=tn∣xn)=σ(tnzn). P(T_n=t_n\mid x_n)=\sigma(t_nz_n).

So, the individual loss is

−ln⁡σ(tnzn)=ln⁡(1+e−tnzn). -\ln\sigma(t_nz_n) =\ln\left(1+e^{-t_nz_n}\right).

The average error becomes

Ein(w~)=1N∑n=1Nln⁡(1+e−tnx~nTw~).(4.42) E_{\mathrm{in}}(\widetilde w) =\frac1N\sum_{n=1}^{N} \ln\left(1+e^{-t_n \widetilde x_n^{\mathsf T}\widetilde w} \right). \tag{4.42}

The forms (4.41) and (4.42) are equivalent after converting labels. ln⁡(1+ea)\ln(1+e^a) is called softplus.

Relation with margin

In {−1,+1}\{-1,+1\} encoding, the margin is

mn=tnzn. m_n=t_nz_n.

The loss ln⁡(1+e−mn)\ln(1+e^{-m_n}) is decreasing in the margin:

  • large and positive margin: correct classification and close loss of zero;
  • zero margin: probability 0,50{,}5 and loss ln⁡2\ln2;
  • 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. 0,510{,}51 and 0,990{,}99 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 p=σ(z)p=\sigma(z) and then log(p) can produce log(0) by rounding. With {−1,+1}\{-1,+1\} 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 {0,1}\{0,1\} labels, a stable shape directly in * logs* is

ℓ(z,y)=ln⁡(1+ez)−yz. \ell(z,y)=\ln(1+e^z)-yz.
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:

Eλ(w~)=Ein(w~)+λ2∥w∥22. E_\lambda(\widetilde w) =E_{\mathrm{in}}(\widetilde w) +\frac{\lambda}{2}\|w\|_2^2.

The intercept is normally not penalized. extreme coefficients, help in perfect separation and control overfit. The λ\lambda 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 p=0,8p=0{,}8,

−ln⁡(0,8)≈0,223. -\ln(0{,}8)\approx0{,}223.

If the model assigns p=0,01p=0{,}01 to the same result,

−ln⁡(0,01)≈4,605. -\ln(0{,}01)\approx4{,}605.

The second forecast is not only incorrect according to a 0,50{,}5 threshold ; It’s incorrect with high confidence.

Exercises

  1. Derive (4.41) from (4.40).
  2. Show that −ln⁡σ(a)=ln⁡(1+e−a)-\ln\sigma(a)=\ln(1+e^{-a}).
  3. Calculate the log-ins for y=0y=0 and forecasts p=0,1p=0{,}1 and p=0,9p=0{,}9.
  4. Explain why maximizing likelihood is tantamount to minimizing negative log-likeness.
  5. Compare logistic loss and zero-one loss on margins −2,0,2-2,0,2.

4.4.17 Algorithm

Training logistic regression means finding parameters that minimise cross-entropy, or equivalently maximize cross-entropy Bernoulli likelihood. For y∈{0,1}y\in\{0,1\} labels the problem is

w~∗∈arg min⁡w~1N∑n=1N[ln⁡(1+ezn)−ynzn],z=X~w~.(4.43) \widetilde w^* \in\operatorname*{arg\,min}_{\widetilde w} \frac1N\sum_{n=1}^{N} \left[ \ln(1+e^{z_n})-y_nz_n \right], \qquad z=\widetilde X\widetilde w. \tag{4.43}

In linear regression, zeroing the gradient produced a linear system with Here, the odds pn=σ(x~nTw~)p_n=\sigma(\widetilde x_n^{\mathsf T}\widetilde w) 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 pp, the gradient is

∇E(w~)=1NX~T(p−y).(4.44) \nabla E(\widetilde w) =\frac1N\widetilde X^{\mathsf T}(p-y). \tag{4.44}

The gradient points in the direction of greater local growth. The loss, we move in the opposite direction, −∇E-\nabla E.

The Hessian is

∇2E(w~)=1NX~TSX~,(4.45) \nabla^2E(\widetilde w) =\frac1N\widetilde X^{\mathsf T}S\widetilde X, \tag{4.45}

where

S=diag⁡(p1(1−p1),…,pN(1−pN)). S=\operatorname{diag}\left(p_1(1-p_1),\ldots, p_N(1-p_N)\right).

For any vv vector,

vT∇2E(w~)v=1N(X~v)TS(X~v)≥0, v^{\mathsf T}\nabla^2E(\widetilde w)v =\frac1N (\widetilde Xv)^{\mathsf T}S(\widetilde Xv) \geq0,

because the diagonal elements of SS 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:

MethodInformation usedCost per iterationFeature
downward gradientfirst derivativeusually O(Nd)O(Nd)simple and scalable
Newton/IRLSgradient and Hessianincludes system in variable d+1d+1few iterations close to minimum
maximum slope with step searchgradient and adaptive choice of η\etamultiple loss assessmentsreduces 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 L2L_2, we minimize

Eλ(w~)=E(w~)+λ2∥w∥22, E_\lambda(\widetilde w) =E(\widetilde w)+\frac{\lambda}{2}\|w\|_2^2,

usually excluding the bb intercept. The gradient gains the term λw\lambda w and Hessiana wins λI\lambda I 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:

  1. calculate the * logs* z=X~w~z=\widetilde X\widetilde w;
  2. calculate probabilities or equivalent quantities in a stable manner;
  3. evaluate loss and gradient;
  4. determine a direction dtd_t;
  5. choose a step size ηt\eta_t;
  6. update w~(t+1)=w~(t)+ηtdt\widetilde w^{(t+1)}=\widetilde w^{(t)}+\eta_td_t;
  7. check stop criteria.

For descending gradient, dt=−∇Ed_t=-\nabla E.

dt=−[∇2E(w~(t))]−1∇E(w~(t)), d_t=-[\nabla^2E(\widetilde w^{(t)})]^{-1} \nabla E(\widetilde w^{(t)}),

but an implementation solves the linear system ∇2E dt=−∇E\nabla^2E\,d_t=-\nabla E 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. 10−610^{-6} may be irrelevant for a loss of 10610^6 and important for a loss of 10−810^{-8}; 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

b(0)=ln⁡(y‾1−y‾), b^{(0)} =\ln\left(\frac{\overline y}{1-\overline y}\right),

with initially zero weights, since 0<y‾<10<\overline y<1. 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 f:Rp→Rf:\mathbb R^p\to\mathbb R, the gradient gathers Partial derivatives:

∇f(w)=[∂f/∂w1⋮∂f/∂wp]. \nabla f(w)= \begin{bmatrix} \partial f/\partial w_1\\ \vdots\\ \partial f/\partial w_p \end{bmatrix}.

We’ll adopt gradients as column vectors. unit direction vv is

Dvf(w)=∇f(w)Tv. D_vf(w)=\nabla f(w)^{\mathsf T}v.

By Cauchy–Schwarz, this value is maximum when vv points in the direction of gradient. Therefore, −∇f(w)-\nabla f(w) is the direction of highest local slope.

Derivation with {0,1}\{0,1\} labels

For an example, set

zn=x~nTw~,pn=σ(zn), z_n=\widetilde x_n^{\mathsf T}\widetilde w, \qquad p_n=\sigma(z_n),

and use stable loss in logits

ℓn(w~)=ln⁡(1+ezn)−ynzn. \ell_n(\widetilde w) =\ln(1+e^{z_n})-y_nz_n.

Since the derivative of softplus is sigmoid,

∂ℓn∂zn=σ(zn)−yn=pn−yn. \frac{\partial\ell_n}{\partial z_n} =\sigma(z_n)-y_n =p_n-y_n.

Besides,

∇w~zn=x~n. \nabla_{\widetilde w}z_n=\widetilde x_n.

By the rule of jail,

∇w~ℓn=(pn−yn)x~n.(4.46) \nabla_{\widetilde w}\ell_n =(p_n-y_n)\widetilde x_n. \tag{4.46}

Calculating the average and gathering the examples in the design matrix,

∇E(w~)=1N∑n=1N(pn−yn)x~n=1NX~T(p−y).(4.47) \nabla E(\widetilde w) =\frac1N\sum_{n=1}^{N}(p_n-y_n)\widetilde x_n =\frac1N\widetilde X^{\mathsf T}(p-y). \tag{4.47}

The formula has a simple interpretation: p−yp-y measures error Probabilistic of each example, and multiplication by X~T\widetilde X^{\mathsf T} distributes these errors between the parameters of according to the features values.

Derivation with {−1,+1}\{-1,+1\} labels

For tn∈{−1,+1}t_n\in\{-1,+1\}, the loss is

ℓn=ln⁡(1+e−tnzn). \ell_n=\ln(1+e^{-t_nz_n}).

Its derivative is

∇w~ℓn=−tnσ(−tnzn)x~n=−tnx~n1+etnzn.(4.48) \nabla_{\widetilde w}\ell_n =-t_n\sigma(-t_nz_n)\widetilde x_n =-\frac{t_n\widetilde x_n}{1+e^{t_nz_n}}. \tag{4.48}

Note the exponent +tnzn+t_nz_n in the denominator. When the margin is large and positive, the contribution tends to zero; when it is negative, the contribution It’s approaching −tnx~n-t_n\widetilde x_n.

Batch update

The descending gradient in batch uses all examples:

w~(k+1)=w~(k)−ηk1NX~T(p(k)−y).(4.49) \widetilde w^{(k+1)} =\widetilde w^{(k)} -\eta_k \frac1N\widetilde X^{\mathsf T} \left(p^{(k)}-y\right). \tag{4.49}

With regularization L2L_2, we added λw\lambda w 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 O(Nd)O(Nd) per iteration. For large bases, we can estimate it using a BB subset:

gB(w~)=1∣B∣∑n∈B(pn−yn)x~n. g_B(\widetilde w) =\frac1{|B|} \sum_{n\in B}(p_n-y_n)\widetilde x_n.
  • SGD: ∣B∣=1|B|=1; cheap and noisy updates;
  • minilot: 1<∣B∣<N1<|B|<N; takes advantage of vectorization and reduces variance;
  • complete batch: ∣B∣=N|B|=N; 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:

∂E∂wj≈E(w+εej)−E(w−εej)2ε. \frac{\partial E}{\partial w_j} \approx \frac{E(w+\varepsilon e_j)-E(w-\varepsilon e_j)} {2\varepsilon}.
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 L2L_2 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

  1. Derive (4.46) by the chain rule.
  2. Convert (4.48) to {0,1}\{0,1\} encoding.
  3. Implement finite difference verification for ww and bb.
  4. Compare full batch and minilots in the same sample, using the same number of seasons.
  5. 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 ww point , the second-order Taylor expansion is

E(w+d)≈E(w)+∇E(w)Td+12dTH(w)d, E(w+d) \approx E(w)+\nabla E(w)^{\mathsf T}d +\frac12d^{\mathsf T}H(w)d,

where H(w)=∇2E(w)H(w)=\nabla^2E(w). To minimize this quadratic approach in with respect to dd, we zeroed its gradient:

∇E(w)+H(w)d=0. \nabla E(w)+H(w)d=0.

Newton’s direction resolves, therefore,

H(w)d=−∇E(w),(4.50) H(w)d=-\nabla E(w), \tag{4.50}

and the update is

wnovo=w+ηd,(4.51) w_{\mathrm{novo}}=w+\eta d, \tag{4.51}

with η=1\eta=1 in pure Newton. In code, we solved (4.50); We didn’t calculate H−1H^{-1} explicitly.

In a dimension, this expression reduces the

wnovo=w−E′(w)E′′(w), w_{\mathrm{novo}} =w-\frac{E'(w)}{E''(w)},

which is Newton’s method applied to the equation E′(w)=0E'(w)=0.

Gradient and Logistic Hessian

For the homogeneous matrix X~\widetilde X, we have

g=∇E(w~)=1NX~T(p−y) g=\nabla E(\widetilde w) =\frac1N\widetilde X^{\mathsf T}(p-y)

e

H=∇2E(w~)=1NX~TSX~, H=\nabla^2E(\widetilde w) =\frac1N\widetilde X^{\mathsf T}S\widetilde X,

where

S=diag⁡(p1(1−p1),…,pN(1−pN)). S=\operatorname{diag} \left(p_1(1-p_1),\ldots,p_N(1-p_N)\right).

The matrix SS assigns greater weight to the examples whose probability is close to 0,50{,}5 and weight lower than those that are saturated close to zero or one. If there is regularization L2L_2, we add λI\lambda I to penalized coordinates from Hessiana and λw\lambda w 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

r=X~w~+S−1(y−p). r =\widetilde X\widetilde w +S^{-1}(y-p).

Next vector solves

w~novo=arg min⁡v∥S1/2(r−X~v)∥22.(4.52) \widetilde w_{\mathrm{novo}} =\operatorname*{arg\,min}_{v} \left\|S^{1/2}(r-\widetilde Xv)\right\|_2^2. \tag{4.52}

The normal equations of (4.52) are

X~TSX~w~novo=X~TSr, \widetilde X^{\mathsf T}S\widetilde X \widetilde w_{\mathrm{novo}} =\widetilde X^{\mathsf T}Sr,

which are equivalent to Newton’s step. The name “repondered” comes from the fact that SS change with each iteration as the odds change.

In practice, it is not necessary to form SS as a matrix N×NN\times N. If s=p(1−p)s=p(1-p), multiply by SS equals multiplying each line or component by the corresponding element of ss.

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 η<1\eta<1 by linear search;
  • add μI\mu I 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 p=d+1p=d+1 is the number of parameters, calculate gradient and dense Hessian costs approximately O(Np2)O(Np^2), and solving the system costs O(p3)O(p^3). Hessian’s memory is O(p2)O(p^2).

The descending gradient avoids Hessian and costs approximately IterationO(Np)O(Np) . 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 pnp_n is numerically zero or one, pn(1−pn)p_n(1-p_n) 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

  1. Confirm that gTd<0g^{\mathsf T}d<0 for a descent direction.
  2. Check that the loss accepted by backtracking does not increase.
  3. Monitor the HH condition number.
  4. Compare the result with a library optimizer.
  5. Test a perfectly separable base with and without regularization.

Exercises

  1. Derive Hessiana from (4.47).
  2. Show the equivalence between (4.50) and (4.52).
  3. Explain why we should not explicitly form SS .
  4. Compare costs of a Newton iteration and gradient to N=106N=10^6 e p=100p=100.
  5. 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 vv, the directional derivative is

DvE(w)=∇E(w)Tv. D_vE(w)=\nabla E(w)^{\mathsf T}v.

For the inequality of Cauchy–Schwarz,

−∥∇E(w)∥2≤∇E(w)Tv≤∥∇E(w)∥2. -\|\nabla E(w)\|_2 \leq \nabla E(w)^{\mathsf T}v \leq \|\nabla E(w)\|_2.

The lowest value occurs in

v=−∇E(w)∥∇E(w)∥2. v=-\frac{\nabla E(w)}{\|\nabla E(w)\|_2}.

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:

w(k+1)=w(k)−ηk∇E(w(k)).(4.53) w^{(k+1)}=w^{(k)}-\eta_k\nabla E(w^{(k)}). \tag{4.53}

The gradient points perpendicular to the level curves. curves are very elongated, the trajectory can cross repeatedly the valley and form a zigzag.

The maximum slope crosses the level curves in the local perpendicular direction, and may oscillate in elongated valleys.

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:

dNewton=−H−1g. d_{\mathrm{Newton}}=-H^{-1}g.

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 ηk\eta_k along the iterations;
  • linear search: chooses a step that produces enough reduction.

For unregulated logistic regression, Hessiana satisfies

∇2E(w)⪯14NX~TX~, \nabla^2E(w) \preceq \frac{1}{4N}\widetilde X^{\mathsf T}\widetilde X,

Yeah. pn(1−pn)≤1/4p_n(1-p_n)\leq1/4. Therefore, Lipschitz’s lowest constant LgradL_{\mathrm{grad}} satisfies

Lgrad≤∥X~∥224N=:Lcota. L_{\mathrm{grad}} \leq\frac{\|\widetilde X\|_2^2}{4N} =:L_{\mathrm{cota}}.

With penalty L2L_2 intensity λ\lambda, we add approximately λ\lambda at the bound in the penalized directions. η≤1/Lcota\eta\leq1/L_{\mathrm{cota}} provides a conservative choice for monotonic reduction in the convex and smooth problem.

Calculate ∥X~∥2\|\widetilde X\|_2 exactly can be expensive; linear search or estimates are practical alternatives.

Linear search by backtracking

If g=∇E(w)g=\nabla E(w) and d=−gd=-g, Armijo’s condition accepts η\eta when

E(w+ηd)≤E(w)+cηgTd,0<c<1.(4.54) E(w+\eta d) \leq E(w)+c\eta g^{\mathsf T}d, \qquad 0<c<1. \tag{4.54}

Like gTd=−∥g∥2<0g^{\mathsf T}d=-\|g\|^2<0, 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 L2L_2 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

AspectMaximum slopeNewton.
derivativesgradientgradient and Hessian
additional memoryO(d)O(d)O(d2)O(d^2) for dense Hessian
typical cost per iterationO(Nd)O(Nd)O(Nd2+d3)O(Nd^2+d^3)
sensitivity to scalehighsmaller, by the correction of curvature
use with minilotsnaturalless common in exact form
speed near the greatslowerpotentially quadratic

Local descent, global goal

The −g-g 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

  1. Use Cauchy–Schwarz to demonstrate maximum slope direction.
  2. Show that gT(−g)=−∥g∥2g^{\mathsf T}(-g)=-\|g\|^2.
  3. Explain how multiplying an attribute by 1 0001\,000 changes the path the downward gradient.
  4. Implement (4.54) and register how many step reductions they occur by iteration.
  5. 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:

  1. Newton cushioned, suitable for dense bases of moderate size;
  2. 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

X∈RN×d,y∈{0,1}N. X\in\mathbb R^{N\times d}, \qquad y\in\{0,1\}^N.

Each line of XX is an example; each column is an attribute. Before adjustment, we checked:

  • the same number of lines in XX and inputs in yy;
  • 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:

precisa~o⁡=VPVP+FP,revocac\ca~o⁡=VPVP+FN. \operatorname{precisão}=\frac{VP}{VP+FP}, \qquad \operatorname{revocação}=\frac{VP}{VP+FN}.

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

Htdt=−gt,w~t+1=w~t+ηtdt, H_t d_t=-g_t, \qquad \widetilde w_{t+1} =\widetilde w_t+\eta_t d_t,

where gtg_t and HtH_t are the gradient and the Hessian in the current state. Note the negative sign: adding Ht−1gtH_t^{-1}g_t 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 ww 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 0,50{,}5. When the positive class is rare, we can initialize only the intercept with the smoothed prevalence:

b0=ln⁡(n1+αn0+α), b_0 =\ln\left( \frac{n_1+\alpha}{n_0+\alpha} \right),

where n1n_1 and n0n_0 are class counts and α>0\alpha>0 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 H−1H^{-1}. 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:

∥gt∥∞≤εg, \|g_t\|_\infty \leq \varepsilon_g, ∣Et+1−Et∣max⁡(1,∣Et∣)≤εE, \frac{|E_{t+1}-E_t|} {\max(1,|E_t|)} \leq\varepsilon_E, ∥w~t+1−w~t∥2max⁡(1,∥w~t∥2)≤εw. \frac{\|\widetilde w_{t+1}-\widetilde w_t\|_2} {\max(1,\|\widetilde w_t\|_2)} \leq\varepsilon_w.

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 λ=0,1\lambda=0{,}1 in weights and zero boot, Newton produces a sequence as:

iterationloss penalisedgradient standard
00,69310{,}69310,55900{,}5590
1lower valuelower standard
2refined approachclose 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

SymptomsProbable causeAction
unique systemredundant columns or saturated weightscheck rank and regularize
loss increasesinadequate unit step or gradient erroruse backtracking and check derivatives
coefficients grow nonstopPerfect separationregularize and monitor standard
non-finite loss valueexponential or unstable logarithmwork directly with logits
slow convergencepoor conditioningstandardize and review features
validation worsenoverfitregularization 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 dd 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

  1. Correct the pseudocode if the objective function is the sum, not the average, the losses.
  2. Implement the three relative stopping criteria.
  3. Force two identical columns and observe the system without regularisation.
  4. Compare null initialization and intercepted by prevalence.
  5. 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

gt=1NX~T(pt−y)+λRw~t, g_t =\frac1N\widetilde X^{\mathsf T}(p_t-y) +\lambda R\widetilde w_t,

where R=diag⁡(0,1,…,1)R=\operatorname{diag}(0,1,\ldots,1) leaves the intercept without Penalty. Update is

w~t+1=w~t−ηtgt. \widetilde w_{t+1} =\widetilde w_t-\eta_tg_t.

We don’t have to normalize gtg_t. −gt/∥gt∥-g_t/\|g_t\|, all steps would have length ηt\eta_t, 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 λ\lambda 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:

  1. manages probabilities in validation;
  2. assess threshold candidates according to the desired cost or metric;
  3. set the threshold;
  4. evaluate once in the test.

If the false positive cost is CFPC_{FP} and the false negative cost is CFNC_{FN}, under simple conditions and calibrated probabilities, the decision with lower cost predicts positive when

p(x)≥CFPCFP+CFN. p(x)\geq \frac{C_{FP}}{C_{FP}+C_{FN}}.

Costs, prevalence and real actions need to be defined with the The Commission shall adopt implementing acts.

Final comparison of methods

CriteriaNewton’s deadBatch Gradient
moderate parametersgenerally efficientworks, with more iterations
many featuresHessian can be prohibitivememory smaller
learning ratesearch for still useful stepcentral choice
curvatureexplicitly usedignored
minilotsunnatural in the exact formnatural
implementationmore complexsimpler
essential diagnosiscondition of the Hessianscale and rate

Recapitulation of logistic regression

  1. The linear score models log-odds.
  2. The sigmoid converts scores into probability.
  3. Cross-entropy comes from the verisimilitude Bernoulli.
  4. The gradient is X~T(p−y)/N\widetilde X^{\mathsf T}(p-y)/N.
  5. The Hessian is X~TSX~/N\widetilde X^{\mathsf T}S\widetilde X/N.
  6. Regularization controls coefficients and improves conditioning.
  7. Probability, class and action are conceptually distinct outputs.
  8. 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

  1. Run Newton and gradient in the same division and compare losses, Iterations and time.
  2. Produce a separable sample and observe the coefficients without regularisation.
  3. Select a threshold that maximizes recall under minimal precision.
  4. Build a calibration diagram in ten probability ranges.
  5. Simulate test prevalence change and observe accuracy, accuracy, recall and calibration.
  6. 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.

  1. In the perceptron with y∈{−1,+1}y\in\{-1,+1\} labels , an example is correctly classified when:

    1. y(wTx+b)>0y(\mathbf{w}^{\mathsf T}\mathbf{x}+b)>0.
    2. y(wTx+b)<0y(\mathbf{w}^{\mathsf T}\mathbf{x}+b)<0.
    3. w=0\mathbf{w}=\mathbf{0} for any input.
    4. bb is necessarily positive.
  2. When finding a poorly classified example, the basic perceptron update for weights:

    1. w←w−ηyx\mathbf{w}\leftarrow\mathbf{w}-\eta y\mathbf{x}.
    2. w←w+ηyx\mathbf{w}\leftarrow\mathbf{w}+\eta y\mathbf{x}.
    3. w←ηw2\mathbf{w}\leftarrow\eta\mathbf{w}^2.
    4. w←x−y\mathbf{w}\leftarrow\mathbf{x}-y.
  3. The convergence theorem of the perceptron ensures ending in finite number of updates when the data is:

    1. linearly separable with positive margin.
    2. always not separate.
    3. produced by regression.
    4. standard, irrespective of the labels.
  4. Pocket algorithm is useful mainly because:

    1. turns any problem into separable.
    2. keeps the best solution observed during execution.
    3. calculates perfectly calibrated probabilities.
    4. does not require a stop criterion.
  5. In the linear regression by least squares, the orthogonality condition of the waste is:

    1. XT(Xw−y)=0X^{\mathsf T}(X\mathbf{w}-\mathbf{y})=\mathbf{0}.
    2. Xy=0X\mathbf{y}=\mathbf{0}.
    3. wTw=0\mathbf{w}^{\mathsf T}\mathbf{w}=0.
    4. XTX=0X^{\mathsf T}X=0.
  6. Why solve or a QR factoring is usually preferable to calculating explicitly (XTX)−1(X^{\mathsf T}X)^{-1}?

    1. Because it avoids all multiplication.
    2. Because it tends to offer greater numerical stability.
    3. Because it eliminates data need.
    4. Because it always produces whole coefficients.
  7. The determination coefficient R2R^2 compares the model error with:

    1. a reference predictor based on the mean output.
    2. the amount of classes.
    3. the highest singular value of XX.
    4. the zero-one classification error.
  8. The logistic function turns a real score into a value in the range:

    1. (−∞,+∞)(-\infty,+\infty).
    2. [−1,1][-1,1].
    3. (0,1)(0,1).
    4. [0,+∞)[0,+\infty).
  9. In binary logistic regression, choose a different decision threshold from 0,50{,}5:

    1. is impossible mathematically.
    2. may alter the compromise between false positives and false negatives.
    3. it modifies the weights already trained.
    4. makes all odds equal.
  10. Compared to maximum slope, Newton’s method uses:

    1. only the sign of the labels.
    2. second-order information through Hessiana.
    3. a learning rate always equals zero.
    4. just one observation of the whole.

Answer key with explanations

  1. a. The positive product indicates that the score has the same signal as the label.
  2. b. The ηyx\eta y\mathbf{x} plot shifts the example score in the direction Correct.
  3. a. Separability with margin supports the bound of updates; this is not guarantee of generalization.
  4. b. In non-separable data, current weights may worsen; Pocket preserves the best configuration found.
  5. a. In normal equations, the residual is orthogonal to the column space of XX.
  6. b. Form the inverse and normal equations can zoom point errors Floating and worsening conditioning.
  7. a. R2R^2 measures the relative reduction of the sum of squares compared to the forecast constant by average.
  8. c. For every finite real input, the sigmoid produces strictly value between 0 and 1.
  9. b. The threshold converts probability into action and should reflect costs and application requirements.
  10. b. The Hessiana describes the local curvature and allows to build a step of Newton.