-
Notifications
You must be signed in to change notification settings - Fork 385
/
classification_learner.py
53 lines (39 loc) · 1.66 KB
/
classification_learner.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
import warnings
import logging
import torch.distributed as dist
from rastervision.pytorch_learner.learner import Learner
from rastervision.pytorch_learner.utils import (
compute_conf_mat_metrics, compute_conf_mat, aggregate_metrics)
from rastervision.pytorch_learner.dataset.visualizer import (
ClassificationVisualizer)
warnings.filterwarnings('ignore')
log = logging.getLogger(__name__)
class ClassificationLearner(Learner):
def get_visualizer_class(self):
return ClassificationVisualizer
def train_step(self, batch, batch_ind):
x, y = batch
out = self.post_forward(self.model(x))
return {'train_loss': self.loss(out, y)}
def validate_step(self, batch, batch_ind):
x, y = batch
out = self.post_forward(self.model(x))
val_loss = self.loss(out, y)
num_labels = len(self.cfg.data.class_names)
out = self.prob_to_pred(out)
conf_mat = compute_conf_mat(out, y, num_labels)
return {'val_loss': val_loss, 'conf_mat': conf_mat}
def validate_end(self, outputs):
metrics = aggregate_metrics(outputs, exclude_keys={'conf_mat'})
conf_mat = sum([o['conf_mat'] for o in outputs])
if self.is_ddp_process:
metrics = self.reduce_distributed_metrics(metrics)
dist.reduce(conf_mat, dst=0, op=dist.ReduceOp.SUM)
if not self.is_ddp_master:
return metrics
conf_mat_metrics = compute_conf_mat_metrics(conf_mat,
self.cfg.data.class_names)
metrics.update(conf_mat_metrics)
return metrics
def prob_to_pred(self, x):
return x.argmax(-1)