File size: 11,420 Bytes
2952455
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
"""Model.py: 
Defines the neural network architecture (the math layers, filters, and neurons). 
It expects images that are already resized before they are fed into it.

Model definitions for the Oxford-IIIT Pet breed classifier.

Two architectures are provided:

* ``PetBreedCNN``: a convolutional network trained from scratch.
* ``build_resnet18_classifier``: an ImageNet-pretrained ResNet18 with a new
  classification head, used as a transfer-learning baseline and as the
  deployed model.
"""

from __future__ import annotations

# region
## importing nn is essential, it is the parent class of PyTorch models that will be inherited from.
### It will provide the building blocks to adapt and modify the models so they outputs predictions for the 37 pet breeds.
## torchvision is used with resnet18 in this project. It gives access to pretrained weights trained on large benchmarks
### such as ImageNet-1k.
# endregion
import torch
from torch import nn
from torchvision import models

# region
## NUM_CLASSES: The Oxford-IIIT Pet dataset comprises exactly 37 distinct pet breeds: 25 dog breeds and 12 cat breeds.
## Any classification network must end with an output layer whose number of output features (out_features) 
### matches the total number of target classes.
# endregion
NUM_CLASSES = 37

###### TRAINING CUSTOM MODEL named the class PetBreedCNN #########

# region
## _conv_block() is a helper function for this file (hence the underscore in front)
## in_channels: is a number of incoming color channels or feature matching. For example RBG is 3 channels for color
## out_channels: number of filters (feature maps) layers in this block will learn and output. A feature map is a
### 'filter' that the PyTorch sets up. Filter 2 slides over RGB image to product a @d map showing where the vertical
### edges are. Filter 2 finds the diagonval edges, etc. The tensor shape is the same, but values change:
### input is batch, channel (rgb), hight, width: (32, 3, 224, 224). Block 1 changes to: (32, 32, 112, 112)
### Block 2 changes to: (32, 64, 56, 56), and so on. Something learned here is:
### # If you do this:
#### _conv_block(3, 16)
#### The next block MUST receive 16:
####_conv_block(16, 64)  # in_channels must match!
## nn.sequential: Retuns the annotation of the function which is a PyTorch container. Sequential is a Class in PyTorch. 
# endregion
def _conv_block(in_channels: int, out_channels: int) -> nn.Sequential:
    """Two 3x3 convolutions followed by 2x2 max pooling.

    Each convolution is followed by batch normalization and a ReLU. The pooling
    layer halves the spatial resolution, so the receptive field grows with depth
    while the channel count increases.
    """
    # region
    ## return Sequential: this is what PyTorch expects. It will store the values aka container
    ## NOTE this are hard to understand for now. Had to go with best practice. 
    # endregion
    return nn.Sequential(
        nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, bias=False),
        nn.BatchNorm2d(out_channels),
        nn.ReLU(inplace=True),
        nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1, bias=False),
        nn.BatchNorm2d(out_channels),
        nn.ReLU(inplace=True),
        nn.MaxPool2d(kernel_size=2),
    )

# region
## the PetBreedCNN class inherits from nn.Module and allows to process easily on NVIDA (.to("cuda"))
## Convolution: detects visual features (edges, shapes, textures). Image filters bundled together.
## Adaptive Pooling: Ensures that they picture ends up the exact target size. Needed because nn.Linear expects
### an exact number of input points. Adaptive pooling forces the size of the filters to 4x4 grid.
## Logit: Confidence Score given to each option, and the highest score is more likely. They get passed into a 
### formula to become a percentage.
## CrossEntropyLoss: Grades how wrong the model is. Tweaks happen to internal 'dials' over and over until the 
### penalty number becomes smaller.
# endregion
class PetBreedCNN(nn.Module):
    """Convolutional neural network for 37-way breed classification.
    Purpose: To aid the nn to 'see' the images.

    Architecture:
        4 convolutional blocks (32, 64, 128, 256 channels)
        -> adaptive average pooling to a fixed 4x4 grid
        -> Linear(4096, 512) + ReLU + Dropout
        -> Linear(512, num_classes)

    The adaptive pooling layer makes the classifier head independent of the
    input resolution. The model outputs unnormalized logits, which is the input
    format expected by ``nn.CrossEntropyLoss``.
    """

