45 lines
1.0 KiB
Python
45 lines
1.0 KiB
Python
|
from __future__ import absolute_import
|
||
|
|
||
|
import os
|
||
|
import os.path as osp
|
||
|
import errno
|
||
|
import json
|
||
|
import shutil
|
||
|
|
||
|
import torch
|
||
|
|
||
|
|
||
|
def mkdir_if_missing(directory):
|
||
|
if not osp.exists(directory):
|
||
|
try:
|
||
|
os.makedirs(directory)
|
||
|
except OSError as e:
|
||
|
if e.errno != errno.EEXIST:
|
||
|
raise
|
||
|
|
||
|
|
||
|
def check_isfile(path):
|
||
|
isfile = osp.isfile(path)
|
||
|
if not isfile:
|
||
|
print("=> Warning: no file found at '{}' (ignored)".format(path))
|
||
|
return isfile
|
||
|
|
||
|
|
||
|
def read_json(fpath):
|
||
|
with open(fpath, 'r') as f:
|
||
|
obj = json.load(f)
|
||
|
return obj
|
||
|
|
||
|
|
||
|
def write_json(obj, fpath):
|
||
|
mkdir_if_missing(osp.dirname(fpath))
|
||
|
with open(fpath, 'w') as f:
|
||
|
json.dump(obj, f, indent=4, separators=(',', ': '))
|
||
|
|
||
|
|
||
|
def save_checkpoint(state, is_best=False, fpath='checkpoint.pth.tar'):
|
||
|
if len(osp.dirname(fpath)) != 0:
|
||
|
mkdir_if_missing(osp.dirname(fpath))
|
||
|
torch.save(state, fpath)
|
||
|
if is_best:
|
||
|
shutil.copy(fpath, osp.join(osp.dirname(fpath), 'best_model.pth.tar'))
|