-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelper.py
143 lines (104 loc) · 3.37 KB
/
helper.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
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
import time
import numpy as np
from torch.cuda import amp
import torch
from tri_index import index_by_occurrence
from tqdm import tqdm
from torch.optim.lr_scheduler import (
CosineAnnealingWarmRestarts,
CosineAnnealingLR,
ReduceLROnPlateau,
)
import torch.nn as nn
# Helper functions
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def train_fn(
train_loader, model, CFG, criterion, optimizer, epoch, scheduler, device, scaler
):
losses = AverageMeter()
# switch to train mode
# model.train()
start_time = time.time()
model.train()
# for step, data in enumerate(train_loader):
for step, (images, labels) in enumerate(tqdm(train_loader, desc="Training")):
# Get the batch of images and labels
# images, labels = data
batch_size = labels.size(0)
# Start the optimizer
optimizer.zero_grad()
# Send the images and labels to gpu
images = images.to(device)
labels = labels.to(device)
# Apply mixed precision
with amp.autocast():
# Get the predictions
y_preds = model(images)
# Compute the loss on multitask or triplets only
if CFG.multi:
loss = criterion(y_preds, labels)
else:
loss = criterion(y_preds[:, :100], labels[:, :100])
# Update the loss
losses.update(loss.item(), batch_size)
# Backward pass
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
return losses.avg
def valid_fn(valid_loader, model, CFG, criterion, device):
losses = AverageMeter()
scores = AverageMeter()
# switch to evaluation mode
model.eval()
# Start a list to store the predictions
preds = []
# Loop over the dataloader
for step, data in enumerate(valid_loader):
# Get the images and labels
images, labels = data
batch_size = labels.size(0)
# Send images and labels to gpu
images = images.to(device)
labels = labels.to(device)
# Eval mode
with torch.no_grad():
# Run the model on the validation set
y_preds = model(images)
# Compute the validation loss on the triplets only
loss = criterion(y_preds[:, :100], labels[:, :100])
# Update the loss
losses.update(loss.item(), batch_size)
# Update predictions
preds.append(y_preds.to("cpu").numpy())
# Concat and predictions
predictions = np.concatenate(preds)
return losses.avg, predictions
def inference_fn(valid_loader, model, device):
losses = AverageMeter()
scores = AverageMeter()
# switch to evaluation mode
model.eval()
preds = []
for step, images in enumerate(valid_loader):
# measure data loading time
images = images.to(device)
# compute loss
with torch.no_grad():
y_preds = model(images)
preds.append(y_preds.sigmoid().to("cpu").numpy())
predictions = np.concatenate(preds)
return predictions