From logit to cross-enultation, what's changed at once

Starting with a two-class score, the probability, loss and gradient are calculated manually, and then see why extreme input needs to be calculated steadily.

System Chapter . StepCollate in 2 Graphics6 self-measurement4 First-hand sources
Start Body Change the variable
Learning objectives and first steps4 objectives 2 first repairs

Try to do it after reading

  • Distinguishing model fractions, probability, loss and classification thresholds
  • From Bernoulli, it seems to understand the cross entropy of Category II
  • Manual gradient for sample and a parameter update
  • Check logits interfaces and numerical stability

Suggested first

  • Conditional probabilities and logarithmics
  • Average number of cases and batches

We'll sort out the four things that the model produces

When you're in the second class, the model may give points first z=wx+bAnd turn it into a probability pI don't know. The difference between this projection and the label is measured by loss during training; A threshold is also selected for a real output category. They responded, respectively, to the question “how many points were given in the model” “how likely the event was to occur” “how well was this forecast punished” and “what kind of result was ultimately taken”. High scores, low losses and appropriate decision-making thresholds are not the same objective.

This chapter deals only with labels y A Logistic model for 0 or 1, a single numeric feature, without a regular item. The three samples are synthetic teaching data and do not correspond to any real user or business judgement.

2-Class training calculation process Input features are given scores, then the probability is obtained by sigmoid, and the probability and authenticity labels jointly determine the loss. Feature xScore zProbability pLoss I (z, y)
Probability from sigmoid; The label does not enter the predictive formula, but is involved in loss calculation during training.

Where's the cross entropy

If you see a label as a Bernoulli random variable, see y=1 The probability is pWe've got a visual y=0 The probability is 1−pI don't know. The probabilities of the real labels are negative, and the second class cross entropy, also known as binary cross entropy. The more impossible the real events are predicted, the greater the punishment.CS229 handouts This modelling process appears to be given.

p=σ(z)=11+e−z ℓ=−ylog(p)−(1−y)log(1−p)

When y=1and the latter disappears; When y=0The first one disappeared. When the probability is completely negative and very confident, the loss is considerable. The loss is not a percentage, and there is no requirement to fall between 0 and 1.

The logarithm for guidance can be simplified to ∂ℓ/∂z=p−yI don't know. This explains the orientation of the update: when the probability of a positive case is low, a decrease in the gradient will drive the score to increase; When the probability of a negative case is high, the reduction of the score is promoted. And the gradient's going to follow z=wx+b Pass the parameters, so the single sample has ∂ℓ/∂w=x(p−y)、∂ℓ/∂b=p−y。

Let's get a sample. Let's update it

Take x=[−1,0,1]、y=[0,0,1], Initial w=b=0I don't know. All three odds are 0.5, and the average cross-lock is 0.5 log 2≈0.69314718I don't know. Three samples are taken on average here:

Sample x Label y p−y x(p−y)
−1 0 0.5 −0.5
0 0 0.5 0
1 1 −0.5 −0.5

So the parameter gradient is dJ/dw=−1/3、dJ/db=1/6I don't know. With study rate 0.3 and update, get w=0.1、b=−0.05, the new score is [−0.15,−0.05,0.05], the new probability is about [0.462570,0.487503,0.512497]♪ And the average loss is down to 0.65262545。

This only shows one step from the current three samples. It does not demonstrate that the model is better on the new data, let alone the optimal threshold. Practical training also involves the separation of non-leakable validation data.

Why should the code be received directly from logits

Mathematically count sigmoid and then take log. No problem, but limited accuracy makes extreme probability 0 or 1. For logits, an equivalent stabilizer is available:

ℓ(z,y)=max(z,0)−yz+log(1+exp(−|z|))

It doesn't need to be calculated directly exp(1000)I don't know. Here is a small example of the standard Python used to check arithmetic:

import math
def binary_loss(logit, label):
return max(logit, 0.0) - label * logit + math.log1p(math.exp(-abs(logit)))
x, y = [-1.0, 0.0, 1.0], [0.0, 0.0, 1.0]
w, b = 0.1, -0.05
mean_loss = sum(binary_loss(w * xi + b, yi) for xi, yi in zip(x, y)) / len(x)
print(mean_loss) # 约 0.6526254479

Multi-category classification to group logits and softmax. Like what [1000,999] For category 1 Stabilised cross entropy approximately 1.31326169I don't know. PyTorch CrossEntropyLoss Received logits without manual softmax; Use of second classification BCEWithLogitsLoss , also enter logits; Don't start with sigmoid.

Another common error was to make the summation evenly, while ignoring that the gradient had narrowed. Category weights, neglected tags may also change the unicoded caliber and cannot be mechanically divided by batch size.

Loss curves and gradient curves answer different questions

The higher the score, the smaller the loss, for example; However, “small” losses and “high gradient” do not occur simultaneously. When the case was strongly misjudged, the fractional gradient was close to negative, and losses could continue to grow without any upper limit. The gradient is close to zero when the true example has been predicted to be correct and confident. This explains why a few difficult samples may be missing from the average gradient only, and also why the training logs should also record loss distributions, gradient parameters and sample coverage.

A normal cross-alcerium and fraction gradientThe left chart scores dropped from negative to negative to negative to negative to negative to zero to one eight; The gradient with the same fractions in the right chart was increased from negative point 0982 to negative point 008. The gradient is not equivalent to a loss, unlike the vertical axis units of the two figures.Loss I (z, 1)Gradient p−140−10−404−404Score zScore z
Original numeric chart, which connects five measured points; Left and right vertical axes represent loss and lead numbers, respectively, and cannot be compared across the graphs to height.

