File size: 2,466 Bytes
9351b33 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | """Build the TinyVGG baseline and the EfficientNet-B0 transfer-learning model."""
from torch import nn
from torchvision import models
BASELINE_HIDDEN_UNITS = 32
class TinyVGG(nn.Module):
# Lecture 29 TinyVGG, adapted for 3-channel, 64 x 64 photos
def __init__(self, input_shape, hidden_units, output_shape):
super().__init__()
self.block_1 = nn.Sequential(
nn.Conv2d(input_shape, hidden_units, kernel_size=3, stride=1, padding=1),
nn.ReLU(),
nn.Conv2d(hidden_units, hidden_units, kernel_size=3, stride=1, padding=1),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2)
)
self.block_2 = nn.Sequential(
nn.Conv2d(hidden_units, hidden_units, kernel_size=3, padding=1),
nn.ReLU(),
nn.Conv2d(hidden_units, hidden_units, kernel_size=3, padding=1),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2)
)
self.classifier = nn.Sequential(
nn.Flatten(),
# Pooling changes 64 x 64 to 32 x 32, then 16 x 16.
nn.Linear(hidden_units * 16 * 16, output_shape)
)
def forward(self, x):
x = self.block_1(x)
x = self.block_2(x)
return self.classifier(x)
def create_tinyvgg(num_classes):
return TinyVGG(input_shape=3, hidden_units=BASELINE_HIDDEN_UNITS, output_shape=num_classes)
def create_efficientnet_b0(num_classes, pretrained=True):
# EfficientNet-B0 with frozen feature blocks and a new classifier head;
# pretrained=False skips the ImageNet download when trained weights are loaded afterward
# DEFAULT selects ImageNet-pretrained weights.
weights = models.EfficientNet_B0_Weights.DEFAULT if pretrained else None
model = models.efficientnet_b0(weights=weights)
for param in model.features.parameters():
param.requires_grad = False
model.classifier = nn.Sequential(
nn.Dropout(p=0.2, inplace=True),
nn.Linear(in_features=1280, out_features=num_classes)
)
return model
def unfreeze_last_blocks(model, num_blocks):
# Let the last feature blocks train along with the head
for param in model.features[-num_blocks:].parameters():
param.requires_grad = True
return model
def count_parameters(model, trainable_only=False):
return sum(
param.numel() for param in model.parameters()
if param.requires_grad or not trainable_only
)
|