Daniel Voigt Godoy - Deep Learning with PyTorch Step-by-Step A Beginner’s Guide-leanpub

peiying410632
from peiying410632 More from this publisher
22.02.2024 Views

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

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

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!