Fonction PyTorch torch.nn.SiLU
Manuel de référence torch.nn de PyTorch
torch.nn.SiLUC'est la fonction d'activation Sigmoid Linear Unit dans PyTorch, également connue sous le nom de Swish.
Elle possède des propriétés d'auto-gating, est plus lisse que ReLU et offre de meilleures performances sur certaines tâches.
Définition de fonction
torch.nn.SiLU(inplace=False)
Principe mathématique
SiLU(x) = x * sigmoid(x)
Exemples d'utilisation
Exemple 1 : Utilisation de base
Exemple
import torch
import torch.nn as nn
silu = nn.SiLU()
x = torch.tensor([-2.0, -1.0, 0.0, 1.0, 2.0])
output = silu(x)
print("Input:", x.tolist())
print("Sortie :", output.tolist())
import torch.nn as nn
silu = nn.SiLU()
x = torch.tensor([-2.0, -1.0, 0.0, 1.0, 2.0])
output = silu(x)
print("Input:", x.tolist())
print("Sortie :", output.tolist())
Exemple 2 : Comparaison avec ReLU
Exemple
import torch
import torch.nn as nn
import numpy as np
x = np.linspace(-3, 3, 7)
x_tensor = torch.tensor(x)
print("x SiLU ReLU")
print("-" * 30)
for xi in x_tensor:
print(f"{xi.item():5.1f} {nn.SiLU()(xi.unsqueeze(0)).item():9.4f} {nn.ReLU()(xi.unsqueeze(0)).item():9.4f}")
import torch.nn as nn
import numpy as np
x = np.linspace(-3, 3, 7)
x_tensor = torch.tensor(x)
print("x SiLU ReLU")
print("-" * 30)
for xi in x_tensor:
print(f"{xi.item():5.1f} {nn.SiLU()(xi.unsqueeze(0)).item():9.4f} {nn.ReLU()(xi.unsqueeze(0)).item():9.4f}")
Exemple 3 : Utilisation dans MobileNet
Exemple
import torch
import torch.nn as nn
# MobileNetV3 utilise SiLU
model = nn.Sequential(
nn.Conv2d(3, 32, 3, stride=2, padding=1),
nn.BatchNorm2d(32),
nn.SiLU(),
nn.Conv2d(32, 64, 3, padding=1),
nn.BatchNorm2d(64),
nn.SiLU()
)
x = torch.randn(1, 3, 224, 224)
output = model(x)
print("Entrée :", x.shape, "-> Sortie :", output.shape)
import torch.nn as nn
# MobileNetV3 utilise SiLU
model = nn.Sequential(
nn.Conv2d(3, 32, 3, stride=2, padding=1),
nn.BatchNorm2d(32),
nn.SiLU(),
nn.Conv2d(32, 64, 3, padding=1),
nn.BatchNorm2d(64),
nn.SiLU()
)
x = torch.randn(1, 3, 224, 224)
output = model(x)
print("Entrée :", x.shape, "-> Sortie :", output.shape)
Cas d'utilisation
- MobileNet: MobileNetV3
- EfficientNet
- Activation lisse: nécessite des propriétés de gating
Remarque : SiLU est plus complexe en calcul que ReLU, mais ses performances sont généralement meilleures.
Autres extensions