Daniel Voigt Godoy - Deep Learning with PyTorch Step-by-Step A Beginner’s Guide-leanpub
Data Preparation1 # ImageNet statistics2 normalizer = Normalize(mean=[0.485, 0.456, 0.406],3 std=[0.229, 0.224, 0.225])45 composer = Compose([Resize(256),6 CenterCrop(224),7 ToTensor(),8 normalizer])910 train_data = ImageFolder(root='rps', transform=composer)11 val_data = ImageFolder(root='rps-test-set', transform=composer)1213 # Builds a loader of each set14 train_loader = DataLoader(15 train_data, batch_size=16, shuffle=True16 )17 val_loader = DataLoader(val_data, batch_size=16)This time, we’ll use the smallest version of the ResNet model (resnet18) and eitherfine-tune it or use it as a feature extractor only.Fine-TuningModel Configuration (1)1 model = resnet18(pretrained=True)2 torch.manual_seed(42)3 model.fc = nn.Linear(512, 3)There is no freezing since fine-tuning entails the training of all the weights, not onlythose from the "top" layer.Model Configuration (2)1 multi_loss_fn = nn.CrossEntropyLoss(reduction='mean')2 optimizer_model = optim.Adam(model.parameters(), lr=3e-4)Putting It All Together | 555
Model Training1 sbs_transfer = StepByStep(model, multi_loss_fn, optimizer_model)2 sbs_transfer.set_loaders(train_loader, val_loader)3 sbs_transfer.train(1)Let’s see what the model can accomplish after training for a single epoch:EvaluationStepByStep.loader_apply(val_loader, sbs_transfer.correct)Outputtensor([[124, 124],[124, 124],[124, 124]])Perfect score!If we had frozen the layers in the model above, it would have been a case offeature extraction suitable for data augmentation since we would be training the"top" layer while it was still attached to the rest of the model.Feature ExtractionIn the model that follows, we’re modifying the model (replacing the "top" layerwith an identity layer) to generate a dataset of features first and then using it totrain the real "top" layer independently.Model Configuration (1)1 device = 'cuda' if torch.cuda.is_available() else 'cpu'2 model = resnet18(pretrained=True).to(device)3 model.fc = nn.Identity()4 freeze_model(model)556 | Chapter 7: Transfer Learning
- Page 530 and 531: Transfer Learning in PracticeIn Cha
- Page 532 and 533: dropout. You’re already familiar
- Page 534 and 535: OutputDownloading: "https://downloa
- Page 536 and 537: Replacing the "Top" of the Model1 a
- Page 538 and 539: Model Size Classifier Layer(s) Repl
- Page 540 and 541: Model TrainingWe have everything se
- Page 542 and 543: "Removing" the Top Layer1 alex.clas
- Page 544 and 545: torch.save(train_preproc.tensors, '
- Page 546 and 547: Outputtensor([[109, 124],[124, 124]
- Page 548 and 549: Model Configuration1 optimizer_mode
- Page 550 and 551: Figure 7.4 - 1x1 convolutionThe inp
- Page 552 and 553: The weights used by PIL are 0.299 f
- Page 554 and 555: • reduce the number of output cha
- Page 556 and 557: The constructor method defines the
- Page 558 and 559: Does it sound familiar? That’s wh
- Page 560 and 561: and w to represent these parameters
- Page 562 and 563: A mini-batch of size 64 is small en
- Page 564 and 565: normed1 = batch_normalizer(batch1[0
- Page 566 and 567: OutputOrderedDict([('running_mean',
- Page 568 and 569: OutputOrderedDict([('running_mean',
- Page 570 and 571: batch_normalizer = nn.BatchNorm2d(n
- Page 572 and 573: torch.manual_seed(23)dummy_points =
- Page 574 and 575: np.concatenate([dummy_points[:5].nu
- Page 576 and 577: Another advantage of these shortcut
- Page 578 and 579: It should be pretty clear, except f
- Page 582 and 583: Data Preparation — Preprocessing1
- Page 584 and 585: • freezing the layers of the mode
- Page 586 and 587: Extra ChapterVanishing and Explodin
- Page 588 and 589: discussing it, let me illustrate it
- Page 590 and 591: Model Configuration (2)1 loss_fn =
- Page 592 and 593: weights. If done properly, the init
- Page 594 and 595: just did), or, if you are training
- Page 596 and 597: Figure E.3 - The effect of batch no
- Page 598 and 599: Model Configuration1 torch.manual_s
- Page 600 and 601: torch.manual_seed(42)parm = nn.Para
- Page 602 and 603: (and only if) the norm exceeds the
- Page 604 and 605: if callable(self.clipping): 1self.c
- Page 606 and 607: Moreover, let’s use a ten times h
- Page 608 and 609: Clipping with HooksFirst, we reset
- Page 610 and 611: • visualizing the difference betw
- Page 612 and 613: Chapter 8SequencesSpoilersIn this c
- Page 614 and 615: Before shuffling, the pixels were o
- Page 616 and 617: And then let’s visualize the firs
- Page 618 and 619: sequence so far, and a data point f
- Page 620 and 621: Considering this, the not "unrolled
- Page 622 and 623: linear_input = nn.Linear(n_features
- Page 624 and 625: Outputtensor([[0.3924, 0.8146]], gr
- Page 626 and 627: Now we’re talking! The last hidde
- Page 628 and 629: Let’s take a look at the RNN’s
Model Training
1 sbs_transfer = StepByStep(model, multi_loss_fn, optimizer_model)
2 sbs_transfer.set_loaders(train_loader, val_loader)
3 sbs_transfer.train(1)
Let’s see what the model can accomplish after training for a single epoch:
Evaluation
StepByStep.loader_apply(val_loader, sbs_transfer.correct)
Output
tensor([[124, 124],
[124, 124],
[124, 124]])
Perfect score!
If we had frozen the layers in the model above, it would have been a case of
feature extraction suitable for data augmentation since we would be training the
"top" layer while it was still attached to the rest of the model.
Feature Extraction
In the model that follows, we’re modifying the model (replacing the "top" layer
with an identity layer) to generate a dataset of features first and then using it to
train the real "top" layer independently.
Model Configuration (1)
1 device = 'cuda' if torch.cuda.is_available() else 'cpu'
2 model = resnet18(pretrained=True).to(device)
3 model.fc = nn.Identity()
4 freeze_model(model)
556 | Chapter 7: Transfer Learning