Écrire notre première boucle d'entraînement

Introduction au Deep Learning avec PyTorch

Jasmin Ludolf

Senior Data Science Content Developer, DataCamp

Entraîner un réseau de neurones

  1. Créer un modèle
  2. Choisir une fonction de perte
  3. Définir un ensemble de données
  4. Définir un optimiseur
  5. Exécuter une boucle d'entraînement :
    • Calculer la perte (passage avant)
    • Calculer les gradients (rétropropagation)
    • Mettre à jour les paramètres du modèle
Introduction au Deep Learning avec PyTorch

Présentation de l'ensemble de données Data Science Salary

 experience_level  employment_type  remote_ratio  company_size  salary_in_usd  
        0                0               0.5             1            0.036 
        1                0               1.0             2            0.133     
        2                0               0.0             1            0.234  
        1                0               1.0             0            0.076  
        2                0               1.0             1            0.170

$$

  • Caractéristiques : catégorielles, cible : salaire (USD)
  • Sortie finale : couche linéaire
  • Perte : spécifique à la régression
Introduction au Deep Learning avec PyTorch

Perte à erreur quadratique moyenne (MSE)

$$

  • La perte MSE est la moyenne des carrés de l'écart entre les prédictions et la vérité terrain
def mean_squared_loss(prediction, target):
  return np.mean((prediction - target)**2)

$$

  • dans PyTorch :
criterion = nn.MSELoss()
# Prediction and target are float tensors
loss = criterion(prediction, target)
Introduction au Deep Learning avec PyTorch

Avant la boucle d'entraînement

# Create the dataset and the dataloader
dataset = TensorDataset(torch.tensor(features).float(),
                        torch.tensor(target).float())


dataloader = DataLoader(dataset, batch_size=4, shuffle=True)
# Create the model model = nn.Sequential(nn.Linear(4, 2), nn.Linear(2, 1))
# Create the loss and optimizer criterion = nn.MSELoss() optimizer = optim.SGD(model.parameters(), lr=0.001)
Introduction au Deep Learning avec PyTorch

La boucle d'entraînement

for epoch in range(num_epochs):

for data in dataloader:
# Set the gradients to zero optimizer.zero_grad()
# Get feature and target from the data loader feature, target = data
# Run a forward pass pred = model(feature) # Compute loss and gradients loss = criterion(pred, target) loss.backward()
# Update the parameters optimizer.step()
Introduction au Deep Learning avec PyTorch

Passons à la pratique !

Introduction au Deep Learning avec PyTorch

Preparing Video For Download...