text stringlengths 1 93.6k |
|---|
return tot
|
class Logger(object):
|
"""
|
Redirect stderr to stdout, optionally print stdout to a file,
|
and optionally force flushing on both stdout and the file.
|
"""
|
def __init__(self, file_name: str = None, file_mode: str = "w", should_flush: bool = True):
|
self.file = None
|
if file_name is not None:
|
self.file = open(file_name, file_mode)
|
self.should_flush = should_flush
|
self.stdout = sys.stdout
|
self.stderr = sys.stderr
|
sys.stdout = self
|
sys.stderr = self
|
def __enter__(self) -> "Logger":
|
return self
|
def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
|
self.close()
|
def write(self, text: str) -> None:
|
"""Write text to stdout (and a file) and optionally flush."""
|
if len(text) == 0: # workaround for a bug in VSCode debugger: sys.stdout.write(''); sys.stdout.flush() => crash
|
return
|
if self.file is not None:
|
self.file.write(text)
|
self.stdout.write(text)
|
if self.should_flush:
|
self.flush()
|
def flush(self) -> None:
|
"""Flush written text to both stdout and a file, if open."""
|
if self.file is not None:
|
self.file.flush()
|
self.stdout.flush()
|
def close(self) -> None:
|
"""Flush, close possible files, and remove stdout/stderr mirroring."""
|
self.flush()
|
# if using multiple loggers, prevent closing in wrong order
|
if sys.stdout is self:
|
sys.stdout = self.stdout
|
if sys.stderr is self:
|
sys.stderr = self.stderr
|
if self.file is not None:
|
self.file.close()
|
def dict2namespace(config):
|
namespace = argparse.Namespace()
|
for key, value in config.items():
|
if isinstance(value, dict):
|
new_value = dict2namespace(value)
|
else:
|
new_value = value
|
setattr(namespace, key, new_value)
|
return namespace
|
def str2bool(v):
|
if isinstance(v, bool):
|
return v
|
if v.lower() in ('yes', 'true', 't', 'y', '1'):
|
return True
|
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
|
return False
|
else:
|
raise argparse.ArgumentTypeError('Boolean value expected.')
|
def update_state_dict(state_dict, idx_start=9):
|
from collections import OrderedDict
|
new_state_dict = OrderedDict()
|
for k, v in state_dict.items():
|
name = k[idx_start:] # remove 'module.0.' of dataparallel
|
new_state_dict[name]=v
|
return new_state_dict
|
# ------------------------------------------------------------------------
|
def get_accuracy(model, x_orig, y_orig, bs=64, device=torch.device('cuda:0')):
|
n_batches = x_orig.shape[0] // bs
|
acc = 0.
|
for counter in range(n_batches):
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.