-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.py
72 lines (57 loc) · 2.23 KB
/
model.py
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
import torch
import torch.nn as nn
from torchvision import models
# Device - GPU or CPU
device = ('cuda' if torch.cuda.is_available() else 'cpu')
# print(f"Computation device: {device}")
def get_model_params(model):
"""Get model parameters"""
total_params = sum(p.numel() for p in model.parameters())
print(f"Total parameters: {total_params:,}")
total_trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
print(f"Trainable parameters: {total_trainable_params:,}")
def build_model(pretrained=True, freeze=False, num_classes=196):
torch.manual_seed(42)
torch.cuda.manual_seed(42)
# Model Weights - Load Pretrained / Not Pretrained model
if pretrained:
weights = models.EfficientNet_B0_Weights.DEFAULT # .DEFAULT = best available weights
model = models.efficientnet_b0(weights=weights).to(device)
else:
model = models.efficientnet_b0(weights=None).to(device)
print("-"*50)
print("Original model parameters:")
get_model_params(model)
print("-"*50)
# Freeze the model
if freeze:
print("Freezing the base model")
for param in model.features.parameters():
param.requires_grad = False
elif not freeze:
print("Not freezing the base model")
for param in model.features.parameters():
param.requires_grad = True
print("\nAdding Classification Head . . .")
## Add the classification head
# Classficication Head 1
model.classifier[1] = nn.Linear(in_features=1280, out_features=num_classes).to(device)
# Classficication Head 2
model.classifier = torch.nn.Sequential(
torch.nn.Linear(in_features=1280, out_features=640, bias=True),
torch.nn.Dropout(p=0.2, inplace=True),
torch.nn.Linear(in_features=640, out_features=320, bias=True),
torch.nn.Dropout(p=0.2, inplace=True),
torch.nn.Linear(in_features=320, out_features=num_classes, bias=True)).to(device)
# Classficication Head 3
model.classifier = nn.Sequential(
nn.Linear(in_features=1280, out_features=640),
nn.Linear(in_features=640, out_features=320),
nn.Dropout(0.5),
nn.Linear(in_features=320, out_features=num_classes)).to(device)
# Print the model parameters
print("-"*50)
print("New model parameters:")
get_model_params(model)
print("-"*50)
return model