-
Notifications
You must be signed in to change notification settings - Fork 4
/
utils.py
71 lines (60 loc) · 1.95 KB
/
utils.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
import numpy as np
import math
import torch
import random
import os
import logging
import time
class AverageMeter:
"""Compute running average."""
def __init__(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 clear(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def logger_configuration(config, save_log=False, test_mode=False):
# 配置 logger
logger = logging.getLogger("Deep joint source channel coder")
if test_mode:
config.workdir += '_test'
if save_log:
makedirs(config.workdir)
makedirs(config.samples)
makedirs(config.models)
formatter = logging.Formatter('%(asctime)s - %(levelname)s] %(message)s')
stdhandler = logging.StreamHandler()
stdhandler.setLevel(logging.INFO)
stdhandler.setFormatter(formatter)
logger.addHandler(stdhandler)
if save_log:
filehandler = logging.FileHandler(config.log)
filehandler.setLevel(logging.INFO)
filehandler.setFormatter(formatter)
logger.addHandler(filehandler)
logger.setLevel(logging.INFO)
config.logger = logger
return config.logger
def makedirs(directory):
if not os.path.exists(directory):
os.makedirs(directory)
def save_model(model, save_path):
torch.save(model.state_dict(), save_path)
def seed_torch(seed=1029):
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed) # 为了禁止hash随机化,使得实验可复现
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed) # if you are using multi-GPU.
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True