Fonction torch.nn.L1Loss de PyTorch
Manuel de référence torch.nn de PyTorch
torch.nn.L1LossIl s'agit de la fonction de perte L1 dans PyTorch, également connue sous le nom d'erreur absolue moyenne (MAE).
Définition de fonction
torch.nn.L1Loss(reduction='mean')
Exemple d'utilisation
Exemple 1 : Utilisation de base
Exemple
import torch
import torch.nn as nn
criterion = nn.L1Loss()
pred = torch.tensor([3.0, 4.0, 5.0])
target = torch.tensor([2.0, 4.5, 5.5])
loss = criterion(pred, target)
print("Perte L1 :", loss.item())
# Vérification manuelle
manual = (pred - target).abs().mean()
print("Calcul manuel :", manual.item())
import torch.nn as nn
criterion = nn.L1Loss()
pred = torch.tensor([3.0, 4.0, 5.0])
target = torch.tensor([2.0, 4.5, 5.5])
loss = criterion(pred, target)
print("Perte L1 :", loss.item())
# Vérification manuelle
manual = (pred - target).abs().mean()
print("Calcul manuel :", manual.item())
Exemple 2 : Comparaison avec MSE
Exemple
import torch
import torch.nn as nn
pred = torch.tensor([10.0, 20.0])
target = torch.tensor([0.0, 0.0])
print("Perte L1 (robuste aux valeurs aberrantes) :", nn.L1Loss()(pred, target).item())
print("Perte MSE (sensible aux valeurs aberrantes) :", nn.MSELoss()(pred, target).item())
import torch.nn as nn
pred = torch.tensor([10.0, 20.0])
target = torch.tensor([0.0, 0.0])
print("Perte L1 (robuste aux valeurs aberrantes) :", nn.L1Loss()(pred, target).item())
print("Perte MSE (sensible aux valeurs aberrantes) :", nn.MSELoss()(pred, target).item())
Cas d'utilisation
- Tâches de régression: Nécessitent de la robustesse
- Valeurs aberrantes: Données bruitées
- Régularisation L1: Sparsification
Autres extensions