# region
## NUM_CLASSES: Sets the number of outputs in the final classification layer (37 pet breeds by default)
## dropout: half of the hidden neurons in the dense head will be randomly switched off each step to prevent overfitting.
## self.features = nn.Sequential: 3 is rgb; the 2nd parameter is the feature maps (starting with edges,contrasts). 
# Each block getss deeper to see more (ending with more details, such as ears, paws, etc.)
# endregion
    def __init__(self, num_classes: int = NUM_CLASSES, dropout: float = 0.5) -> None:
        super().__init__()
        self.features = nn.Sequential(
            _conv_block(3, 32),
            _conv_block(32, 64),
            _conv_block(64, 128),
            _conv_block(128, 256),
        )
        # region
        ## .pool = nn.AdaptiveAvgPool2d: squeezeds dimentions of feature maps into a 4x4 grid so they are the same
        ## .Flatten: flattens the tensor into a single 1D vector (256 x 4 x 4 = 4096 per image)
        ## Linear: Compresses the 4096 flattened features into 512 hidden nodes.
        ## ReLU: Rectified linear activation function. Required to run non-linear relationships
        ## Dropout: Randomly zeros out 50% of hidden values so that the neurons don't memorize the training images
        ## Linear: Final output layer that maps 512 featurs to the 37 scores (logits), one for each pet breed.
        ## WHy 512? Dropping from $4{,}096 \rightarrow 512 \rightarrow 37$ compresses the dimensions gradually, 
        ### giving the model an intermediate stage to distill 4,096 raw spatial patterns down into 512 high-level 
        ### concept indicators before making the final 37-breed 
        # endregion
        self.pool = nn.AdaptiveAvgPool2d((4, 4))
        self.classifier = nn.Sequential(
            nn.Flatten(),
            nn.Linear(256 * 4 * 4, 512),
            nn.ReLU(inplace=True),
            nn.Dropout(p=dropout),
            nn.Linear(512, num_classes),
        )
    # region
    ## The forward function will define the execution path for the data. nn.Module defines the layers, and forward
    ## defines the path 'forward'. 
    ## It will expect a 4D tensor of images with N=batch size; 3=RGB; H=Height; W=Width. 
    ## Will return a 2D tensor of (N, 37) --> 37 pet classifications
    ## self.features: Passes batch of images into the convolution feature extraction. Input=(N,3,224,224) Output=(N,256,14,14)
    ## self.pool: Passes the extracted feature maps through nn.AdaptiveAvePool2d((4,4)) Input=(N,256,14,14) Output=(N,256,4,4)
    ### Squeezes the diminensions down to 4x4 gride so the tensor size is always constant. 
    ## self.classifier: passes pooled feature maps and retruns final batch predictions. Returns (N,37)
    # endregion
    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """Map a batch of images (N, 3, H, W) to logits/scoring (N, num_classes)."""
        x = self.features(x)
        x = self.pool(x)
        return self.classifier(x)

######### Using a pretrained model called resnet18 for more acurrate results (trained on WAY more images) ############

# region
## function that will return a modified ResNet-18 model to add content from Oxford-IIIT Pet dataset
## num_classes: getting the data from the Oxford-IIIT dataset
## pretrained: bool = True: setting the initial flag for pretrained weights from ImageNet-iK or initialze random weights
### when True we use transfered learning, when false, overwrite weights by loading a fine-tuned file pet_breed_model.pth
## dropout: float = 0.3: sets dropout probability to 30% before the final classification decision. 
### Dropout probability is regularization technique where individual neurons  are randomly "dropped out"temporarily 
### turned off during training to prevent the network from memorizing the data (overfitting). Used 30% instead of 50% 
### like in the custom model because resnet18 is already pretrained.
## network = models.resnet18(weights=weights): If weights is provided, PyTorch automatically downloads the weights 
### trained on ImageNet's 1.28 million images 
### and loads them into all 18 layers
## nn.Linear(network.fc.in_features, num_classes): Maps the 512 visual features (resnet has 512, my previous has 37) 
### from an image features directly to the 37 raw class logits
## returns network: Returns the complete, adapted ResNet-18 model ready to receive image batches of shape (N, 3, H, W) 
### and output unnormalized logits of shape (N, 37).
# endregion
def build_resnet18_classifier(
    num_classes: int = NUM_CLASSES,
    pretrained: bool = True,
    dropout: float = 0.3,
) -> nn.Module:
    """Create a ResNet18 whose final layer is replaced for ``num_classes`` outputs.

    Args:
        num_classes: Number of output classes.
        pretrained: If True, initialize the backbone with ImageNet weights
            (requires a download on first use). Use False at inference time,
            because the fine-tuned weights are loaded from ``pet_breed_model.pth``.
        dropout: Dropout probability applied before the new linear layer.
    """
    weights = models.ResNet18_Weights.IMAGENET1K_V1 if pretrained else None
    network = models.resnet18(weights=weights)
    network.fc = nn.Sequential(
        nn.Dropout(p=dropout),
        nn.Linear(network.fc.in_features, num_classes),
    )
    return network

# region
## count_parameters function: Since I am using a custom model and pretrained model, this function
### inspects any model architecture and calculates the exact number of weights and biases inside it.
## network.parameters(): A built-in PyTorch generator provided by nn.Module. It iterates over every 
### single weight matrix and bias vector across every layer in the model.
### parameter.numel(): Short for "number of elements". If a convolutional weight tensor has a shape 
### of (32, 3, 3, 3), its numel() is 32 x 3 x 3 x 3 = 864 individual numbers. 
## sum: Adds up all the individual weight and bias numbers across the entire network
## If requires_grad=True, the optimizer updates this parameter. 
### If requires_grad=False, the parameter is frozen and will not change.
## returns both total and trainable into a dict for benchmarks. Total are all the values, while trainable are
### only trainable ones. in both models, everything is trainable. Technically the pretrained: bool = True is always True
### because there is nothing setting it differently at the moment.
# endregion
def count_parameters(network: nn.Module) -> dict[str, int]:
    """Return the total and trainable parameter counts of ``network``."""
    total = sum(parameter.numel() for parameter in network.parameters())
    trainable = sum(
        parameter.numel() for parameter in network.parameters() if parameter.requires_grad
    )
    return {"total": total, "trainable": trainable}