PyTorch torch.nn.LogSoftmax-Funktion
PyTorch torch.nn Referenzhandbuch
torch.nn.LogSoftmaxEs ist die Log-Softmax-Aktivierungsfunktion in PyTorch.
Es ist die logarithmische Form von Softmax, die numerisch stabiler ist und oft mit NLLLoss verwendet wird.
Funktionsdefinition
torch.nn.LogSoftmax(dim=None)
Formel
LogSoftmax(x_i) = log(exp(x_i) / sum(exp(x_j)))
Anwendungsbeispiele
Beispiel 1: Grundlegende Verwendung
Beispiel
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("Nach 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("Nach exp:", log_probs.exp().tolist())
Beispiel 2: Mit NLLLoss
Beispiel
import torch
import torch.nn as nn
# Klassifizierungsaufgabe
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("NLL-Verlust:", loss.item())
# Entspricht
loss2 = nn.CrossEntropyLoss()(logits, targets)
print("CrossEntropyLoss:", loss2.item())
import torch.nn as nn
# Klassifizierungsaufgabe
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("NLL-Verlust:", loss.item())
# Entspricht
loss2 = nn.CrossEntropyLoss()(logits, targets)
print("CrossEntropyLoss:", loss2.item())
Beispiel 3: Numerische Stabilität
Beispiel
import torch
import torch.nn as nn
# Große Logits
logits = torch.tensor([[1000, 1001, 1002]])
# Softmax kann überlaufen
try:
sm = nn.Softmax(dim=1)(logits)
print("Softmax:", sm)
except:
print("Softmax-Überlauf")
# LogSoftmax ist numerisch stabil
lsm = nn.LogSoftmax(dim=1)(logits)
print("LogSoftmax:", lsm)
import torch.nn as nn
# Große Logits
logits = torch.tensor([[1000, 1001, 1002]])
# Softmax kann überlaufen
try:
sm = nn.Softmax(dim=1)(logits)
print("Softmax:", sm)
except:
print("Softmax-Überlauf")
# LogSoftmax ist numerisch stabil
lsm = nn.LogSoftmax(dim=1)(logits)
print("LogSoftmax:", lsm)
Anwendungsfälle
- Klassifikationsaufgaben: Mit NLLLoss
- Numerische Stabilität: Große Logit-Werte
Tipp: LogSoftmax + NLLLoss ist äquivalent zu CrossEntropyLoss.
Andere Erweiterungen