-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMobilenetV2.py
67 lines (54 loc) · 2.26 KB
/
MobilenetV2.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
from torch import nn,optim
import pytorch_lightning as pl
import timm
import torch
import torchmetrics
class MobileNetV2(pl.LightningModule):
def __init__(self, num_classes, lr):
super(MobileNetV2, self).__init__()
self.Lr = lr
self.validation_step_outputs = []
self.lossfn = nn.NLLLoss()
self.acc = torchmetrics.Accuracy(task="multiclass", num_classes=num_classes)
# Load the pretrained MobileNetV2 model
self.model = timm.create_model('mobilenetv2_100', pretrained=True)
# Freeze training for all layers
for param in self.model.parameters():
param.requires_grad = False
# Replace the classifier head with a new one
self.model.classifier = nn.Sequential(
nn.BatchNorm1d(self.model.classifier.in_features),
nn.Linear(self.model.classifier.in_features, 256),
nn.Dropout(0.2),
nn.ReLU(inplace=True),
nn.BatchNorm1d(256),
nn.Linear(256, num_classes),
nn.LogSoftmax(dim=1))
def forward(self, x):
out = self.model(x)
return out
def training_step(self,batch,batch_idx):
input, label = batch
output = self(input)
loss = self.lossfn(output,label)
return loss
def validation_step(self,batch,batch_idx):
input, label = batch
output = self(input)
loss = self.lossfn(output,label)
self.validation_step_outputs.append(loss)
self.log("val_loss", loss)
y_pred = torch.argmax(output,dim=1)
self.acc.update(y_pred, label)
def on_validation_epoch_end(self):
mean_val = torch.mean(torch.tensor(self.validation_step_outputs))
self.log('mean_val', mean_val)
self.validation_step_outputs.clear() # free memory
val_accuracy = self.acc.compute()
self.log("val_accuracy", val_accuracy)
# reset all metrics
self.acc.reset()
print(f"\nVal Accuracy: {val_accuracy:.4} "\
f"Val Loss: {mean_val:.4}")
def configure_optimizers(self):
return optim.AdamW(self.parameters(),lr=self.Lr)