How to save model in a specific directory,
torch.save({
‘epoch’: var_epoch,
‘model_state_dict’: var_best_weight,
‘optimizer_state_dict’: optimizer.state_dict(),
‘accuracy’: var_best_accuracy,
}, save_path)
Let’s break down the torch.save() function and its contents in detail:
```python
torch.save({
‘epoch’: var_epoch,
‘model_state_dict’: var_best_weight,
‘optimizer_state_dict’: optimizer.state_dict(),
‘accuracy’: var_best_accuracy,
}, save_path)
~~~
torch.save() function:'epoch': var_epoch'model_state_dict': var_best_weightpython
{
'conv1.weight': tensor(...),
'conv1.bias': tensor(...),
'fc1.weight': tensor(...),
'fc1.bias': tensor(...),
...
}
c. 'optimizer_state_dict': optimizer.state_dict()'accuracy': var_best_accuracysave_path:To later load this saved model:
```python
checkpoint = torch.load(save_path)
model.load_state_dict(checkpoint[‘model_state_dict’])
optimizer.load_state_dict(checkpoint[‘optimizer_state_dict’])
epoch = checkpoint[‘epoch’]
accuracy = checkpoint[‘accuracy’]
~~~
This comprehensive saving approach is beneficial because:
1. You can resume training exactly where you left off
2. You maintain the optimizer’s state, which is important for optimization algorithms that maintain internal state (like momentum)
3. You keep track of metadata like epoch number and accuracy
4. You can implement model versioning and track different checkpoints