Bird
Raised Fist0
PyTorchml~20 mins

Best model saving pattern in PyTorch - ML Experiment: Train & Evaluate

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Experiment - Best model saving pattern
Problem:You have trained a PyTorch model for image classification. The training accuracy is high, but you want to save the best model based on validation accuracy during training to avoid losing the best performing model.
Current Metrics:Training accuracy: 95%, Validation accuracy: 80%, but the saved model is always the last epoch model which has validation accuracy 75%.
Issue:The saved model is not the best one because the saving happens only at the end of training, causing loss of the best validation accuracy model.
Your Task
Implement a model saving pattern that saves the model only when the validation accuracy improves, ensuring the best model is saved.
Use PyTorch framework.
Do not save the model every epoch, only when validation accuracy improves.
Keep the training loop structure simple and clear.
Hint 1
Hint 2
Hint 3
Solution
PyTorch
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset

# Dummy dataset
X_train = torch.randn(100, 10)
y_train = torch.randint(0, 2, (100,))
X_val = torch.randn(20, 10)
y_val = torch.randint(0, 2, (20,))

train_ds = TensorDataset(X_train, y_train)
val_ds = TensorDataset(X_val, y_val)

train_loader = DataLoader(train_ds, batch_size=16)
val_loader = DataLoader(val_ds, batch_size=16)

# Simple model
class SimpleNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc = nn.Linear(10, 2)
    def forward(self, x):
        return self.fc(x)

model = SimpleNet()
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.01)

best_val_acc = 0.0
num_epochs = 10

for epoch in range(num_epochs):
    model.train()
    for xb, yb in train_loader:
        optimizer.zero_grad()
        preds = model(xb)
        loss = criterion(preds, yb)
        loss.backward()
        optimizer.step()

    # Validation
    model.eval()
    correct = 0
    total = 0
    with torch.no_grad():
        for xb, yb in val_loader:
            preds = model(xb)
            predicted = preds.argmax(dim=1)
            correct += (predicted == yb).sum().item()
            total += yb.size(0)
    val_acc = correct / total
    print(f"Epoch {epoch+1}, Validation Accuracy: {val_acc:.4f}")

    # Save best model
    if val_acc > best_val_acc:
        best_val_acc = val_acc
        torch.save(model.state_dict(), "best_model.pth")
        print(f"Saved best model with accuracy: {best_val_acc:.4f}")
Added tracking of best validation accuracy with variable best_val_acc.
Added condition to save model weights only if current validation accuracy is higher than best_val_acc.
Used torch.save(model.state_dict(), 'best_model.pth') to save the best model.
Results Interpretation

Before: The model saved was always from the last epoch with validation accuracy 75%, which is lower than the best validation accuracy achieved (80%).

After: The model saved is the one with the highest validation accuracy (80%), ensuring the best performing model is kept.

Saving the model only when validation accuracy improves prevents losing the best model during training and helps in deploying the most accurate model.
Bonus Experiment
Modify the saving pattern to also save the optimizer state along with the model to resume training exactly from the best checkpoint.
💡 Hint
Save a dictionary with model.state_dict() and optimizer.state_dict() using torch.save, and load them together to resume training.

Practice

(1/5)
1. What is the best practice for saving a PyTorch model during training?
easy
A. Save the model only at the start of training.
B. Save the model only when it improves on validation data.
C. Save the model after every training batch.
D. Save the model only if the training loss increases.

Solution

  1. Step 1: Understand model saving timing

    Saving the model only when validation improves ensures you keep the best version, avoiding unnecessary saves.
  2. Step 2: Compare other options

    Saving every batch wastes space; saving at start or on loss increase is not useful for best model.
  3. Final Answer:

    Save the model only when it improves on validation data. -> Option B
  4. Quick Check:

    Save best validation model = C [OK]
Hint: Save model only on validation improvement to keep best [OK]
Common Mistakes:
  • Saving model too frequently wastes storage
  • Saving only at start misses improvements
  • Saving on training loss increase is wrong
