File size: 1,262 Bytes
f1c7739
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import torch
import torchvision

from torch import nn


def create_effnetv2_m_model(num_classes, seed: int = 42):
    """Creates an EfficientNetV2_M feature extractor model and transforms.

    Args:
        num_classes (int): Number of classes in the classifier head.
        seed (int, optional): Random seed value. Defaults to 42.

    Returns:
        model (torch.nn.Module): EffNetV2_M feature extractor model.
        transforms (torchvision.transforms): EffNetV2_M image transforms.
    """
    # 1. Use EfficientNet_V2_M pretrained weights and transforms
    weights = torchvision.models.EfficientNet_V2_M_Weights.DEFAULT
    transforms = weights.transforms()
    model = torchvision.models.efficientnet_v2_m(weights=weights)

    # 2. Freeze all layers in the base model
    for param in model.parameters():
        param.requires_grad = False

    # 3. Replace the classifier head, set the random seed for reproducibility
    torch.manual_seed(seed)
    num_features = model.classifier[
        1
    ].in_features  # Assuming the structure is similar; verify this
    model.classifier = nn.Sequential(
        nn.Dropout(p=0.3, inplace=True),
        nn.Linear(in_features=num_features, out_features=num_classes),
    )

    return model, transforms