-
Notifications
You must be signed in to change notification settings - Fork 7
/
util.py
46 lines (35 loc) · 1022 Bytes
/
util.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Author: Yue Wang
@Contact: [email protected]
@File: util
@Time: 4/5/19 3:47 PM
"""
import torch
import torch.nn.functional as F
import numpy as np
def cal_loss(pred, label, smoothing=True):
"""
Calculate cross entropy loss, apply label smoothing if needed.
"""
label = label.contiguous().view(-1) # [Batch_size]
if smoothing:
eps = 0.2
n_class = pred.size(1)
one_hot = torch.zeros_like(pred).scatter(1, label.view(-1, 1), 1)
one_hot = one_hot * (1 - eps) + (1 - one_hot) * eps / (n_class - 1)
log_prb = F.log_softmax(pred, dim=1)
loss = -(one_hot * log_prb).sum(dim=1).mean()
else:
loss = F.cross_entropy(pred, label, reduction='mean')
return loss
class IOStream:
def __init__(self, path):
self.f = open(path, 'a')
def cprint(self, text):
print(text)
self.f.write(text + '\n')
self.f.flush()
def close(self):
self.f.close()