Daniel Voigt Godoy - Deep Learning with PyTorch Step-by-Step A Beginner’s Guide-leanpub
If, by any chance, you ended up with something like the weird plot below, don’tworry just yet!Figure 2.7 - Weird results on TensorBoard :PRemember, I said writing the data of multiple runs into the samefolder was bad? This is why…Since we’re writing data to the folderruns/simple_linear_regression, if we do not change the nameof the folder (or erase the data there) before running the code asecond time, TensorBoard gets somewhat confused, as you canguess from its output:• Found more than one graph event per run (because we ranadd_graph() more than once)• Found more than one "run metadata" event with tag step1(because we ran add_scalars() more than once)If you are using a local installation, you can see those messages inthe terminal window or Anaconda prompt you used to runtensorboard --log_dir=runs.So, you finished training your model, you inspected TensorBoard plots, and you’rehappy with the losses you got.Congratulations! Your job is done; you successfully trained your model!There is only one more thing you need to know, and that is how to handle…TensorBoard | 163
Saving and Loading ModelsTraining a model successfully is great, no doubt about that, but not all models willtrain quickly, and training may get interrupted (computer crashing, timeout after12 hours of continuous GPU usage on Google Colab, etc.). It would be a pity to haveto start over, right?So, it is important to be able to checkpoint or save our model, that is, save it to disk,in case we’d like to restart training later or deploy it as an application to makepredictions.Model StateTo checkpoint a model, we basically have to save its state to a file so that it can beloaded back later—nothing special, actually.What defines the state of a model?• model.state_dict(): kinda obvious, right?• optimizer.state_dict(): remember, optimizers have a state_dict() as well• losses: after all, you should keep track of its evolution• epoch: it is just a number, so why not? :-)• anything else you’d like to have restored laterSavingNow, we wrap everything into a Python dictionary and use torch.save() to dumpit all into a file. Easy peasy! We have just saved our model to a file namedmodel_checkpoint.pth.Notebook Cell 2.4 - Saving checkpointcheckpoint = {'epoch': n_epochs,'model_state_dict': model.state_dict(),'optimizer_state_dict': optimizer.state_dict(),'loss': losses,'val_loss': val_losses}torch.save(checkpoint, 'model_checkpoint.pth')164 | Chapter 2: Rethinking the Training Loop
- Page 138 and 139: LayersA Linear model can be seen as
- Page 140 and 141: There are MANY different layers tha
- Page 142 and 143: We use magic, just like that:%run -
- Page 144 and 145: • Step 1: compute model’s predi
- Page 146 and 147: RecapFirst of all, congratulations
- Page 148 and 149: Chapter 2Rethinking the Training Lo
- Page 150 and 151: Let’s take a look at the code onc
- Page 152 and 153: Higher-Order FunctionsAlthough this
- Page 154 and 155: def exponentiation_builder(exponent
- Page 156 and 157: Apart from returning the loss value
- Page 158 and 159: Our code should look like this; see
- Page 160 and 161: There is no need to load the whole
- Page 162 and 163: but if we want to get serious about
- Page 164 and 165: How does this change our code so fa
- Page 166 and 167: Run - Model Training V2%run -i mode
- Page 168 and 169: piece of code that’s going to be
- Page 170 and 171: for it. We could do the same for th
- Page 172 and 173: EvaluationHow can we evaluate the m
- Page 174 and 175: And then, we update our model confi
- Page 176 and 177: Run - Model Training V4%run -i mode
- Page 178 and 179: Loading Extension# Load the TensorB
- Page 180 and 181: browser, you’ll likely see someth
- Page 182 and 183: model’s graph (not quite the same
- Page 184 and 185: Figure 2.5 - Scalars on TensorBoard
- Page 186 and 187: Define - Model Training V51 %%write
- Page 190 and 191: The procedure is exactly the same,
- Page 192 and 193: soon, so please bear with me for no
- Page 194 and 195: After recovering our model’s stat
- Page 196 and 197: Run - Model Configuration V31 # %lo
- Page 198 and 199: This is the general structure you
- Page 200 and 201: Chapter 2.1Going ClassySpoilersIn t
- Page 202 and 203: # A completely empty (and useless)
- Page 204 and 205: # These attributes are defined here
- Page 206 and 207: # Creates the train_step function f
- Page 208 and 209: # Builds function that performs a s
- Page 210 and 211: setattrThe setattr function sets th
- Page 212 and 213: See? We effectively modified the un
- Page 214 and 215: the random seed as arguments.This s
- Page 216 and 217: The current state of development of
- Page 218 and 219: Lossesdef plot_losses(self):fig = p
- Page 220 and 221: Run - Data Preparation V21 # %load
- Page 222 and 223: Model TrainingWe start by instantia
- Page 224 and 225: Making PredictionsLet’s make up s
- Page 226 and 227: OutputOrderedDict([('0.weight', ten
- Page 228 and 229: Run - Data Preparation V21 # %load
- Page 230 and 231: • defining our StepByStep class
- Page 232 and 233: import numpy as npimport torchimpor
- Page 234 and 235: Next, we’ll standardize the featu
- Page 236 and 237: Equation 3.1 - A linear regression
If, by any chance, you ended up with something like the weird plot below, don’t
worry just yet!
Figure 2.7 - Weird results on TensorBoard :P
Remember, I said writing the data of multiple runs into the same
folder was bad? This is why…
Since we’re writing data to the folder
runs/simple_linear_regression, if we do not change the name
of the folder (or erase the data there) before running the code a
second time, TensorBoard gets somewhat confused, as you can
guess from its output:
• Found more than one graph event per run (because we ran
add_graph() more than once)
• Found more than one "run metadata" event with tag step1
(because we ran add_scalars() more than once)
If you are using a local installation, you can see those messages in
the terminal window or Anaconda prompt you used to run
tensorboard --log_dir=runs.
So, you finished training your model, you inspected TensorBoard plots, and you’re
happy with the losses you got.
Congratulations! Your job is done; you successfully trained your model!
There is only one more thing you need to know, and that is how to handle…
TensorBoard | 163