Fonction torch.nn.LogSoftmax de PyTorch
Manuel de référence torch.nn de PyTorch
torch.nn.LogSoftmaxC'est la fonction d'activation Log Softmax dans PyTorch.
C'est la forme logarithmique de Softmax, qui est numériquement plus stable et souvent utilisée avec NLLLoss.
Définition de fonction
torch.nn.LogSoftmax(dim=None)
Formule
LogSoftmax(x_i) = log(exp(x_i) / sum(exp(x_j)))
Exemples d'utilisation
Exemple 1 : Utilisation de base
Exemple
import torch
import torch.nn as nn
log_softmax = nn.LogSoftmax(dim=1)
logits = torch.tensor([[2.0, 1.0, 0.1]])
log_probs = log_softmax(logits)
print("Logits :", logits.tolist())
print("Log Softmax :", log_probs.tolist())
print("Après exp :", log_probs.exp().tolist())
import torch.nn as nn
log_softmax = nn.LogSoftmax(dim=1)
logits = torch.tensor([[2.0, 1.0, 0.1]])
log_probs = log_softmax(logits)
print("Logits :", logits.tolist())
print("Log Softmax :", log_probs.tolist())
print("Après exp :", log_probs.exp().tolist())
Exemple 2 : Avec NLLLoss
Exemple
import torch
import torch.nn as nn
# Tâche de classification
logits = torch.randn(4, 10)
targets = torch.tensor([2, 5, 1, 7])
# LogSoftmax + NLLLoss = CrossEntropyLoss
loss = nn.NLLLoss()(nn.LogSoftmax(dim=1)(logits), targets)
print("Perte NLL :", loss.item())
# Équivalent à
loss2 = nn.CrossEntropyLoss()(logits, targets)
print("CrossEntropyLoss:", loss2.item())
import torch.nn as nn
# Tâche de classification
logits = torch.randn(4, 10)
targets = torch.tensor([2, 5, 1, 7])
# LogSoftmax + NLLLoss = CrossEntropyLoss
loss = nn.NLLLoss()(nn.LogSoftmax(dim=1)(logits), targets)
print("Perte NLL :", loss.item())
# Équivalent à
loss2 = nn.CrossEntropyLoss()(logits, targets)
print("CrossEntropyLoss:", loss2.item())
Exemple 3 : Stabilité numérique
Exemple
import torch
import torch.nn as nn
# Logits élevés
logits = torch.tensor([[1000, 1001, 1002]])
# Softmax peut déborder
try:
sm = nn.Softmax(dim=1)(logits)
print("Softmax:", sm)
except:
print("Débordement de Softmax")
# LogSoftmax est numériquement stable
lsm = nn.LogSoftmax(dim=1)(logits)
print("LogSoftmax:", lsm)
import torch.nn as nn
# Logits élevés
logits = torch.tensor([[1000, 1001, 1002]])
# Softmax peut déborder
try:
sm = nn.Softmax(dim=1)(logits)
print("Softmax:", sm)
except:
print("Débordement de Softmax")
# LogSoftmax est numériquement stable
lsm = nn.LogSoftmax(dim=1)(logits)
print("LogSoftmax:", lsm)
Cas d'utilisation
- Tâches de classification: avec NLLLoss
- Stabilité numérique: valeurs de logits élevées
Astuce : LogSoftmax + NLLLoss équivaut à CrossEntropyLoss.
Autres extensions