2. Which of the following is the correct PyTorch code to save only the model weights?
easy
A. torch.save(model.state_dict(), 'model.pth')
B. torch.save(model, 'model.pth')
C. model.save('model.pth')
D. model.state_dict().save('model.pth')

Solution

  1. Step 1: Identify correct saving method

    PyTorch saves weights using torch.save(model.state_dict(), filename).
  2. Step 2: Check other options

    Saving the whole model (torch.save(model, 'model.pth')) is possible but less flexible; options C and D are invalid syntax.
  3. Final Answer:

    torch.save(model.state_dict(), 'model.pth') -> Option A
  4. Quick Check:

    Save weights with state_dict() = A [OK]
Hint: Use torch.save(model.state_dict(), filename) to save weights [OK]
Common Mistakes:
  • Trying to save model directly without state_dict
  • Using non-existent save methods on model
  • Confusing saving weights vs full model
3. Given this code snippet, what will be printed?
import torch
import torch.nn as nn

model = nn.Linear(2, 1)
torch.save(model.state_dict(), 'best.pth')
new_model = nn.Linear(2, 1)
new_model.load_state_dict(torch.load('best.pth'))
print(new_model.weight.shape)
medium
A. torch.Size([1, 2])
B. torch.Size([2, 1])
C. torch.Size([1, 1])
D. Error: shape mismatch

Solution

  1. Step 1: Understand model architecture

    nn.Linear(2,1) creates weights of shape [1, 2] (output features, input features).
  2. Step 2: Loading weights into new model

    Loading saved weights into identical model keeps weight shape same.
  3. Final Answer:

    torch.Size([1, 2]) -> Option A
  4. Quick Check:

    Linear(2,1) weight shape = [1, 2] [OK]
Hint: Linear layer weights shape = (out_features, in_features) [OK]
Common Mistakes:
  • Confusing input/output dimensions order
  • Expecting error when loading identical model
  • Misreading weight shape as (2,1)
4. What is wrong with this code snippet for saving the best model?
if val_loss < best_loss:
    best_loss = val_loss
    torch.save(model, 'best_model.pth')
medium
A. There is no condition to check validation loss.
B. It should save model.state_dict() instead of model.
C. It does not update best_loss correctly.
D. It saves the entire model, which is less flexible than saving state_dict.

Solution

  1. Step 1: Analyze saving method

    Saving entire model works but is less flexible and may cause issues when loading on different devices or PyTorch versions.
  2. Step 2: Compare with best practice

    Best practice is saving model.state_dict() for portability and smaller files.
  3. Final Answer:

    It saves the entire model, which is less flexible than saving state_dict. -> Option D
  4. Quick Check:

    Save state_dict() preferred over full model [OK]
Hint: Save state_dict() for flexibility, not full model [OK]
Common Mistakes:
  • Saving full model without state_dict
  • Ignoring portability issues
  • Assuming full model save is always best
5. You want to save the best model during training based on validation accuracy. Which code snippet correctly implements this pattern?
best_acc = 0.0
for epoch in range(epochs):
    train()
    val_acc = validate()
    # Save best model here
    ???
hard
A. if val_acc < best_acc: best_acc = val_acc torch.save(model.state_dict(), 'best_model.pth')
B. if val_acc == best_acc: torch.save(model.state_dict(), 'best_model.pth')
C. if val_acc > best_acc: best_acc = val_acc torch.save(model.state_dict(), 'best_model.pth')
D. torch.save(model.state_dict(), 'best_model.pth') # save every epoch

Solution

  1. Step 1: Identify saving condition

    We save model only if validation accuracy improves (val_acc > best_acc).
  2. Step 2: Update best accuracy and save weights

    Update best_acc and save model.state_dict() to keep best weights.
  3. Final Answer:

    if val_acc > best_acc: best_acc = val_acc torch.save(model.state_dict(), 'best_model.pth') -> Option C
  4. Quick Check:

    Save on val_acc improvement = B [OK]
Hint: Save model only if validation accuracy improves [OK]
Common Mistakes:
  • Saving when accuracy decreases
  • Saving every epoch wastes space
  • Not updating best accuracy variable