The fraction gradient is multiplied by the input to get the weight gradient. If a given input is significant, even if the fraction gradient is limited to negative one to one, the parameter gradient may still be large; Gradient crop and input scaling are therefore treated at different levels. On the contrary, the input of a zero sample does not have a gradient for that weight, but it still affects the bias. When examining a training cycle, local guides, chain multipliers and batch attributions shall be separately measured.

Weighted and output shapes change probabilities

If a positive loss is multiplied by three, the best prediction is generally no longer the probability of events for the original population. For the synthetic distribution of the true event rate of 0.2, the weighted target has a maximum output of 0.6 divided by 1.4, approximately 0.428571. Weighting can express training preferences, but it does not directly prove that the output has been calibrated. When deploying to calculate the amount of event expectations or losses, sampling, weighting and calibration protocols should be retained and the change in scores cannot be interpreted as a true change in risk.

A logit is commonly used for the second classification, multiple cross-checking tasks use each sample group category logits, while multilabelling tasks allow for the use of sigmoid for each label. They correspond to different sample spaces. The target category index, probability label and mask also have different shapes; Radio sometimes allows the program to run smoothly, while quietly grouping each sample with a batch of labels. In a small example, check the input, target, element by element loss and, after return, shape.

The return must also be verified against the specific API. BCE Default mean The element is usually averaged and the contribution of the change in the weight of the right is not automatically converted to the re-establishment of the gross right; Weighted CrossEntropyLoss in the category index form, whose mean denominator is related to the weight of the valid target category. The default denominator for other losses cannot be extrapolated from one interface. This document only performs standard library algorithms below and does not run PyTorch or GPU training.

import math
def stable_loss(z,y):
return max(z,0.)-y*z+math.log1p(math.exp(-abs(z)))
def sigmoid(z):
return 1/(1+math.exp(-z)) if z>=0 else math.exp(z)/(1+math.exp(z))
for z in [-4.,-2.,0.,2.,4.]:
print(z,round(stable_loss(z,1),6),round(sigmoid(z)-1,6))
eps=1e-5
numeric=(stable_loss(z+eps,1)-stable_loss(z-eps,1))/(2*eps)
assert math.isclose(numeric,sigmoid(z)-1,abs_tol=1e-8)
assert stable_loss(1000,0)==1000
assert stable_loss(-1000,1)==1000
weighted_optimum=3*.2/(3*.2+.8)
assert math.isclose(weighted_optimum,3/7)
logits=[1000.,999.]
m=max(logits)
ce=m+math.log(sum(math.exp(v-m) for v in logits))-logits[1]
assert math.isclose(ce,1.3132616875,abs_tol=1e-9)

The above standard Python 3 procedure has been implemented in CPU without third party dependency and randomity. (a) The limited differential is only checked against the score-direction gradient; The complete network also needs to check that parameters sharing, regular entries and multiple gradients are added, and that a marker lead cannot be correctly used as the entire training system.

Check understanding

Would the average loss in this case be updated by replacing it with a summation, and keeping the learning rate unchanged?

No, I won't. The gradient of the three samples will triple, so the same learning rate will produce a greater update. The comparison is achieved by checking reduction and learning rates simultaneously.

The probabilities are 0.5 and do they represent a gradient of 0 for all parameters?

No, it's not. The gradient also depends on the true labels and characteristics. The probability is 0.5, but the weight gradient is -1/3 and the gradient is 1/6.

By training the cross entropy to become smaller, can you directly use 0.5 to make all classification decisions?

No, you can't. (b) Probability quality, category ratio, error cost and threshold selection need to be examined separately; The threshold shall be determined in an independent certification agreement.

Is the actual loss more than one, which means the error is made?

No, it's not. Cross entropy is a negative logarithm probability, with no one upper limit; The score was -4 p.m. about 4.018115, but the gradient remained close to -1.

Does the fraction gradient not exceed one, and must the parameter gradient not exceed one?

Not necessarily. The weight gradient shall also be multiplied by input and by batch; Larger input, shared parameters and sample summation may be enlarged.

How much is the real event rate of 0.2 for the best output after giving the right weight three times?

For 0.6(0.6+0.8) = 3/7, approximately 0.428571. It reflects a weighted target and is no longer directly equal to the original overall incident rate of 0.2.

Next you can read Reverse Transmission: From local lead numbers to parameter updates p−y (a) The receipt of deeper calculations; Read again " Write a training loop " and check the actual code shape, mode and statistical denominator.

Source core for 2026-10-29. The composite data, descriptions and diagrams above were originally created at the station; Values have been reviewed with independent arithmeticals and do not represent running GPU training. Frame interface continues to read scikit-learn linear model description And the official documents listed here. API 。

Change a variable

Scores, probabilities and penalties

Synthetic teaching algorithms
Forecast probability for y = 10.5000
BCE loss
0.693147
Gradient for logit
-0.5000

The current is the case. The General Assembly will increase the number of points to increase the probability of a positive event and reduce the loss of the sample.

Displays the calculation of the default parameters at the moment. The parameters can be changed when JavaScript is turned on.

Sources and reconciliations

Definitions, methods and interfaces are available.

  1. Stanford CS229 Lecture Notes
  2. PyTorch BCEWithLogitsLoss
  3. PyTorch CrossEntropyLoss
  4. scikit-learn Linear Models

Figures and calculations are reorganized according to this chapter. Mathematical measurements, framework operations and real business effects are described separately in the body of the text.

← Back to the knowledge directory
Ask Max Ask about this site
Ask Max ↗

Opening the assistant…

Paper figure

Photo comments

LEAVE A NOTE

About this photograph

Connecting to the discussion board…

    Comments become public after moderation. You can delete your own comments from this browser.
    No email is required. Clearing cookies prevents this browser from claiming earlier comments.

    MAX WANG / INDEX

    Find something

    Enter a keyword, or explore the directory below.