ホーム 暮らし Learn PyTorch in 3 Minutes | torch.nn.CrossEntropyLoss

Learn PyTorch in 3 Minutes | torch.nn.CrossEntropyLoss

篠原 沙世 篠原 沙世 • 更新: • 公開: • 読了約 11 分
目次

Official Docs: https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html
Verified Version: PyTorch 2.11 (based on official Docs)

1. What it does

n78662725fc76

torch.nn.CrossEntropyLoss is the most commonly used loss function for multi-class classification tasks. It takes the model output (logits) and the ground truth labels, and returns a numerical value representing how far off the predictions are. It internally calculates Softmax and NLLLoss simultaneously.

2. When to use it

  • Image classification (MNIST digit recognition, ImageNet category classification, etc.)

  • Text classification (sentiment analysis, news category classification, etc.)

  • General classification tasks with two or more classes

3. How to use it (minimal code)

import torch
import torch.nn as nn

criterion = nn.CrossEntropyLoss()
モデルの出力(ロジット):バッチサイズ=4, クラス数=3
logits = torch.tensor([
    [2.0, 1.0, 0.1],
    [0.5, 2.5, 0.3],
    [0.1, 0.2, 3.0],
    [1.0, 1.0, 1.0]
])  # shape: (4, 3)
正解ラベル(クラスインデックス)
labels = torch.tensor([0, 1, 2, 0])  # shape: (4,)  dtype=torch.long

loss = criterion(logits, labels)
print(loss)  # tensor(0.4018)  ※値は例
logits.shape = (バッチサイズ, クラス数) = (4, 3)
labels.shape = (バッチサイズ,)           = (4,)
loss.shape   = ()  ← スカラー値

4. Common pitfalls

1. Do not include Softmax in the final layer of the model

Since CrossEntropyLoss calculates Softmax internally, adding nn.Softmax() to the final layer will result in double application. Please keep the final layer as nn.Linear.

# ❌ Softmaxを入れるとダメ
model = nn.Sequential(nn.Linear(4, 3), nn.Softmax(dim=1))
✅ LinearだけでOK
model = nn.Sequential(nn.Linear(4, 3))

2. Labels must be torch.long (int64)

Passing labels as float32 will cause an error. Please create them using torch.tensor(labels, dtype=torch.long).

3. Labels should be class indices (starting from 0)

Pass them in index format like [0, 1, 2, ...], not as one-hot vectors.

4. CrossEntropyLoss can also be used for binary classification

It can be used even when the number of classes is 2 (you do not have to use BCEWithLogitsLoss).

5. Common errors and solutions

Error example
RuntimeError: Expected target size (N, C), got torch.Size([N])

Cause:
The label shape is in (N, C) one-hot format.

Solution:
Pass the labels as a 1D tensor (N,) of class indices.

# ❌ one-hot はNG
labels = torch.tensor([[1,0,0],[0,1,0]])   # shape: (2, 3)
✅ インデックスで渡す
labels = torch.tensor([0, 1])              # shape: (2,)
Error Example
RuntimeError: Expected object of scalar type Long but got Float

Cause:
The label dtype is set to torch.float32.

Solution:
Create them using labels = labels.long() or dtype=torch.long.

⑥ A Quick Tip

⑦ Related Functions

  • torch.nn.BCEWithLogitsLoss — For binary classification and multi-label classification

  • torch.nn.NLLLoss — A loss function used for outputs that have already undergone log-softmax

  • torch.nn.MSELoss — A loss function for regression tasks

⑧ Version Notes

Since PyTorch 1.10, the label_smoothing argument has been added. You can use it when you want to suppress overfitting with label smoothing.

criterion = nn.CrossEntropyLoss(label_smoothing=0.1)

[For those who want to learn by doing]

I have published an article (free) that includes an exercise notebook so you can verify things by actually running the code instead of just reading.

▼ Exercise: Implementing an MLP in PyTorch | Writing classification and regression with the same framework [Basics Part 1, Free Notebook]

[Taking it a step further (Paid)]
After the basics, there is an advanced section (1,000 yen, includes exercise notebook) where we add learning rate schedulers, mixed precision, and torch.compile to the same framework.
▼ From "Writing a working MLP" to "Writing an MLP for production" | PyTorch Advanced Techniques Exercise


[About this series]

"Learn PyTorch in 3 Minutes" is a series that explains one PyTorch API at a time in a format that can be read in 3 minutes. It is updated on Mondays, Wednesdays, and Fridays, with 32 installments planned.

▼ Follow the magazine to receive new updates

Learn PyTorch in 3 Minutes
https://note.com/technosend/m/m84d841b6d067

同じカテゴリの記事

篠原 沙世

アニメとゲームの新作情報を担当。制作会社・配信元の公式告知と登壇情報を照合して記事化します。

おすすめの関連記事