-
Notifications
You must be signed in to change notification settings - Fork 0
/
log_util.py
executable file
·53 lines (45 loc) · 1.7 KB
/
log_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
47
48
49
50
51
52
53
import os, sys, shutil, time, random
import argparse
import torch
import torch.backends.cudnn as cudnn
import torchvision.datasets as dset
import torchvision.transforms as transforms
from utils import AverageMeter, RecorderMeter, time_string, convert_secs2time, clustering_loss, change_quan_bitwidth
import models
import torch.nn.functional as F
import copy
import pandas as pd
import numpy as np
def print_log(print_string, log):
print("{}".format(print_string))
log.write("{}\n".format(print_string))
log.flush()
def accuracy(output, target, topk=(1, )):
"""Computes the precision@k for the specified values of k"""
with torch.no_grad():
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0)
res.append(correct_k.mul_(100.0 / batch_size))
return res
def accuracy_logger(base_dir, epoch, train_accuracy, test_accuracy):
file_name = 'accuracy.txt'
file_path = "%s/%s" % (base_dir, file_name)
# create and format the log file if it does not exists
if not os.path.exists(file_path):
create_log = open(file_path, 'w')
create_log.write('epochs train test\n')
create_log.close()
recorder = {}
recorder['epoch'] = epoch
recorder['train'] = train_accuracy
recorder['test'] = test_accuracy
# append the epoch index, train accuracy and test accuracy:
with open(file_path, 'a') as accuracy_log:
accuracy_log.write(
'{epoch} {train} {test}\n'.format(**recorder))