Download model_builder.py from crashn/FloraFind: direct link, hf CLI and curl.
- Browser
- Download file 2.47 kB
-
https://huggingface.co/spaces/crashn/FloraFind/resolve/main/model_builder.py
- Command line
-
hf download hf://spaces/crashn/FloraFind/model_builder.py
-
curl -L -o model_builder.py https://huggingface.co/spaces/crashn/FloraFind/resolve/main/model_builder.py
2.47 kB
| """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 | |
| ) | |