0Pricing
Deep Learning Academy · Урок

Бинарная кросс-энтропия с логитами

Стабильная функция потерь для задач с двумя классами

«Бинарная кросс-энтропия с логитами» — бесплатный урок Deep Learning Academy на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Deep Learning Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Deep Learning Academy содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Two Classes, One Decision

When your model answers a yes or no question like spam or not spam, you reach for binary cross-entropy, the loss built for two-class problems. ✅

From Score to Probability

A model first outputs a raw score called a logit. The sigmoid function squashes that logit into a probability between 0 and 1.

import torch
prob = torch.sigmoid(logit)

What Cross-Entropy Rewards

Cross-entropy gives a small loss when the predicted probability is close to the true label, and a large loss when it is confidently wrong.

Confident and Wrong Hurts

Predicting 0.99 when the true label is 0 produces a huge loss. Cross-entropy punishes confident mistakes far more than uncertain ones.

The Naive Loss Choice

You could apply sigmoid yourself, then use nn.BCELoss on the probabilities. It works, but there is a safer way for real training.

import torch.nn as nn
loss_fn = nn.BCELoss()
loss = loss_fn(prob, target)

Feed Logits, Not Probabilities

The preferred loss is BCEWithLogitsLoss. It takes raw logits directly and applies the sigmoid internally for you.

import torch.nn as nn
loss_fn = nn.BCEWithLogitsLoss()
loss = loss_fn(logit, target)

Why Combine the Steps

Fusing sigmoid and the loss uses the log-sum-exp trick, which avoids overflow and gives stable gradients even at extreme logits.

Skip the Extra Sigmoid

Because BCEWithLogitsLoss applies sigmoid itself, your model's last layer should output raw logits with no sigmoid attached.

Targets Are 0 or 1

Pass float targets of 0.0 or 1.0 with the same shape as your logits. A mismatched shape is the classic BCE bug to watch for.

target = torch.tensor([1.0, 0.0, 1.0])

Sigmoid Only at Inference

During training the loss handles the squashing. To read a probability for a prediction, apply sigmoid to the logit at inference time.

Tilt the Balance with pos_weight

If positives are rare, the pos_weight argument scales up their contribution so the model stops ignoring the minority class.

Quick Check

You are doing binary classification and want numerical stability. What should you feed the loss?

Recap: Stable Yes or No

For two-class tasks you feed raw logits to BCEWithLogitsLoss, which squashes and scores in one stable step. Save sigmoid for reading probabilities later. 👍

Часто задаваемые вопросы

Урок «Бинарная кросс-энтропия с логитами» бесплатный?

Да — полный текст урока «Бинарная кросс-энтропия с логитами» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Deep Learning Academy, подпишись на CoddyKit PRO. Курс Deep Learning Academy содержит 4 уроков всего.

Чему я научусь в уроке «Бинарная кросс-энтропия с логитами»?

Стабильная функция потерь для задач с двумя классами Ты практикуешь Deep Learning Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Deep Learning Academy?

Предыдущий опыт не требуется. Deep Learning Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.

Сколько времени занимает урок «Бинарная кросс-энтропия с логитами»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Deep Learning Academy?

Да. Каждый урок Deep Learning Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. MSE и MAE для регрессии
  2. Бинарная кросс-энтропия с логитами
  3. Кросс-энтропия для нескольких классов
  4. Веса классов для несбалансированных данных
← Назад к Deep Learning Academy