37 lines
825 B
Python
37 lines
825 B
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 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, fpath='checkpoint.pth.tar'):
|
|
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')) |