|
import torch |
|
import torchvision |
|
from torchvision import transforms |
|
import torch.nn as nn |
|
from torchvision.models import mobilenet_v2 |
|
|
|
|
|
|
|
|
|
def create_mobilenet_model(num_classes:int=4, |
|
seed:int=42): |
|
"""Creates an EfficientNetB2 feature extractor model and transforms. |
|
Args: |
|
num_classes (int, optional): number of classes in the classifier head. |
|
Defaults to 3. |
|
seed (int, optional): random seed value. Defaults to 42. |
|
Returns: |
|
model (torch.nn.Module): EffNetB2 feature extractor model. |
|
transforms (torchvision.transforms): EffNetB2 image transforms. |
|
""" |
|
|
|
|
|
transform = transforms.Compose([ |
|
transforms.Resize((224, 224)), |
|
transforms.ToTensor(), |
|
transforms.Normalize(mean=[0.485, 0.456, 0.406], |
|
std=[0.229, 0.224, 0.225]) |
|
]) |
|
model = mobilenet_v2(pretrained=True) |
|
|
|
|
|
|
|
for param in model.parameters(): |
|
param.requires_grad = False |
|
|
|
|
|
|
|
torch.manual_seed(42) |
|
|
|
|
|
model.classifier = nn.Sequential( |
|
nn.Dropout(p=0.2, inplace=True), |
|
nn.Linear(in_features=model.classifier[1].in_features, |
|
out_features=num_classes, |
|
bias=True) |
|
) |
|
|
|
return model, transform |
|
|
|
|