partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
COCODetection.load
Args: add_gt: whether to add ground truth bounding box annotations to the dicts add_mask: whether to also add ground truth mask Returns: a list of dict, each has keys including: 'image_id', 'file_name', and (if add_gt is True) 'boxes', 'class'...
examples/FasterRCNN/dataset.py
def load(self, add_gt=True, add_mask=False): """ Args: add_gt: whether to add ground truth bounding box annotations to the dicts add_mask: whether to also add ground truth mask Returns: a list of dict, each has keys including: 'image_id', 'fil...
def load(self, add_gt=True, add_mask=False): """ Args: add_gt: whether to add ground truth bounding box annotations to the dicts add_mask: whether to also add ground truth mask Returns: a list of dict, each has keys including: 'image_id', 'fil...
[ "Args", ":", "add_gt", ":", "whether", "to", "add", "ground", "truth", "bounding", "box", "annotations", "to", "the", "dicts", "add_mask", ":", "whether", "to", "also", "add", "ground", "truth", "mask" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/dataset.py#L77-L102
[ "def", "load", "(", "self", ",", "add_gt", "=", "True", ",", "add_mask", "=", "False", ")", ":", "if", "add_mask", ":", "assert", "add_gt", "with", "timed_operation", "(", "'Load Groundtruth Boxes for {}'", ".", "format", "(", "self", ".", "name", ")", ")"...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
COCODetection._use_absolute_file_name
Change relative filename to abosolute file name.
examples/FasterRCNN/dataset.py
def _use_absolute_file_name(self, img): """ Change relative filename to abosolute file name. """ img['file_name'] = os.path.join( self._imgdir, img['file_name']) assert os.path.isfile(img['file_name']), img['file_name']
def _use_absolute_file_name(self, img): """ Change relative filename to abosolute file name. """ img['file_name'] = os.path.join( self._imgdir, img['file_name']) assert os.path.isfile(img['file_name']), img['file_name']
[ "Change", "relative", "filename", "to", "abosolute", "file", "name", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/dataset.py#L104-L110
[ "def", "_use_absolute_file_name", "(", "self", ",", "img", ")", ":", "img", "[", "'file_name'", "]", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_imgdir", ",", "img", "[", "'file_name'", "]", ")", "assert", "os", ".", "path", ".", "isfile...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
COCODetection._add_detection_gt
Add 'boxes', 'class', 'is_crowd' of this image to the dict, used by detection. If add_mask is True, also add 'segmentation' in coco poly format.
examples/FasterRCNN/dataset.py
def _add_detection_gt(self, img, add_mask): """ Add 'boxes', 'class', 'is_crowd' of this image to the dict, used by detection. If add_mask is True, also add 'segmentation' in coco poly format. """ # ann_ids = self.coco.getAnnIds(imgIds=img['image_id']) # objs = self.coco....
def _add_detection_gt(self, img, add_mask): """ Add 'boxes', 'class', 'is_crowd' of this image to the dict, used by detection. If add_mask is True, also add 'segmentation' in coco poly format. """ # ann_ids = self.coco.getAnnIds(imgIds=img['image_id']) # objs = self.coco....
[ "Add", "boxes", "class", "is_crowd", "of", "this", "image", "to", "the", "dict", "used", "by", "detection", ".", "If", "add_mask", "is", "True", "also", "add", "segmentation", "in", "coco", "poly", "format", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/dataset.py#L112-L170
[ "def", "_add_detection_gt", "(", "self", ",", "img", ",", "add_mask", ")", ":", "# ann_ids = self.coco.getAnnIds(imgIds=img['image_id'])", "# objs = self.coco.loadAnns(ann_ids)", "objs", "=", "self", ".", "coco", ".", "imgToAnns", "[", "img", "[", "'image_id'", "]", "...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
COCODetection.load_many
Load and merges several instance files together. Returns the same format as :meth:`COCODetection.load`.
examples/FasterRCNN/dataset.py
def load_many(basedir, names, add_gt=True, add_mask=False): """ Load and merges several instance files together. Returns the same format as :meth:`COCODetection.load`. """ if not isinstance(names, (list, tuple)): names = [names] ret = [] for n in name...
def load_many(basedir, names, add_gt=True, add_mask=False): """ Load and merges several instance files together. Returns the same format as :meth:`COCODetection.load`. """ if not isinstance(names, (list, tuple)): names = [names] ret = [] for n in name...
[ "Load", "and", "merges", "several", "instance", "files", "together", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/dataset.py#L173-L185
[ "def", "load_many", "(", "basedir", ",", "names", ",", "add_gt", "=", "True", ",", "add_mask", "=", "False", ")", ":", "if", "not", "isinstance", "(", "names", ",", "(", "list", ",", "tuple", ")", ")", ":", "names", "=", "[", "names", "]", "ret", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
DetectionDataset.load_training_roidbs
Args: names (list[str]): name of the training datasets, e.g. ['train2014', 'valminusminival2014'] Returns: roidbs (list[dict]): Produce "roidbs" as a list of dict, each dict corresponds to one image with k>=0 instances. and the following keys are expected for training:...
examples/FasterRCNN/dataset.py
def load_training_roidbs(self, names): """ Args: names (list[str]): name of the training datasets, e.g. ['train2014', 'valminusminival2014'] Returns: roidbs (list[dict]): Produce "roidbs" as a list of dict, each dict corresponds to one image with k>=0 instances...
def load_training_roidbs(self, names): """ Args: names (list[str]): name of the training datasets, e.g. ['train2014', 'valminusminival2014'] Returns: roidbs (list[dict]): Produce "roidbs" as a list of dict, each dict corresponds to one image with k>=0 instances...
[ "Args", ":", "names", "(", "list", "[", "str", "]", ")", ":", "name", "of", "the", "training", "datasets", "e", ".", "g", ".", "[", "train2014", "valminusminival2014", "]" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/dataset.py#L203-L229
[ "def", "load_training_roidbs", "(", "self", ",", "names", ")", ":", "return", "COCODetection", ".", "load_many", "(", "cfg", ".", "DATA", ".", "BASEDIR", ",", "names", ",", "add_gt", "=", "True", ",", "add_mask", "=", "cfg", ".", "MODE_MASK", ")" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
DetectionDataset.load_inference_roidbs
Args: name (str): name of one inference dataset, e.g. 'minival2014' Returns: roidbs (list[dict]): Each dict corresponds to one image to run inference on. The following keys in the dict are expected: file_name (str): full path to the image ...
examples/FasterRCNN/dataset.py
def load_inference_roidbs(self, name): """ Args: name (str): name of one inference dataset, e.g. 'minival2014' Returns: roidbs (list[dict]): Each dict corresponds to one image to run inference on. The following keys in the dict are expected: ...
def load_inference_roidbs(self, name): """ Args: name (str): name of one inference dataset, e.g. 'minival2014' Returns: roidbs (list[dict]): Each dict corresponds to one image to run inference on. The following keys in the dict are expected: ...
[ "Args", ":", "name", "(", "str", ")", ":", "name", "of", "one", "inference", "dataset", "e", ".", "g", ".", "minival2014" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/dataset.py#L231-L245
[ "def", "load_inference_roidbs", "(", "self", ",", "name", ")", ":", "return", "COCODetection", ".", "load_many", "(", "cfg", ".", "DATA", ".", "BASEDIR", ",", "name", ",", "add_gt", "=", "False", ")" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
DetectionDataset.eval_or_save_inference_results
Args: results (list[dict]): the inference results as dicts. Each dict corresponds to one __instance__. It contains the following keys: image_id (str): the id that matches `load_inference_roidbs`. category_id (int): the category prediction, in range [1, #categ...
examples/FasterRCNN/dataset.py
def eval_or_save_inference_results(self, results, dataset, output=None): """ Args: results (list[dict]): the inference results as dicts. Each dict corresponds to one __instance__. It contains the following keys: image_id (str): the id that matches `load_infer...
def eval_or_save_inference_results(self, results, dataset, output=None): """ Args: results (list[dict]): the inference results as dicts. Each dict corresponds to one __instance__. It contains the following keys: image_id (str): the id that matches `load_infer...
[ "Args", ":", "results", "(", "list", "[", "dict", "]", ")", ":", "the", "inference", "results", "as", "dicts", ".", "Each", "dict", "corresponds", "to", "one", "__instance__", ".", "It", "contains", "the", "following", "keys", ":" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/dataset.py#L247-L282
[ "def", "eval_or_save_inference_results", "(", "self", ",", "results", ",", "dataset", ",", "output", "=", "None", ")", ":", "continuous_id_to_COCO_id", "=", "{", "v", ":", "k", "for", "k", ",", "v", "in", "COCODetection", ".", "COCO_id_to_category_id", ".", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
timed_operation
Surround a context with a timer. Args: msg(str): the log to print. log_start(bool): whether to print also at the beginning. Example: .. code-block:: python with timed_operation('Good Stuff'): time.sleep(1) Will print: .. code-block:: pytho...
tensorpack/utils/timer.py
def timed_operation(msg, log_start=False): """ Surround a context with a timer. Args: msg(str): the log to print. log_start(bool): whether to print also at the beginning. Example: .. code-block:: python with timed_operation('Good Stuff'): time.sleep...
def timed_operation(msg, log_start=False): """ Surround a context with a timer. Args: msg(str): the log to print. log_start(bool): whether to print also at the beginning. Example: .. code-block:: python with timed_operation('Good Stuff'): time.sleep...
[ "Surround", "a", "context", "with", "a", "timer", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/timer.py#L23-L50
[ "def", "timed_operation", "(", "msg", ",", "log_start", "=", "False", ")", ":", "assert", "len", "(", "msg", ")", "if", "log_start", ":", "logger", ".", "info", "(", "'Start {} ...'", ".", "format", "(", "msg", ")", ")", "start", "=", "timer", "(", "...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
total_timer
A context which add the time spent inside to TotalTimer.
tensorpack/utils/timer.py
def total_timer(msg): """ A context which add the time spent inside to TotalTimer. """ start = timer() yield t = timer() - start _TOTAL_TIMER_DATA[msg].feed(t)
def total_timer(msg): """ A context which add the time spent inside to TotalTimer. """ start = timer() yield t = timer() - start _TOTAL_TIMER_DATA[msg].feed(t)
[ "A", "context", "which", "add", "the", "time", "spent", "inside", "to", "TotalTimer", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/timer.py#L57-L62
[ "def", "total_timer", "(", "msg", ")", ":", "start", "=", "timer", "(", ")", "yield", "t", "=", "timer", "(", ")", "-", "start", "_TOTAL_TIMER_DATA", "[", "msg", "]", ".", "feed", "(", "t", ")" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
print_total_timer
Print the content of the TotalTimer, if it's not empty. This function will automatically get called when program exits.
tensorpack/utils/timer.py
def print_total_timer(): """ Print the content of the TotalTimer, if it's not empty. This function will automatically get called when program exits. """ if len(_TOTAL_TIMER_DATA) == 0: return for k, v in six.iteritems(_TOTAL_TIMER_DATA): logger.info("Total Time: {} -> {:.2f} sec,...
def print_total_timer(): """ Print the content of the TotalTimer, if it's not empty. This function will automatically get called when program exits. """ if len(_TOTAL_TIMER_DATA) == 0: return for k, v in six.iteritems(_TOTAL_TIMER_DATA): logger.info("Total Time: {} -> {:.2f} sec,...
[ "Print", "the", "content", "of", "the", "TotalTimer", "if", "it", "s", "not", "empty", ".", "This", "function", "will", "automatically", "get", "called", "when", "program", "exits", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/timer.py#L65-L74
[ "def", "print_total_timer", "(", ")", ":", "if", "len", "(", "_TOTAL_TIMER_DATA", ")", "==", "0", ":", "return", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "_TOTAL_TIMER_DATA", ")", ":", "logger", ".", "info", "(", "\"Total Time: {} -> {:.2f...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
AugmentorList.reset_state
Will reset state of each augmentor
tensorpack/dataflow/imgaug/base.py
def reset_state(self): """ Will reset state of each augmentor """ super(AugmentorList, self).reset_state() for a in self.augmentors: a.reset_state()
def reset_state(self): """ Will reset state of each augmentor """ super(AugmentorList, self).reset_state() for a in self.augmentors: a.reset_state()
[ "Will", "reset", "state", "of", "each", "augmentor" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/imgaug/base.py#L224-L228
[ "def", "reset_state", "(", "self", ")", ":", "super", "(", "AugmentorList", ",", "self", ")", ".", "reset_state", "(", ")", "for", "a", "in", "self", ".", "augmentors", ":", "a", ".", "reset_state", "(", ")" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
ensure_proc_terminate
Make sure processes terminate when main process exit. Args: proc (multiprocessing.Process or list)
tensorpack/utils/concurrency.py
def ensure_proc_terminate(proc): """ Make sure processes terminate when main process exit. Args: proc (multiprocessing.Process or list) """ if isinstance(proc, list): for p in proc: ensure_proc_terminate(p) return def stop_proc_by_weak_ref(ref): proc...
def ensure_proc_terminate(proc): """ Make sure processes terminate when main process exit. Args: proc (multiprocessing.Process or list) """ if isinstance(proc, list): for p in proc: ensure_proc_terminate(p) return def stop_proc_by_weak_ref(ref): proc...
[ "Make", "sure", "processes", "terminate", "when", "main", "process", "exit", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/concurrency.py#L152-L174
[ "def", "ensure_proc_terminate", "(", "proc", ")", ":", "if", "isinstance", "(", "proc", ",", "list", ")", ":", "for", "p", "in", "proc", ":", "ensure_proc_terminate", "(", "p", ")", "return", "def", "stop_proc_by_weak_ref", "(", "ref", ")", ":", "proc", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
enable_death_signal
Set the "death signal" of the current process, so that the current process will be cleaned with guarantee in case the parent dies accidentally.
tensorpack/utils/concurrency.py
def enable_death_signal(_warn=True): """ Set the "death signal" of the current process, so that the current process will be cleaned with guarantee in case the parent dies accidentally. """ if platform.system() != 'Linux': return try: import prctl # pip install python-prctl...
def enable_death_signal(_warn=True): """ Set the "death signal" of the current process, so that the current process will be cleaned with guarantee in case the parent dies accidentally. """ if platform.system() != 'Linux': return try: import prctl # pip install python-prctl...
[ "Set", "the", "death", "signal", "of", "the", "current", "process", "so", "that", "the", "current", "process", "will", "be", "cleaned", "with", "guarantee", "in", "case", "the", "parent", "dies", "accidentally", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/concurrency.py#L177-L196
[ "def", "enable_death_signal", "(", "_warn", "=", "True", ")", ":", "if", "platform", ".", "system", "(", ")", "!=", "'Linux'", ":", "return", "try", ":", "import", "prctl", "# pip install python-prctl", "except", "ImportError", ":", "if", "_warn", ":", "log_...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
mask_sigint
Returns: If called in main thread, returns a context where ``SIGINT`` is ignored, and yield True. Otherwise yield False.
tensorpack/utils/concurrency.py
def mask_sigint(): """ Returns: If called in main thread, returns a context where ``SIGINT`` is ignored, and yield True. Otherwise yield False. """ if is_main_thread(): sigint_handler = signal.signal(signal.SIGINT, signal.SIG_IGN) yield True signal.signal(signal.S...
def mask_sigint(): """ Returns: If called in main thread, returns a context where ``SIGINT`` is ignored, and yield True. Otherwise yield False. """ if is_main_thread(): sigint_handler = signal.signal(signal.SIGINT, signal.SIG_IGN) yield True signal.signal(signal.S...
[ "Returns", ":", "If", "called", "in", "main", "thread", "returns", "a", "context", "where", "SIGINT", "is", "ignored", "and", "yield", "True", ".", "Otherwise", "yield", "False", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/concurrency.py#L208-L219
[ "def", "mask_sigint", "(", ")", ":", "if", "is_main_thread", "(", ")", ":", "sigint_handler", "=", "signal", ".", "signal", "(", "signal", ".", "SIGINT", ",", "signal", ".", "SIG_IGN", ")", "yield", "True", "signal", ".", "signal", "(", "signal", ".", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
start_proc_mask_signal
Start process(es) with SIGINT ignored. Args: proc: (mp.Process or list) Note: The signal mask is only applied when called from main thread.
tensorpack/utils/concurrency.py
def start_proc_mask_signal(proc): """ Start process(es) with SIGINT ignored. Args: proc: (mp.Process or list) Note: The signal mask is only applied when called from main thread. """ if not isinstance(proc, list): proc = [proc] with mask_sigint(): for p in p...
def start_proc_mask_signal(proc): """ Start process(es) with SIGINT ignored. Args: proc: (mp.Process or list) Note: The signal mask is only applied when called from main thread. """ if not isinstance(proc, list): proc = [proc] with mask_sigint(): for p in p...
[ "Start", "process", "(", "es", ")", "with", "SIGINT", "ignored", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/concurrency.py#L222-L244
[ "def", "start_proc_mask_signal", "(", "proc", ")", ":", "if", "not", "isinstance", "(", "proc", ",", "list", ")", ":", "proc", "=", "[", "proc", "]", "with", "mask_sigint", "(", ")", ":", "for", "p", "in", "proc", ":", "if", "isinstance", "(", "p", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
subproc_call
Execute a command with timeout, and return STDOUT and STDERR Args: cmd(str): the command to execute. timeout(float): timeout in seconds. Returns: output(bytes), retcode(int). If timeout, retcode is -1.
tensorpack/utils/concurrency.py
def subproc_call(cmd, timeout=None): """ Execute a command with timeout, and return STDOUT and STDERR Args: cmd(str): the command to execute. timeout(float): timeout in seconds. Returns: output(bytes), retcode(int). If timeout, retcode is -1. """ try: output = s...
def subproc_call(cmd, timeout=None): """ Execute a command with timeout, and return STDOUT and STDERR Args: cmd(str): the command to execute. timeout(float): timeout in seconds. Returns: output(bytes), retcode(int). If timeout, retcode is -1. """ try: output = s...
[ "Execute", "a", "command", "with", "timeout", "and", "return", "STDOUT", "and", "STDERR" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/concurrency.py#L247-L273
[ "def", "subproc_call", "(", "cmd", ",", "timeout", "=", "None", ")", ":", "try", ":", "output", "=", "subprocess", ".", "check_output", "(", "cmd", ",", "stderr", "=", "subprocess", ".", "STDOUT", ",", "shell", "=", "True", ",", "timeout", "=", "timeou...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
StoppableThread.queue_put_stoppable
Put obj to queue, but will give up when the thread is stopped
tensorpack/utils/concurrency.py
def queue_put_stoppable(self, q, obj): """ Put obj to queue, but will give up when the thread is stopped""" while not self.stopped(): try: q.put(obj, timeout=5) break except queue.Full: pass
def queue_put_stoppable(self, q, obj): """ Put obj to queue, but will give up when the thread is stopped""" while not self.stopped(): try: q.put(obj, timeout=5) break except queue.Full: pass
[ "Put", "obj", "to", "queue", "but", "will", "give", "up", "when", "the", "thread", "is", "stopped" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/concurrency.py#L59-L66
[ "def", "queue_put_stoppable", "(", "self", ",", "q", ",", "obj", ")", ":", "while", "not", "self", ".", "stopped", "(", ")", ":", "try", ":", "q", ".", "put", "(", "obj", ",", "timeout", "=", "5", ")", "break", "except", "queue", ".", "Full", ":"...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
StoppableThread.queue_get_stoppable
Take obj from queue, but will give up when the thread is stopped
tensorpack/utils/concurrency.py
def queue_get_stoppable(self, q): """ Take obj from queue, but will give up when the thread is stopped""" while not self.stopped(): try: return q.get(timeout=5) except queue.Empty: pass
def queue_get_stoppable(self, q): """ Take obj from queue, but will give up when the thread is stopped""" while not self.stopped(): try: return q.get(timeout=5) except queue.Empty: pass
[ "Take", "obj", "from", "queue", "but", "will", "give", "up", "when", "the", "thread", "is", "stopped" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/concurrency.py#L68-L74
[ "def", "queue_get_stoppable", "(", "self", ",", "q", ")", ":", "while", "not", "self", ".", "stopped", "(", ")", ":", "try", ":", "return", "q", ".", "get", "(", "timeout", "=", "5", ")", "except", "queue", ".", "Empty", ":", "pass" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
OrderedContainer.put
Args: rank(int): rank of th element. All elements must have different ranks. val: an object
tensorpack/utils/concurrency.py
def put(self, rank, val): """ Args: rank(int): rank of th element. All elements must have different ranks. val: an object """ idx = bisect.bisect(self.ranks, rank) self.ranks.insert(idx, rank) self.data.insert(idx, val)
def put(self, rank, val): """ Args: rank(int): rank of th element. All elements must have different ranks. val: an object """ idx = bisect.bisect(self.ranks, rank) self.ranks.insert(idx, rank) self.data.insert(idx, val)
[ "Args", ":", "rank", "(", "int", ")", ":", "rank", "of", "th", "element", ".", "All", "elements", "must", "have", "different", "ranks", ".", "val", ":", "an", "object" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/concurrency.py#L294-L302
[ "def", "put", "(", "self", ",", "rank", ",", "val", ")", ":", "idx", "=", "bisect", ".", "bisect", "(", "self", ".", "ranks", ",", "rank", ")", "self", ".", "ranks", ".", "insert", "(", "idx", ",", "rank", ")", "self", ".", "data", ".", "insert...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
visualize_conv_weights
Visualize use weights in convolution filters. Args: filters: tensor containing the weights [H,W,Cin,Cout] name: label for tensorboard Returns: image of all weight
examples/basics/mnist-visualizations.py
def visualize_conv_weights(filters, name): """Visualize use weights in convolution filters. Args: filters: tensor containing the weights [H,W,Cin,Cout] name: label for tensorboard Returns: image of all weight """ with tf.name_scope('visualize_w_' + name): filters = ...
def visualize_conv_weights(filters, name): """Visualize use weights in convolution filters. Args: filters: tensor containing the weights [H,W,Cin,Cout] name: label for tensorboard Returns: image of all weight """ with tf.name_scope('visualize_w_' + name): filters = ...
[ "Visualize", "use", "weights", "in", "convolution", "filters", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/basics/mnist-visualizations.py#L17-L36
[ "def", "visualize_conv_weights", "(", "filters", ",", "name", ")", ":", "with", "tf", ".", "name_scope", "(", "'visualize_w_'", "+", "name", ")", ":", "filters", "=", "tf", ".", "transpose", "(", "filters", ",", "(", "3", ",", "2", ",", "0", ",", "1"...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
visualize_conv_activations
Visualize activations for convolution layers. Remarks: This tries to place all activations into a square. Args: activation: tensor with the activation [B,H,W,C] name: label for tensorboard Returns: image of almost all activations
examples/basics/mnist-visualizations.py
def visualize_conv_activations(activation, name): """Visualize activations for convolution layers. Remarks: This tries to place all activations into a square. Args: activation: tensor with the activation [B,H,W,C] name: label for tensorboard Returns: image of almost al...
def visualize_conv_activations(activation, name): """Visualize activations for convolution layers. Remarks: This tries to place all activations into a square. Args: activation: tensor with the activation [B,H,W,C] name: label for tensorboard Returns: image of almost al...
[ "Visualize", "activations", "for", "convolution", "layers", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/basics/mnist-visualizations.py#L39-L64
[ "def", "visualize_conv_activations", "(", "activation", ",", "name", ")", ":", "import", "math", "with", "tf", ".", "name_scope", "(", "'visualize_act_'", "+", "name", ")", ":", "_", ",", "h", ",", "w", ",", "c", "=", "activation", ".", "get_shape", "(",...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
shapeless_placeholder
Make the static shape of a tensor less specific. If you want to feed to a tensor, the shape of the feed value must match the tensor's static shape. This function creates a placeholder which defaults to x if not fed, but has a less specific static shape than x. See also `tensorflow#5680 <https://github....
examples/GAN/InfoGAN-mnist.py
def shapeless_placeholder(x, axis, name): """ Make the static shape of a tensor less specific. If you want to feed to a tensor, the shape of the feed value must match the tensor's static shape. This function creates a placeholder which defaults to x if not fed, but has a less specific static shape ...
def shapeless_placeholder(x, axis, name): """ Make the static shape of a tensor less specific. If you want to feed to a tensor, the shape of the feed value must match the tensor's static shape. This function creates a placeholder which defaults to x if not fed, but has a less specific static shape ...
[ "Make", "the", "static", "shape", "of", "a", "tensor", "less", "specific", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/InfoGAN-mnist.py#L40-L66
[ "def", "shapeless_placeholder", "(", "x", ",", "axis", ",", "name", ")", ":", "shp", "=", "x", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "if", "not", "isinstance", "(", "axis", ",", "list", ")", ":", "axis", "=", "[", "axis", "]", "fo...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
entropy_from_samples
Estimate H(x|s) ~= -E_{x \sim P(x|s)}[\log Q(x|s)], where x are samples, and Q is parameterized by vec.
examples/GAN/InfoGAN-mnist.py
def entropy_from_samples(samples, vec): """ Estimate H(x|s) ~= -E_{x \sim P(x|s)}[\log Q(x|s)], where x are samples, and Q is parameterized by vec. """ samples_cat = tf.argmax(samples[:, :NUM_CLASS], axis=1, output_type=tf.int32) samples_uniform = samples[:, NUM_CLASS:] cat, uniform = get_distri...
def entropy_from_samples(samples, vec): """ Estimate H(x|s) ~= -E_{x \sim P(x|s)}[\log Q(x|s)], where x are samples, and Q is parameterized by vec. """ samples_cat = tf.argmax(samples[:, :NUM_CLASS], axis=1, output_type=tf.int32) samples_uniform = samples[:, NUM_CLASS:] cat, uniform = get_distri...
[ "Estimate", "H", "(", "x|s", ")", "~", "=", "-", "E_", "{", "x", "\\", "sim", "P", "(", "x|s", ")", "}", "[", "\\", "log", "Q", "(", "x|s", ")", "]", "where", "x", "are", "samples", "and", "Q", "is", "parameterized", "by", "vec", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/InfoGAN-mnist.py#L75-L90
[ "def", "entropy_from_samples", "(", "samples", ",", "vec", ")", ":", "samples_cat", "=", "tf", ".", "argmax", "(", "samples", "[", ":", ",", ":", "NUM_CLASS", "]", ",", "axis", "=", "1", ",", "output_type", "=", "tf", ".", "int32", ")", "samples_unifor...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
sample_prior
OpenAI official code actually models the "uniform" latent code as a Gaussian distribution, but obtain the samples from a uniform distribution.
examples/GAN/InfoGAN-mnist.py
def sample_prior(batch_size): cat, _ = get_distributions(DIST_PRIOR_PARAM[:NUM_CLASS], DIST_PRIOR_PARAM[NUM_CLASS:]) sample_cat = tf.one_hot(cat.sample(batch_size), NUM_CLASS) """ OpenAI official code actually models the "uniform" latent code as a Gaussian distribution, but obtain the samples from ...
def sample_prior(batch_size): cat, _ = get_distributions(DIST_PRIOR_PARAM[:NUM_CLASS], DIST_PRIOR_PARAM[NUM_CLASS:]) sample_cat = tf.one_hot(cat.sample(batch_size), NUM_CLASS) """ OpenAI official code actually models the "uniform" latent code as a Gaussian distribution, but obtain the samples from ...
[ "OpenAI", "official", "code", "actually", "models", "the", "uniform", "latent", "code", "as", "a", "Gaussian", "distribution", "but", "obtain", "the", "samples", "from", "a", "uniform", "distribution", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/InfoGAN-mnist.py#L94-L104
[ "def", "sample_prior", "(", "batch_size", ")", ":", "cat", ",", "_", "=", "get_distributions", "(", "DIST_PRIOR_PARAM", "[", ":", "NUM_CLASS", "]", ",", "DIST_PRIOR_PARAM", "[", "NUM_CLASS", ":", "]", ")", "sample_cat", "=", "tf", ".", "one_hot", "(", "cat...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
Model.build_graph
Mutual information between x (i.e. zc in this case) and some information s (the generated samples in this case): I(x;s) = H(x) - H(x|s) = H(x) + E[\log P(x|s)] The distribution from which zc is sampled, in this case, is set to a fixed prior already. ...
examples/GAN/InfoGAN-mnist.py
def build_graph(self, real_sample): real_sample = tf.expand_dims(real_sample, -1) # sample the latent code: zc = shapeless_placeholder(sample_prior(BATCH), 0, name='z_code') z_noise = shapeless_placeholder( tf.random_uniform([BATCH, NOISE_DIM], -1, 1), 0, name='z_noise') ...
def build_graph(self, real_sample): real_sample = tf.expand_dims(real_sample, -1) # sample the latent code: zc = shapeless_placeholder(sample_prior(BATCH), 0, name='z_code') z_noise = shapeless_placeholder( tf.random_uniform([BATCH, NOISE_DIM], -1, 1), 0, name='z_noise') ...
[ "Mutual", "information", "between", "x", "(", "i", ".", "e", ".", "zc", "in", "this", "case", ")", "and", "some", "information", "s", "(", "the", "generated", "samples", "in", "this", "case", ")", ":" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/InfoGAN-mnist.py#L141-L202
[ "def", "build_graph", "(", "self", ",", "real_sample", ")", ":", "real_sample", "=", "tf", ".", "expand_dims", "(", "real_sample", ",", "-", "1", ")", "# sample the latent code:", "zc", "=", "shapeless_placeholder", "(", "sample_prior", "(", "BATCH", ")", ",",...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
DynamicConvFilter
see "Dynamic Filter Networks" (NIPS 2016) by Bert De Brabandere*, Xu Jia*, Tinne Tuytelaars and Luc Van Gool Remarks: This is the convolution version of a dynamic filter. Args: inputs : unfiltered input [b, h, w, 1] only grayscale images. filters : learned filters of [b, k, k, ...
examples/DynamicFilterNetwork/steering-filter.py
def DynamicConvFilter(inputs, filters, out_channel, kernel_shape, stride=1, padding='SAME'): """ see "Dynamic Filter Networks" (NIPS 2016) by Bert De Brabandere*, Xu Jia*, Tinne Tuytelaars and Luc Van Gool Remarks: This is the co...
def DynamicConvFilter(inputs, filters, out_channel, kernel_shape, stride=1, padding='SAME'): """ see "Dynamic Filter Networks" (NIPS 2016) by Bert De Brabandere*, Xu Jia*, Tinne Tuytelaars and Luc Van Gool Remarks: This is the co...
[ "see", "Dynamic", "Filter", "Networks", "(", "NIPS", "2016", ")", "by", "Bert", "De", "Brabandere", "*", "Xu", "Jia", "*", "Tinne", "Tuytelaars", "and", "Luc", "Van", "Gool" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DynamicFilterNetwork/steering-filter.py#L24-L59
[ "def", "DynamicConvFilter", "(", "inputs", ",", "filters", ",", "out_channel", ",", "kernel_shape", ",", "stride", "=", "1", ",", "padding", "=", "'SAME'", ")", ":", "# tf.unstack only works with known batch_size :-(", "batch_size", ",", "h", ",", "w", ",", "in_...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
Model._parameter_net
Estimate filters for convolution layers Args: theta: angle of filter kernel_shape: size of each filter Returns: learned filter as [B, k, k, 1]
examples/DynamicFilterNetwork/steering-filter.py
def _parameter_net(self, theta, kernel_shape=9): """Estimate filters for convolution layers Args: theta: angle of filter kernel_shape: size of each filter Returns: learned filter as [B, k, k, 1] """ with argscope(FullyConnected, nl=tf.nn.leak...
def _parameter_net(self, theta, kernel_shape=9): """Estimate filters for convolution layers Args: theta: angle of filter kernel_shape: size of each filter Returns: learned filter as [B, k, k, 1] """ with argscope(FullyConnected, nl=tf.nn.leak...
[ "Estimate", "filters", "for", "convolution", "layers" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DynamicFilterNetwork/steering-filter.py#L103-L120
[ "def", "_parameter_net", "(", "self", ",", "theta", ",", "kernel_shape", "=", "9", ")", ":", "with", "argscope", "(", "FullyConnected", ",", "nl", "=", "tf", ".", "nn", ".", "leaky_relu", ")", ":", "net", "=", "FullyConnected", "(", "'fc1'", ",", "thet...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
ThetaImages.filter_with_theta
Implements a steerable Gaussian filter. This function can be used to evaluate the first directional derivative of an image, using the method outlined in W. T. Freeman and E. H. Adelson, "The Design and Use of Steerable Filters", IEEE PAMI, 1991. It evaluates th...
examples/DynamicFilterNetwork/steering-filter.py
def filter_with_theta(image, theta, sigma=1., filter_size=9): """Implements a steerable Gaussian filter. This function can be used to evaluate the first directional derivative of an image, using the method outlined in W. T. Freeman and E. H. Adelson, "The Design ...
def filter_with_theta(image, theta, sigma=1., filter_size=9): """Implements a steerable Gaussian filter. This function can be used to evaluate the first directional derivative of an image, using the method outlined in W. T. Freeman and E. H. Adelson, "The Design ...
[ "Implements", "a", "steerable", "Gaussian", "filter", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DynamicFilterNetwork/steering-filter.py#L162-L204
[ "def", "filter_with_theta", "(", "image", ",", "theta", ",", "sigma", "=", "1.", ",", "filter_size", "=", "9", ")", ":", "x", "=", "np", ".", "arange", "(", "-", "filter_size", "//", "2", "+", "1", ",", "filter_size", "//", "2", "+", "1", ")", "#...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
GANModelDesc.collect_variables
Assign `self.g_vars` to the parameters under scope `g_scope`, and same with `self.d_vars`.
examples/GAN/GAN.py
def collect_variables(self, g_scope='gen', d_scope='discrim'): """ Assign `self.g_vars` to the parameters under scope `g_scope`, and same with `self.d_vars`. """ self.g_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, g_scope) assert self.g_vars self.d_v...
def collect_variables(self, g_scope='gen', d_scope='discrim'): """ Assign `self.g_vars` to the parameters under scope `g_scope`, and same with `self.d_vars`. """ self.g_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, g_scope) assert self.g_vars self.d_v...
[ "Assign", "self", ".", "g_vars", "to", "the", "parameters", "under", "scope", "g_scope", "and", "same", "with", "self", ".", "d_vars", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/GAN.py#L17-L25
[ "def", "collect_variables", "(", "self", ",", "g_scope", "=", "'gen'", ",", "d_scope", "=", "'discrim'", ")", ":", "self", ".", "g_vars", "=", "tf", ".", "get_collection", "(", "tf", ".", "GraphKeys", ".", "TRAINABLE_VARIABLES", ",", "g_scope", ")", "asser...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
GANModelDesc.build_losses
Build standard GAN loss and set `self.g_loss` and `self.d_loss`. D and G play two-player minimax game with value function V(G,D) min_G max _D V(D, G) = IE_{x ~ p_data} [log D(x)] + IE_{z ~ p_fake} [log (1 - D(G(z)))] Args: logits_real (tf.Tensor): discrim logits from real sample...
examples/GAN/GAN.py
def build_losses(self, logits_real, logits_fake): """ Build standard GAN loss and set `self.g_loss` and `self.d_loss`. D and G play two-player minimax game with value function V(G,D) min_G max _D V(D, G) = IE_{x ~ p_data} [log D(x)] + IE_{z ~ p_fake} [log (1 - D(G(z)))] Args...
def build_losses(self, logits_real, logits_fake): """ Build standard GAN loss and set `self.g_loss` and `self.d_loss`. D and G play two-player minimax game with value function V(G,D) min_G max _D V(D, G) = IE_{x ~ p_data} [log D(x)] + IE_{z ~ p_fake} [log (1 - D(G(z)))] Args...
[ "Build", "standard", "GAN", "loss", "and", "set", "self", ".", "g_loss", "and", "self", ".", "d_loss", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/GAN.py#L27-L62
[ "def", "build_losses", "(", "self", ",", "logits_real", ",", "logits_fake", ")", ":", "with", "tf", ".", "name_scope", "(", "\"GAN_loss\"", ")", ":", "score_real", "=", "tf", ".", "sigmoid", "(", "logits_real", ")", "score_fake", "=", "tf", ".", "sigmoid",...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
GANTrainer._build_gan_trainer
We need to set tower_func because it's a TowerTrainer, and only TowerTrainer supports automatic graph creation for inference during training. If we don't care about inference during training, using tower_func is not needed. Just calling model.build_graph directly is OK.
examples/GAN/GAN.py
def _build_gan_trainer(self, input, model): """ We need to set tower_func because it's a TowerTrainer, and only TowerTrainer supports automatic graph creation for inference during training. If we don't care about inference during training, using tower_func is not needed. Just ca...
def _build_gan_trainer(self, input, model): """ We need to set tower_func because it's a TowerTrainer, and only TowerTrainer supports automatic graph creation for inference during training. If we don't care about inference during training, using tower_func is not needed. Just ca...
[ "We", "need", "to", "set", "tower_func", "because", "it", "s", "a", "TowerTrainer", "and", "only", "TowerTrainer", "supports", "automatic", "graph", "creation", "for", "inference", "during", "training", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/GAN.py#L99-L119
[ "def", "_build_gan_trainer", "(", "self", ",", "input", ",", "model", ")", ":", "# Build the graph", "self", ".", "tower_func", "=", "TowerFuncWrapper", "(", "model", ".", "build_graph", ",", "model", ".", "get_input_signature", "(", ")", ")", "with", "TowerCo...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
convert_to_tflayer_args
After applying this decorator: 1. data_format becomes tf.layers style 2. nl becomes activation 3. initializers are renamed 4. positional args are transformed to corresponding kwargs, according to args_names 5. kwargs are mapped to tf.layers names if needed, by name_mapping
tensorpack/models/tflayer.py
def convert_to_tflayer_args(args_names, name_mapping): """ After applying this decorator: 1. data_format becomes tf.layers style 2. nl becomes activation 3. initializers are renamed 4. positional args are transformed to corresponding kwargs, according to args_names 5. kwargs are mapped to tf...
def convert_to_tflayer_args(args_names, name_mapping): """ After applying this decorator: 1. data_format becomes tf.layers style 2. nl becomes activation 3. initializers are renamed 4. positional args are transformed to corresponding kwargs, according to args_names 5. kwargs are mapped to tf...
[ "After", "applying", "this", "decorator", ":", "1", ".", "data_format", "becomes", "tf", ".", "layers", "style", "2", ".", "nl", "becomes", "activation", "3", ".", "initializers", "are", "renamed", "4", ".", "positional", "args", "are", "transformed", "to", ...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/tflayer.py#L33-L70
[ "def", "convert_to_tflayer_args", "(", "args_names", ",", "name_mapping", ")", ":", "def", "decorator", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "decorated_func", "(", "inputs", ",", "*", "args", ",", "*", "*", "kwa...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
rename_get_variable
Args: mapping(dict): an old -> new mapping for variable basename. e.g. {'kernel': 'W'} Returns: A context where the variables are renamed.
tensorpack/models/tflayer.py
def rename_get_variable(mapping): """ Args: mapping(dict): an old -> new mapping for variable basename. e.g. {'kernel': 'W'} Returns: A context where the variables are renamed. """ def custom_getter(getter, name, *args, **kwargs): splits = name.split('/') basename = ...
def rename_get_variable(mapping): """ Args: mapping(dict): an old -> new mapping for variable basename. e.g. {'kernel': 'W'} Returns: A context where the variables are renamed. """ def custom_getter(getter, name, *args, **kwargs): splits = name.split('/') basename = ...
[ "Args", ":", "mapping", "(", "dict", ")", ":", "an", "old", "-", ">", "new", "mapping", "for", "variable", "basename", ".", "e", ".", "g", ".", "{", "kernel", ":", "W", "}" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/tflayer.py#L73-L89
[ "def", "rename_get_variable", "(", "mapping", ")", ":", "def", "custom_getter", "(", "getter", ",", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "splits", "=", "name", ".", "split", "(", "'/'", ")", "basename", "=", "splits", "[", "-"...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
regularize_cost
Apply a regularizer on trainable variables matching the regex, and print the matched variables (only print once in multi-tower training). In replicated mode, it will only regularize variables within the current tower. If called under a TowerContext with `is_training==False`, this function returns a zero co...
tensorpack/models/regularize.py
def regularize_cost(regex, func, name='regularize_cost'): """ Apply a regularizer on trainable variables matching the regex, and print the matched variables (only print once in multi-tower training). In replicated mode, it will only regularize variables within the current tower. If called under a T...
def regularize_cost(regex, func, name='regularize_cost'): """ Apply a regularizer on trainable variables matching the regex, and print the matched variables (only print once in multi-tower training). In replicated mode, it will only regularize variables within the current tower. If called under a T...
[ "Apply", "a", "regularizer", "on", "trainable", "variables", "matching", "the", "regex", "and", "print", "the", "matched", "variables", "(", "only", "print", "once", "in", "multi", "-", "tower", "training", ")", ".", "In", "replicated", "mode", "it", "will",...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/regularize.py#L33-L100
[ "def", "regularize_cost", "(", "regex", ",", "func", ",", "name", "=", "'regularize_cost'", ")", ":", "assert", "len", "(", "regex", ")", "ctx", "=", "get_current_tower_context", "(", ")", "if", "not", "ctx", ".", "is_training", ":", "# Currently cannot build ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
regularize_cost_from_collection
Get the cost from the regularizers in ``tf.GraphKeys.REGULARIZATION_LOSSES``. If in replicated mode, will only regularize variables created within the current tower. Args: name (str): the name of the returned tensor Returns: tf.Tensor: a scalar, the total regularization cost.
tensorpack/models/regularize.py
def regularize_cost_from_collection(name='regularize_cost'): """ Get the cost from the regularizers in ``tf.GraphKeys.REGULARIZATION_LOSSES``. If in replicated mode, will only regularize variables created within the current tower. Args: name (str): the name of the returned tensor Returns: ...
def regularize_cost_from_collection(name='regularize_cost'): """ Get the cost from the regularizers in ``tf.GraphKeys.REGULARIZATION_LOSSES``. If in replicated mode, will only regularize variables created within the current tower. Args: name (str): the name of the returned tensor Returns: ...
[ "Get", "the", "cost", "from", "the", "regularizers", "in", "tf", ".", "GraphKeys", ".", "REGULARIZATION_LOSSES", ".", "If", "in", "replicated", "mode", "will", "only", "regularize", "variables", "created", "within", "the", "current", "tower", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/regularize.py#L103-L141
[ "def", "regularize_cost_from_collection", "(", "name", "=", "'regularize_cost'", ")", ":", "ctx", "=", "get_current_tower_context", "(", ")", "if", "not", "ctx", ".", "is_training", ":", "# TODO Currently cannot build the wd_cost correctly at inference,", "# because ths vs_na...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
Dropout
Same as `tf.layers.dropout`. However, for historical reasons, the first positional argument is interpreted as keep_prob rather than drop_prob. Explicitly use `rate=` keyword arguments to ensure things are consistent.
tensorpack/models/regularize.py
def Dropout(x, *args, **kwargs): """ Same as `tf.layers.dropout`. However, for historical reasons, the first positional argument is interpreted as keep_prob rather than drop_prob. Explicitly use `rate=` keyword arguments to ensure things are consistent. """ if 'is_training' in kwargs: ...
def Dropout(x, *args, **kwargs): """ Same as `tf.layers.dropout`. However, for historical reasons, the first positional argument is interpreted as keep_prob rather than drop_prob. Explicitly use `rate=` keyword arguments to ensure things are consistent. """ if 'is_training' in kwargs: ...
[ "Same", "as", "tf", ".", "layers", ".", "dropout", ".", "However", "for", "historical", "reasons", "the", "first", "positional", "argument", "is", "interpreted", "as", "keep_prob", "rather", "than", "drop_prob", ".", "Explicitly", "use", "rate", "=", "keyword"...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/regularize.py#L145-L175
[ "def", "Dropout", "(", "x", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "'is_training'", "in", "kwargs", ":", "kwargs", "[", "'training'", "]", "=", "kwargs", ".", "pop", "(", "'is_training'", ")", "if", "len", "(", "args", ")", ">",...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
BackgroundFiller.fill
Return a proper background image of background_shape, given img. Args: background_shape (tuple): a shape (h, w) img: an image Returns: a background image
tensorpack/dataflow/imgaug/paste.py
def fill(self, background_shape, img): """ Return a proper background image of background_shape, given img. Args: background_shape (tuple): a shape (h, w) img: an image Returns: a background image """ background_shape = tuple(backgroun...
def fill(self, background_shape, img): """ Return a proper background image of background_shape, given img. Args: background_shape (tuple): a shape (h, w) img: an image Returns: a background image """ background_shape = tuple(backgroun...
[ "Return", "a", "proper", "background", "image", "of", "background_shape", "given", "img", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/imgaug/paste.py#L17-L28
[ "def", "fill", "(", "self", ",", "background_shape", ",", "img", ")", ":", "background_shape", "=", "tuple", "(", "background_shape", ")", "return", "self", ".", "_fill", "(", "background_shape", ",", "img", ")" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
LinearWrap.apply
Apply a function on the wrapped tensor. Returns: LinearWrap: ``LinearWrap(func(self.tensor(), *args, **kwargs))``.
tensorpack/models/linearwrap.py
def apply(self, func, *args, **kwargs): """ Apply a function on the wrapped tensor. Returns: LinearWrap: ``LinearWrap(func(self.tensor(), *args, **kwargs))``. """ ret = func(self._t, *args, **kwargs) return LinearWrap(ret)
def apply(self, func, *args, **kwargs): """ Apply a function on the wrapped tensor. Returns: LinearWrap: ``LinearWrap(func(self.tensor(), *args, **kwargs))``. """ ret = func(self._t, *args, **kwargs) return LinearWrap(ret)
[ "Apply", "a", "function", "on", "the", "wrapped", "tensor", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/linearwrap.py#L68-L76
[ "def", "apply", "(", "self", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "func", "(", "self", ".", "_t", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "LinearWrap", "(", "ret", ")" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
LinearWrap.apply2
Apply a function on the wrapped tensor. The tensor will be the second argument of func. This is because many symbolic functions (such as tensorpack's layers) takes 'scope' as the first argument. Returns: LinearWrap: ``LinearWrap(func(args[0], self.tensor(), *args[1:], **kwa...
tensorpack/models/linearwrap.py
def apply2(self, func, *args, **kwargs): """ Apply a function on the wrapped tensor. The tensor will be the second argument of func. This is because many symbolic functions (such as tensorpack's layers) takes 'scope' as the first argument. Returns: LinearWra...
def apply2(self, func, *args, **kwargs): """ Apply a function on the wrapped tensor. The tensor will be the second argument of func. This is because many symbolic functions (such as tensorpack's layers) takes 'scope' as the first argument. Returns: LinearWra...
[ "Apply", "a", "function", "on", "the", "wrapped", "tensor", ".", "The", "tensor", "will", "be", "the", "second", "argument", "of", "func", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/linearwrap.py#L78-L90
[ "def", "apply2", "(", "self", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "func", "(", "args", "[", "0", "]", ",", "self", ".", "_t", ",", "*", "(", "args", "[", "1", ":", "]", ")", ",", "*", "*", "kwargs...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
guided_relu
Returns: A context where the gradient of :meth:`tf.nn.relu` is replaced by guided back-propagation, as described in the paper: `Striving for Simplicity: The All Convolutional Net <https://arxiv.org/abs/1412.6806>`_
examples/Saliency/saliency-maps.py
def guided_relu(): """ Returns: A context where the gradient of :meth:`tf.nn.relu` is replaced by guided back-propagation, as described in the paper: `Striving for Simplicity: The All Convolutional Net <https://arxiv.org/abs/1412.6806>`_ """ from tensorflow.python.ops imp...
def guided_relu(): """ Returns: A context where the gradient of :meth:`tf.nn.relu` is replaced by guided back-propagation, as described in the paper: `Striving for Simplicity: The All Convolutional Net <https://arxiv.org/abs/1412.6806>`_ """ from tensorflow.python.ops imp...
[ "Returns", ":", "A", "context", "where", "the", "gradient", "of", ":", "meth", ":", "tf", ".", "nn", ".", "relu", "is", "replaced", "by", "guided", "back", "-", "propagation", "as", "described", "in", "the", "paper", ":", "Striving", "for", "Simplicity",...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/Saliency/saliency-maps.py#L19-L37
[ "def", "guided_relu", "(", ")", ":", "from", "tensorflow", ".", "python", ".", "ops", "import", "gen_nn_ops", "# noqa", "@", "tf", ".", "RegisterGradient", "(", "\"GuidedReLU\"", ")", "def", "GuidedReluGrad", "(", "op", ",", "grad", ")", ":", "return", "tf...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
saliency_map
Produce a saliency map as described in the paper: `Deep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Maps <https://arxiv.org/abs/1312.6034>`_. The saliency map is the gradient of the max element in output w.r.t input. Returns: tf.Tensor: the saliency map. ...
examples/Saliency/saliency-maps.py
def saliency_map(output, input, name="saliency_map"): """ Produce a saliency map as described in the paper: `Deep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Maps <https://arxiv.org/abs/1312.6034>`_. The saliency map is the gradient of the max element in outpu...
def saliency_map(output, input, name="saliency_map"): """ Produce a saliency map as described in the paper: `Deep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Maps <https://arxiv.org/abs/1312.6034>`_. The saliency map is the gradient of the max element in outpu...
[ "Produce", "a", "saliency", "map", "as", "described", "in", "the", "paper", ":", "Deep", "Inside", "Convolutional", "Networks", ":", "Visualising", "Image", "Classification", "Models", "and", "Saliency", "Maps", "<https", ":", "//", "arxiv", ".", "org", "/", ...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/Saliency/saliency-maps.py#L40-L52
[ "def", "saliency_map", "(", "output", ",", "input", ",", "name", "=", "\"saliency_map\"", ")", ":", "max_outp", "=", "tf", ".", "reduce_max", "(", "output", ",", "1", ")", "saliency_op", "=", "tf", ".", "gradients", "(", "max_outp", ",", "input", ")", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
Conv2D
A wrapper around `tf.layers.Conv2D`. Some differences to maintain backward-compatibility: 1. Default kernel initializer is variance_scaling_initializer(2.0). 2. Default padding is 'same'. 3. Support 'split' argument to do group conv. Note that this is not efficient. Variable Names: * ``W``: w...
tensorpack/models/conv2d.py
def Conv2D( inputs, filters, kernel_size, strides=(1, 1), padding='same', data_format='channels_last', dilation_rate=(1, 1), activation=None, use_bias=True, kernel_initializer=None, bias_initializer=tf.zeros_initializer(), k...
def Conv2D( inputs, filters, kernel_size, strides=(1, 1), padding='same', data_format='channels_last', dilation_rate=(1, 1), activation=None, use_bias=True, kernel_initializer=None, bias_initializer=tf.zeros_initializer(), k...
[ "A", "wrapper", "around", "tf", ".", "layers", ".", "Conv2D", ".", "Some", "differences", "to", "maintain", "backward", "-", "compatibility", ":" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/conv2d.py#L23-L140
[ "def", "Conv2D", "(", "inputs", ",", "filters", ",", "kernel_size", ",", "strides", "=", "(", "1", ",", "1", ")", ",", "padding", "=", "'same'", ",", "data_format", "=", "'channels_last'", ",", "dilation_rate", "=", "(", "1", ",", "1", ")", ",", "act...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
Conv2DTranspose
A wrapper around `tf.layers.Conv2DTranspose`. Some differences to maintain backward-compatibility: 1. Default kernel initializer is variance_scaling_initializer(2.0). 2. Default padding is 'same' Variable Names: * ``W``: weights * ``b``: bias
tensorpack/models/conv2d.py
def Conv2DTranspose( inputs, filters, kernel_size, strides=(1, 1), padding='same', data_format='channels_last', activation=None, use_bias=True, kernel_initializer=None, bias_initializer=tf.zeros_initializer(), kernel_regularizer=Non...
def Conv2DTranspose( inputs, filters, kernel_size, strides=(1, 1), padding='same', data_format='channels_last', activation=None, use_bias=True, kernel_initializer=None, bias_initializer=tf.zeros_initializer(), kernel_regularizer=Non...
[ "A", "wrapper", "around", "tf", ".", "layers", ".", "Conv2DTranspose", ".", "Some", "differences", "to", "maintain", "backward", "-", "compatibility", ":" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/conv2d.py#L151-L252
[ "def", "Conv2DTranspose", "(", "inputs", ",", "filters", ",", "kernel_size", ",", "strides", "=", "(", "1", ",", "1", ")", ",", "padding", "=", "'same'", ",", "data_format", "=", "'channels_last'", ",", "activation", "=", "None", ",", "use_bias", "=", "T...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
GraphVarParam.setup_graph
Will setup the assign operator for that variable.
tensorpack/callbacks/param.py
def setup_graph(self): """ Will setup the assign operator for that variable. """ all_vars = tfv1.global_variables() + tfv1.local_variables() for v in all_vars: if v.name == self.var_name: self.var = v break else: raise ValueError("{...
def setup_graph(self): """ Will setup the assign operator for that variable. """ all_vars = tfv1.global_variables() + tfv1.local_variables() for v in all_vars: if v.name == self.var_name: self.var = v break else: raise ValueError("{...
[ "Will", "setup", "the", "assign", "operator", "for", "that", "variable", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/param.py#L68-L76
[ "def", "setup_graph", "(", "self", ")", ":", "all_vars", "=", "tfv1", ".", "global_variables", "(", ")", "+", "tfv1", ".", "local_variables", "(", ")", "for", "v", "in", "all_vars", ":", "if", "v", ".", "name", "==", "self", ".", "var_name", ":", "se...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
HyperParamSetter.get_value_to_set
Returns: The value to assign to the variable. Note: Subclasses will implement the abstract method :meth:`_get_value_to_set`, which should return a new value to set, or return None to do nothing.
tensorpack/callbacks/param.py
def get_value_to_set(self): """ Returns: The value to assign to the variable. Note: Subclasses will implement the abstract method :meth:`_get_value_to_set`, which should return a new value to set, or return None to do nothing. """ ...
def get_value_to_set(self): """ Returns: The value to assign to the variable. Note: Subclasses will implement the abstract method :meth:`_get_value_to_set`, which should return a new value to set, or return None to do nothing. """ ...
[ "Returns", ":", "The", "value", "to", "assign", "to", "the", "variable", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/param.py#L143-L164
[ "def", "get_value_to_set", "(", "self", ")", ":", "ret", "=", "self", ".", "_get_value_to_set", "(", ")", "if", "ret", "is", "not", "None", "and", "ret", "!=", "self", ".", "_last_value", ":", "if", "self", ".", "epoch_num", "!=", "self", ".", "_last_e...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
ScheduledHyperParamSetter._get_value_to_set_at_point
Using schedule, compute the value to be set at a given point.
tensorpack/callbacks/param.py
def _get_value_to_set_at_point(self, point): """ Using schedule, compute the value to be set at a given point. """ laste, lastv = None, None for e, v in self.schedule: if e == point: return v # meet the exact boundary, return directly if...
def _get_value_to_set_at_point(self, point): """ Using schedule, compute the value to be set at a given point. """ laste, lastv = None, None for e, v in self.schedule: if e == point: return v # meet the exact boundary, return directly if...
[ "Using", "schedule", "compute", "the", "value", "to", "be", "set", "at", "a", "given", "point", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/param.py#L283-L301
[ "def", "_get_value_to_set_at_point", "(", "self", ",", "point", ")", ":", "laste", ",", "lastv", "=", "None", ",", "None", "for", "e", ",", "v", "in", "self", ".", "schedule", ":", "if", "e", "==", "point", ":", "return", "v", "# meet the exact boundary,...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
Model.build_graph
This function should build the model which takes the input variables and return cost at the end
examples/basics/mnist-convnet.py
def build_graph(self, image, label): """This function should build the model which takes the input variables and return cost at the end""" # In tensorflow, inputs to convolution function are assumed to be # NHWC. Add a single channel here. image = tf.expand_dims(image, 3) ...
def build_graph(self, image, label): """This function should build the model which takes the input variables and return cost at the end""" # In tensorflow, inputs to convolution function are assumed to be # NHWC. Add a single channel here. image = tf.expand_dims(image, 3) ...
[ "This", "function", "should", "build", "the", "model", "which", "takes", "the", "input", "variables", "and", "return", "cost", "at", "the", "end" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/basics/mnist-convnet.py#L27-L76
[ "def", "build_graph", "(", "self", ",", "image", ",", "label", ")", ":", "# In tensorflow, inputs to convolution function are assumed to be", "# NHWC. Add a single channel here.", "image", "=", "tf", ".", "expand_dims", "(", "image", ",", "3", ")", "image", "=", "imag...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
name_conversion
Convert a caffe parameter name to a tensorflow parameter name as defined in the above model
examples/ResNet/load-resnet.py
def name_conversion(caffe_layer_name): """ Convert a caffe parameter name to a tensorflow parameter name as defined in the above model """ # beginning & end mapping NAME_MAP = {'bn_conv1/beta': 'conv0/bn/beta', 'bn_conv1/gamma': 'conv0/bn/gamma', 'bn_conv1/mean/EMA': ...
def name_conversion(caffe_layer_name): """ Convert a caffe parameter name to a tensorflow parameter name as defined in the above model """ # beginning & end mapping NAME_MAP = {'bn_conv1/beta': 'conv0/bn/beta', 'bn_conv1/gamma': 'conv0/bn/gamma', 'bn_conv1/mean/EMA': ...
[ "Convert", "a", "caffe", "parameter", "name", "to", "a", "tensorflow", "parameter", "name", "as", "defined", "in", "the", "above", "model" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/ResNet/load-resnet.py#L101-L138
[ "def", "name_conversion", "(", "caffe_layer_name", ")", ":", "# beginning & end mapping", "NAME_MAP", "=", "{", "'bn_conv1/beta'", ":", "'conv0/bn/beta'", ",", "'bn_conv1/gamma'", ":", "'conv0/bn/gamma'", ",", "'bn_conv1/mean/EMA'", ":", "'conv0/bn/mean/EMA'", ",", "'bn_c...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
custom_getter_scope
Args: custom_getter: the same as in :func:`tf.get_variable` Returns: The current variable scope with a custom_getter.
tensorpack/tfutils/varreplace.py
def custom_getter_scope(custom_getter): """ Args: custom_getter: the same as in :func:`tf.get_variable` Returns: The current variable scope with a custom_getter. """ scope = tf.get_variable_scope() if get_tf_version_tuple() >= (1, 5): with tf.variable_scope( ...
def custom_getter_scope(custom_getter): """ Args: custom_getter: the same as in :func:`tf.get_variable` Returns: The current variable scope with a custom_getter. """ scope = tf.get_variable_scope() if get_tf_version_tuple() >= (1, 5): with tf.variable_scope( ...
[ "Args", ":", "custom_getter", ":", "the", "same", "as", "in", ":", "func", ":", "tf", ".", "get_variable" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/varreplace.py#L14-L33
[ "def", "custom_getter_scope", "(", "custom_getter", ")", ":", "scope", "=", "tf", ".", "get_variable_scope", "(", ")", "if", "get_tf_version_tuple", "(", ")", ">=", "(", "1", ",", "5", ")", ":", "with", "tf", ".", "variable_scope", "(", "scope", ",", "cu...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
remap_variables
Use fn to map the output of any variable getter. Args: fn (tf.Variable -> tf.Tensor) Returns: The current variable scope with a custom_getter that maps all the variables by fn. Example: .. code-block:: python with varreplace.remap_variables(lambda var: quantiz...
tensorpack/tfutils/varreplace.py
def remap_variables(fn): """ Use fn to map the output of any variable getter. Args: fn (tf.Variable -> tf.Tensor) Returns: The current variable scope with a custom_getter that maps all the variables by fn. Example: .. code-block:: python with varreplac...
def remap_variables(fn): """ Use fn to map the output of any variable getter. Args: fn (tf.Variable -> tf.Tensor) Returns: The current variable scope with a custom_getter that maps all the variables by fn. Example: .. code-block:: python with varreplac...
[ "Use", "fn", "to", "map", "the", "output", "of", "any", "variable", "getter", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/varreplace.py#L36-L56
[ "def", "remap_variables", "(", "fn", ")", ":", "def", "custom_getter", "(", "getter", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "v", "=", "getter", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "fn", "(", "v", ")", "return"...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
freeze_variables
Return a context to freeze variables, by wrapping ``tf.get_variable`` with a custom getter. It works by either applying ``tf.stop_gradient`` on the variables, or by keeping them out of the ``TRAINABLE_VARIABLES`` collection, or both. Example: .. code-block:: python with varrepl...
tensorpack/tfutils/varreplace.py
def freeze_variables(stop_gradient=True, skip_collection=False): """ Return a context to freeze variables, by wrapping ``tf.get_variable`` with a custom getter. It works by either applying ``tf.stop_gradient`` on the variables, or by keeping them out of the ``TRAINABLE_VARIABLES`` collection, or ...
def freeze_variables(stop_gradient=True, skip_collection=False): """ Return a context to freeze variables, by wrapping ``tf.get_variable`` with a custom getter. It works by either applying ``tf.stop_gradient`` on the variables, or by keeping them out of the ``TRAINABLE_VARIABLES`` collection, or ...
[ "Return", "a", "context", "to", "freeze", "variables", "by", "wrapping", "tf", ".", "get_variable", "with", "a", "custom", "getter", ".", "It", "works", "by", "either", "applying", "tf", ".", "stop_gradient", "on", "the", "variables", "or", "by", "keeping", ...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/varreplace.py#L59-L97
[ "def", "freeze_variables", "(", "stop_gradient", "=", "True", ",", "skip_collection", "=", "False", ")", ":", "def", "custom_getter", "(", "getter", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "trainable", "=", "kwargs", ".", "get", "(", "'train...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
load_caffe
Load a caffe model. You must be able to ``import caffe`` to use this function. Args: model_desc (str): path to caffe model description file (.prototxt). model_file (str): path to caffe model parameter file (.caffemodel). Returns: dict: the parameters.
tensorpack/utils/loadcaffe.py
def load_caffe(model_desc, model_file): """ Load a caffe model. You must be able to ``import caffe`` to use this function. Args: model_desc (str): path to caffe model description file (.prototxt). model_file (str): path to caffe model parameter file (.caffemodel). Returns: di...
def load_caffe(model_desc, model_file): """ Load a caffe model. You must be able to ``import caffe`` to use this function. Args: model_desc (str): path to caffe model description file (.prototxt). model_file (str): path to caffe model parameter file (.caffemodel). Returns: di...
[ "Load", "a", "caffe", "model", ".", "You", "must", "be", "able", "to", "import", "caffe", "to", "use", "this", "function", ".", "Args", ":", "model_desc", "(", "str", ")", ":", "path", "to", "caffe", "model", "description", "file", "(", ".", "prototxt"...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/loadcaffe.py#L96-L113
[ "def", "load_caffe", "(", "model_desc", ",", "model_file", ")", ":", "with", "change_env", "(", "'GLOG_minloglevel'", ",", "'2'", ")", ":", "import", "caffe", "caffe", ".", "set_mode_cpu", "(", ")", "net", "=", "caffe", ".", "Net", "(", "model_desc", ",", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
get_caffe_pb
Get caffe protobuf. Returns: The imported caffe protobuf module.
tensorpack/utils/loadcaffe.py
def get_caffe_pb(): """ Get caffe protobuf. Returns: The imported caffe protobuf module. """ dir = get_dataset_path('caffe') caffe_pb_file = os.path.join(dir, 'caffe_pb2.py') if not os.path.isfile(caffe_pb_file): download(CAFFE_PROTO_URL, dir) assert os.path.isfile(os...
def get_caffe_pb(): """ Get caffe protobuf. Returns: The imported caffe protobuf module. """ dir = get_dataset_path('caffe') caffe_pb_file = os.path.join(dir, 'caffe_pb2.py') if not os.path.isfile(caffe_pb_file): download(CAFFE_PROTO_URL, dir) assert os.path.isfile(os...
[ "Get", "caffe", "protobuf", ".", "Returns", ":", "The", "imported", "caffe", "protobuf", "module", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/loadcaffe.py#L116-L147
[ "def", "get_caffe_pb", "(", ")", ":", "dir", "=", "get_dataset_path", "(", "'caffe'", ")", "caffe_pb_file", "=", "os", ".", "path", ".", "join", "(", "dir", ",", "'caffe_pb2.py'", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "caffe_pb_file", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
finalize_configs
Run some sanity checks, and populate some configs from others
examples/FasterRCNN/config.py
def finalize_configs(is_training): """ Run some sanity checks, and populate some configs from others """ _C.freeze(False) # populate new keys now _C.DATA.NUM_CLASS = _C.DATA.NUM_CATEGORY + 1 # +1 background _C.DATA.BASEDIR = os.path.expanduser(_C.DATA.BASEDIR) if isinstance(_C.DATA.VAL, si...
def finalize_configs(is_training): """ Run some sanity checks, and populate some configs from others """ _C.freeze(False) # populate new keys now _C.DATA.NUM_CLASS = _C.DATA.NUM_CATEGORY + 1 # +1 background _C.DATA.BASEDIR = os.path.expanduser(_C.DATA.BASEDIR) if isinstance(_C.DATA.VAL, si...
[ "Run", "some", "sanity", "checks", "and", "populate", "some", "configs", "from", "others" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/config.py#L214-L282
[ "def", "finalize_configs", "(", "is_training", ")", ":", "_C", ".", "freeze", "(", "False", ")", "# populate new keys now", "_C", ".", "DATA", ".", "NUM_CLASS", "=", "_C", ".", "DATA", ".", "NUM_CATEGORY", "+", "1", "# +1 background", "_C", ".", "DATA", "....
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
AttrDict.to_dict
Convert to a nested dict.
examples/FasterRCNN/config.py
def to_dict(self): """Convert to a nested dict. """ return {k: v.to_dict() if isinstance(v, AttrDict) else v for k, v in self.__dict__.items() if not k.startswith('_')}
def to_dict(self): """Convert to a nested dict. """ return {k: v.to_dict() if isinstance(v, AttrDict) else v for k, v in self.__dict__.items() if not k.startswith('_')}
[ "Convert", "to", "a", "nested", "dict", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/config.py#L41-L44
[ "def", "to_dict", "(", "self", ")", ":", "return", "{", "k", ":", "v", ".", "to_dict", "(", ")", "if", "isinstance", "(", "v", ",", "AttrDict", ")", "else", "v", "for", "k", ",", "v", "in", "self", ".", "__dict__", ".", "items", "(", ")", "if",...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
AttrDict.update_args
Update from command line args.
examples/FasterRCNN/config.py
def update_args(self, args): """Update from command line args. """ for cfg in args: keys, v = cfg.split('=', maxsplit=1) keylist = keys.split('.') dic = self for i, k in enumerate(keylist[:-1]): assert k in dir(dic), "Unknown config key: {...
def update_args(self, args): """Update from command line args. """ for cfg in args: keys, v = cfg.split('=', maxsplit=1) keylist = keys.split('.') dic = self for i, k in enumerate(keylist[:-1]): assert k in dir(dic), "Unknown config key: {...
[ "Update", "from", "command", "line", "args", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/config.py#L46-L61
[ "def", "update_args", "(", "self", ",", "args", ")", ":", "for", "cfg", "in", "args", ":", "keys", ",", "v", "=", "cfg", ".", "split", "(", "'='", ",", "maxsplit", "=", "1", ")", "keylist", "=", "keys", ".", "split", "(", "'.'", ")", "dic", "="...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
get_model_loader
Get a corresponding model loader by looking at the file name. Returns: SessInit: either a :class:`DictRestore` (if name ends with 'npy/npz') or :class:`SaverRestore` (otherwise).
tensorpack/tfutils/sessinit.py
def get_model_loader(filename): """ Get a corresponding model loader by looking at the file name. Returns: SessInit: either a :class:`DictRestore` (if name ends with 'npy/npz') or :class:`SaverRestore` (otherwise). """ assert isinstance(filename, six.string_types), filename file...
def get_model_loader(filename): """ Get a corresponding model loader by looking at the file name. Returns: SessInit: either a :class:`DictRestore` (if name ends with 'npy/npz') or :class:`SaverRestore` (otherwise). """ assert isinstance(filename, six.string_types), filename file...
[ "Get", "a", "corresponding", "model", "loader", "by", "looking", "at", "the", "file", "name", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/sessinit.py#L245-L263
[ "def", "get_model_loader", "(", "filename", ")", ":", "assert", "isinstance", "(", "filename", ",", "six", ".", "string_types", ")", ",", "filename", "filename", "=", "os", ".", "path", ".", "expanduser", "(", "filename", ")", "if", "filename", ".", "endsw...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
SaverRestore._read_checkpoint_vars
return a set of strings
tensorpack/tfutils/sessinit.py
def _read_checkpoint_vars(model_path): """ return a set of strings """ reader = tf.train.NewCheckpointReader(model_path) reader = CheckpointReaderAdapter(reader) # use an adapter to standardize the name ckpt_vars = reader.get_variable_to_shape_map().keys() return reader, set(c...
def _read_checkpoint_vars(model_path): """ return a set of strings """ reader = tf.train.NewCheckpointReader(model_path) reader = CheckpointReaderAdapter(reader) # use an adapter to standardize the name ckpt_vars = reader.get_variable_to_shape_map().keys() return reader, set(c...
[ "return", "a", "set", "of", "strings" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/sessinit.py#L118-L123
[ "def", "_read_checkpoint_vars", "(", "model_path", ")", ":", "reader", "=", "tf", ".", "train", ".", "NewCheckpointReader", "(", "model_path", ")", "reader", "=", "CheckpointReaderAdapter", "(", "reader", ")", "# use an adapter to standardize the name", "ckpt_vars", "...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
argscope
Args: layers (list or layer): layer or list of layers to apply the arguments. Returns: a context where all appearance of these layer will by default have the arguments specified by kwargs. Example: .. code-block:: python with argscope(Conv2D, kernel_shape=3, nl=tf....
tensorpack/tfutils/argscope.py
def argscope(layers, **kwargs): """ Args: layers (list or layer): layer or list of layers to apply the arguments. Returns: a context where all appearance of these layer will by default have the arguments specified by kwargs. Example: .. code-block:: python ...
def argscope(layers, **kwargs): """ Args: layers (list or layer): layer or list of layers to apply the arguments. Returns: a context where all appearance of these layer will by default have the arguments specified by kwargs. Example: .. code-block:: python ...
[ "Args", ":", "layers", "(", "list", "or", "layer", ")", ":", "layer", "or", "list", "of", "layers", "to", "apply", "the", "arguments", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/argscope.py#L22-L57
[ "def", "argscope", "(", "layers", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "layers", ",", "list", ")", ":", "layers", "=", "[", "layers", "]", "# def _check_args_exist(l):", "# args = inspect.getargspec(l).args", "# for k, v in si...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
enable_argscope_for_function
Decorator for function to support argscope Example: .. code-block:: python from mylib import myfunc myfunc = enable_argscope_for_function(myfunc) Args: func: A function mapping one or multiple tensors to one or multiple tensors. log_shape (bool): S...
tensorpack/tfutils/argscope.py
def enable_argscope_for_function(func, log_shape=True): """Decorator for function to support argscope Example: .. code-block:: python from mylib import myfunc myfunc = enable_argscope_for_function(myfunc) Args: func: A function mapping one or multiple tensors to o...
def enable_argscope_for_function(func, log_shape=True): """Decorator for function to support argscope Example: .. code-block:: python from mylib import myfunc myfunc = enable_argscope_for_function(myfunc) Args: func: A function mapping one or multiple tensors to o...
[ "Decorator", "for", "function", "to", "support", "argscope" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/argscope.py#L73-L123
[ "def", "enable_argscope_for_function", "(", "func", ",", "log_shape", "=", "True", ")", ":", "assert", "callable", "(", "func", ")", ",", "\"func should be a callable\"", "@", "wraps", "(", "func", ")", "def", "wrapped_func", "(", "*", "args", ",", "*", "*",...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
enable_argscope_for_module
Overwrite all functions of a given module to support argscope. Note that this function monkey-patches the module and therefore could have unexpected consequences. It has been only tested to work well with ``tf.layers`` module. Example: .. code-block:: python import tensorflow as t...
tensorpack/tfutils/argscope.py
def enable_argscope_for_module(module, log_shape=True): """ Overwrite all functions of a given module to support argscope. Note that this function monkey-patches the module and therefore could have unexpected consequences. It has been only tested to work well with ``tf.layers`` module. Example:...
def enable_argscope_for_module(module, log_shape=True): """ Overwrite all functions of a given module to support argscope. Note that this function monkey-patches the module and therefore could have unexpected consequences. It has been only tested to work well with ``tf.layers`` module. Example:...
[ "Overwrite", "all", "functions", "of", "a", "given", "module", "to", "support", "argscope", ".", "Note", "that", "this", "function", "monkey", "-", "patches", "the", "module", "and", "therefore", "could", "have", "unexpected", "consequences", ".", "It", "has",...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/argscope.py#L126-L148
[ "def", "enable_argscope_for_module", "(", "module", ",", "log_shape", "=", "True", ")", ":", "if", "is_tfv2", "(", ")", "and", "module", "==", "tf", ".", "layers", ":", "module", "=", "tf", ".", "compat", ".", "v1", ".", "layers", "for", "name", ",", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
visualize_tensors
Generate tensor for TensorBoard (casting, clipping) Args: name: name for visualization operation *imgs: multiple tensors as list scale_func: scale input tensors to fit range [0, 255] Example: visualize_tensors('viz1', [img1]) visualize_tensors('viz2', [img1, img2, img3]...
examples/GAN/Image2Image.py
def visualize_tensors(name, imgs, scale_func=lambda x: (x + 1.) * 128., max_outputs=1): """Generate tensor for TensorBoard (casting, clipping) Args: name: name for visualization operation *imgs: multiple tensors as list scale_func: scale input tensors to fit range [0, 255] Example:...
def visualize_tensors(name, imgs, scale_func=lambda x: (x + 1.) * 128., max_outputs=1): """Generate tensor for TensorBoard (casting, clipping) Args: name: name for visualization operation *imgs: multiple tensors as list scale_func: scale input tensors to fit range [0, 255] Example:...
[ "Generate", "tensor", "for", "TensorBoard", "(", "casting", "clipping", ")" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/Image2Image.py#L46-L60
[ "def", "visualize_tensors", "(", "name", ",", "imgs", ",", "scale_func", "=", "lambda", "x", ":", "(", "x", "+", "1.", ")", "*", "128.", ",", "max_outputs", "=", "1", ")", ":", "xy", "=", "scale_func", "(", "tf", ".", "concat", "(", "imgs", ",", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
split_input
img: an RGB image of shape (s, 2s, 3). :return: [input, output]
examples/GAN/Image2Image.py
def split_input(img): """ img: an RGB image of shape (s, 2s, 3). :return: [input, output] """ # split the image into left + right pairs s = img.shape[0] assert img.shape[1] == 2 * s input, output = img[:, :s, :], img[:, s:, :] if args.mode == 'BtoA': input, output = output, i...
def split_input(img): """ img: an RGB image of shape (s, 2s, 3). :return: [input, output] """ # split the image into left + right pairs s = img.shape[0] assert img.shape[1] == 2 * s input, output = img[:, :s, :], img[:, s:, :] if args.mode == 'BtoA': input, output = output, i...
[ "img", ":", "an", "RGB", "image", "of", "shape", "(", "s", "2s", "3", ")", ".", ":", "return", ":", "[", "input", "output", "]" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/Image2Image.py#L149-L164
[ "def", "split_input", "(", "img", ")", ":", "# split the image into left + right pairs", "s", "=", "img", ".", "shape", "[", "0", "]", "assert", "img", ".", "shape", "[", "1", "]", "==", "2", "*", "s", "input", ",", "output", "=", "img", "[", ":", ",...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
Model.discriminator
return a (b, 1) logits
examples/GAN/Image2Image.py
def discriminator(self, inputs, outputs): """ return a (b, 1) logits""" l = tf.concat([inputs, outputs], 3) with argscope(Conv2D, kernel_size=4, strides=2, activation=BNLReLU): l = (LinearWrap(l) .Conv2D('conv0', NF, activation=tf.nn.leaky_relu) .Con...
def discriminator(self, inputs, outputs): """ return a (b, 1) logits""" l = tf.concat([inputs, outputs], 3) with argscope(Conv2D, kernel_size=4, strides=2, activation=BNLReLU): l = (LinearWrap(l) .Conv2D('conv0', NF, activation=tf.nn.leaky_relu) .Con...
[ "return", "a", "(", "b", "1", ")", "logits" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/Image2Image.py#L106-L116
[ "def", "discriminator", "(", "self", ",", "inputs", ",", "outputs", ")", ":", "l", "=", "tf", ".", "concat", "(", "[", "inputs", ",", "outputs", "]", ",", "3", ")", "with", "argscope", "(", "Conv2D", ",", "kernel_size", "=", "4", ",", "strides", "=...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
print_stat
A simple print Op that might be easier to use than :meth:`tf.Print`. Use it like: ``x = print_stat(x, message='This is x')``.
tensorpack/tfutils/symbolic_functions.py
def print_stat(x, message=None): """ A simple print Op that might be easier to use than :meth:`tf.Print`. Use it like: ``x = print_stat(x, message='This is x')``. """ if message is None: message = x.op.name lst = [tf.shape(x), tf.reduce_mean(x)] if x.dtype.is_floating: lst.ap...
def print_stat(x, message=None): """ A simple print Op that might be easier to use than :meth:`tf.Print`. Use it like: ``x = print_stat(x, message='This is x')``. """ if message is None: message = x.op.name lst = [tf.shape(x), tf.reduce_mean(x)] if x.dtype.is_floating: lst.ap...
[ "A", "simple", "print", "Op", "that", "might", "be", "easier", "to", "use", "than", ":", "meth", ":", "tf", ".", "Print", ".", "Use", "it", "like", ":", "x", "=", "print_stat", "(", "x", "message", "=", "This", "is", "x", ")", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/symbolic_functions.py#L13-L23
[ "def", "print_stat", "(", "x", ",", "message", "=", "None", ")", ":", "if", "message", "is", "None", ":", "message", "=", "x", ".", "op", ".", "name", "lst", "=", "[", "tf", ".", "shape", "(", "x", ")", ",", "tf", ".", "reduce_mean", "(", "x", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
rms
Returns: root mean square of tensor x.
tensorpack/tfutils/symbolic_functions.py
def rms(x, name=None): """ Returns: root mean square of tensor x. """ if name is None: name = x.op.name + '/rms' with tfv1.name_scope(None): # name already contains the scope return tf.sqrt(tf.reduce_mean(tf.square(x)), name=name) return tf.sqrt(tf.reduce_mean(t...
def rms(x, name=None): """ Returns: root mean square of tensor x. """ if name is None: name = x.op.name + '/rms' with tfv1.name_scope(None): # name already contains the scope return tf.sqrt(tf.reduce_mean(tf.square(x)), name=name) return tf.sqrt(tf.reduce_mean(t...
[ "Returns", ":", "root", "mean", "square", "of", "tensor", "x", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/symbolic_functions.py#L27-L36
[ "def", "rms", "(", "x", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "x", ".", "op", ".", "name", "+", "'/rms'", "with", "tfv1", ".", "name_scope", "(", "None", ")", ":", "# name already contains the scope", "retu...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
psnr
`Peek Signal to Noise Ratio <https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio>`_. .. math:: PSNR = 20 \cdot \log_{10}(MAX_p) - 10 \cdot \log_{10}(MSE) Args: prediction: a :class:`tf.Tensor` representing the prediction signal. ground_truth: another :class:`tf.Tensor` with the s...
tensorpack/tfutils/symbolic_functions.py
def psnr(prediction, ground_truth, maxp=None, name='psnr'): """`Peek Signal to Noise Ratio <https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio>`_. .. math:: PSNR = 20 \cdot \log_{10}(MAX_p) - 10 \cdot \log_{10}(MSE) Args: prediction: a :class:`tf.Tensor` representing the prediction ...
def psnr(prediction, ground_truth, maxp=None, name='psnr'): """`Peek Signal to Noise Ratio <https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio>`_. .. math:: PSNR = 20 \cdot \log_{10}(MAX_p) - 10 \cdot \log_{10}(MSE) Args: prediction: a :class:`tf.Tensor` representing the prediction ...
[ "Peek", "Signal", "to", "Noise", "Ratio", "<https", ":", "//", "en", ".", "wikipedia", ".", "org", "/", "wiki", "/", "Peak_signal", "-", "to", "-", "noise_ratio", ">", "_", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/symbolic_functions.py#L41-L72
[ "def", "psnr", "(", "prediction", ",", "ground_truth", ",", "maxp", "=", "None", ",", "name", "=", "'psnr'", ")", ":", "maxp", "=", "float", "(", "maxp", ")", "def", "log10", "(", "x", ")", ":", "with", "tf", ".", "name_scope", "(", "\"log10\"", ")...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
GaussianMap.get_gaussian_weight
Args: anchor: coordinate of the center
tensorpack/dataflow/imgaug/deform.py
def get_gaussian_weight(self, anchor): """ Args: anchor: coordinate of the center """ ret = np.zeros(self.shape, dtype='float32') y, x = np.mgrid[:self.shape[0], :self.shape[1]] y = y.astype('float32') / ret.shape[0] - anchor[0] x = x.astype('float32'...
def get_gaussian_weight(self, anchor): """ Args: anchor: coordinate of the center """ ret = np.zeros(self.shape, dtype='float32') y, x = np.mgrid[:self.shape[0], :self.shape[1]] y = y.astype('float32') / ret.shape[0] - anchor[0] x = x.astype('float32'...
[ "Args", ":", "anchor", ":", "coordinate", "of", "the", "center" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/imgaug/deform.py#L26-L39
[ "def", "get_gaussian_weight", "(", "self", ",", "anchor", ")", ":", "ret", "=", "np", ".", "zeros", "(", "self", ".", "shape", ",", "dtype", "=", "'float32'", ")", "y", ",", "x", "=", "np", ".", "mgrid", "[", ":", "self", ".", "shape", "[", "0", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
pad
Pad tensor in H, W Remarks: TensorFlow uses "ceil(input_spatial_shape[i] / strides[i])" rather than explicit padding like Caffe, pyTorch does. Hence, we need to pad here beforehand. Args: x (tf.tensor): incoming tensor p (int, optional): padding for H, W Returns: t...
examples/OpticalFlow/flownet_models.py
def pad(x, p=3): """Pad tensor in H, W Remarks: TensorFlow uses "ceil(input_spatial_shape[i] / strides[i])" rather than explicit padding like Caffe, pyTorch does. Hence, we need to pad here beforehand. Args: x (tf.tensor): incoming tensor p (int, optional): padding for H, W...
def pad(x, p=3): """Pad tensor in H, W Remarks: TensorFlow uses "ceil(input_spatial_shape[i] / strides[i])" rather than explicit padding like Caffe, pyTorch does. Hence, we need to pad here beforehand. Args: x (tf.tensor): incoming tensor p (int, optional): padding for H, W...
[ "Pad", "tensor", "in", "H", "W" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/OpticalFlow/flownet_models.py#L17-L31
[ "def", "pad", "(", "x", ",", "p", "=", "3", ")", ":", "return", "tf", ".", "pad", "(", "x", ",", "[", "[", "0", ",", "0", "]", ",", "[", "0", ",", "0", "]", ",", "[", "p", ",", "p", "]", ",", "[", "p", ",", "p", "]", "]", ")" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
correlation
Correlation Cost Volume computation. This is a fallback Python-only implementation, specialized just for FlowNet2. It takes a lot of memory and is slow. If you know to compile a custom op yourself, it's better to use the cuda implementation here: https://github.com/PatWie/tensorflow-recipes/tree/maste...
examples/OpticalFlow/flownet_models.py
def correlation(ina, inb, kernel_size, max_displacement, stride_1, stride_2, pad, data_format): """ Correlation Cost Volume computation. This is a fallback Python-only implementation, specialized just for FlowNet2. It takes a lot of memory and is slow. ...
def correlation(ina, inb, kernel_size, max_displacement, stride_1, stride_2, pad, data_format): """ Correlation Cost Volume computation. This is a fallback Python-only implementation, specialized just for FlowNet2. It takes a lot of memory and is slow. ...
[ "Correlation", "Cost", "Volume", "computation", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/OpticalFlow/flownet_models.py#L38-L72
[ "def", "correlation", "(", "ina", ",", "inb", ",", "kernel_size", ",", "max_displacement", ",", "stride_1", ",", "stride_2", ",", "pad", ",", "data_format", ")", ":", "assert", "pad", "==", "max_displacement", "assert", "kernel_size", "==", "1", "assert", "d...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
resize
Resize input tensor with unkown input-shape by a factor Args: x (tf.Tensor): tensor NCHW factor (int, optional): resize factor for H, W Note: Differences here against Caffe have huge impacts on the quality of the predictions. Returns: tf.Tensor: resized tensor NCHW
examples/OpticalFlow/flownet_models.py
def resize(x, mode, factor=4): """Resize input tensor with unkown input-shape by a factor Args: x (tf.Tensor): tensor NCHW factor (int, optional): resize factor for H, W Note: Differences here against Caffe have huge impacts on the quality of the predictions. Returns: ...
def resize(x, mode, factor=4): """Resize input tensor with unkown input-shape by a factor Args: x (tf.Tensor): tensor NCHW factor (int, optional): resize factor for H, W Note: Differences here against Caffe have huge impacts on the quality of the predictions. Returns: ...
[ "Resize", "input", "tensor", "with", "unkown", "input", "-", "shape", "by", "a", "factor" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/OpticalFlow/flownet_models.py#L115-L139
[ "def", "resize", "(", "x", ",", "mode", ",", "factor", "=", "4", ")", ":", "assert", "mode", "in", "[", "'bilinear'", ",", "'nearest'", "]", ",", "mode", "shp", "=", "tf", ".", "shape", "(", "x", ")", "[", "2", ":", "]", "*", "factor", "# NCHW ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
FlowNet2.flownet2_fusion
Architecture in Table 4 of FlowNet 2.0. Args: x: NCHW tensor, where C=11 is the concatenation of 7 items of [3, 2, 2, 1, 1, 1, 1] channels.
examples/OpticalFlow/flownet_models.py
def flownet2_fusion(self, x): """ Architecture in Table 4 of FlowNet 2.0. Args: x: NCHW tensor, where C=11 is the concatenation of 7 items of [3, 2, 2, 1, 1, 1, 1] channels. """ with argscope([tf.layers.conv2d], activation=lambda x: tf.nn.leaky_relu(x, 0.1), ...
def flownet2_fusion(self, x): """ Architecture in Table 4 of FlowNet 2.0. Args: x: NCHW tensor, where C=11 is the concatenation of 7 items of [3, 2, 2, 1, 1, 1, 1] channels. """ with argscope([tf.layers.conv2d], activation=lambda x: tf.nn.leaky_relu(x, 0.1), ...
[ "Architecture", "in", "Table", "4", "of", "FlowNet", "2", ".", "0", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/OpticalFlow/flownet_models.py#L230-L264
[ "def", "flownet2_fusion", "(", "self", ",", "x", ")", ":", "with", "argscope", "(", "[", "tf", ".", "layers", ".", "conv2d", "]", ",", "activation", "=", "lambda", "x", ":", "tf", ".", "nn", ".", "leaky_relu", "(", "x", ",", "0.1", ")", ",", "pad...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
FlowNet2.flownet2_sd
Architecture in Table 3 of FlowNet 2.0. Args: x: concatenation of two inputs, of shape [1, 2xC, H, W]
examples/OpticalFlow/flownet_models.py
def flownet2_sd(self, x): """ Architecture in Table 3 of FlowNet 2.0. Args: x: concatenation of two inputs, of shape [1, 2xC, H, W] """ with argscope([tf.layers.conv2d], activation=lambda x: tf.nn.leaky_relu(x, 0.1), padding='valid', strides=2, ...
def flownet2_sd(self, x): """ Architecture in Table 3 of FlowNet 2.0. Args: x: concatenation of two inputs, of shape [1, 2xC, H, W] """ with argscope([tf.layers.conv2d], activation=lambda x: tf.nn.leaky_relu(x, 0.1), padding='valid', strides=2, ...
[ "Architecture", "in", "Table", "3", "of", "FlowNet", "2", ".", "0", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/OpticalFlow/flownet_models.py#L266-L320
[ "def", "flownet2_sd", "(", "self", ",", "x", ")", ":", "with", "argscope", "(", "[", "tf", ".", "layers", ".", "conv2d", "]", ",", "activation", "=", "lambda", "x", ":", "tf", ".", "nn", ".", "leaky_relu", "(", "x", ",", "0.1", ")", ",", "padding...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
FlowNet2S.graph_structure
Architecture of FlowNetSimple in Figure 2 of FlowNet 1.0. Args: x: 2CHW if standalone==True, else NCHW where C=12 is a concatenation of 5 tensors of [3, 3, 3, 2, 1] channels. standalone: If True, this model is used to predict flow from two inputs. If Fals...
examples/OpticalFlow/flownet_models.py
def graph_structure(self, x, standalone=True): """ Architecture of FlowNetSimple in Figure 2 of FlowNet 1.0. Args: x: 2CHW if standalone==True, else NCHW where C=12 is a concatenation of 5 tensors of [3, 3, 3, 2, 1] channels. standalone: If True, this mod...
def graph_structure(self, x, standalone=True): """ Architecture of FlowNetSimple in Figure 2 of FlowNet 1.0. Args: x: 2CHW if standalone==True, else NCHW where C=12 is a concatenation of 5 tensors of [3, 3, 3, 2, 1] channels. standalone: If True, this mod...
[ "Architecture", "of", "FlowNetSimple", "in", "Figure", "2", "of", "FlowNet", "1", ".", "0", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/OpticalFlow/flownet_models.py#L324-L375
[ "def", "graph_structure", "(", "self", ",", "x", ",", "standalone", "=", "True", ")", ":", "if", "standalone", ":", "x", "=", "tf", ".", "concat", "(", "tf", ".", "split", "(", "x", ",", "2", ",", "axis", "=", "0", ")", ",", "axis", "=", "1", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
FlowNet2C.graph_structure
Architecture of FlowNetCorr in Figure 2 of FlowNet 1.0. Args: x: 2CHW.
examples/OpticalFlow/flownet_models.py
def graph_structure(self, x1x2): """ Architecture of FlowNetCorr in Figure 2 of FlowNet 1.0. Args: x: 2CHW. """ with argscope([tf.layers.conv2d], activation=lambda x: tf.nn.leaky_relu(x, 0.1), padding='valid', strides=2, kernel_size=3, ...
def graph_structure(self, x1x2): """ Architecture of FlowNetCorr in Figure 2 of FlowNet 1.0. Args: x: 2CHW. """ with argscope([tf.layers.conv2d], activation=lambda x: tf.nn.leaky_relu(x, 0.1), padding='valid', strides=2, kernel_size=3, ...
[ "Architecture", "of", "FlowNetCorr", "in", "Figure", "2", "of", "FlowNet", "1", ".", "0", ".", "Args", ":", "x", ":", "2CHW", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/OpticalFlow/flownet_models.py#L379-L442
[ "def", "graph_structure", "(", "self", ",", "x1x2", ")", ":", "with", "argscope", "(", "[", "tf", ".", "layers", ".", "conv2d", "]", ",", "activation", "=", "lambda", "x", ":", "tf", ".", "nn", ".", "leaky_relu", "(", "x", ",", "0.1", ")", ",", "...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
draw_annotation
Will not modify img
examples/FasterRCNN/viz.py
def draw_annotation(img, boxes, klass, is_crowd=None): """Will not modify img""" labels = [] assert len(boxes) == len(klass) if is_crowd is not None: assert len(boxes) == len(is_crowd) for cls, crd in zip(klass, is_crowd): clsname = cfg.DATA.CLASS_NAMES[cls] if cr...
def draw_annotation(img, boxes, klass, is_crowd=None): """Will not modify img""" labels = [] assert len(boxes) == len(klass) if is_crowd is not None: assert len(boxes) == len(is_crowd) for cls, crd in zip(klass, is_crowd): clsname = cfg.DATA.CLASS_NAMES[cls] if cr...
[ "Will", "not", "modify", "img" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/viz.py#L15-L30
[ "def", "draw_annotation", "(", "img", ",", "boxes", ",", "klass", ",", "is_crowd", "=", "None", ")", ":", "labels", "=", "[", "]", "assert", "len", "(", "boxes", ")", "==", "len", "(", "klass", ")", "if", "is_crowd", "is", "not", "None", ":", "asse...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
draw_proposal_recall
Draw top3 proposals for each gt. Args: proposals: NPx4 proposal_scores: NP gt_boxes: NG
examples/FasterRCNN/viz.py
def draw_proposal_recall(img, proposals, proposal_scores, gt_boxes): """ Draw top3 proposals for each gt. Args: proposals: NPx4 proposal_scores: NP gt_boxes: NG """ box_ious = np_iou(gt_boxes, proposals) # ng x np box_ious_argsort = np.argsort(-box_ious, axis=1) go...
def draw_proposal_recall(img, proposals, proposal_scores, gt_boxes): """ Draw top3 proposals for each gt. Args: proposals: NPx4 proposal_scores: NP gt_boxes: NG """ box_ious = np_iou(gt_boxes, proposals) # ng x np box_ious_argsort = np.argsort(-box_ious, axis=1) go...
[ "Draw", "top3", "proposals", "for", "each", "gt", ".", "Args", ":", "proposals", ":", "NPx4", "proposal_scores", ":", "NP", "gt_boxes", ":", "NG" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/viz.py#L33-L49
[ "def", "draw_proposal_recall", "(", "img", ",", "proposals", ",", "proposal_scores", ",", "gt_boxes", ")", ":", "box_ious", "=", "np_iou", "(", "gt_boxes", ",", "proposals", ")", "# ng x np", "box_ious_argsort", "=", "np", ".", "argsort", "(", "-", "box_ious",...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
draw_predictions
Args: boxes: kx4 scores: kxC
examples/FasterRCNN/viz.py
def draw_predictions(img, boxes, scores): """ Args: boxes: kx4 scores: kxC """ if len(boxes) == 0: return img labels = scores.argmax(axis=1) scores = scores.max(axis=1) tags = ["{},{:.2f}".format(cfg.DATA.CLASS_NAMES[lb], score) for lb, score in zip(labels, scores)] ...
def draw_predictions(img, boxes, scores): """ Args: boxes: kx4 scores: kxC """ if len(boxes) == 0: return img labels = scores.argmax(axis=1) scores = scores.max(axis=1) tags = ["{},{:.2f}".format(cfg.DATA.CLASS_NAMES[lb], score) for lb, score in zip(labels, scores)] ...
[ "Args", ":", "boxes", ":", "kx4", "scores", ":", "kxC" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/viz.py#L52-L63
[ "def", "draw_predictions", "(", "img", ",", "boxes", ",", "scores", ")", ":", "if", "len", "(", "boxes", ")", "==", "0", ":", "return", "img", "labels", "=", "scores", ".", "argmax", "(", "axis", "=", "1", ")", "scores", "=", "scores", ".", "max", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
draw_final_outputs
Args: results: [DetectionResult]
examples/FasterRCNN/viz.py
def draw_final_outputs(img, results): """ Args: results: [DetectionResult] """ if len(results) == 0: return img # Display in largest to smallest order to reduce occlusion boxes = np.asarray([r.box for r in results]) areas = np_area(boxes) sorted_inds = np.argsort(-areas)...
def draw_final_outputs(img, results): """ Args: results: [DetectionResult] """ if len(results) == 0: return img # Display in largest to smallest order to reduce occlusion boxes = np.asarray([r.box for r in results]) areas = np_area(boxes) sorted_inds = np.argsort(-areas)...
[ "Args", ":", "results", ":", "[", "DetectionResult", "]" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/viz.py#L66-L91
[ "def", "draw_final_outputs", "(", "img", ",", "results", ")", ":", "if", "len", "(", "results", ")", "==", "0", ":", "return", "img", "# Display in largest to smallest order to reduce occlusion", "boxes", "=", "np", ".", "asarray", "(", "[", "r", ".", "box", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
draw_mask
Overlay a mask on top of the image. Args: im: a 3-channel uint8 image in BGR mask: a binary 1-channel image of the same size color: if None, will choose automatically
examples/FasterRCNN/viz.py
def draw_mask(im, mask, alpha=0.5, color=None): """ Overlay a mask on top of the image. Args: im: a 3-channel uint8 image in BGR mask: a binary 1-channel image of the same size color: if None, will choose automatically """ if color is None: color = PALETTE_RGB[np.ran...
def draw_mask(im, mask, alpha=0.5, color=None): """ Overlay a mask on top of the image. Args: im: a 3-channel uint8 image in BGR mask: a binary 1-channel image of the same size color: if None, will choose automatically """ if color is None: color = PALETTE_RGB[np.ran...
[ "Overlay", "a", "mask", "on", "top", "of", "the", "image", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/viz.py#L94-L108
[ "def", "draw_mask", "(", "im", ",", "mask", ",", "alpha", "=", "0.5", ",", "color", "=", "None", ")", ":", "if", "color", "is", "None", ":", "color", "=", "PALETTE_RGB", "[", "np", ".", "random", ".", "choice", "(", "len", "(", "PALETTE_RGB", ")", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
send_dataflow_zmq
Run DataFlow and send data to a ZMQ socket addr. It will serialize and send each datapoint to this address with a PUSH socket. This function never returns. Args: df (DataFlow): Will infinitely loop over the DataFlow. addr: a ZMQ socket endpoint. hwm (int): ZMQ high-water mark (buffe...
tensorpack/dataflow/remote.py
def send_dataflow_zmq(df, addr, hwm=50, format=None, bind=False): """ Run DataFlow and send data to a ZMQ socket addr. It will serialize and send each datapoint to this address with a PUSH socket. This function never returns. Args: df (DataFlow): Will infinitely loop over the DataFlow. ...
def send_dataflow_zmq(df, addr, hwm=50, format=None, bind=False): """ Run DataFlow and send data to a ZMQ socket addr. It will serialize and send each datapoint to this address with a PUSH socket. This function never returns. Args: df (DataFlow): Will infinitely loop over the DataFlow. ...
[ "Run", "DataFlow", "and", "send", "data", "to", "a", "ZMQ", "socket", "addr", ".", "It", "will", "serialize", "and", "send", "each", "datapoint", "to", "this", "address", "with", "a", "PUSH", "socket", ".", "This", "function", "never", "returns", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/remote.py#L26-L85
[ "def", "send_dataflow_zmq", "(", "df", ",", "addr", ",", "hwm", "=", "50", ",", "format", "=", "None", ",", "bind", "=", "False", ")", ":", "assert", "format", "in", "[", "None", ",", "'zmq_op'", ",", "'zmq_ops'", "]", "if", "format", "is", "None", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
dump_dataflow_to_process_queue
Convert a DataFlow to a :class:`multiprocessing.Queue`. The DataFlow will only be reset in the spawned process. Args: df (DataFlow): the DataFlow to dump. size (int): size of the queue nr_consumer (int): number of consumer of the queue. The producer will add this many of ``D...
tensorpack/dataflow/remote.py
def dump_dataflow_to_process_queue(df, size, nr_consumer): """ Convert a DataFlow to a :class:`multiprocessing.Queue`. The DataFlow will only be reset in the spawned process. Args: df (DataFlow): the DataFlow to dump. size (int): size of the queue nr_consumer (int): number of co...
def dump_dataflow_to_process_queue(df, size, nr_consumer): """ Convert a DataFlow to a :class:`multiprocessing.Queue`. The DataFlow will only be reset in the spawned process. Args: df (DataFlow): the DataFlow to dump. size (int): size of the queue nr_consumer (int): number of co...
[ "Convert", "a", "DataFlow", "to", "a", ":", "class", ":", "multiprocessing", ".", "Queue", ".", "The", "DataFlow", "will", "only", "be", "reset", "in", "the", "spawned", "process", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/remote.py#L164-L200
[ "def", "dump_dataflow_to_process_queue", "(", "df", ",", "size", ",", "nr_consumer", ")", ":", "q", "=", "mp", ".", "Queue", "(", "size", ")", "class", "EnqueProc", "(", "mp", ".", "Process", ")", ":", "def", "__init__", "(", "self", ",", "df", ",", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
AtariPlayer._grab_raw_image
:returns: the current 3-channel image
examples/DeepQNetwork/atari.py
def _grab_raw_image(self): """ :returns: the current 3-channel image """ m = self.ale.getScreenRGB() return m.reshape((self.height, self.width, 3))
def _grab_raw_image(self): """ :returns: the current 3-channel image """ m = self.ale.getScreenRGB() return m.reshape((self.height, self.width, 3))
[ ":", "returns", ":", "the", "current", "3", "-", "channel", "image" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DeepQNetwork/atari.py#L103-L108
[ "def", "_grab_raw_image", "(", "self", ")", ":", "m", "=", "self", ".", "ale", ".", "getScreenRGB", "(", ")", "return", "m", ".", "reshape", "(", "(", "self", ".", "height", ",", "self", ".", "width", ",", "3", ")", ")" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
AtariPlayer._current_state
:returns: a gray-scale (h, w) uint8 image
examples/DeepQNetwork/atari.py
def _current_state(self): """ :returns: a gray-scale (h, w) uint8 image """ ret = self._grab_raw_image() # max-pooled over the last screen ret = np.maximum(ret, self.last_raw_screen) if self.viz: if isinstance(self.viz, float): cv2.imsh...
def _current_state(self): """ :returns: a gray-scale (h, w) uint8 image """ ret = self._grab_raw_image() # max-pooled over the last screen ret = np.maximum(ret, self.last_raw_screen) if self.viz: if isinstance(self.viz, float): cv2.imsh...
[ ":", "returns", ":", "a", "gray", "-", "scale", "(", "h", "w", ")", "uint8", "image" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DeepQNetwork/atari.py#L110-L124
[ "def", "_current_state", "(", "self", ")", ":", "ret", "=", "self", ".", "_grab_raw_image", "(", ")", "# max-pooled over the last screen", "ret", "=", "np", ".", "maximum", "(", "ret", ",", "self", ".", "last_raw_screen", ")", "if", "self", ".", "viz", ":"...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
clip_boxes
Args: boxes: nx4, xyxy window: [h, w]
examples/FasterRCNN/model_box.py
def clip_boxes(boxes, window, name=None): """ Args: boxes: nx4, xyxy window: [h, w] """ boxes = tf.maximum(boxes, 0.0) m = tf.tile(tf.reverse(window, [0]), [2]) # (4,) boxes = tf.minimum(boxes, tf.cast(m, tf.float32), name=name) return boxes
def clip_boxes(boxes, window, name=None): """ Args: boxes: nx4, xyxy window: [h, w] """ boxes = tf.maximum(boxes, 0.0) m = tf.tile(tf.reverse(window, [0]), [2]) # (4,) boxes = tf.minimum(boxes, tf.cast(m, tf.float32), name=name) return boxes
[ "Args", ":", "boxes", ":", "nx4", "xyxy", "window", ":", "[", "h", "w", "]" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_box.py#L14-L23
[ "def", "clip_boxes", "(", "boxes", ",", "window", ",", "name", "=", "None", ")", ":", "boxes", "=", "tf", ".", "maximum", "(", "boxes", ",", "0.0", ")", "m", "=", "tf", ".", "tile", "(", "tf", ".", "reverse", "(", "window", ",", "[", "0", "]", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
decode_bbox_target
Args: box_predictions: (..., 4), logits anchors: (..., 4), floatbox. Must have the same shape Returns: box_decoded: (..., 4), float32. With the same shape.
examples/FasterRCNN/model_box.py
def decode_bbox_target(box_predictions, anchors): """ Args: box_predictions: (..., 4), logits anchors: (..., 4), floatbox. Must have the same shape Returns: box_decoded: (..., 4), float32. With the same shape. """ orig_shape = tf.shape(anchors) box_pred_txtytwth = tf.res...
def decode_bbox_target(box_predictions, anchors): """ Args: box_predictions: (..., 4), logits anchors: (..., 4), floatbox. Must have the same shape Returns: box_decoded: (..., 4), float32. With the same shape. """ orig_shape = tf.shape(anchors) box_pred_txtytwth = tf.res...
[ "Args", ":", "box_predictions", ":", "(", "...", "4", ")", "logits", "anchors", ":", "(", "...", "4", ")", "floatbox", ".", "Must", "have", "the", "same", "shape" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_box.py#L27-L52
[ "def", "decode_bbox_target", "(", "box_predictions", ",", "anchors", ")", ":", "orig_shape", "=", "tf", ".", "shape", "(", "anchors", ")", "box_pred_txtytwth", "=", "tf", ".", "reshape", "(", "box_predictions", ",", "(", "-", "1", ",", "2", ",", "2", ")"...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
encode_bbox_target
Args: boxes: (..., 4), float32 anchors: (..., 4), float32 Returns: box_encoded: (..., 4), float32 with the same shape.
examples/FasterRCNN/model_box.py
def encode_bbox_target(boxes, anchors): """ Args: boxes: (..., 4), float32 anchors: (..., 4), float32 Returns: box_encoded: (..., 4), float32 with the same shape. """ anchors_x1y1x2y2 = tf.reshape(anchors, (-1, 2, 2)) anchors_x1y1, anchors_x2y2 = tf.split(anchors_x1y1x2y...
def encode_bbox_target(boxes, anchors): """ Args: boxes: (..., 4), float32 anchors: (..., 4), float32 Returns: box_encoded: (..., 4), float32 with the same shape. """ anchors_x1y1x2y2 = tf.reshape(anchors, (-1, 2, 2)) anchors_x1y1, anchors_x2y2 = tf.split(anchors_x1y1x2y...
[ "Args", ":", "boxes", ":", "(", "...", "4", ")", "float32", "anchors", ":", "(", "...", "4", ")", "float32" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_box.py#L56-L79
[ "def", "encode_bbox_target", "(", "boxes", ",", "anchors", ")", ":", "anchors_x1y1x2y2", "=", "tf", ".", "reshape", "(", "anchors", ",", "(", "-", "1", ",", "2", ",", "2", ")", ")", "anchors_x1y1", ",", "anchors_x2y2", "=", "tf", ".", "split", "(", "...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
crop_and_resize
Aligned version of tf.image.crop_and_resize, following our definition of floating point boxes. Args: image: NCHW boxes: nx4, x1y1x2y2 box_ind: (n,) crop_size (int): Returns: n,C,size,size
examples/FasterRCNN/model_box.py
def crop_and_resize(image, boxes, box_ind, crop_size, pad_border=True): """ Aligned version of tf.image.crop_and_resize, following our definition of floating point boxes. Args: image: NCHW boxes: nx4, x1y1x2y2 box_ind: (n,) crop_size (int): Returns: n,C,size,size...
def crop_and_resize(image, boxes, box_ind, crop_size, pad_border=True): """ Aligned version of tf.image.crop_and_resize, following our definition of floating point boxes. Args: image: NCHW boxes: nx4, x1y1x2y2 box_ind: (n,) crop_size (int): Returns: n,C,size,size...
[ "Aligned", "version", "of", "tf", ".", "image", ".", "crop_and_resize", "following", "our", "definition", "of", "floating", "point", "boxes", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_box.py#L83-L153
[ "def", "crop_and_resize", "(", "image", ",", "boxes", ",", "box_ind", ",", "crop_size", ",", "pad_border", "=", "True", ")", ":", "assert", "isinstance", "(", "crop_size", ",", "int", ")", ",", "crop_size", "boxes", "=", "tf", ".", "stop_gradient", "(", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
roi_align
Args: featuremap: 1xCxHxW boxes: Nx4 floatbox resolution: output spatial resolution Returns: NxCx res x res
examples/FasterRCNN/model_box.py
def roi_align(featuremap, boxes, resolution): """ Args: featuremap: 1xCxHxW boxes: Nx4 floatbox resolution: output spatial resolution Returns: NxCx res x res """ # sample 4 locations per roi bin ret = crop_and_resize( featuremap, boxes, tf.zeros([...
def roi_align(featuremap, boxes, resolution): """ Args: featuremap: 1xCxHxW boxes: Nx4 floatbox resolution: output spatial resolution Returns: NxCx res x res """ # sample 4 locations per roi bin ret = crop_and_resize( featuremap, boxes, tf.zeros([...
[ "Args", ":", "featuremap", ":", "1xCxHxW", "boxes", ":", "Nx4", "floatbox", "resolution", ":", "output", "spatial", "resolution" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_box.py#L157-L173
[ "def", "roi_align", "(", "featuremap", ",", "boxes", ",", "resolution", ")", ":", "# sample 4 locations per roi bin", "ret", "=", "crop_and_resize", "(", "featuremap", ",", "boxes", ",", "tf", ".", "zeros", "(", "[", "tf", ".", "shape", "(", "boxes", ")", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
RPNAnchors.narrow_to
Slice anchors to the spatial size of this featuremap.
examples/FasterRCNN/model_box.py
def narrow_to(self, featuremap): """ Slice anchors to the spatial size of this featuremap. """ shape2d = tf.shape(featuremap)[2:] # h,w slice3d = tf.concat([shape2d, [-1]], axis=0) slice4d = tf.concat([shape2d, [-1, -1]], axis=0) boxes = tf.slice(self.boxes, [0, ...
def narrow_to(self, featuremap): """ Slice anchors to the spatial size of this featuremap. """ shape2d = tf.shape(featuremap)[2:] # h,w slice3d = tf.concat([shape2d, [-1]], axis=0) slice4d = tf.concat([shape2d, [-1, -1]], axis=0) boxes = tf.slice(self.boxes, [0, ...
[ "Slice", "anchors", "to", "the", "spatial", "size", "of", "this", "featuremap", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_box.py#L189-L199
[ "def", "narrow_to", "(", "self", ",", "featuremap", ")", ":", "shape2d", "=", "tf", ".", "shape", "(", "featuremap", ")", "[", "2", ":", "]", "# h,w", "slice3d", "=", "tf", ".", "concat", "(", "[", "shape2d", ",", "[", "-", "1", "]", "]", ",", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
colorize
img: bgr, [0,255] heatmap: [0,1]
examples/CaffeModels/load-cpm.py
def colorize(img, heatmap): """ img: bgr, [0,255] heatmap: [0,1] """ heatmap = viz.intensity_to_rgb(heatmap, cmap='jet')[:, :, ::-1] return img * 0.5 + heatmap * 0.5
def colorize(img, heatmap): """ img: bgr, [0,255] heatmap: [0,1] """ heatmap = viz.intensity_to_rgb(heatmap, cmap='jet')[:, :, ::-1] return img * 0.5 + heatmap * 0.5
[ "img", ":", "bgr", "[", "0", "255", "]", "heatmap", ":", "[", "0", "1", "]" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/CaffeModels/load-cpm.py#L27-L32
[ "def", "colorize", "(", "img", ",", "heatmap", ")", ":", "heatmap", "=", "viz", ".", "intensity_to_rgb", "(", "heatmap", ",", "cmap", "=", "'jet'", ")", "[", ":", ",", ":", ",", ":", ":", "-", "1", "]", "return", "img", "*", "0.5", "+", "heatmap"...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
Rotation._get_augment_params
The correct center is shape*0.5-0.5. This can be verified by: SHAPE = 7 arr = np.random.rand(SHAPE, SHAPE) orig = arr c = SHAPE * 0.5 - 0.5 c = (c, c) for k in range(4): mat = cv2.getRotationMatrix2D(c, 90, 1) arr = cv2.warpAffine(arr, mat, arr.sh...
tensorpack/dataflow/imgaug/geometry.py
def _get_augment_params(self, img): center = img.shape[1::-1] * self._rand_range( self.center_range[0], self.center_range[1], (2,)) deg = self._rand_range(-self.max_deg, self.max_deg) if self.step_deg: deg = deg // self.step_deg * self.step_deg """ The cor...
def _get_augment_params(self, img): center = img.shape[1::-1] * self._rand_range( self.center_range[0], self.center_range[1], (2,)) deg = self._rand_range(-self.max_deg, self.max_deg) if self.step_deg: deg = deg // self.step_deg * self.step_deg """ The cor...
[ "The", "correct", "center", "is", "shape", "*", "0", ".", "5", "-", "0", ".", "5", ".", "This", "can", "be", "verified", "by", ":" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/imgaug/geometry.py#L64-L86
[ "def", "_get_augment_params", "(", "self", ",", "img", ")", ":", "center", "=", "img", ".", "shape", "[", "1", ":", ":", "-", "1", "]", "*", "self", ".", "_rand_range", "(", "self", ".", "center_range", "[", "0", "]", ",", "self", ".", "center_rang...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
RotationAndCropValid.largest_rotated_rect
Get largest rectangle after rotation. http://stackoverflow.com/questions/16702966/rotate-image-and-crop-out-black-borders
tensorpack/dataflow/imgaug/geometry.py
def largest_rotated_rect(w, h, angle): """ Get largest rectangle after rotation. http://stackoverflow.com/questions/16702966/rotate-image-and-crop-out-black-borders """ angle = angle / 180.0 * math.pi if w <= 0 or h <= 0: return 0, 0 width_is_longer =...
def largest_rotated_rect(w, h, angle): """ Get largest rectangle after rotation. http://stackoverflow.com/questions/16702966/rotate-image-and-crop-out-black-borders """ angle = angle / 180.0 * math.pi if w <= 0 or h <= 0: return 0, 0 width_is_longer =...
[ "Get", "largest", "rectangle", "after", "rotation", ".", "http", ":", "//", "stackoverflow", ".", "com", "/", "questions", "/", "16702966", "/", "rotate", "-", "image", "-", "and", "-", "crop", "-", "out", "-", "black", "-", "borders" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/imgaug/geometry.py#L128-L152
[ "def", "largest_rotated_rect", "(", "w", ",", "h", ",", "angle", ")", ":", "angle", "=", "angle", "/", "180.0", "*", "math", ".", "pi", "if", "w", "<=", "0", "or", "h", "<=", "0", ":", "return", "0", ",", "0", "width_is_longer", "=", "w", ">=", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
map_arg
Apply a mapping on certain argument before calling the original function. Args: maps (dict): {argument_name: map_func}
tensorpack/utils/argtools.py
def map_arg(**maps): """ Apply a mapping on certain argument before calling the original function. Args: maps (dict): {argument_name: map_func} """ def deco(func): @functools.wraps(func) def wrapper(*args, **kwargs): if six.PY2: argmap = inspect.g...
def map_arg(**maps): """ Apply a mapping on certain argument before calling the original function. Args: maps (dict): {argument_name: map_func} """ def deco(func): @functools.wraps(func) def wrapper(*args, **kwargs): if six.PY2: argmap = inspect.g...
[ "Apply", "a", "mapping", "on", "certain", "argument", "before", "calling", "the", "original", "function", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/argtools.py#L19-L40
[ "def", "map_arg", "(", "*", "*", "maps", ")", ":", "def", "deco", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "six", ".", "PY2", ":", "a...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
graph_memoized
Like memoized, but keep one cache per default graph.
tensorpack/utils/argtools.py
def graph_memoized(func): """ Like memoized, but keep one cache per default graph. """ # TODO it keeps the graph alive from ..compat import tfv1 GRAPH_ARG_NAME = '__IMPOSSIBLE_NAME_FOR_YOU__' @memoized def func_with_graph_arg(*args, **kwargs): kwargs.pop(GRAPH_ARG_NAME) ...
def graph_memoized(func): """ Like memoized, but keep one cache per default graph. """ # TODO it keeps the graph alive from ..compat import tfv1 GRAPH_ARG_NAME = '__IMPOSSIBLE_NAME_FOR_YOU__' @memoized def func_with_graph_arg(*args, **kwargs): kwargs.pop(GRAPH_ARG_NAME) ...
[ "Like", "memoized", "but", "keep", "one", "cache", "per", "default", "graph", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/argtools.py#L49-L69
[ "def", "graph_memoized", "(", "func", ")", ":", "# TODO it keeps the graph alive", "from", ".", ".", "compat", "import", "tfv1", "GRAPH_ARG_NAME", "=", "'__IMPOSSIBLE_NAME_FOR_YOU__'", "@", "memoized", "def", "func_with_graph_arg", "(", "*", "args", ",", "*", "*", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
memoized_ignoreargs
A decorator. It performs memoization ignoring the arguments used to call the function.
tensorpack/utils/argtools.py
def memoized_ignoreargs(func): """ A decorator. It performs memoization ignoring the arguments used to call the function. """ def wrapper(*args, **kwargs): if func not in _MEMOIZED_NOARGS: res = func(*args, **kwargs) _MEMOIZED_NOARGS[func] = res return res...
def memoized_ignoreargs(func): """ A decorator. It performs memoization ignoring the arguments used to call the function. """ def wrapper(*args, **kwargs): if func not in _MEMOIZED_NOARGS: res = func(*args, **kwargs) _MEMOIZED_NOARGS[func] = res return res...
[ "A", "decorator", ".", "It", "performs", "memoization", "ignoring", "the", "arguments", "used", "to", "call", "the", "function", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/argtools.py#L75-L86
[ "def", "memoized_ignoreargs", "(", "func", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "func", "not", "in", "_MEMOIZED_NOARGS", ":", "res", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "_ME...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
shape2d
Ensure a 2D shape. Args: a: a int or tuple/list of length 2 Returns: list: of length 2. if ``a`` is a int, return ``[a, a]``.
tensorpack/utils/argtools.py
def shape2d(a): """ Ensure a 2D shape. Args: a: a int or tuple/list of length 2 Returns: list: of length 2. if ``a`` is a int, return ``[a, a]``. """ if type(a) == int: return [a, a] if isinstance(a, (list, tuple)): assert len(a) == 2 return list(a) ...
def shape2d(a): """ Ensure a 2D shape. Args: a: a int or tuple/list of length 2 Returns: list: of length 2. if ``a`` is a int, return ``[a, a]``. """ if type(a) == int: return [a, a] if isinstance(a, (list, tuple)): assert len(a) == 2 return list(a) ...
[ "Ensure", "a", "2D", "shape", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/argtools.py#L89-L104
[ "def", "shape2d", "(", "a", ")", ":", "if", "type", "(", "a", ")", "==", "int", ":", "return", "[", "a", ",", "a", "]", "if", "isinstance", "(", "a", ",", "(", "list", ",", "tuple", ")", ")", ":", "assert", "len", "(", "a", ")", "==", "2", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
shape4d
Ensuer a 4D shape, to use with 4D symbolic functions. Args: a: a int or tuple/list of length 2 Returns: list: of length 4. if ``a`` is a int, return ``[1, a, a, 1]`` or ``[1, 1, a, a]`` depending on data_format.
tensorpack/utils/argtools.py
def shape4d(a, data_format='NHWC'): """ Ensuer a 4D shape, to use with 4D symbolic functions. Args: a: a int or tuple/list of length 2 Returns: list: of length 4. if ``a`` is a int, return ``[1, a, a, 1]`` or ``[1, 1, a, a]`` depending on data_format. """ s2d = shap...
def shape4d(a, data_format='NHWC'): """ Ensuer a 4D shape, to use with 4D symbolic functions. Args: a: a int or tuple/list of length 2 Returns: list: of length 4. if ``a`` is a int, return ``[1, a, a, 1]`` or ``[1, 1, a, a]`` depending on data_format. """ s2d = shap...
[ "Ensuer", "a", "4D", "shape", "to", "use", "with", "4D", "symbolic", "functions", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/argtools.py#L118-L133
[ "def", "shape4d", "(", "a", ",", "data_format", "=", "'NHWC'", ")", ":", "s2d", "=", "shape2d", "(", "a", ")", "if", "get_data_format", "(", "data_format", ",", "False", ")", "==", "'NHWC'", ":", "return", "[", "1", "]", "+", "s2d", "+", "[", "1", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
call_only_once
Decorate a method or property of a class, so that this method can only be called once for every instance. Calling it more than once will result in exception.
tensorpack/utils/argtools.py
def call_only_once(func): """ Decorate a method or property of a class, so that this method can only be called once for every instance. Calling it more than once will result in exception. """ @functools.wraps(func) def wrapper(*args, **kwargs): self = args[0] # cannot use has...
def call_only_once(func): """ Decorate a method or property of a class, so that this method can only be called once for every instance. Calling it more than once will result in exception. """ @functools.wraps(func) def wrapper(*args, **kwargs): self = args[0] # cannot use has...
[ "Decorate", "a", "method", "or", "property", "of", "a", "class", "so", "that", "this", "method", "can", "only", "be", "called", "once", "for", "every", "instance", ".", "Calling", "it", "more", "than", "once", "will", "result", "in", "exception", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/argtools.py#L149-L178
[ "def", "call_only_once", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", "=", "args", "[", "0", "]", "# cannot use hasattr here, because hasattr tries t...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
memoized_method
A decorator that performs memoization on methods. It stores the cache on the object instance itself.
tensorpack/utils/argtools.py
def memoized_method(func): """ A decorator that performs memoization on methods. It stores the cache on the object instance itself. """ @functools.wraps(func) def wrapper(*args, **kwargs): self = args[0] assert func.__name__ in dir(self), "memoized_method can only be used on method!...
def memoized_method(func): """ A decorator that performs memoization on methods. It stores the cache on the object instance itself. """ @functools.wraps(func) def wrapper(*args, **kwargs): self = args[0] assert func.__name__ in dir(self), "memoized_method can only be used on method!...
[ "A", "decorator", "that", "performs", "memoization", "on", "methods", ".", "It", "stores", "the", "cache", "on", "the", "object", "instance", "itself", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/argtools.py#L181-L204
[ "def", "memoized_method", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", "=", "args", "[", "0", "]", "assert", "func", ".", "__name__", "in", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f