Daniel Voigt Godoy - Deep Learning with PyTorch Step-by-Step A Beginner’s Guide-leanpub
It is not that hard, to be honest. Remember the reduction argument? If we set it tosum, our loss function will only return the numerator of the equation above. Andthen we can divide it by the weighted counts ourselves:loss_fn_imb_sum = nn.BCEWithLogitsLoss(reduction='sum',pos_weight=pos_weight)loss = loss_fn_imb_sum(dummy_imb_logits, dummy_imb_labels)loss = loss / (pos_weight * n_pos + n_neg)lossOutputtensor([0.1643])There we go!Model ConfigurationIn Chapter 2.1, we ended up with a lean "Model Configuration" section: We onlyneed to define a model, an appropriate loss function, and an optimizer. Let’s definea model that produces logits and use nn.BCEWithLogitsLoss() as the loss function.Since we have two features, and we are producing logits instead of probabilities,our model will have one layer and one layer alone: Linear(2, 1). We will keepusing the SGD optimizer with a learning rate of 0.1 for now.Model Configuration | 231
This is what the model configuration looks like for our classification problem:Model Configuration1 # Sets learning rate - this is "eta" ~ the "n"-like Greek letter2 lr = 0.134 torch.manual_seed(42)5 model = nn.Sequential()6 model.add_module('linear', nn.Linear(2, 1))78 # Defines an SGD optimizer to update the parameters9 optimizer = optim.SGD(model.parameters(), lr=lr)1011 # Defines a BCE with logits loss function12 loss_fn = nn.BCEWithLogitsLoss()Model TrainingTime to train our model! We can leverage the StepByStep class we built in Chapter2.1 and use pretty much the same code as before:Model Training1 n_epochs = 10023 sbs = StepByStep(model, loss_fn, optimizer)4 sbs.set_loaders(train_loader, val_loader)5 sbs.train(n_epochs)fig = sbs.plot_losses()232 | Chapter 3: A Simple Classification Problem
- 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
- Page 238 and 239: The odds ratio is given by the rati
- Page 240 and 241: As expected, probabilities that add
- Page 242 and 243: Sigmoid Functiondef sigmoid(z):retu
- Page 244 and 245: A picture is worth a thousand words
- Page 246 and 247: OutputOrderedDict([('linear.weight'
- Page 248 and 249: The first summation adds up the err
- Page 250 and 251: IMPORTANT: Make sure to pass the pr
- Page 252 and 253: To make it clear: In this chapter,
- Page 254 and 255: argument of nn.BCEWithLogitsLoss().
- Page 258 and 259: Figure 3.6 - Training and validatio
- Page 260 and 261: Outputarray([[0.5504593 ],[0.949995
- Page 262 and 263: decision boundary.Look at the expre
- Page 264 and 265: Are my data points separable?That
- Page 266 and 267: model = nn.Sequential()model.add_mo
- Page 268 and 269: It looks like this:Figure 3.10 - Sp
- Page 270 and 271: True and False Positives and Negati
- Page 272 and 273: tpr_fpr(cm_thresh50)Output(0.909090
- Page 274 and 275: The trade-off between precision and
- Page 276 and 277: Figure 3.13 - Using a low threshold
- Page 278 and 279: Figure 3.16 - Trade-offs for two di
- Page 280 and 281: thresholds do not necessarily inclu
- Page 282 and 283: actual data, it is as bad as it can
- Page 284 and 285: If you want to learn more about bot
- Page 286 and 287: Model Training1 n_epochs = 10023 sb
- Page 288 and 289: step in your journey! What’s next
- Page 290 and 291: Chapter 4Classifying ImagesSpoilers
- Page 292 and 293: Data GenerationOur images are quite
- Page 294 and 295: Images and ChannelsIn case you’re
- Page 296 and 297: image_rgb = np.stack([image_r, imag
- Page 298 and 299: That’s fairly straightforward; we
- Page 300 and 301: • Transformations based on Tensor
- Page 302 and 303: position of an object in a picture
- Page 304 and 305: Outputtensor([[[0., 0., 0., 1., 0.]
This is what the model configuration looks like for our classification problem:
Model Configuration
1 # Sets learning rate - this is "eta" ~ the "n"-like Greek letter
2 lr = 0.1
3
4 torch.manual_seed(42)
5 model = nn.Sequential()
6 model.add_module('linear', nn.Linear(2, 1))
7
8 # Defines an SGD optimizer to update the parameters
9 optimizer = optim.SGD(model.parameters(), lr=lr)
10
11 # Defines a BCE with logits loss function
12 loss_fn = nn.BCEWithLogitsLoss()
Model Training
Time to train our model! We can leverage the StepByStep class we built in Chapter
2.1 and use pretty much the same code as before:
Model Training
1 n_epochs = 100
2
3 sbs = StepByStep(model, loss_fn, optimizer)
4 sbs.set_loaders(train_loader, val_loader)
5 sbs.train(n_epochs)
fig = sbs.plot_losses()
232 | Chapter 3: A Simple Classification Problem