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
auto_reuse_variable_scope
A decorator which automatically reuses the current variable scope if the function has been called with the same variable scope before. Example: .. code-block:: python @auto_reuse_variable_scope def myfunc(x): return tf.layers.conv2d(x, 128, 3) myfunc(x1) # will inher...
tensorpack/tfutils/scope_utils.py
def auto_reuse_variable_scope(func): """ A decorator which automatically reuses the current variable scope if the function has been called with the same variable scope before. Example: .. code-block:: python @auto_reuse_variable_scope def myfunc(x): return tf.layers.co...
def auto_reuse_variable_scope(func): """ A decorator which automatically reuses the current variable scope if the function has been called with the same variable scope before. Example: .. code-block:: python @auto_reuse_variable_scope def myfunc(x): return tf.layers.co...
[ "A", "decorator", "which", "automatically", "reuses", "the", "current", "variable", "scope", "if", "the", "function", "has", "been", "called", "with", "the", "same", "variable", "scope", "before", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/scope_utils.py#L15-L54
[ "def", "auto_reuse_variable_scope", "(", "func", ")", ":", "used_scope", "=", "set", "(", ")", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "scope", "=", "tf", ".", "get_vari...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
under_name_scope
Args: name_scope(str): the default scope to use. If None, will use the name of the function. Returns: A decorator which makes the function run under a name scope. The name scope is obtained by the following: 1. The 'name_scope' keyword argument when the decorated function is called....
tensorpack/tfutils/scope_utils.py
def under_name_scope(name_scope=None): """ Args: name_scope(str): the default scope to use. If None, will use the name of the function. Returns: A decorator which makes the function run under a name scope. The name scope is obtained by the following: 1. The 'name_scope' keyw...
def under_name_scope(name_scope=None): """ Args: name_scope(str): the default scope to use. If None, will use the name of the function. Returns: A decorator which makes the function run under a name scope. The name scope is obtained by the following: 1. The 'name_scope' keyw...
[ "Args", ":", "name_scope", "(", "str", ")", ":", "the", "default", "scope", "to", "use", ".", "If", "None", "will", "use", "the", "name", "of", "the", "function", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/scope_utils.py#L57-L96
[ "def", "under_name_scope", "(", "name_scope", "=", "None", ")", ":", "def", "_impl", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "scopename", "=", "...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
under_variable_scope
Returns: A decorator which makes the function happen under a variable scope, which is named by the function itself. Example: .. code-block:: python @under_variable_scope() def mid_level(x): with argscope(Conv2D, kernel_shape=3, nl=BNReLU): x = Conv2...
tensorpack/tfutils/scope_utils.py
def under_variable_scope(): """ Returns: A decorator which makes the function happen under a variable scope, which is named by the function itself. Example: .. code-block:: python @under_variable_scope() def mid_level(x): with argscope(Conv2D, kernel_shape=...
def under_variable_scope(): """ Returns: A decorator which makes the function happen under a variable scope, which is named by the function itself. Example: .. code-block:: python @under_variable_scope() def mid_level(x): with argscope(Conv2D, kernel_shape=...
[ "Returns", ":", "A", "decorator", "which", "makes", "the", "function", "happen", "under", "a", "variable", "scope", "which", "is", "named", "by", "the", "function", "itself", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/scope_utils.py#L99-L125
[ "def", "under_variable_scope", "(", ")", ":", "def", "_impl", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "name", "=", "func", ".", "__name__", "wit...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
cached_name_scope
Return a context which either opens and caches a new name scope, or reenter an existing one. Args: top_level(bool): if True, the name scope will always be top-level. It will not be nested under any existing name scope of the caller.
tensorpack/tfutils/scope_utils.py
def cached_name_scope(name, top_level=True): """ Return a context which either opens and caches a new name scope, or reenter an existing one. Args: top_level(bool): if True, the name scope will always be top-level. It will not be nested under any existing name scope of the caller. ...
def cached_name_scope(name, top_level=True): """ Return a context which either opens and caches a new name scope, or reenter an existing one. Args: top_level(bool): if True, the name scope will always be top-level. It will not be nested under any existing name scope of the caller. ...
[ "Return", "a", "context", "which", "either", "opens", "and", "caches", "a", "new", "name", "scope", "or", "reenter", "an", "existing", "one", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/scope_utils.py#L136-L151
[ "def", "cached_name_scope", "(", "name", ",", "top_level", "=", "True", ")", ":", "if", "not", "top_level", ":", "current_ns", "=", "tf", ".", "get_default_graph", "(", ")", ".", "get_name_scope", "(", ")", "if", "current_ns", ":", "name", "=", "current_ns...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
DataParallelBuilder._check_grad_list
Args: grad_list: list of list of tuples, shape is Ngpu x Nvar x 2
tensorpack/graph_builder/training.py
def _check_grad_list(grad_list): """ Args: grad_list: list of list of tuples, shape is Ngpu x Nvar x 2 """ nvars = [len(k) for k in grad_list] def basename(x): return re.sub('tower[0-9]+/', '', x.op.name) if len(set(nvars)) != 1: name...
def _check_grad_list(grad_list): """ Args: grad_list: list of list of tuples, shape is Ngpu x Nvar x 2 """ nvars = [len(k) for k in grad_list] def basename(x): return re.sub('tower[0-9]+/', '', x.op.name) if len(set(nvars)) != 1: name...
[ "Args", ":", "grad_list", ":", "list", "of", "list", "of", "tuples", "shape", "is", "Ngpu", "x", "Nvar", "x", "2" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/training.py#L57-L75
[ "def", "_check_grad_list", "(", "grad_list", ")", ":", "nvars", "=", "[", "len", "(", "k", ")", "for", "k", "in", "grad_list", "]", "def", "basename", "(", "x", ")", ":", "return", "re", ".", "sub", "(", "'tower[0-9]+/'", ",", "''", ",", "x", ".", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
DataParallelBuilder.call_for_each_tower
Run `func` on all GPUs (towers) and return the results. Args: towers (list[int]): a list of GPU id. func: a lambda to be called inside each tower devices: a list of devices to be used. By default will use '/gpu:{tower}' use_vs (list[bool]): list of use_vs to pass...
tensorpack/graph_builder/training.py
def call_for_each_tower( towers, func, devices=None, use_vs=None): """ Run `func` on all GPUs (towers) and return the results. Args: towers (list[int]): a list of GPU id. func: a lambda to be called inside each tower devices: a list of devices to ...
def call_for_each_tower( towers, func, devices=None, use_vs=None): """ Run `func` on all GPUs (towers) and return the results. Args: towers (list[int]): a list of GPU id. func: a lambda to be called inside each tower devices: a list of devices to ...
[ "Run", "func", "on", "all", "GPUs", "(", "towers", ")", "and", "return", "the", "results", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/training.py#L78-L118
[ "def", "call_for_each_tower", "(", "towers", ",", "func", ",", "devices", "=", "None", ",", "use_vs", "=", "None", ")", ":", "ret", "=", "[", "]", "if", "devices", "is", "not", "None", ":", "assert", "len", "(", "devices", ")", "==", "len", "(", "t...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
SyncMultiGPUParameterServerBuilder.build
Reduce the gradients, apply them with the optimizer, and set self.grads to a list of (g, v), containing the averaged gradients. Args: grad_list ([[(grad, var), ...], ...]): #GPU lists to be reduced. Each is the gradients computed on each GPU. get_opt_fn (-> tf.train.Optimizer): ...
tensorpack/graph_builder/training.py
def build(self, grad_list, get_opt_fn): """ Reduce the gradients, apply them with the optimizer, and set self.grads to a list of (g, v), containing the averaged gradients. Args: grad_list ([[(grad, var), ...], ...]): #GPU lists to be reduced. Each is the gradients computed o...
def build(self, grad_list, get_opt_fn): """ Reduce the gradients, apply them with the optimizer, and set self.grads to a list of (g, v), containing the averaged gradients. Args: grad_list ([[(grad, var), ...], ...]): #GPU lists to be reduced. Each is the gradients computed o...
[ "Reduce", "the", "gradients", "apply", "them", "with", "the", "optimizer", "and", "set", "self", ".", "grads", "to", "a", "list", "of", "(", "g", "v", ")", "containing", "the", "averaged", "gradients", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/training.py#L161-L190
[ "def", "build", "(", "self", ",", "grad_list", ",", "get_opt_fn", ")", ":", "assert", "len", "(", "grad_list", ")", "==", "len", "(", "self", ".", "towers", ")", "DataParallelBuilder", ".", "_check_grad_list", "(", "grad_list", ")", "# debug tower performance ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
SyncMultiGPUReplicatedBuilder.call_for_each_tower
Call the function `tower_fn` under :class:`TowerContext` for each tower. Returns: a list, contains the return values of `tower_fn` on each tower.
tensorpack/graph_builder/training.py
def call_for_each_tower(self, tower_fn): """ Call the function `tower_fn` under :class:`TowerContext` for each tower. Returns: a list, contains the return values of `tower_fn` on each tower. """ # if tower_fn returns [(grad, var), ...], this returns #GPU x #VAR x 2 ...
def call_for_each_tower(self, tower_fn): """ Call the function `tower_fn` under :class:`TowerContext` for each tower. Returns: a list, contains the return values of `tower_fn` on each tower. """ # if tower_fn returns [(grad, var), ...], this returns #GPU x #VAR x 2 ...
[ "Call", "the", "function", "tower_fn", "under", ":", "class", ":", "TowerContext", "for", "each", "tower", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/training.py#L214-L226
[ "def", "call_for_each_tower", "(", "self", ",", "tower_fn", ")", ":", "# if tower_fn returns [(grad, var), ...], this returns #GPU x #VAR x 2", "return", "DataParallelBuilder", ".", "build_on_towers", "(", "self", ".", "towers", ",", "tower_fn", ",", "# use no variable scope ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
SyncMultiGPUReplicatedBuilder.build
Reduce the gradients, apply them with the optimizer, and set self.grads to #GPU number of lists of (g, v), containing the all-reduced gradients on each device. Args: grad_list ([[(grad, var), ...], ...]): #GPU lists to be reduced. Each is the gradients computed on each GPU. get_...
tensorpack/graph_builder/training.py
def build(self, grad_list, get_opt_fn): """ Reduce the gradients, apply them with the optimizer, and set self.grads to #GPU number of lists of (g, v), containing the all-reduced gradients on each device. Args: grad_list ([[(grad, var), ...], ...]): #GPU lists to be reduced. ...
def build(self, grad_list, get_opt_fn): """ Reduce the gradients, apply them with the optimizer, and set self.grads to #GPU number of lists of (g, v), containing the all-reduced gradients on each device. Args: grad_list ([[(grad, var), ...], ...]): #GPU lists to be reduced. ...
[ "Reduce", "the", "gradients", "apply", "them", "with", "the", "optimizer", "and", "set", "self", ".", "grads", "to", "#GPU", "number", "of", "lists", "of", "(", "g", "v", ")", "containing", "the", "all", "-", "reduced", "gradients", "on", "each", "device...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/training.py#L228-L305
[ "def", "build", "(", "self", ",", "grad_list", ",", "get_opt_fn", ")", ":", "assert", "len", "(", "grad_list", ")", "==", "len", "(", "self", ".", "towers", ")", "raw_devices", "=", "[", "'/gpu:{}'", ".", "format", "(", "k", ")", "for", "k", "in", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
SyncMultiGPUReplicatedBuilder.get_post_init_ops
Copy values of variables on GPU 0 to other GPUs.
tensorpack/graph_builder/training.py
def get_post_init_ops(): """ Copy values of variables on GPU 0 to other GPUs. """ # literally all variables, because it's better to sync optimizer-internal variables as well all_vars = tf.global_variables() + tf.local_variables() var_by_name = dict([(v.name, v) for v in a...
def get_post_init_ops(): """ Copy values of variables on GPU 0 to other GPUs. """ # literally all variables, because it's better to sync optimizer-internal variables as well all_vars = tf.global_variables() + tf.local_variables() var_by_name = dict([(v.name, v) for v in a...
[ "Copy", "values", "of", "variables", "on", "GPU", "0", "to", "other", "GPUs", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/training.py#L309-L349
[ "def", "get_post_init_ops", "(", ")", ":", "# literally all variables, because it's better to sync optimizer-internal variables as well", "all_vars", "=", "tf", ".", "global_variables", "(", ")", "+", "tf", ".", "local_variables", "(", ")", "var_by_name", "=", "dict", "("...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
AsyncMultiGPUBuilder.call_for_each_tower
Call the function `tower_fn` under :class:`TowerContext` for each tower. Returns: a list, contains the return values of `tower_fn` on each tower.
tensorpack/graph_builder/training.py
def call_for_each_tower(self, tower_fn): """ Call the function `tower_fn` under :class:`TowerContext` for each tower. Returns: a list, contains the return values of `tower_fn` on each tower. """ ps_device = 'cpu' if len(self.towers) >= 4 else 'gpu' raw_devic...
def call_for_each_tower(self, tower_fn): """ Call the function `tower_fn` under :class:`TowerContext` for each tower. Returns: a list, contains the return values of `tower_fn` on each tower. """ ps_device = 'cpu' if len(self.towers) >= 4 else 'gpu' raw_devic...
[ "Call", "the", "function", "tower_fn", "under", ":", "class", ":", "TowerContext", "for", "each", "tower", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/training.py#L369-L385
[ "def", "call_for_each_tower", "(", "self", ",", "tower_fn", ")", ":", "ps_device", "=", "'cpu'", "if", "len", "(", "self", ".", "towers", ")", ">=", "4", "else", "'gpu'", "raw_devices", "=", "[", "'/gpu:{}'", ".", "format", "(", "k", ")", "for", "k", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
AsyncMultiGPUBuilder.build
Args: grad_list ([[(grad, var), ...], ...]): #GPU lists to be reduced. Each is the gradients computed on each GPU. get_opt_fn (-> tf.train.Optimizer): callable which returns an optimizer Returns: tf.Operation: the training op
tensorpack/graph_builder/training.py
def build(self, grad_list, get_opt_fn): """ Args: grad_list ([[(grad, var), ...], ...]): #GPU lists to be reduced. Each is the gradients computed on each GPU. get_opt_fn (-> tf.train.Optimizer): callable which returns an optimizer Returns: tf.Operation: the t...
def build(self, grad_list, get_opt_fn): """ Args: grad_list ([[(grad, var), ...], ...]): #GPU lists to be reduced. Each is the gradients computed on each GPU. get_opt_fn (-> tf.train.Optimizer): callable which returns an optimizer Returns: tf.Operation: the t...
[ "Args", ":", "grad_list", "(", "[[", "(", "grad", "var", ")", "...", "]", "...", "]", ")", ":", "#GPU", "lists", "to", "be", "reduced", ".", "Each", "is", "the", "gradients", "computed", "on", "each", "GPU", ".", "get_opt_fn", "(", "-", ">", "tf", ...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/training.py#L387-L416
[ "def", "build", "(", "self", ",", "grad_list", ",", "get_opt_fn", ")", ":", "assert", "len", "(", "grad_list", ")", "==", "len", "(", "self", ".", "towers", ")", "DataParallelBuilder", ".", "_check_grad_list", "(", "grad_list", ")", "if", "self", ".", "_...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
humanize_time_delta
Humanize timedelta given in seconds Args: sec (float): time difference in seconds. Must be positive. Returns: str - time difference as a readable string Example: .. code-block:: python print(humanize_time_delta(1)) # 1 second print(h...
tensorpack/utils/utils.py
def humanize_time_delta(sec): """Humanize timedelta given in seconds Args: sec (float): time difference in seconds. Must be positive. Returns: str - time difference as a readable string Example: .. code-block:: python print(humanize_time_delta(1)) ...
def humanize_time_delta(sec): """Humanize timedelta given in seconds Args: sec (float): time difference in seconds. Must be positive. Returns: str - time difference as a readable string Example: .. code-block:: python print(humanize_time_delta(1)) ...
[ "Humanize", "timedelta", "given", "in", "seconds" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/utils.py#L26-L65
[ "def", "humanize_time_delta", "(", "sec", ")", ":", "if", "sec", "<", "0", ":", "logger", ".", "warn", "(", "\"humanize_time_delta() obtains negative seconds!\"", ")", "return", "\"{:.3g} seconds\"", ".", "format", "(", "sec", ")", "if", "sec", "==", "0", ":",...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
change_env
Args: name(str), val(str): Returns: a context where the environment variable ``name`` being set to ``val``. It will be set back after the context exits.
tensorpack/utils/utils.py
def change_env(name, val): """ Args: name(str), val(str): Returns: a context where the environment variable ``name`` being set to ``val``. It will be set back after the context exits. """ oldval = os.environ.get(name, None) os.environ[name] = val yield if oldval ...
def change_env(name, val): """ Args: name(str), val(str): Returns: a context where the environment variable ``name`` being set to ``val``. It will be set back after the context exits. """ oldval = os.environ.get(name, None) os.environ[name] = val yield if oldval ...
[ "Args", ":", "name", "(", "str", ")", "val", "(", "str", ")", ":" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/utils.py#L69-L84
[ "def", "change_env", "(", "name", ",", "val", ")", ":", "oldval", "=", "os", ".", "environ", ".", "get", "(", "name", ",", "None", ")", "os", ".", "environ", "[", "name", "]", "=", "val", "yield", "if", "oldval", "is", "None", ":", "del", "os", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
get_rng
Get a good RNG seeded with time, pid and the object. Args: obj: some object to use to generate random seed. Returns: np.random.RandomState: the RNG.
tensorpack/utils/utils.py
def get_rng(obj=None): """ Get a good RNG seeded with time, pid and the object. Args: obj: some object to use to generate random seed. Returns: np.random.RandomState: the RNG. """ seed = (id(obj) + os.getpid() + int(datetime.now().strftime("%Y%m%d%H%M%S%f"))) % 42949...
def get_rng(obj=None): """ Get a good RNG seeded with time, pid and the object. Args: obj: some object to use to generate random seed. Returns: np.random.RandomState: the RNG. """ seed = (id(obj) + os.getpid() + int(datetime.now().strftime("%Y%m%d%H%M%S%f"))) % 42949...
[ "Get", "a", "good", "RNG", "seeded", "with", "time", "pid", "and", "the", "object", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/utils.py#L117-L130
[ "def", "get_rng", "(", "obj", "=", "None", ")", ":", "seed", "=", "(", "id", "(", "obj", ")", "+", "os", ".", "getpid", "(", ")", "+", "int", "(", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "\"%Y%m%d%H%M%S%f\"", ")", ")", ")", "%",...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
execute_only_once
Each called in the code to this function is guaranteed to return True the first time and False afterwards. Returns: bool: whether this is the first time this function gets called from this line of code. Example: .. code-block:: python if execute_only_once(): # ...
tensorpack/utils/utils.py
def execute_only_once(): """ Each called in the code to this function is guaranteed to return True the first time and False afterwards. Returns: bool: whether this is the first time this function gets called from this line of code. Example: .. code-block:: python if ex...
def execute_only_once(): """ Each called in the code to this function is guaranteed to return True the first time and False afterwards. Returns: bool: whether this is the first time this function gets called from this line of code. Example: .. code-block:: python if ex...
[ "Each", "called", "in", "the", "code", "to", "this", "function", "is", "guaranteed", "to", "return", "True", "the", "first", "time", "and", "False", "afterwards", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/utils.py#L136-L155
[ "def", "execute_only_once", "(", ")", ":", "f", "=", "inspect", ".", "currentframe", "(", ")", ".", "f_back", "ident", "=", "(", "f", ".", "f_code", ".", "co_filename", ",", "f", ".", "f_lineno", ")", "if", "ident", "in", "_EXECUTE_HISTORY", ":", "retu...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
get_tqdm_kwargs
Return default arguments to be used with tqdm. Args: kwargs: extra arguments to be used. Returns: dict:
tensorpack/utils/utils.py
def get_tqdm_kwargs(**kwargs): """ Return default arguments to be used with tqdm. Args: kwargs: extra arguments to be used. Returns: dict: """ default = dict( smoothing=0.5, dynamic_ncols=True, ascii=True, bar_format='{l_bar}{bar}|{n_fmt}/{total_f...
def get_tqdm_kwargs(**kwargs): """ Return default arguments to be used with tqdm. Args: kwargs: extra arguments to be used. Returns: dict: """ default = dict( smoothing=0.5, dynamic_ncols=True, ascii=True, bar_format='{l_bar}{bar}|{n_fmt}/{total_f...
[ "Return", "default", "arguments", "to", "be", "used", "with", "tqdm", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/utils.py#L190-L214
[ "def", "get_tqdm_kwargs", "(", "*", "*", "kwargs", ")", ":", "default", "=", "dict", "(", "smoothing", "=", "0.5", ",", "dynamic_ncols", "=", "True", ",", "ascii", "=", "True", ",", "bar_format", "=", "'{l_bar}{bar}|{n_fmt}/{total_fmt}[{elapsed}<{remaining},{rate_...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
find_library_full_path
Similar to `from ctypes.util import find_library`, but try to return full path if possible.
tensorpack/utils/utils.py
def find_library_full_path(name): """ Similar to `from ctypes.util import find_library`, but try to return full path if possible. """ from ctypes.util import find_library if os.name == "posix" and sys.platform == "darwin": # on Mac, ctypes already returns full path return find_l...
def find_library_full_path(name): """ Similar to `from ctypes.util import find_library`, but try to return full path if possible. """ from ctypes.util import find_library if os.name == "posix" and sys.platform == "darwin": # on Mac, ctypes already returns full path return find_l...
[ "Similar", "to", "from", "ctypes", ".", "util", "import", "find_library", "but", "try", "to", "return", "full", "path", "if", "possible", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/utils.py#L223-L293
[ "def", "find_library_full_path", "(", "name", ")", ":", "from", "ctypes", ".", "util", "import", "find_library", "if", "os", ".", "name", "==", "\"posix\"", "and", "sys", ".", "platform", "==", "\"darwin\"", ":", "# on Mac, ctypes already returns full path", "retu...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
LMDBSerializer.save
Args: df (DataFlow): the DataFlow to serialize. path (str): output path. Either a directory or an lmdb file. write_frequency (int): the frequency to write back data to disk.
tensorpack/dataflow/serialize.py
def save(df, path, write_frequency=5000): """ Args: df (DataFlow): the DataFlow to serialize. path (str): output path. Either a directory or an lmdb file. write_frequency (int): the frequency to write back data to disk. """ assert isinstance(df, DataFl...
def save(df, path, write_frequency=5000): """ Args: df (DataFlow): the DataFlow to serialize. path (str): output path. Either a directory or an lmdb file. write_frequency (int): the frequency to write back data to disk. """ assert isinstance(df, DataFl...
[ "Args", ":", "df", "(", "DataFlow", ")", ":", "the", "DataFlow", "to", "serialize", ".", "path", "(", "str", ")", ":", "output", "path", ".", "Either", "a", "directory", "or", "an", "lmdb", "file", ".", "write_frequency", "(", "int", ")", ":", "the",...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/serialize.py#L37-L74
[ "def", "save", "(", "df", ",", "path", ",", "write_frequency", "=", "5000", ")", ":", "assert", "isinstance", "(", "df", ",", "DataFlow", ")", ",", "type", "(", "df", ")", "isdir", "=", "os", ".", "path", ".", "isdir", "(", "path", ")", "if", "is...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
LMDBSerializer.load
Note: If you found deserialization being the bottleneck, you can use :class:`LMDBData` as the reader and run deserialization as a mapper in parallel.
tensorpack/dataflow/serialize.py
def load(path, shuffle=True): """ Note: If you found deserialization being the bottleneck, you can use :class:`LMDBData` as the reader and run deserialization as a mapper in parallel. """ df = LMDBData(path, shuffle=shuffle) return MapData(df, lambda dp: l...
def load(path, shuffle=True): """ Note: If you found deserialization being the bottleneck, you can use :class:`LMDBData` as the reader and run deserialization as a mapper in parallel. """ df = LMDBData(path, shuffle=shuffle) return MapData(df, lambda dp: l...
[ "Note", ":", "If", "you", "found", "deserialization", "being", "the", "bottleneck", "you", "can", "use", ":", "class", ":", "LMDBData", "as", "the", "reader", "and", "run", "deserialization", "as", "a", "mapper", "in", "parallel", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/serialize.py#L77-L84
[ "def", "load", "(", "path", ",", "shuffle", "=", "True", ")", ":", "df", "=", "LMDBData", "(", "path", ",", "shuffle", "=", "shuffle", ")", "return", "MapData", "(", "df", ",", "lambda", "dp", ":", "loads", "(", "dp", "[", "1", "]", ")", ")" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
NumpySerializer.save
Args: df (DataFlow): the DataFlow to serialize. path (str): output npz file.
tensorpack/dataflow/serialize.py
def save(df, path): """ Args: df (DataFlow): the DataFlow to serialize. path (str): output npz file. """ buffer = [] size = _reset_df_and_get_size(df) with get_tqdm(total=size) as pbar: for dp in df: buffer.append(dp) ...
def save(df, path): """ Args: df (DataFlow): the DataFlow to serialize. path (str): output npz file. """ buffer = [] size = _reset_df_and_get_size(df) with get_tqdm(total=size) as pbar: for dp in df: buffer.append(dp) ...
[ "Args", ":", "df", "(", "DataFlow", ")", ":", "the", "DataFlow", "to", "serialize", ".", "path", "(", "str", ")", ":", "output", "npz", "file", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/serialize.py#L95-L107
[ "def", "save", "(", "df", ",", "path", ")", ":", "buffer", "=", "[", "]", "size", "=", "_reset_df_and_get_size", "(", "df", ")", "with", "get_tqdm", "(", "total", "=", "size", ")", "as", "pbar", ":", "for", "dp", "in", "df", ":", "buffer", ".", "...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
TFRecordSerializer.save
Args: df (DataFlow): the DataFlow to serialize. path (str): output tfrecord file.
tensorpack/dataflow/serialize.py
def save(df, path): """ Args: df (DataFlow): the DataFlow to serialize. path (str): output tfrecord file. """ if os.environ.get('TENSORPACK_COMPATIBLE_SERIALIZE', 'msgpack') == 'msgpack': def _dumps(dp): return dumps(dp) else: ...
def save(df, path): """ Args: df (DataFlow): the DataFlow to serialize. path (str): output tfrecord file. """ if os.environ.get('TENSORPACK_COMPATIBLE_SERIALIZE', 'msgpack') == 'msgpack': def _dumps(dp): return dumps(dp) else: ...
[ "Args", ":", "df", "(", "DataFlow", ")", ":", "the", "DataFlow", "to", "serialize", ".", "path", "(", "str", ")", ":", "output", "tfrecord", "file", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/serialize.py#L125-L142
[ "def", "save", "(", "df", ",", "path", ")", ":", "if", "os", ".", "environ", ".", "get", "(", "'TENSORPACK_COMPATIBLE_SERIALIZE'", ",", "'msgpack'", ")", "==", "'msgpack'", ":", "def", "_dumps", "(", "dp", ")", ":", "return", "dumps", "(", "dp", ")", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
TFRecordSerializer.load
Args: size (int): total number of records. If not provided, the returned dataflow will have no `__len__()`. It's needed because this metadata is not stored in the TFRecord file.
tensorpack/dataflow/serialize.py
def load(path, size=None): """ Args: size (int): total number of records. If not provided, the returned dataflow will have no `__len__()`. It's needed because this metadata is not stored in the TFRecord file. """ gen = tf.python_io.tf_record_iterator(path) ...
def load(path, size=None): """ Args: size (int): total number of records. If not provided, the returned dataflow will have no `__len__()`. It's needed because this metadata is not stored in the TFRecord file. """ gen = tf.python_io.tf_record_iterator(path) ...
[ "Args", ":", "size", "(", "int", ")", ":", "total", "number", "of", "records", ".", "If", "not", "provided", "the", "returned", "dataflow", "will", "have", "no", "__len__", "()", ".", "It", "s", "needed", "because", "this", "metadata", "is", "not", "st...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/serialize.py#L145-L156
[ "def", "load", "(", "path", ",", "size", "=", "None", ")", ":", "gen", "=", "tf", ".", "python_io", ".", "tf_record_iterator", "(", "path", ")", "ds", "=", "DataFromGenerator", "(", "gen", ")", "ds", "=", "MapData", "(", "ds", ",", "loads", ")", "i...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
HDF5Serializer.save
Args: df (DataFlow): the DataFlow to serialize. path (str): output hdf5 file. data_paths (list[str]): list of h5 paths. It should have the same length as each datapoint, and each path should correspond to one component of the datapoint.
tensorpack/dataflow/serialize.py
def save(df, path, data_paths): """ Args: df (DataFlow): the DataFlow to serialize. path (str): output hdf5 file. data_paths (list[str]): list of h5 paths. It should have the same length as each datapoint, and each path should correspond to one ...
def save(df, path, data_paths): """ Args: df (DataFlow): the DataFlow to serialize. path (str): output hdf5 file. data_paths (list[str]): list of h5 paths. It should have the same length as each datapoint, and each path should correspond to one ...
[ "Args", ":", "df", "(", "DataFlow", ")", ":", "the", "DataFlow", "to", "serialize", ".", "path", "(", "str", ")", ":", "output", "hdf5", "file", ".", "data_paths", "(", "list", "[", "str", "]", ")", ":", "list", "of", "h5", "paths", ".", "It", "s...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/serialize.py#L167-L189
[ "def", "save", "(", "df", ",", "path", ",", "data_paths", ")", ":", "size", "=", "_reset_df_and_get_size", "(", "df", ")", "buffer", "=", "defaultdict", "(", "list", ")", "with", "get_tqdm", "(", "total", "=", "size", ")", "as", "pbar", ":", "for", "...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
setup_keras_trainer
Args: trainer (SingleCostTrainer): get_model (input1, input2, ... -> tf.keras.Model): A function which takes tensors, builds and returns a Keras model. It will be part of the tower function. input (InputSource): optimizer (tf.train.Optimizer): loss, metric...
tensorpack/contrib/keras.py
def setup_keras_trainer( trainer, get_model, input_signature, target_signature, input, optimizer, loss, metrics): """ Args: trainer (SingleCostTrainer): get_model (input1, input2, ... -> tf.keras.Model): A function which takes tensors, builds and returns a Ker...
def setup_keras_trainer( trainer, get_model, input_signature, target_signature, input, optimizer, loss, metrics): """ Args: trainer (SingleCostTrainer): get_model (input1, input2, ... -> tf.keras.Model): A function which takes tensors, builds and returns a Ker...
[ "Args", ":", "trainer", "(", "SingleCostTrainer", ")", ":", "get_model", "(", "input1", "input2", "...", "-", ">", "tf", ".", "keras", ".", "Model", ")", ":", "A", "function", "which", "takes", "tensors", "builds", "and", "returns", "a", "Keras", "model"...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/contrib/keras.py#L142-L220
[ "def", "setup_keras_trainer", "(", "trainer", ",", "get_model", ",", "input_signature", ",", "target_signature", ",", "input", ",", "optimizer", ",", "loss", ",", "metrics", ")", ":", "assert", "isinstance", "(", "optimizer", ",", "tf", ".", "train", ".", "O...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
KerasModel.compile
Args: optimizer (tf.train.Optimizer): loss, metrics: string or list of strings
tensorpack/contrib/keras.py
def compile(self, optimizer, loss, metrics=None): """ Args: optimizer (tf.train.Optimizer): loss, metrics: string or list of strings """ if isinstance(loss, six.string_types): loss = [loss] if metrics is None: metrics = [] i...
def compile(self, optimizer, loss, metrics=None): """ Args: optimizer (tf.train.Optimizer): loss, metrics: string or list of strings """ if isinstance(loss, six.string_types): loss = [loss] if metrics is None: metrics = [] i...
[ "Args", ":", "optimizer", "(", "tf", ".", "train", ".", "Optimizer", ")", ":", "loss", "metrics", ":", "string", "or", "list", "of", "strings" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/contrib/keras.py#L259-L280
[ "def", "compile", "(", "self", ",", "optimizer", ",", "loss", ",", "metrics", "=", "None", ")", ":", "if", "isinstance", "(", "loss", ",", "six", ".", "string_types", ")", ":", "loss", "=", "[", "loss", "]", "if", "metrics", "is", "None", ":", "met...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
KerasModel.fit
Args: validation_data (DataFlow or InputSource): to be used for inference. The inference callback is added as the first in the callback list. If you need to use it in a different order, please write it in the callback list manually. kwargs: same arguments as :meth...
tensorpack/contrib/keras.py
def fit(self, validation_data=None, **kwargs): """ Args: validation_data (DataFlow or InputSource): to be used for inference. The inference callback is added as the first in the callback list. If you need to use it in a different order, please write it in the ...
def fit(self, validation_data=None, **kwargs): """ Args: validation_data (DataFlow or InputSource): to be used for inference. The inference callback is added as the first in the callback list. If you need to use it in a different order, please write it in the ...
[ "Args", ":", "validation_data", "(", "DataFlow", "or", "InputSource", ")", ":", "to", "be", "used", "for", "inference", ".", "The", "inference", "callback", "is", "added", "as", "the", "first", "in", "the", "callback", "list", ".", "If", "you", "need", "...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/contrib/keras.py#L282-L297
[ "def", "fit", "(", "self", ",", "validation_data", "=", "None", ",", "*", "*", "kwargs", ")", ":", "callbacks", "=", "kwargs", ".", "pop", "(", "'callbacks'", ",", "[", "]", ")", "if", "validation_data", "is", "not", "None", ":", "# There is no way to gu...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
get_dorefa
Return the three quantization functions fw, fa, fg, for weights, activations and gradients respectively
examples/DoReFa-Net/dorefa.py
def get_dorefa(bitW, bitA, bitG): """ Return the three quantization functions fw, fa, fg, for weights, activations and gradients respectively """ def quantize(x, k): n = float(2 ** k - 1) @tf.custom_gradient def _quantize(x): return tf.round(x * n) / n, lambda dy: dy...
def get_dorefa(bitW, bitA, bitG): """ Return the three quantization functions fw, fa, fg, for weights, activations and gradients respectively """ def quantize(x, k): n = float(2 ** k - 1) @tf.custom_gradient def _quantize(x): return tf.round(x * n) / n, lambda dy: dy...
[ "Return", "the", "three", "quantization", "functions", "fw", "fa", "fg", "for", "weights", "activations", "and", "gradients", "respectively" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DoReFa-Net/dorefa.py#L8-L64
[ "def", "get_dorefa", "(", "bitW", ",", "bitA", ",", "bitG", ")", ":", "def", "quantize", "(", "x", ",", "k", ")", ":", "n", "=", "float", "(", "2", "**", "k", "-", "1", ")", "@", "tf", ".", "custom_gradient", "def", "_quantize", "(", "x", ")", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
ternarize
Implemented Trained Ternary Quantization: https://arxiv.org/abs/1612.01064 Code modified from the authors' at: https://github.com/czhu95/ternarynet/blob/master/examples/Ternary-Net/ternary.py
examples/DoReFa-Net/dorefa.py
def ternarize(x, thresh=0.05): """ Implemented Trained Ternary Quantization: https://arxiv.org/abs/1612.01064 Code modified from the authors' at: https://github.com/czhu95/ternarynet/blob/master/examples/Ternary-Net/ternary.py """ shape = x.get_shape() thre_x = tf.stop_gradient(tf.redu...
def ternarize(x, thresh=0.05): """ Implemented Trained Ternary Quantization: https://arxiv.org/abs/1612.01064 Code modified from the authors' at: https://github.com/czhu95/ternarynet/blob/master/examples/Ternary-Net/ternary.py """ shape = x.get_shape() thre_x = tf.stop_gradient(tf.redu...
[ "Implemented", "Trained", "Ternary", "Quantization", ":", "https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1612", ".", "01064" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DoReFa-Net/dorefa.py#L67-L99
[ "def", "ternarize", "(", "x", ",", "thresh", "=", "0.05", ")", ":", "shape", "=", "x", ".", "get_shape", "(", ")", "thre_x", "=", "tf", ".", "stop_gradient", "(", "tf", ".", "reduce_max", "(", "tf", ".", "abs", "(", "x", ")", ")", "*", "thresh", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
interactive_imshow
Args: img (np.ndarray): an image (expect BGR) to show. lclick_cb, rclick_cb: a callback ``func(img, x, y)`` for left/right click event. kwargs: can be {key_cb_a: callback_img, key_cb_b: callback_img}, to specify a callback ``func(img)`` for keypress. Some existing keypress event...
tensorpack/utils/viz.py
def interactive_imshow(img, lclick_cb=None, rclick_cb=None, **kwargs): """ Args: img (np.ndarray): an image (expect BGR) to show. lclick_cb, rclick_cb: a callback ``func(img, x, y)`` for left/right click event. kwargs: can be {key_cb_a: callback_img, key_cb_b: callback_img}, to ...
def interactive_imshow(img, lclick_cb=None, rclick_cb=None, **kwargs): """ Args: img (np.ndarray): an image (expect BGR) to show. lclick_cb, rclick_cb: a callback ``func(img, x, y)`` for left/right click event. kwargs: can be {key_cb_a: callback_img, key_cb_b: callback_img}, to ...
[ "Args", ":", "img", "(", "np", ".", "ndarray", ")", ":", "an", "image", "(", "expect", "BGR", ")", "to", "show", ".", "lclick_cb", "rclick_cb", ":", "a", "callback", "func", "(", "img", "x", "y", ")", "for", "left", "/", "right", "click", "event", ...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/viz.py#L25-L66
[ "def", "interactive_imshow", "(", "img", ",", "lclick_cb", "=", "None", ",", "rclick_cb", "=", "None", ",", "*", "*", "kwargs", ")", ":", "name", "=", "'tensorpack_viz_window'", "cv2", ".", "imshow", "(", "name", ",", "img", ")", "def", "mouse_cb", "(", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
stack_patches
Stacked patches into grid, to produce visualizations like the following: .. image:: https://github.com/tensorpack/tensorpack/raw/master/examples/GAN/demo/BEGAN-CelebA-samples.jpg Args: patch_list(list[ndarray] or ndarray): NHW or NHWC images in [0,255]. nr_row(int), nr_col(int): rows and cols ...
tensorpack/utils/viz.py
def stack_patches( patch_list, nr_row, nr_col, border=None, pad=False, bgcolor=255, viz=False, lclick_cb=None): """ Stacked patches into grid, to produce visualizations like the following: .. image:: https://github.com/tensorpack/tensorpack/raw/master/examples/GAN/demo/BEGAN-CelebA-samples....
def stack_patches( patch_list, nr_row, nr_col, border=None, pad=False, bgcolor=255, viz=False, lclick_cb=None): """ Stacked patches into grid, to produce visualizations like the following: .. image:: https://github.com/tensorpack/tensorpack/raw/master/examples/GAN/demo/BEGAN-CelebA-samples....
[ "Stacked", "patches", "into", "grid", "to", "produce", "visualizations", "like", "the", "following", ":" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/viz.py#L157-L203
[ "def", "stack_patches", "(", "patch_list", ",", "nr_row", ",", "nr_col", ",", "border", "=", "None", ",", "pad", "=", "False", ",", "bgcolor", "=", "255", ",", "viz", "=", "False", ",", "lclick_cb", "=", "None", ")", ":", "if", "pad", ":", "patch_lis...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
gen_stack_patches
Similar to :func:`stack_patches` but with a generator interface. It takes a much-longer list and yields stacked results one by one. For example, if ``patch_list`` contains 1000 images and ``nr_row==nr_col==10``, this generator yields 10 stacked images. Args: nr_row(int), nr_col(int): rows and c...
tensorpack/utils/viz.py
def gen_stack_patches(patch_list, nr_row=None, nr_col=None, border=None, max_width=1000, max_height=1000, bgcolor=255, viz=False, lclick_cb=None): """ Similar to :func:`stack_patches` but with a generator interface. It takes a much-longer lis...
def gen_stack_patches(patch_list, nr_row=None, nr_col=None, border=None, max_width=1000, max_height=1000, bgcolor=255, viz=False, lclick_cb=None): """ Similar to :func:`stack_patches` but with a generator interface. It takes a much-longer lis...
[ "Similar", "to", ":", "func", ":", "stack_patches", "but", "with", "a", "generator", "interface", ".", "It", "takes", "a", "much", "-", "longer", "list", "and", "yields", "stacked", "results", "one", "by", "one", ".", "For", "example", "if", "patch_list", ...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/viz.py#L206-L262
[ "def", "gen_stack_patches", "(", "patch_list", ",", "nr_row", "=", "None", ",", "nr_col", "=", "None", ",", "border", "=", "None", ",", "max_width", "=", "1000", ",", "max_height", "=", "1000", ",", "bgcolor", "=", "255", ",", "viz", "=", "False", ",",...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
dump_dataflow_images
Dump or visualize images of a :class:`DataFlow`. Args: df (DataFlow): the DataFlow. index (int): the index of the image component. batched (bool): whether the component contains batched images (NHW or NHWC) or not (HW or HWC). number (int): how many datapoint to take fro...
tensorpack/utils/viz.py
def dump_dataflow_images(df, index=0, batched=True, number=1000, output_dir=None, scale=1, resize=None, viz=None, flipRGB=False): """ Dump or visualize images of a :class:`DataFlow`. Args: df (DataFlow): the DataFlow. ...
def dump_dataflow_images(df, index=0, batched=True, number=1000, output_dir=None, scale=1, resize=None, viz=None, flipRGB=False): """ Dump or visualize images of a :class:`DataFlow`. Args: df (DataFlow): the DataFlow. ...
[ "Dump", "or", "visualize", "images", "of", "a", ":", "class", ":", "DataFlow", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/viz.py#L265-L322
[ "def", "dump_dataflow_images", "(", "df", ",", "index", "=", "0", ",", "batched", "=", "True", ",", "number", "=", "1000", ",", "output_dir", "=", "None", ",", "scale", "=", "1", ",", "resize", "=", "None", ",", "viz", "=", "None", ",", "flipRGB", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
intensity_to_rgb
Convert a 1-channel matrix of intensities to an RGB image employing a colormap. This function requires matplotlib. See `matplotlib colormaps <http://matplotlib.org/examples/color/colormaps_reference.html>`_ for a list of available colormap. Args: intensity (np.ndarray): array of intensities suc...
tensorpack/utils/viz.py
def intensity_to_rgb(intensity, cmap='cubehelix', normalize=False): """ Convert a 1-channel matrix of intensities to an RGB image employing a colormap. This function requires matplotlib. See `matplotlib colormaps <http://matplotlib.org/examples/color/colormaps_reference.html>`_ for a list of availab...
def intensity_to_rgb(intensity, cmap='cubehelix', normalize=False): """ Convert a 1-channel matrix of intensities to an RGB image employing a colormap. This function requires matplotlib. See `matplotlib colormaps <http://matplotlib.org/examples/color/colormaps_reference.html>`_ for a list of availab...
[ "Convert", "a", "1", "-", "channel", "matrix", "of", "intensities", "to", "an", "RGB", "image", "employing", "a", "colormap", ".", "This", "function", "requires", "matplotlib", ".", "See", "matplotlib", "colormaps", "<http", ":", "//", "matplotlib", ".", "or...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/viz.py#L325-L350
[ "def", "intensity_to_rgb", "(", "intensity", ",", "cmap", "=", "'cubehelix'", ",", "normalize", "=", "False", ")", ":", "assert", "intensity", ".", "ndim", "==", "2", ",", "intensity", ".", "shape", "intensity", "=", "intensity", ".", "astype", "(", "\"flo...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
draw_text
Draw text on an image. Args: pos (tuple): x, y; the position of the text text (str): font_scale (float): color (tuple): a 3-tuple BGR color in [0, 255]
tensorpack/utils/viz.py
def draw_text(img, pos, text, color, font_scale=0.4): """ Draw text on an image. Args: pos (tuple): x, y; the position of the text text (str): font_scale (float): color (tuple): a 3-tuple BGR color in [0, 255] """ img = img.astype(np.uint8) x0, y0 = int(pos[0]), ...
def draw_text(img, pos, text, color, font_scale=0.4): """ Draw text on an image. Args: pos (tuple): x, y; the position of the text text (str): font_scale (float): color (tuple): a 3-tuple BGR color in [0, 255] """ img = img.astype(np.uint8) x0, y0 = int(pos[0]), ...
[ "Draw", "text", "on", "an", "image", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/viz.py#L353-L379
[ "def", "draw_text", "(", "img", ",", "pos", ",", "text", ",", "color", ",", "font_scale", "=", "0.4", ")", ":", "img", "=", "img", ".", "astype", "(", "np", ".", "uint8", ")", "x0", ",", "y0", "=", "int", "(", "pos", "[", "0", "]", ")", ",", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
draw_boxes
Args: im (np.ndarray): a BGR image in range [0,255]. It will not be modified. boxes (np.ndarray): a numpy array of shape Nx4 where each row is [x1, y1, x2, y2]. labels: (list[str] or None) color: a 3-tuple BGR color (in range [0, 255]) Returns: np.ndarray: a new image.
tensorpack/utils/viz.py
def draw_boxes(im, boxes, labels=None, color=None): """ Args: im (np.ndarray): a BGR image in range [0,255]. It will not be modified. boxes (np.ndarray): a numpy array of shape Nx4 where each row is [x1, y1, x2, y2]. labels: (list[str] or None) color: a 3-tuple BGR color (in rang...
def draw_boxes(im, boxes, labels=None, color=None): """ Args: im (np.ndarray): a BGR image in range [0,255]. It will not be modified. boxes (np.ndarray): a numpy array of shape Nx4 where each row is [x1, y1, x2, y2]. labels: (list[str] or None) color: a 3-tuple BGR color (in rang...
[ "Args", ":", "im", "(", "np", ".", "ndarray", ")", ":", "a", "BGR", "image", "in", "range", "[", "0", "255", "]", ".", "It", "will", "not", "be", "modified", ".", "boxes", "(", "np", ".", "ndarray", ")", ":", "a", "numpy", "array", "of", "shape...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/viz.py#L382-L415
[ "def", "draw_boxes", "(", "im", ",", "boxes", ",", "labels", "=", "None", ",", "color", "=", "None", ")", ":", "boxes", "=", "np", ".", "asarray", "(", "boxes", ",", "dtype", "=", "'int32'", ")", "if", "labels", "is", "not", "None", ":", "assert", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
ConcatWith
A wrapper around ``tf.concat`` to cooperate with :class:`LinearWrap`. Args: x (tf.Tensor): input tensor (list[tf.Tensor]): a tensor or list of tensors to concatenate with x. x will be at the beginning dim (int): the dimension along which to concatenate Returns: tf.T...
tensorpack/models/shapes.py
def ConcatWith(x, tensor, dim): """ A wrapper around ``tf.concat`` to cooperate with :class:`LinearWrap`. Args: x (tf.Tensor): input tensor (list[tf.Tensor]): a tensor or list of tensors to concatenate with x. x will be at the beginning dim (int): the dimension along whi...
def ConcatWith(x, tensor, dim): """ A wrapper around ``tf.concat`` to cooperate with :class:`LinearWrap`. Args: x (tf.Tensor): input tensor (list[tf.Tensor]): a tensor or list of tensors to concatenate with x. x will be at the beginning dim (int): the dimension along whi...
[ "A", "wrapper", "around", "tf", ".", "concat", "to", "cooperate", "with", ":", "class", ":", "LinearWrap", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/shapes.py#L13-L28
[ "def", "ConcatWith", "(", "x", ",", "tensor", ",", "dim", ")", ":", "if", "type", "(", "tensor", ")", "!=", "list", ":", "tensor", "=", "[", "tensor", "]", "return", "tf", ".", "concat", "(", "[", "x", "]", "+", "tensor", ",", "dim", ")" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
point8_to_box
Args: points: (nx4)x2 Returns: nx4 boxes (x1y1x2y2)
examples/FasterRCNN/common.py
def point8_to_box(points): """ Args: points: (nx4)x2 Returns: nx4 boxes (x1y1x2y2) """ p = points.reshape((-1, 4, 2)) minxy = p.min(axis=1) # nx2 maxxy = p.max(axis=1) # nx2 return np.concatenate((minxy, maxxy), axis=1)
def point8_to_box(points): """ Args: points: (nx4)x2 Returns: nx4 boxes (x1y1x2y2) """ p = points.reshape((-1, 4, 2)) minxy = p.min(axis=1) # nx2 maxxy = p.max(axis=1) # nx2 return np.concatenate((minxy, maxxy), axis=1)
[ "Args", ":", "points", ":", "(", "nx4", ")", "x2", "Returns", ":", "nx4", "boxes", "(", "x1y1x2y2", ")" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/common.py#L78-L88
[ "def", "point8_to_box", "(", "points", ")", ":", "p", "=", "points", ".", "reshape", "(", "(", "-", "1", ",", "4", ",", "2", ")", ")", "minxy", "=", "p", ".", "min", "(", "axis", "=", "1", ")", "# nx2", "maxxy", "=", "p", ".", "max", "(", "...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
segmentation_to_mask
Convert polygons to binary masks. Args: polys: a list of nx2 float array. Each array contains many (x, y) coordinates. Returns: a binary matrix of (height, width)
examples/FasterRCNN/common.py
def segmentation_to_mask(polys, height, width): """ Convert polygons to binary masks. Args: polys: a list of nx2 float array. Each array contains many (x, y) coordinates. Returns: a binary matrix of (height, width) """ polys = [p.flatten().tolist() for p in polys] assert le...
def segmentation_to_mask(polys, height, width): """ Convert polygons to binary masks. Args: polys: a list of nx2 float array. Each array contains many (x, y) coordinates. Returns: a binary matrix of (height, width) """ polys = [p.flatten().tolist() for p in polys] assert le...
[ "Convert", "polygons", "to", "binary", "masks", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/common.py#L91-L107
[ "def", "segmentation_to_mask", "(", "polys", ",", "height", ",", "width", ")", ":", "polys", "=", "[", "p", ".", "flatten", "(", ")", ".", "tolist", "(", ")", "for", "p", "in", "polys", "]", "assert", "len", "(", "polys", ")", ">", "0", ",", "\"P...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
clip_boxes
Args: boxes: (...)x4, float shape: h, w
examples/FasterRCNN/common.py
def clip_boxes(boxes, shape): """ Args: boxes: (...)x4, float shape: h, w """ orig_shape = boxes.shape boxes = boxes.reshape([-1, 4]) h, w = shape boxes[:, [0, 1]] = np.maximum(boxes[:, [0, 1]], 0) boxes[:, 2] = np.minimum(boxes[:, 2], w) boxes[:, 3] = np.minimum(boxe...
def clip_boxes(boxes, shape): """ Args: boxes: (...)x4, float shape: h, w """ orig_shape = boxes.shape boxes = boxes.reshape([-1, 4]) h, w = shape boxes[:, [0, 1]] = np.maximum(boxes[:, [0, 1]], 0) boxes[:, 2] = np.minimum(boxes[:, 2], w) boxes[:, 3] = np.minimum(boxe...
[ "Args", ":", "boxes", ":", "(", "...", ")", "x4", "float", "shape", ":", "h", "w" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/common.py#L110-L122
[ "def", "clip_boxes", "(", "boxes", ",", "shape", ")", ":", "orig_shape", "=", "boxes", ".", "shape", "boxes", "=", "boxes", ".", "reshape", "(", "[", "-", "1", ",", "4", "]", ")", "h", ",", "w", "=", "shape", "boxes", "[", ":", ",", "[", "0", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
filter_boxes_inside_shape
Args: boxes: (nx4), float shape: (h, w) Returns: indices: (k, ) selection: (kx4)
examples/FasterRCNN/common.py
def filter_boxes_inside_shape(boxes, shape): """ Args: boxes: (nx4), float shape: (h, w) Returns: indices: (k, ) selection: (kx4) """ assert boxes.ndim == 2, boxes.shape assert len(shape) == 2, shape h, w = shape indices = np.where( (boxes[:, 0] >...
def filter_boxes_inside_shape(boxes, shape): """ Args: boxes: (nx4), float shape: (h, w) Returns: indices: (k, ) selection: (kx4) """ assert boxes.ndim == 2, boxes.shape assert len(shape) == 2, shape h, w = shape indices = np.where( (boxes[:, 0] >...
[ "Args", ":", "boxes", ":", "(", "nx4", ")", "float", "shape", ":", "(", "h", "w", ")" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/common.py#L125-L143
[ "def", "filter_boxes_inside_shape", "(", "boxes", ",", "shape", ")", ":", "assert", "boxes", ".", "ndim", "==", "2", ",", "boxes", ".", "shape", "assert", "len", "(", "shape", ")", "==", "2", ",", "shape", "h", ",", "w", "=", "shape", "indices", "=",...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
MaxPooling
Same as `tf.layers.MaxPooling2D`. Default strides is equal to pool_size.
tensorpack/models/pool.py
def MaxPooling( inputs, pool_size, strides=None, padding='valid', data_format='channels_last'): """ Same as `tf.layers.MaxPooling2D`. Default strides is equal to pool_size. """ if strides is None: strides = pool_size layer = tf.layers.MaxPooling2D(pool...
def MaxPooling( inputs, pool_size, strides=None, padding='valid', data_format='channels_last'): """ Same as `tf.layers.MaxPooling2D`. Default strides is equal to pool_size. """ if strides is None: strides = pool_size layer = tf.layers.MaxPooling2D(pool...
[ "Same", "as", "tf", ".", "layers", ".", "MaxPooling2D", ".", "Default", "strides", "is", "equal", "to", "pool_size", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/pool.py#L21-L34
[ "def", "MaxPooling", "(", "inputs", ",", "pool_size", ",", "strides", "=", "None", ",", "padding", "=", "'valid'", ",", "data_format", "=", "'channels_last'", ")", ":", "if", "strides", "is", "None", ":", "strides", "=", "pool_size", "layer", "=", "tf", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
AvgPooling
Same as `tf.layers.AveragePooling2D`. Default strides is equal to pool_size.
tensorpack/models/pool.py
def AvgPooling( inputs, pool_size, strides=None, padding='valid', data_format='channels_last'): """ Same as `tf.layers.AveragePooling2D`. Default strides is equal to pool_size. """ if strides is None: strides = pool_size layer = tf.layers.AveragePoolin...
def AvgPooling( inputs, pool_size, strides=None, padding='valid', data_format='channels_last'): """ Same as `tf.layers.AveragePooling2D`. Default strides is equal to pool_size. """ if strides is None: strides = pool_size layer = tf.layers.AveragePoolin...
[ "Same", "as", "tf", ".", "layers", ".", "AveragePooling2D", ".", "Default", "strides", "is", "equal", "to", "pool_size", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/pool.py#L41-L54
[ "def", "AvgPooling", "(", "inputs", ",", "pool_size", ",", "strides", "=", "None", ",", "padding", "=", "'valid'", ",", "data_format", "=", "'channels_last'", ")", ":", "if", "strides", "is", "None", ":", "strides", "=", "pool_size", "layer", "=", "tf", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
GlobalAvgPooling
Global average pooling as in the paper `Network In Network <http://arxiv.org/abs/1312.4400>`_. Args: x (tf.Tensor): a 4D tensor. Returns: tf.Tensor: a NC tensor named ``output``.
tensorpack/models/pool.py
def GlobalAvgPooling(x, data_format='channels_last'): """ Global average pooling as in the paper `Network In Network <http://arxiv.org/abs/1312.4400>`_. Args: x (tf.Tensor): a 4D tensor. Returns: tf.Tensor: a NC tensor named ``output``. """ assert x.shape.ndims == 4 dat...
def GlobalAvgPooling(x, data_format='channels_last'): """ Global average pooling as in the paper `Network In Network <http://arxiv.org/abs/1312.4400>`_. Args: x (tf.Tensor): a 4D tensor. Returns: tf.Tensor: a NC tensor named ``output``. """ assert x.shape.ndims == 4 dat...
[ "Global", "average", "pooling", "as", "in", "the", "paper", "Network", "In", "Network", "<http", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1312", ".", "4400", ">", "_", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/pool.py#L58-L72
[ "def", "GlobalAvgPooling", "(", "x", ",", "data_format", "=", "'channels_last'", ")", ":", "assert", "x", ".", "shape", ".", "ndims", "==", "4", "data_format", "=", "get_data_format", "(", "data_format", ")", "axis", "=", "[", "1", ",", "2", "]", "if", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
FixedUnPooling
Unpool the input with a fixed matrix to perform kronecker product with. Args: x (tf.Tensor): a 4D image tensor shape: int or (h, w) tuple unpool_mat: a tf.Tensor or np.ndarray 2D matrix with size=shape. If is None, will use a matrix with 1 at top-left corner. Returns: ...
tensorpack/models/pool.py
def FixedUnPooling(x, shape, unpool_mat=None, data_format='channels_last'): """ Unpool the input with a fixed matrix to perform kronecker product with. Args: x (tf.Tensor): a 4D image tensor shape: int or (h, w) tuple unpool_mat: a tf.Tensor or np.ndarray 2D matrix with size=shape. ...
def FixedUnPooling(x, shape, unpool_mat=None, data_format='channels_last'): """ Unpool the input with a fixed matrix to perform kronecker product with. Args: x (tf.Tensor): a 4D image tensor shape: int or (h, w) tuple unpool_mat: a tf.Tensor or np.ndarray 2D matrix with size=shape. ...
[ "Unpool", "the", "input", "with", "a", "fixed", "matrix", "to", "perform", "kronecker", "product", "with", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/pool.py#L91-L140
[ "def", "FixedUnPooling", "(", "x", ",", "shape", ",", "unpool_mat", "=", "None", ",", "data_format", "=", "'channels_last'", ")", ":", "data_format", "=", "get_data_format", "(", "data_format", ",", "keras_mode", "=", "False", ")", "shape", "=", "shape2d", "...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
get_savename_from_varname
Args: varname(str): a variable name in the graph varname_prefix(str): an optional prefix that may need to be removed in varname savename_prefix(str): an optional prefix to append to all savename Returns: str: the name used to save the variable
tensorpack/tfutils/varmanip.py
def get_savename_from_varname( varname, varname_prefix=None, savename_prefix=None): """ Args: varname(str): a variable name in the graph varname_prefix(str): an optional prefix that may need to be removed in varname savename_prefix(str): an optional prefix to append to al...
def get_savename_from_varname( varname, varname_prefix=None, savename_prefix=None): """ Args: varname(str): a variable name in the graph varname_prefix(str): an optional prefix that may need to be removed in varname savename_prefix(str): an optional prefix to append to al...
[ "Args", ":", "varname", "(", "str", ")", ":", "a", "variable", "name", "in", "the", "graph", "varname_prefix", "(", "str", ")", ":", "an", "optional", "prefix", "that", "may", "need", "to", "be", "removed", "in", "varname", "savename_prefix", "(", "str",...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/varmanip.py#L18-L35
[ "def", "get_savename_from_varname", "(", "varname", ",", "varname_prefix", "=", "None", ",", "savename_prefix", "=", "None", ")", ":", "name", "=", "varname", "if", "varname_prefix", "is", "not", "None", "and", "name", ".", "startswith", "(", "varname_prefix", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
dump_session_params
Dump value of all TRAINABLE + MODEL variables to a dict, and save as npz format (loadable by :func:`sessinit.get_model_loader`). Args: path(str): the file name to save the parameters. Must ends with npz.
tensorpack/tfutils/varmanip.py
def dump_session_params(path): """ Dump value of all TRAINABLE + MODEL variables to a dict, and save as npz format (loadable by :func:`sessinit.get_model_loader`). Args: path(str): the file name to save the parameters. Must ends with npz. """ # save variables that are GLOBAL, and either...
def dump_session_params(path): """ Dump value of all TRAINABLE + MODEL variables to a dict, and save as npz format (loadable by :func:`sessinit.get_model_loader`). Args: path(str): the file name to save the parameters. Must ends with npz. """ # save variables that are GLOBAL, and either...
[ "Dump", "value", "of", "all", "TRAINABLE", "+", "MODEL", "variables", "to", "a", "dict", "and", "save", "as", "npz", "format", "(", "loadable", "by", ":", "func", ":", "sessinit", ".", "get_model_loader", ")", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/varmanip.py#L119-L137
[ "def", "dump_session_params", "(", "path", ")", ":", "# save variables that are GLOBAL, and either TRAINABLE or MODEL", "var", "=", "tf", ".", "get_collection", "(", "tf", ".", "GraphKeys", ".", "TRAINABLE_VARIABLES", ")", "var", ".", "extend", "(", "tf", ".", "get_...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
save_chkpt_vars
Save variables in dic to path. Args: dic: {name: value} path: save as npz if the name ends with '.npz', otherwise save as a checkpoint.
tensorpack/tfutils/varmanip.py
def save_chkpt_vars(dic, path): """ Save variables in dic to path. Args: dic: {name: value} path: save as npz if the name ends with '.npz', otherwise save as a checkpoint. """ logger.info("Variables to save to {}:".format(path)) keys = sorted(list(dic.keys())) logger.info(pp...
def save_chkpt_vars(dic, path): """ Save variables in dic to path. Args: dic: {name: value} path: save as npz if the name ends with '.npz', otherwise save as a checkpoint. """ logger.info("Variables to save to {}:".format(path)) keys = sorted(list(dic.keys())) logger.info(pp...
[ "Save", "variables", "in", "dic", "to", "path", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/varmanip.py#L140-L163
[ "def", "save_chkpt_vars", "(", "dic", ",", "path", ")", ":", "logger", ".", "info", "(", "\"Variables to save to {}:\"", ".", "format", "(", "path", ")", ")", "keys", "=", "sorted", "(", "list", "(", "dic", ".", "keys", "(", ")", ")", ")", "logger", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
get_checkpoint_path
Work around TF problems in checkpoint path handling. Args: model_path: a user-input path Returns: str: the argument that can be passed to NewCheckpointReader
tensorpack/tfutils/varmanip.py
def get_checkpoint_path(model_path): """ Work around TF problems in checkpoint path handling. Args: model_path: a user-input path Returns: str: the argument that can be passed to NewCheckpointReader """ if os.path.basename(model_path) == model_path: model_path = os.path....
def get_checkpoint_path(model_path): """ Work around TF problems in checkpoint path handling. Args: model_path: a user-input path Returns: str: the argument that can be passed to NewCheckpointReader """ if os.path.basename(model_path) == model_path: model_path = os.path....
[ "Work", "around", "TF", "problems", "in", "checkpoint", "path", "handling", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/varmanip.py#L166-L193
[ "def", "get_checkpoint_path", "(", "model_path", ")", ":", "if", "os", ".", "path", ".", "basename", "(", "model_path", ")", "==", "model_path", ":", "model_path", "=", "os", ".", "path", ".", "join", "(", "'.'", ",", "model_path", ")", "# avoid #4921 and ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
load_chkpt_vars
Load all variables from a checkpoint to a dict. Args: model_path(str): path to a checkpoint. Returns: dict: a name:value dict
tensorpack/tfutils/varmanip.py
def load_chkpt_vars(model_path): """ Load all variables from a checkpoint to a dict. Args: model_path(str): path to a checkpoint. Returns: dict: a name:value dict """ model_path = get_checkpoint_path(model_path) reader = tfv1.train.NewCheckpointReader(model_path) var_names ...
def load_chkpt_vars(model_path): """ Load all variables from a checkpoint to a dict. Args: model_path(str): path to a checkpoint. Returns: dict: a name:value dict """ model_path = get_checkpoint_path(model_path) reader = tfv1.train.NewCheckpointReader(model_path) var_names ...
[ "Load", "all", "variables", "from", "a", "checkpoint", "to", "a", "dict", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/varmanip.py#L196-L211
[ "def", "load_chkpt_vars", "(", "model_path", ")", ":", "model_path", "=", "get_checkpoint_path", "(", "model_path", ")", "reader", "=", "tfv1", ".", "train", ".", "NewCheckpointReader", "(", "model_path", ")", "var_names", "=", "reader", ".", "get_variable_to_shap...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
is_training_name
**Guess** if this variable is only used in training. Only used internally to avoid too many logging. Do not use it.
tensorpack/tfutils/varmanip.py
def is_training_name(name): """ **Guess** if this variable is only used in training. Only used internally to avoid too many logging. Do not use it. """ # TODO: maybe simply check against TRAINABLE_VARIABLES and MODEL_VARIABLES? # TODO or use get_slot_names() name = get_op_tensor_name(name)[0...
def is_training_name(name): """ **Guess** if this variable is only used in training. Only used internally to avoid too many logging. Do not use it. """ # TODO: maybe simply check against TRAINABLE_VARIABLES and MODEL_VARIABLES? # TODO or use get_slot_names() name = get_op_tensor_name(name)[0...
[ "**", "Guess", "**", "if", "this", "variable", "is", "only", "used", "in", "training", ".", "Only", "used", "internally", "to", "avoid", "too", "many", "logging", ".", "Do", "not", "use", "it", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/varmanip.py#L214-L238
[ "def", "is_training_name", "(", "name", ")", ":", "# TODO: maybe simply check against TRAINABLE_VARIABLES and MODEL_VARIABLES?", "# TODO or use get_slot_names()", "name", "=", "get_op_tensor_name", "(", "name", ")", "[", "0", "]", "if", "name", ".", "endswith", "(", "'/Ad...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
SessionUpdate.relaxed_value_for_var
Returns a relaxed (possibly reshaped/upcast-ed) version of value, to be loaded to the given variable. Args: value (ndarray): an numpy array to be loaded to var var (tf.Variable): Returns: ndarray: a possibly reshaped or casted version of value
tensorpack/tfutils/varmanip.py
def relaxed_value_for_var(value, var): """ Returns a relaxed (possibly reshaped/upcast-ed) version of value, to be loaded to the given variable. Args: value (ndarray): an numpy array to be loaded to var var (tf.Variable): Returns: ndarray: a ...
def relaxed_value_for_var(value, var): """ Returns a relaxed (possibly reshaped/upcast-ed) version of value, to be loaded to the given variable. Args: value (ndarray): an numpy array to be loaded to var var (tf.Variable): Returns: ndarray: a ...
[ "Returns", "a", "relaxed", "(", "possibly", "reshaped", "/", "upcast", "-", "ed", ")", "version", "of", "value", "to", "be", "loaded", "to", "the", "given", "variable", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/varmanip.py#L51-L99
[ "def", "relaxed_value_for_var", "(", "value", ",", "var", ")", ":", "assert", "isinstance", "(", "var", ",", "tf", ".", "Variable", ")", "name", "=", "var", ".", "op", ".", "name", "# check incompatible shape", "varshape", "=", "tuple", "(", "var", ".", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
SessionUpdate.update
Args: prms(dict): dict of {variable name: value} Any name in prms must be in the graph and in vars_to_update.
tensorpack/tfutils/varmanip.py
def update(self, prms): """ Args: prms(dict): dict of {variable name: value} Any name in prms must be in the graph and in vars_to_update. """ with self.sess.as_default(): fetches = [] feeds = {} for name, value in six.iterit...
def update(self, prms): """ Args: prms(dict): dict of {variable name: value} Any name in prms must be in the graph and in vars_to_update. """ with self.sess.as_default(): fetches = [] feeds = {} for name, value in six.iterit...
[ "Args", ":", "prms", "(", "dict", ")", ":", "dict", "of", "{", "variable", "name", ":", "value", "}", "Any", "name", "in", "prms", "must", "be", "in", "the", "graph", "and", "in", "vars_to_update", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/varmanip.py#L101-L116
[ "def", "update", "(", "self", ",", "prms", ")", ":", "with", "self", ".", "sess", ".", "as_default", "(", ")", ":", "fetches", "=", "[", "]", "feeds", "=", "{", "}", "for", "name", ",", "value", "in", "six", ".", "iteritems", "(", "prms", ")", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
get_distributed_session_creator
Args: server (tf.train.Server): Returns: tf.train.SessionCreator
tensorpack/tfutils/distributed.py
def get_distributed_session_creator(server): """ Args: server (tf.train.Server): Returns: tf.train.SessionCreator """ server_def = server.server_def is_chief = (server_def.job_name == 'worker') and (server_def.task_index == 0) init_op = tf.global_variables_initializer() ...
def get_distributed_session_creator(server): """ Args: server (tf.train.Server): Returns: tf.train.SessionCreator """ server_def = server.server_def is_chief = (server_def.job_name == 'worker') and (server_def.task_index == 0) init_op = tf.global_variables_initializer() ...
[ "Args", ":", "server", "(", "tf", ".", "train", ".", "Server", ")", ":" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/distributed.py#L8-L47
[ "def", "get_distributed_session_creator", "(", "server", ")", ":", "server_def", "=", "server", ".", "server_def", "is_chief", "=", "(", "server_def", ".", "job_name", "==", "'worker'", ")", "and", "(", "server_def", ".", "task_index", "==", "0", ")", "init_op...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
get_num_gpu
Returns: int: #available GPUs in CUDA_VISIBLE_DEVICES, or in the system.
tensorpack/utils/gpu.py
def get_num_gpu(): """ Returns: int: #available GPUs in CUDA_VISIBLE_DEVICES, or in the system. """ def warn_return(ret, message): try: import tensorflow as tf except ImportError: return ret built_with_cuda = tf.test.is_built_with_cuda() ...
def get_num_gpu(): """ Returns: int: #available GPUs in CUDA_VISIBLE_DEVICES, or in the system. """ def warn_return(ret, message): try: import tensorflow as tf except ImportError: return ret built_with_cuda = tf.test.is_built_with_cuda() ...
[ "Returns", ":", "int", ":", "#available", "GPUs", "in", "CUDA_VISIBLE_DEVICES", "or", "in", "the", "system", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/gpu.py#L29-L71
[ "def", "get_num_gpu", "(", ")", ":", "def", "warn_return", "(", "ret", ",", "message", ")", ":", "try", ":", "import", "tensorflow", "as", "tf", "except", "ImportError", ":", "return", "ret", "built_with_cuda", "=", "tf", ".", "test", ".", "is_built_with_c...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
Monitors.put_summary
Put a `tf.Summary`.
tensorpack/callbacks/monitor.py
def put_summary(self, summary): """ Put a `tf.Summary`. """ if isinstance(summary, six.binary_type): summary = tf.Summary.FromString(summary) assert isinstance(summary, tf.Summary), type(summary) # TODO other types for val in summary.value: ...
def put_summary(self, summary): """ Put a `tf.Summary`. """ if isinstance(summary, six.binary_type): summary = tf.Summary.FromString(summary) assert isinstance(summary, tf.Summary), type(summary) # TODO other types for val in summary.value: ...
[ "Put", "a", "tf", ".", "Summary", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/monitor.py#L143-L164
[ "def", "put_summary", "(", "self", ",", "summary", ")", ":", "if", "isinstance", "(", "summary", ",", "six", ".", "binary_type", ")", ":", "summary", "=", "tf", ".", "Summary", ".", "FromString", "(", "summary", ")", "assert", "isinstance", "(", "summary...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
Monitors.put_scalar
Put a scalar.
tensorpack/callbacks/monitor.py
def put_scalar(self, name, val): """ Put a scalar. """ if isinstance(val, np.floating): val = float(val) if isinstance(val, np.integer): val = int(val) self._dispatch(lambda m: m.process_scalar(name, val)) s = create_scalar_summary(name, va...
def put_scalar(self, name, val): """ Put a scalar. """ if isinstance(val, np.floating): val = float(val) if isinstance(val, np.integer): val = int(val) self._dispatch(lambda m: m.process_scalar(name, val)) s = create_scalar_summary(name, va...
[ "Put", "a", "scalar", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/monitor.py#L166-L176
[ "def", "put_scalar", "(", "self", ",", "name", ",", "val", ")", ":", "if", "isinstance", "(", "val", ",", "np", ".", "floating", ")", ":", "val", "=", "float", "(", "val", ")", "if", "isinstance", "(", "val", ",", "np", ".", "integer", ")", ":", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
Monitors.put_image
Put an image. Args: name (str): val (np.ndarray): 2D, 3D (HWC) or 4D (NHWC) numpy array of images in range [0,255]. If channel is 3, assumed to be RGB.
tensorpack/callbacks/monitor.py
def put_image(self, name, val): """ Put an image. Args: name (str): val (np.ndarray): 2D, 3D (HWC) or 4D (NHWC) numpy array of images in range [0,255]. If channel is 3, assumed to be RGB. """ assert isinstance(val, np.ndarray) arr ...
def put_image(self, name, val): """ Put an image. Args: name (str): val (np.ndarray): 2D, 3D (HWC) or 4D (NHWC) numpy array of images in range [0,255]. If channel is 3, assumed to be RGB. """ assert isinstance(val, np.ndarray) arr ...
[ "Put", "an", "image", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/monitor.py#L178-L191
[ "def", "put_image", "(", "self", ",", "name", ",", "val", ")", ":", "assert", "isinstance", "(", "val", ",", "np", ".", "ndarray", ")", "arr", "=", "image_to_nhwc", "(", "val", ")", "self", ".", "_dispatch", "(", "lambda", "m", ":", "m", ".", "proc...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
Monitors.put_event
Put an :class:`tf.Event`. `step` and `wall_time` fields of :class:`tf.Event` will be filled automatically. Args: evt (tf.Event):
tensorpack/callbacks/monitor.py
def put_event(self, evt): """ Put an :class:`tf.Event`. `step` and `wall_time` fields of :class:`tf.Event` will be filled automatically. Args: evt (tf.Event): """ evt.step = self.global_step evt.wall_time = time.time() self._dispatch(lambda m:...
def put_event(self, evt): """ Put an :class:`tf.Event`. `step` and `wall_time` fields of :class:`tf.Event` will be filled automatically. Args: evt (tf.Event): """ evt.step = self.global_step evt.wall_time = time.time() self._dispatch(lambda m:...
[ "Put", "an", ":", "class", ":", "tf", ".", "Event", ".", "step", "and", "wall_time", "fields", "of", ":", "class", ":", "tf", ".", "Event", "will", "be", "filled", "automatically", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/monitor.py#L193-L203
[ "def", "put_event", "(", "self", ",", "evt", ")", ":", "evt", ".", "step", "=", "self", ".", "global_step", "evt", ".", "wall_time", "=", "time", ".", "time", "(", ")", "self", ".", "_dispatch", "(", "lambda", "m", ":", "m", ".", "process_event", "...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
JSONWriter.load_existing_json
Look for an existing json under :meth:`logger.get_logger_dir()` named "stats.json", and return the loaded list of statistics if found. Returns None otherwise.
tensorpack/callbacks/monitor.py
def load_existing_json(): """ Look for an existing json under :meth:`logger.get_logger_dir()` named "stats.json", and return the loaded list of statistics if found. Returns None otherwise. """ dir = logger.get_logger_dir() fname = os.path.join(dir, JSONWriter.FILENAME) ...
def load_existing_json(): """ Look for an existing json under :meth:`logger.get_logger_dir()` named "stats.json", and return the loaded list of statistics if found. Returns None otherwise. """ dir = logger.get_logger_dir() fname = os.path.join(dir, JSONWriter.FILENAME) ...
[ "Look", "for", "an", "existing", "json", "under", ":", "meth", ":", "logger", ".", "get_logger_dir", "()", "named", "stats", ".", "json", "and", "return", "the", "loaded", "list", "of", "statistics", "if", "found", ".", "Returns", "None", "otherwise", "." ...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/monitor.py#L302-L314
[ "def", "load_existing_json", "(", ")", ":", "dir", "=", "logger", ".", "get_logger_dir", "(", ")", "fname", "=", "os", ".", "path", ".", "join", "(", "dir", ",", "JSONWriter", ".", "FILENAME", ")", "if", "tf", ".", "gfile", ".", "Exists", "(", "fname...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
JSONWriter._trigger
Add stats to json and dump to disk. Note that this method is idempotent.
tensorpack/callbacks/monitor.py
def _trigger(self): """ Add stats to json and dump to disk. Note that this method is idempotent. """ if len(self._stat_now): self._stat_now['epoch_num'] = self.epoch_num self._stat_now['global_step'] = self.global_step self._stats.append(self....
def _trigger(self): """ Add stats to json and dump to disk. Note that this method is idempotent. """ if len(self._stat_now): self._stat_now['epoch_num'] = self.epoch_num self._stat_now['global_step'] = self.global_step self._stats.append(self....
[ "Add", "stats", "to", "json", "and", "dump", "to", "disk", ".", "Note", "that", "this", "method", "is", "idempotent", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/monitor.py#L378-L389
[ "def", "_trigger", "(", "self", ")", ":", "if", "len", "(", "self", ".", "_stat_now", ")", ":", "self", ".", "_stat_now", "[", "'epoch_num'", "]", "=", "self", ".", "epoch_num", "self", ".", "_stat_now", "[", "'global_step'", "]", "=", "self", ".", "...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
sample
Args: img: bxhxwxc coords: bxh2xw2x2. each coordinate is (y, x) integer. Out of boundary coordinates will be clipped. Return: bxh2xw2xc image
examples/SpatialTransformer/mnist-addition.py
def sample(img, coords): """ Args: img: bxhxwxc coords: bxh2xw2x2. each coordinate is (y, x) integer. Out of boundary coordinates will be clipped. Return: bxh2xw2xc image """ shape = img.get_shape().as_list()[1:] # h, w, c batch = tf.shape(img)[0] shape2...
def sample(img, coords): """ Args: img: bxhxwxc coords: bxh2xw2x2. each coordinate is (y, x) integer. Out of boundary coordinates will be clipped. Return: bxh2xw2xc image """ shape = img.get_shape().as_list()[1:] # h, w, c batch = tf.shape(img)[0] shape2...
[ "Args", ":", "img", ":", "bxhxwxc", "coords", ":", "bxh2xw2x2", ".", "each", "coordinate", "is", "(", "y", "x", ")", "integer", ".", "Out", "of", "boundary", "coordinates", "will", "be", "clipped", ".", "Return", ":", "bxh2xw2xc", "image" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/SpatialTransformer/mnist-addition.py#L21-L44
[ "def", "sample", "(", "img", ",", "coords", ")", ":", "shape", "=", "img", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "[", "1", ":", "]", "# h, w, c", "batch", "=", "tf", ".", "shape", "(", "img", ")", "[", "0", "]", "shape2", "=", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
GridSample
Sample the images using the given coordinates, by bilinear interpolation. This was described in the paper: `Spatial Transformer Networks <http://arxiv.org/abs/1506.02025>`_. This is equivalent to `torch.nn.functional.grid_sample`, up to some non-trivial coordinate transformation. This implementati...
examples/SpatialTransformer/mnist-addition.py
def GridSample(inputs, borderMode='repeat'): """ Sample the images using the given coordinates, by bilinear interpolation. This was described in the paper: `Spatial Transformer Networks <http://arxiv.org/abs/1506.02025>`_. This is equivalent to `torch.nn.functional.grid_sample`, up to some non-...
def GridSample(inputs, borderMode='repeat'): """ Sample the images using the given coordinates, by bilinear interpolation. This was described in the paper: `Spatial Transformer Networks <http://arxiv.org/abs/1506.02025>`_. This is equivalent to `torch.nn.functional.grid_sample`, up to some non-...
[ "Sample", "the", "images", "using", "the", "given", "coordinates", "by", "bilinear", "interpolation", ".", "This", "was", "described", "in", "the", "paper", ":", "Spatial", "Transformer", "Networks", "<http", ":", "//", "arxiv", ".", "org", "/", "abs", "/", ...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/SpatialTransformer/mnist-addition.py#L48-L105
[ "def", "GridSample", "(", "inputs", ",", "borderMode", "=", "'repeat'", ")", ":", "image", ",", "mapping", "=", "inputs", "assert", "image", ".", "get_shape", "(", ")", ".", "ndims", "==", "4", "and", "mapping", ".", "get_shape", "(", ")", ".", "ndims"...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
enable_call_trace
Enable trace for calls to any function.
tensorpack/utils/debug.py
def enable_call_trace(): """ Enable trace for calls to any function. """ def tracer(frame, event, arg): if event == 'call': co = frame.f_code func_name = co.co_name if func_name == 'write' or func_name == 'print': # ignore write() calls from print stat...
def enable_call_trace(): """ Enable trace for calls to any function. """ def tracer(frame, event, arg): if event == 'call': co = frame.f_code func_name = co.co_name if func_name == 'write' or func_name == 'print': # ignore write() calls from print stat...
[ "Enable", "trace", "for", "calls", "to", "any", "function", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/debug.py#L8-L27
[ "def", "enable_call_trace", "(", ")", ":", "def", "tracer", "(", "frame", ",", "event", ",", "arg", ")", ":", "if", "event", "==", "'call'", ":", "co", "=", "frame", ".", "f_code", "func_name", "=", "co", ".", "co_name", "if", "func_name", "==", "'wr...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
apply_default_prefetch
Apply a set of default rules to make a fast :class:`InputSource`. Args: input_source_or_dataflow(InputSource | DataFlow): trainer (Trainer): Returns: InputSource
tensorpack/train/interface.py
def apply_default_prefetch(input_source_or_dataflow, trainer): """ Apply a set of default rules to make a fast :class:`InputSource`. Args: input_source_or_dataflow(InputSource | DataFlow): trainer (Trainer): Returns: InputSource """ if not isinstance(input_source_or_dat...
def apply_default_prefetch(input_source_or_dataflow, trainer): """ Apply a set of default rules to make a fast :class:`InputSource`. Args: input_source_or_dataflow(InputSource | DataFlow): trainer (Trainer): Returns: InputSource """ if not isinstance(input_source_or_dat...
[ "Apply", "a", "set", "of", "default", "rules", "to", "make", "a", "fast", ":", "class", ":", "InputSource", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/train/interface.py#L15-L45
[ "def", "apply_default_prefetch", "(", "input_source_or_dataflow", ",", "trainer", ")", ":", "if", "not", "isinstance", "(", "input_source_or_dataflow", ",", "InputSource", ")", ":", "# to mimic same behavior of the old trainer interface", "if", "type", "(", "trainer", ")"...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
launch_train_with_config
Train with a :class:`TrainConfig` and a :class:`Trainer`, to present the simple and old training interface. It basically does the following 3 things (and you can easily do them by yourself if you need more control): 1. Setup the input with automatic prefetching heuristics, from `config.data` or `con...
tensorpack/train/interface.py
def launch_train_with_config(config, trainer): """ Train with a :class:`TrainConfig` and a :class:`Trainer`, to present the simple and old training interface. It basically does the following 3 things (and you can easily do them by yourself if you need more control): 1. Setup the input with automati...
def launch_train_with_config(config, trainer): """ Train with a :class:`TrainConfig` and a :class:`Trainer`, to present the simple and old training interface. It basically does the following 3 things (and you can easily do them by yourself if you need more control): 1. Setup the input with automati...
[ "Train", "with", "a", ":", "class", ":", "TrainConfig", "and", "a", ":", "class", ":", "Trainer", "to", "present", "the", "simple", "and", "old", "training", "interface", ".", "It", "basically", "does", "the", "following", "3", "things", "(", "and", "you...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/train/interface.py#L48-L101
[ "def", "launch_train_with_config", "(", "config", ",", "trainer", ")", ":", "if", "is_tfv2", "(", ")", ":", "tfv1", ".", "disable_eager_execution", "(", ")", "assert", "isinstance", "(", "trainer", ",", "SingleCostTrainer", ")", ",", "trainer", "assert", "isin...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
_get_property
Delegate property to self.loop
tensorpack/train/base.py
def _get_property(name): """ Delegate property to self.loop """ ret = property( lambda self: getattr(self.loop, name)) if six.PY3: # __doc__ is readonly in Py2 try: ret.__doc__ = getattr(TrainLoop, name).__doc__ except AttributeError: pass retu...
def _get_property(name): """ Delegate property to self.loop """ ret = property( lambda self: getattr(self.loop, name)) if six.PY3: # __doc__ is readonly in Py2 try: ret.__doc__ = getattr(TrainLoop, name).__doc__ except AttributeError: pass retu...
[ "Delegate", "property", "to", "self", ".", "loop" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/train/base.py#L357-L368
[ "def", "_get_property", "(", "name", ")", ":", "ret", "=", "property", "(", "lambda", "self", ":", "getattr", "(", "self", ".", "loop", ",", "name", ")", ")", "if", "six", ".", "PY3", ":", "# __doc__ is readonly in Py2", "try", ":", "ret", ".", "__doc_...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
TrainLoop.config
Configure the loop given the settings.
tensorpack/train/base.py
def config(self, steps_per_epoch, starting_epoch, max_epoch): """ Configure the loop given the settings. """ self.starting_epoch = int(starting_epoch) self.max_epoch = int(max_epoch) self.steps_per_epoch = int(steps_per_epoch) # Allow empty epoch (no steps), if we...
def config(self, steps_per_epoch, starting_epoch, max_epoch): """ Configure the loop given the settings. """ self.starting_epoch = int(starting_epoch) self.max_epoch = int(max_epoch) self.steps_per_epoch = int(steps_per_epoch) # Allow empty epoch (no steps), if we...
[ "Configure", "the", "loop", "given", "the", "settings", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/train/base.py#L43-L53
[ "def", "config", "(", "self", ",", "steps_per_epoch", ",", "starting_epoch", ",", "max_epoch", ")", ":", "self", ".", "starting_epoch", "=", "int", "(", "starting_epoch", ")", "self", ".", "max_epoch", "=", "int", "(", "max_epoch", ")", "self", ".", "steps...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
Trainer._register_callback
Register callbacks to the trainer. It can only be called before :meth:`Trainer.train()`. Args: cb (Callback or [Callback]): a callback or a list of callbacks Returns: succeed or not
tensorpack/train/base.py
def _register_callback(self, cb): """ Register callbacks to the trainer. It can only be called before :meth:`Trainer.train()`. Args: cb (Callback or [Callback]): a callback or a list of callbacks Returns: succeed or not """ if isinstance(...
def _register_callback(self, cb): """ Register callbacks to the trainer. It can only be called before :meth:`Trainer.train()`. Args: cb (Callback or [Callback]): a callback or a list of callbacks Returns: succeed or not """ if isinstance(...
[ "Register", "callbacks", "to", "the", "trainer", ".", "It", "can", "only", "be", "called", "before", ":", "meth", ":", "Trainer", ".", "train", "()", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/train/base.py#L142-L165
[ "def", "_register_callback", "(", "self", ",", "cb", ")", ":", "if", "isinstance", "(", "cb", ",", "(", "list", ",", "tuple", ")", ")", ":", "for", "x", "in", "cb", ":", "self", ".", "_register_callback", "(", "x", ")", "return", "assert", "isinstanc...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
Trainer.run_step
Defines what to do in one iteration. The default is: ``self.hooked_sess.run(self.train_op)``. The behavior of each iteration can be changed by either setting ``trainer.train_op``, or overriding this method.
tensorpack/train/base.py
def run_step(self): """ Defines what to do in one iteration. The default is: ``self.hooked_sess.run(self.train_op)``. The behavior of each iteration can be changed by either setting ``trainer.train_op``, or overriding this method. """ if not hasattr(self, 'train_...
def run_step(self): """ Defines what to do in one iteration. The default is: ``self.hooked_sess.run(self.train_op)``. The behavior of each iteration can be changed by either setting ``trainer.train_op``, or overriding this method. """ if not hasattr(self, 'train_...
[ "Defines", "what", "to", "do", "in", "one", "iteration", ".", "The", "default", "is", ":", "self", ".", "hooked_sess", ".", "run", "(", "self", ".", "train_op", ")", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/train/base.py#L169-L181
[ "def", "run_step", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'train_op'", ")", ":", "raise", "NotImplementedError", "(", "\"Please either set `Trainer.train_op` or provide an implementation \"", "\"of Trainer.run_step()!\"", ")", "self", ".", "ho...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
Trainer.setup_callbacks
Setup callbacks and monitors. Must be called after the main graph is built. Args: callbacks ([Callback]): monitors ([MonitorBase]):
tensorpack/train/base.py
def setup_callbacks(self, callbacks, monitors): """ Setup callbacks and monitors. Must be called after the main graph is built. Args: callbacks ([Callback]): monitors ([MonitorBase]): """ assert isinstance(callbacks, list), callbacks assert isinst...
def setup_callbacks(self, callbacks, monitors): """ Setup callbacks and monitors. Must be called after the main graph is built. Args: callbacks ([Callback]): monitors ([MonitorBase]): """ assert isinstance(callbacks, list), callbacks assert isinst...
[ "Setup", "callbacks", "and", "monitors", ".", "Must", "be", "called", "after", "the", "main", "graph", "is", "built", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/train/base.py#L184-L211
[ "def", "setup_callbacks", "(", "self", ",", "callbacks", ",", "monitors", ")", ":", "assert", "isinstance", "(", "callbacks", ",", "list", ")", ",", "callbacks", "assert", "isinstance", "(", "monitors", ",", "list", ")", ",", "monitors", "describe_trainable_va...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
Trainer.initialize
Create the session and set `self.sess`. Call `self.initiailize_hooks()` Finalize the graph. It must be called after callbacks are setup. Args: session_creator (tf.train.SessionCreator): session_init (sessinit.SessionInit):
tensorpack/train/base.py
def initialize(self, session_creator, session_init): """ Create the session and set `self.sess`. Call `self.initiailize_hooks()` Finalize the graph. It must be called after callbacks are setup. Args: session_creator (tf.train.SessionCreator): ses...
def initialize(self, session_creator, session_init): """ Create the session and set `self.sess`. Call `self.initiailize_hooks()` Finalize the graph. It must be called after callbacks are setup. Args: session_creator (tf.train.SessionCreator): ses...
[ "Create", "the", "session", "and", "set", "self", ".", "sess", ".", "Call", "self", ".", "initiailize_hooks", "()", "Finalize", "the", "graph", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/train/base.py#L214-L243
[ "def", "initialize", "(", "self", ",", "session_creator", ",", "session_init", ")", ":", "assert", "isinstance", "(", "session_creator", ",", "tfv1", ".", "train", ".", "SessionCreator", ")", ",", "session_creator", "assert", "isinstance", "(", "session_init", "...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
Trainer.initialize_hooks
Create SessionRunHooks for all callbacks, and hook it onto `self.sess` to create `self.hooked_sess`. A new trainer may override this method to create multiple groups of hooks, which can be useful when the training is not done by a single `train_op`.
tensorpack/train/base.py
def initialize_hooks(self): """ Create SessionRunHooks for all callbacks, and hook it onto `self.sess` to create `self.hooked_sess`. A new trainer may override this method to create multiple groups of hooks, which can be useful when the training is not done by a single `train_op`. ...
def initialize_hooks(self): """ Create SessionRunHooks for all callbacks, and hook it onto `self.sess` to create `self.hooked_sess`. A new trainer may override this method to create multiple groups of hooks, which can be useful when the training is not done by a single `train_op`. ...
[ "Create", "SessionRunHooks", "for", "all", "callbacks", "and", "hook", "it", "onto", "self", ".", "sess", "to", "create", "self", ".", "hooked_sess", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/train/base.py#L246-L255
[ "def", "initialize_hooks", "(", "self", ")", ":", "hooks", "=", "self", ".", "_callbacks", ".", "get_hooks", "(", ")", "self", ".", "hooked_sess", "=", "tfv1", ".", "train", ".", "MonitoredSession", "(", "session_creator", "=", "ReuseSessionCreator", "(", "s...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
Trainer.main_loop
Run the main training loop. Args: steps_per_epoch, starting_epoch, max_epoch (int):
tensorpack/train/base.py
def main_loop(self, steps_per_epoch, starting_epoch, max_epoch): """ Run the main training loop. Args: steps_per_epoch, starting_epoch, max_epoch (int): """ with self.sess.as_default(): self.loop.config(steps_per_epoch, starting_epoch, max_epoch) ...
def main_loop(self, steps_per_epoch, starting_epoch, max_epoch): """ Run the main training loop. Args: steps_per_epoch, starting_epoch, max_epoch (int): """ with self.sess.as_default(): self.loop.config(steps_per_epoch, starting_epoch, max_epoch) ...
[ "Run", "the", "main", "training", "loop", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/train/base.py#L258-L297
[ "def", "main_loop", "(", "self", ",", "steps_per_epoch", ",", "starting_epoch", ",", "max_epoch", ")", ":", "with", "self", ".", "sess", ".", "as_default", "(", ")", ":", "self", ".", "loop", ".", "config", "(", "steps_per_epoch", ",", "starting_epoch", ",...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
Trainer.train
Implemented by three lines: .. code-block:: python self.setup_callbacks(callbacks, monitors) self.initialize(session_creator, session_init) self.main_loop(steps_per_epoch, starting_epoch, max_epoch) You can call those methods by yourself to have better control on d...
tensorpack/train/base.py
def train(self, callbacks, monitors, session_creator, session_init, steps_per_epoch, starting_epoch=1, max_epoch=9999999): """ Implemented by three lines: .. code-block:: python self.setup_callbacks(callbacks, monitors) self.ini...
def train(self, callbacks, monitors, session_creator, session_init, steps_per_epoch, starting_epoch=1, max_epoch=9999999): """ Implemented by three lines: .. code-block:: python self.setup_callbacks(callbacks, monitors) self.ini...
[ "Implemented", "by", "three", "lines", ":" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/train/base.py#L299-L316
[ "def", "train", "(", "self", ",", "callbacks", ",", "monitors", ",", "session_creator", ",", "session_init", ",", "steps_per_epoch", ",", "starting_epoch", "=", "1", ",", "max_epoch", "=", "9999999", ")", ":", "self", ".", "setup_callbacks", "(", "callbacks", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
Trainer.train_with_defaults
Same as :meth:`train()`, except: 1. Add `extra_callbacks` to callbacks. The default value for `extra_callbacks` is :meth:`DEFAULT_CALLBACKS()`. 2. Default value for `monitors` is :meth:`DEFAULT_MONITORS()`. 3. Provide default values for every option except `steps_per_epoch`.
tensorpack/train/base.py
def train_with_defaults( self, _sentinel=None, callbacks=None, monitors=None, session_creator=None, session_init=None, steps_per_epoch=None, starting_epoch=1, max_epoch=9999999, extra_callbacks=None): """ Same as :meth:`train()`, except: ...
def train_with_defaults( self, _sentinel=None, callbacks=None, monitors=None, session_creator=None, session_init=None, steps_per_epoch=None, starting_epoch=1, max_epoch=9999999, extra_callbacks=None): """ Same as :meth:`train()`, except: ...
[ "Same", "as", ":", "meth", ":", "train", "()", "except", ":" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/train/base.py#L318-L344
[ "def", "train_with_defaults", "(", "self", ",", "_sentinel", "=", "None", ",", "callbacks", "=", "None", ",", "monitors", "=", "None", ",", "session_creator", "=", "None", ",", "session_init", "=", "None", ",", "steps_per_epoch", "=", "None", ",", "starting_...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
get_default_sess_config
Return a tf.ConfigProto to use as default session config. You can modify the returned config to fit your needs. Args: mem_fraction(float): see the `per_process_gpu_memory_fraction` option in TensorFlow's GPUOptions protobuf: https://github.com/tensorflow/tensorflow/blob/master/t...
tensorpack/tfutils/common.py
def get_default_sess_config(mem_fraction=0.99): """ Return a tf.ConfigProto to use as default session config. You can modify the returned config to fit your needs. Args: mem_fraction(float): see the `per_process_gpu_memory_fraction` option in TensorFlow's GPUOptions protobuf: ...
def get_default_sess_config(mem_fraction=0.99): """ Return a tf.ConfigProto to use as default session config. You can modify the returned config to fit your needs. Args: mem_fraction(float): see the `per_process_gpu_memory_fraction` option in TensorFlow's GPUOptions protobuf: ...
[ "Return", "a", "tf", ".", "ConfigProto", "to", "use", "as", "default", "session", "config", ".", "You", "can", "modify", "the", "returned", "config", "to", "fit", "your", "needs", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/common.py#L30-L68
[ "def", "get_default_sess_config", "(", "mem_fraction", "=", "0.99", ")", ":", "conf", "=", "tfv1", ".", "ConfigProto", "(", ")", "conf", ".", "allow_soft_placement", "=", "True", "# conf.log_device_placement = True", "conf", ".", "intra_op_parallelism_threads", "=", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
get_global_step_var
Returns: tf.Tensor: the global_step variable in the current graph. Create if doesn't exist.
tensorpack/tfutils/common.py
def get_global_step_var(): """ Returns: tf.Tensor: the global_step variable in the current graph. Create if doesn't exist. """ scope = tfv1.VariableScope(reuse=False, name='') # the root vs with tfv1.variable_scope(scope): var = tfv1.train.get_or_create_global_step() return var
def get_global_step_var(): """ Returns: tf.Tensor: the global_step variable in the current graph. Create if doesn't exist. """ scope = tfv1.VariableScope(reuse=False, name='') # the root vs with tfv1.variable_scope(scope): var = tfv1.train.get_or_create_global_step() return var
[ "Returns", ":", "tf", ".", "Tensor", ":", "the", "global_step", "variable", "in", "the", "current", "graph", ".", "Create", "if", "doesn", "t", "exist", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/common.py#L72-L80
[ "def", "get_global_step_var", "(", ")", ":", "scope", "=", "tfv1", ".", "VariableScope", "(", "reuse", "=", "False", ",", "name", "=", "''", ")", "# the root vs", "with", "tfv1", ".", "variable_scope", "(", "scope", ")", ":", "var", "=", "tfv1", ".", "...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
get_tensors_by_names
Get a list of tensors in the default graph by a list of names. Args: names (list):
tensorpack/tfutils/common.py
def get_tensors_by_names(names): """ Get a list of tensors in the default graph by a list of names. Args: names (list): """ ret = [] G = tfv1.get_default_graph() for n in names: opn, varn = get_op_tensor_name(n) ret.append(G.get_tensor_by_name(varn)) return ret
def get_tensors_by_names(names): """ Get a list of tensors in the default graph by a list of names. Args: names (list): """ ret = [] G = tfv1.get_default_graph() for n in names: opn, varn = get_op_tensor_name(n) ret.append(G.get_tensor_by_name(varn)) return ret
[ "Get", "a", "list", "of", "tensors", "in", "the", "default", "graph", "by", "a", "list", "of", "names", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/common.py#L113-L125
[ "def", "get_tensors_by_names", "(", "names", ")", ":", "ret", "=", "[", "]", "G", "=", "tfv1", ".", "get_default_graph", "(", ")", "for", "n", "in", "names", ":", "opn", ",", "varn", "=", "get_op_tensor_name", "(", "n", ")", "ret", ".", "append", "("...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
get_op_or_tensor_by_name
Get either tf.Operation of tf.Tensor from names. Args: name (list[str] or str): names of operations or tensors. Raises: KeyError, if the name doesn't exist
tensorpack/tfutils/common.py
def get_op_or_tensor_by_name(name): """ Get either tf.Operation of tf.Tensor from names. Args: name (list[str] or str): names of operations or tensors. Raises: KeyError, if the name doesn't exist """ G = tfv1.get_default_graph() def f(n): if len(n) >= 3 and n[-2] =...
def get_op_or_tensor_by_name(name): """ Get either tf.Operation of tf.Tensor from names. Args: name (list[str] or str): names of operations or tensors. Raises: KeyError, if the name doesn't exist """ G = tfv1.get_default_graph() def f(n): if len(n) >= 3 and n[-2] =...
[ "Get", "either", "tf", ".", "Operation", "of", "tf", ".", "Tensor", "from", "names", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/common.py#L128-L149
[ "def", "get_op_or_tensor_by_name", "(", "name", ")", ":", "G", "=", "tfv1", ".", "get_default_graph", "(", ")", "def", "f", "(", "n", ")", ":", "if", "len", "(", "n", ")", ">=", "3", "and", "n", "[", "-", "2", "]", "==", "':'", ":", "return", "...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
collect_env_info
Returns: str - a table contains important information about the environment
tensorpack/tfutils/common.py
def collect_env_info(): """ Returns: str - a table contains important information about the environment """ data = [] data.append(("sys.platform", sys.platform)) data.append(("Python", sys.version.replace("\n", ""))) data.append(("Tensorpack", __git_version__)) data.append(("Nump...
def collect_env_info(): """ Returns: str - a table contains important information about the environment """ data = [] data.append(("sys.platform", sys.platform)) data.append(("Python", sys.version.replace("\n", ""))) data.append(("Tensorpack", __git_version__)) data.append(("Nump...
[ "Returns", ":", "str", "-", "a", "table", "contains", "important", "information", "about", "the", "environment" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/common.py#L167-L245
[ "def", "collect_env_info", "(", ")", ":", "data", "=", "[", "]", "data", ".", "append", "(", "(", "\"sys.platform\"", ",", "sys", ".", "platform", ")", ")", "data", ".", "append", "(", "(", "\"Python\"", ",", "sys", ".", "version", ".", "replace", "(...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
DistributedBuilderBase._add_sync_queues_and_barrier
Adds ops to enqueue on all worker queues. Args: name: prefixed for the shared_name of ops. dependencies: control dependency from ops. Returns: an op that should be used as control dependency before starting next step.
tensorpack/graph_builder/distributed.py
def _add_sync_queues_and_barrier(self, name, dependencies): """Adds ops to enqueue on all worker queues. Args: name: prefixed for the shared_name of ops. dependencies: control dependency from ops. Returns: an op that should be used as control dependency befo...
def _add_sync_queues_and_barrier(self, name, dependencies): """Adds ops to enqueue on all worker queues. Args: name: prefixed for the shared_name of ops. dependencies: control dependency from ops. Returns: an op that should be used as control dependency befo...
[ "Adds", "ops", "to", "enqueue", "on", "all", "worker", "queues", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/distributed.py#L30-L58
[ "def", "_add_sync_queues_and_barrier", "(", "self", ",", "name", ",", "dependencies", ")", ":", "self", ".", "_sync_queue_counter", "+=", "1", "with", "tf", ".", "device", "(", "self", ".", "sync_queue_devices", "[", "self", ".", "_sync_queue_counter", "%", "l...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
DistributedReplicatedBuilder._apply_shadow_vars
Create shadow variables on PS, and replace variables in avg_grads by these shadow variables. Args: avg_grads: list of (grad, var) tuples
tensorpack/graph_builder/distributed.py
def _apply_shadow_vars(avg_grads): """ Create shadow variables on PS, and replace variables in avg_grads by these shadow variables. Args: avg_grads: list of (grad, var) tuples """ ps_var_grads = [] for grad, var in avg_grads: assert var.na...
def _apply_shadow_vars(avg_grads): """ Create shadow variables on PS, and replace variables in avg_grads by these shadow variables. Args: avg_grads: list of (grad, var) tuples """ ps_var_grads = [] for grad, var in avg_grads: assert var.na...
[ "Create", "shadow", "variables", "on", "PS", "and", "replace", "variables", "in", "avg_grads", "by", "these", "shadow", "variables", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/distributed.py#L205-L223
[ "def", "_apply_shadow_vars", "(", "avg_grads", ")", ":", "ps_var_grads", "=", "[", "]", "for", "grad", ",", "var", "in", "avg_grads", ":", "assert", "var", ".", "name", ".", "startswith", "(", "'tower'", ")", ",", "var", ".", "name", "my_name", "=", "'...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
DistributedReplicatedBuilder._shadow_model_variables
Create shadow vars for model_variables as well, and add to the list of ``shadow_vars``. Returns: list of (shadow_model_var, local_model_var) used for syncing.
tensorpack/graph_builder/distributed.py
def _shadow_model_variables(shadow_vars): """ Create shadow vars for model_variables as well, and add to the list of ``shadow_vars``. Returns: list of (shadow_model_var, local_model_var) used for syncing. """ G = tf.get_default_graph() curr_shadow_vars = set(...
def _shadow_model_variables(shadow_vars): """ Create shadow vars for model_variables as well, and add to the list of ``shadow_vars``. Returns: list of (shadow_model_var, local_model_var) used for syncing. """ G = tf.get_default_graph() curr_shadow_vars = set(...
[ "Create", "shadow", "vars", "for", "model_variables", "as", "well", "and", "add", "to", "the", "list", "of", "shadow_vars", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/distributed.py#L226-L255
[ "def", "_shadow_model_variables", "(", "shadow_vars", ")", ":", "G", "=", "tf", ".", "get_default_graph", "(", ")", "curr_shadow_vars", "=", "set", "(", "[", "v", ".", "name", "for", "v", "in", "shadow_vars", "]", ")", "model_vars", "=", "tf", ".", "mode...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
DistributedReplicatedBuilder.build
Args: get_grad_fn (-> [(grad, var)]): get_opt_fn (-> tf.train.Optimizer): callable which returns an optimizer Returns: (tf.Operation, tf.Operation, tf.Operation): 1. the training op. 2. the op which sync all the local variables from PS. ...
tensorpack/graph_builder/distributed.py
def build(self, get_grad_fn, get_opt_fn): """ Args: get_grad_fn (-> [(grad, var)]): get_opt_fn (-> tf.train.Optimizer): callable which returns an optimizer Returns: (tf.Operation, tf.Operation, tf.Operation): 1. the training op. 2. t...
def build(self, get_grad_fn, get_opt_fn): """ Args: get_grad_fn (-> [(grad, var)]): get_opt_fn (-> tf.train.Optimizer): callable which returns an optimizer Returns: (tf.Operation, tf.Operation, tf.Operation): 1. the training op. 2. t...
[ "Args", ":", "get_grad_fn", "(", "-", ">", "[", "(", "grad", "var", ")", "]", ")", ":", "get_opt_fn", "(", "-", ">", "tf", ".", "train", ".", "Optimizer", ")", ":", "callable", "which", "returns", "an", "optimizer" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/distributed.py#L257-L311
[ "def", "build", "(", "self", ",", "get_grad_fn", ",", "get_opt_fn", ")", ":", "with", "override_to_local_variable", "(", ")", ":", "get_global_step_var", "(", ")", "get_opt_fn", "=", "memoized", "(", "get_opt_fn", ")", "# Build the optimizer first, before entering any...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
DistributedReplicatedBuilder._apply_gradients_and_copy
Apply averaged gradients to ps vars, and then copy the updated variables back to each tower. Args: raw_grad_list: Ngpu x Nvar x 2 gradient list from all towers ps_var_grads: Nvar x 2 (grad, ps_var) Returns: list of copy ops
tensorpack/graph_builder/distributed.py
def _apply_gradients_and_copy(self, opt, raw_grad_list, ps_var_grads): """ Apply averaged gradients to ps vars, and then copy the updated variables back to each tower. Args: raw_grad_list: Ngpu x Nvar x 2 gradient list from all towers ps_var_grads: Nvar x 2 (grad...
def _apply_gradients_and_copy(self, opt, raw_grad_list, ps_var_grads): """ Apply averaged gradients to ps vars, and then copy the updated variables back to each tower. Args: raw_grad_list: Ngpu x Nvar x 2 gradient list from all towers ps_var_grads: Nvar x 2 (grad...
[ "Apply", "averaged", "gradients", "to", "ps", "vars", "and", "then", "copy", "the", "updated", "variables", "back", "to", "each", "tower", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/distributed.py#L313-L339
[ "def", "_apply_gradients_and_copy", "(", "self", ",", "opt", ",", "raw_grad_list", ",", "ps_var_grads", ")", ":", "# TODO do this for variables together?", "with", "tf", ".", "name_scope", "(", "'apply_gradients'", ")", ":", "var_update_ops", "=", "[", "]", "for", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
DistributedReplicatedBuilder._get_initial_sync_op
Get the op to copy-initialized all local variables from PS.
tensorpack/graph_builder/distributed.py
def _get_initial_sync_op(self): """ Get the op to copy-initialized all local variables from PS. """ def strip_port(s): if s.endswith(':0'): return s[:-2] return s local_vars = tf.local_variables() local_var_by_name = dict([(strip_po...
def _get_initial_sync_op(self): """ Get the op to copy-initialized all local variables from PS. """ def strip_port(s): if s.endswith(':0'): return s[:-2] return s local_vars = tf.local_variables() local_var_by_name = dict([(strip_po...
[ "Get", "the", "op", "to", "copy", "-", "initialized", "all", "local", "variables", "from", "PS", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/distributed.py#L341-L362
[ "def", "_get_initial_sync_op", "(", "self", ")", ":", "def", "strip_port", "(", "s", ")", ":", "if", "s", ".", "endswith", "(", "':0'", ")", ":", "return", "s", "[", ":", "-", "2", "]", "return", "s", "local_vars", "=", "tf", ".", "local_variables", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
DistributedReplicatedBuilder._get_sync_model_vars_op
Get the op to sync local model_variables to PS.
tensorpack/graph_builder/distributed.py
def _get_sync_model_vars_op(self): """ Get the op to sync local model_variables to PS. """ ops = [] for (shadow_v, local_v) in self._shadow_model_vars: ops.append(shadow_v.assign(local_v.read_value())) assert len(ops) return tf.group(*ops, name='sync_{...
def _get_sync_model_vars_op(self): """ Get the op to sync local model_variables to PS. """ ops = [] for (shadow_v, local_v) in self._shadow_model_vars: ops.append(shadow_v.assign(local_v.read_value())) assert len(ops) return tf.group(*ops, name='sync_{...
[ "Get", "the", "op", "to", "sync", "local", "model_variables", "to", "PS", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/distributed.py#L364-L372
[ "def", "_get_sync_model_vars_op", "(", "self", ")", ":", "ops", "=", "[", "]", "for", "(", "shadow_v", ",", "local_v", ")", "in", "self", ".", "_shadow_model_vars", ":", "ops", ".", "append", "(", "shadow_v", ".", "assign", "(", "local_v", ".", "read_val...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
get_tensors_inputs
Args: placeholders (list[Tensor]): tensors (list[Tensor]): list of tf.Tensor names (list[str]): names matching the given tensors Returns: list[Tensor]: inputs to used for the tower function, with the corresponding placeholders replaced by tensors.
tensorpack/input_source/input_source_base.py
def get_tensors_inputs(placeholders, tensors, names): """ Args: placeholders (list[Tensor]): tensors (list[Tensor]): list of tf.Tensor names (list[str]): names matching the given tensors Returns: list[Tensor]: inputs to used for the tower function, with the corre...
def get_tensors_inputs(placeholders, tensors, names): """ Args: placeholders (list[Tensor]): tensors (list[Tensor]): list of tf.Tensor names (list[str]): names matching the given tensors Returns: list[Tensor]: inputs to used for the tower function, with the corre...
[ "Args", ":", "placeholders", "(", "list", "[", "Tensor", "]", ")", ":", "tensors", "(", "list", "[", "Tensor", "]", ")", ":", "list", "of", "tf", ".", "Tensor", "names", "(", "list", "[", "str", "]", ")", ":", "names", "matching", "the", "given", ...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/input_source/input_source_base.py#L20-L44
[ "def", "get_tensors_inputs", "(", "placeholders", ",", "tensors", ",", "names", ")", ":", "assert", "len", "(", "tensors", ")", "==", "len", "(", "names", ")", ",", "\"Input tensors {} and input names {} have different length!\"", ".", "format", "(", "tensors", ",...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
get_sublist_by_names
Args: lst (list): list of objects with "name" property. Returns: list: a sublist of objects, matching names
tensorpack/input_source/input_source_base.py
def get_sublist_by_names(lst, names): """ Args: lst (list): list of objects with "name" property. Returns: list: a sublist of objects, matching names """ orig_names = [p.name for p in lst] ret = [] for name in names: try: idx = orig_names.index(name) ...
def get_sublist_by_names(lst, names): """ Args: lst (list): list of objects with "name" property. Returns: list: a sublist of objects, matching names """ orig_names = [p.name for p in lst] ret = [] for name in names: try: idx = orig_names.index(name) ...
[ "Args", ":", "lst", "(", "list", ")", ":", "list", "of", "objects", "with", "name", "property", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/input_source/input_source_base.py#L47-L65
[ "def", "get_sublist_by_names", "(", "lst", ",", "names", ")", ":", "orig_names", "=", "[", "p", ".", "name", "for", "p", "in", "lst", "]", "ret", "=", "[", "]", "for", "name", "in", "names", ":", "try", ":", "idx", "=", "orig_names", ".", "index", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
remap_input_source
When you have some :class:`InputSource` which doesn't match the inputs of your tower function, use `RemapInputSource`. It produces placeholders for all the inputs in your model, except that the corresponding ones are replaced with the tensor produced by the given :class:`InputSource`. Args: ...
tensorpack/input_source/input_source_base.py
def remap_input_source(input, names): """ When you have some :class:`InputSource` which doesn't match the inputs of your tower function, use `RemapInputSource`. It produces placeholders for all the inputs in your model, except that the corresponding ones are replaced with the tensor produced by ...
def remap_input_source(input, names): """ When you have some :class:`InputSource` which doesn't match the inputs of your tower function, use `RemapInputSource`. It produces placeholders for all the inputs in your model, except that the corresponding ones are replaced with the tensor produced by ...
[ "When", "you", "have", "some", ":", "class", ":", "InputSource", "which", "doesn", "t", "match", "the", "inputs", "of", "your", "tower", "function", "use", "RemapInputSource", ".", "It", "produces", "placeholders", "for", "all", "the", "inputs", "in", "your"...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/input_source/input_source_base.py#L207-L260
[ "def", "remap_input_source", "(", "input", ",", "names", ")", ":", "def", "__init__", "(", "self", ",", "input", ",", "names", ")", ":", "ProxyInputSource", ".", "__init__", "(", "self", ",", "input", ")", "assert", "isinstance", "(", "names", ",", "(", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
rpn_head
Returns: label_logits: fHxfWxNA box_logits: fHxfWxNAx4
examples/FasterRCNN/model_rpn.py
def rpn_head(featuremap, channel, num_anchors): """ Returns: label_logits: fHxfWxNA box_logits: fHxfWxNAx4 """ with argscope(Conv2D, data_format='channels_first', kernel_initializer=tf.random_normal_initializer(stddev=0.01)): hidden = Conv2D('conv0', featuremap,...
def rpn_head(featuremap, channel, num_anchors): """ Returns: label_logits: fHxfWxNA box_logits: fHxfWxNAx4 """ with argscope(Conv2D, data_format='channels_first', kernel_initializer=tf.random_normal_initializer(stddev=0.01)): hidden = Conv2D('conv0', featuremap,...
[ "Returns", ":", "label_logits", ":", "fHxfWxNA", "box_logits", ":", "fHxfWxNAx4" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_rpn.py#L16-L36
[ "def", "rpn_head", "(", "featuremap", ",", "channel", ",", "num_anchors", ")", ":", "with", "argscope", "(", "Conv2D", ",", "data_format", "=", "'channels_first'", ",", "kernel_initializer", "=", "tf", ".", "random_normal_initializer", "(", "stddev", "=", "0.01"...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
rpn_losses
Args: anchor_labels: fHxfWxNA anchor_boxes: fHxfWxNAx4, encoded label_logits: fHxfWxNA box_logits: fHxfWxNAx4 Returns: label_loss, box_loss
examples/FasterRCNN/model_rpn.py
def rpn_losses(anchor_labels, anchor_boxes, label_logits, box_logits): """ Args: anchor_labels: fHxfWxNA anchor_boxes: fHxfWxNAx4, encoded label_logits: fHxfWxNA box_logits: fHxfWxNAx4 Returns: label_loss, box_loss """ with tf.device('/cpu:0'): valid...
def rpn_losses(anchor_labels, anchor_boxes, label_logits, box_logits): """ Args: anchor_labels: fHxfWxNA anchor_boxes: fHxfWxNAx4, encoded label_logits: fHxfWxNA box_logits: fHxfWxNAx4 Returns: label_loss, box_loss """ with tf.device('/cpu:0'): valid...
[ "Args", ":", "anchor_labels", ":", "fHxfWxNA", "anchor_boxes", ":", "fHxfWxNAx4", "encoded", "label_logits", ":", "fHxfWxNA", "box_logits", ":", "fHxfWxNAx4" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_rpn.py#L40-L100
[ "def", "rpn_losses", "(", "anchor_labels", ",", "anchor_boxes", ",", "label_logits", ",", "box_logits", ")", ":", "with", "tf", ".", "device", "(", "'/cpu:0'", ")", ":", "valid_mask", "=", "tf", ".", "stop_gradient", "(", "tf", ".", "not_equal", "(", "anch...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
generate_rpn_proposals
Sample RPN proposals by the following steps: 1. Pick top k1 by scores 2. NMS them 3. Pick top k2 by scores. Default k2 == k1, i.e. does not filter the NMS output. Args: boxes: nx4 float dtype, the proposal boxes. Decoded to floatbox already scores: n float, the logits img_shape:...
examples/FasterRCNN/model_rpn.py
def generate_rpn_proposals(boxes, scores, img_shape, pre_nms_topk, post_nms_topk=None): """ Sample RPN proposals by the following steps: 1. Pick top k1 by scores 2. NMS them 3. Pick top k2 by scores. Default k2 == k1, i.e. does not filter the NMS output. Args: ...
def generate_rpn_proposals(boxes, scores, img_shape, pre_nms_topk, post_nms_topk=None): """ Sample RPN proposals by the following steps: 1. Pick top k1 by scores 2. NMS them 3. Pick top k2 by scores. Default k2 == k1, i.e. does not filter the NMS output. Args: ...
[ "Sample", "RPN", "proposals", "by", "the", "following", "steps", ":", "1", ".", "Pick", "top", "k1", "by", "scores", "2", ".", "NMS", "them", "3", ".", "Pick", "top", "k2", "by", "scores", ".", "Default", "k2", "==", "k1", "i", ".", "e", ".", "do...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_rpn.py#L104-L153
[ "def", "generate_rpn_proposals", "(", "boxes", ",", "scores", ",", "img_shape", ",", "pre_nms_topk", ",", "post_nms_topk", "=", "None", ")", ":", "assert", "boxes", ".", "shape", ".", "ndims", "==", "2", ",", "boxes", ".", "shape", "if", "post_nms_topk", "...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
MergeAllSummaries
This callback is enabled by default. Evaluate all summaries by ``tf.summary.merge_all``, and write them to logs. Args: period (int): by default the callback summarizes once every epoch. This option (if not set to 0) makes it additionally summarize every ``period`` steps. run_alone (...
tensorpack/callbacks/summary.py
def MergeAllSummaries(period=0, run_alone=False, key=None): """ This callback is enabled by default. Evaluate all summaries by ``tf.summary.merge_all``, and write them to logs. Args: period (int): by default the callback summarizes once every epoch. This option (if not set to 0) mak...
def MergeAllSummaries(period=0, run_alone=False, key=None): """ This callback is enabled by default. Evaluate all summaries by ``tf.summary.merge_all``, and write them to logs. Args: period (int): by default the callback summarizes once every epoch. This option (if not set to 0) mak...
[ "This", "callback", "is", "enabled", "by", "default", ".", "Evaluate", "all", "summaries", "by", "tf", ".", "summary", ".", "merge_all", "and", "write", "them", "to", "logs", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/summary.py#L119-L142
[ "def", "MergeAllSummaries", "(", "period", "=", "0", ",", "run_alone", "=", "False", ",", "key", "=", "None", ")", ":", "if", "key", "is", "None", ":", "key", "=", "tf", ".", "GraphKeys", ".", "SUMMARIES", "period", "=", "int", "(", "period", ")", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
ReplayMemory.append
Args: exp (Experience):
examples/DeepQNetwork/expreplay.py
def append(self, exp): """ Args: exp (Experience): """ if self._curr_size < self.max_size: self._assign(self._curr_pos, exp) self._curr_pos = (self._curr_pos + 1) % self.max_size self._curr_size += 1 else: self._assign(s...
def append(self, exp): """ Args: exp (Experience): """ if self._curr_size < self.max_size: self._assign(self._curr_pos, exp) self._curr_pos = (self._curr_pos + 1) % self.max_size self._curr_size += 1 else: self._assign(s...
[ "Args", ":", "exp", "(", "Experience", ")", ":" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DeepQNetwork/expreplay.py#L53-L64
[ "def", "append", "(", "self", ",", "exp", ")", ":", "if", "self", ".", "_curr_size", "<", "self", ".", "max_size", ":", "self", ".", "_assign", "(", "self", ".", "_curr_pos", ",", "exp", ")", "self", ".", "_curr_pos", "=", "(", "self", ".", "_curr_...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
ReplayMemory.sample
return a tuple of (s,r,a,o), where s is of shape self._output_shape, which is [H, W, (hist_len+1) * channel] if input is (H, W, channel)
examples/DeepQNetwork/expreplay.py
def sample(self, idx): """ return a tuple of (s,r,a,o), where s is of shape self._output_shape, which is [H, W, (hist_len+1) * channel] if input is (H, W, channel)""" idx = (self._curr_pos + idx) % self._curr_size k = self.history_len + 1 if idx + k <= self._curr_...
def sample(self, idx): """ return a tuple of (s,r,a,o), where s is of shape self._output_shape, which is [H, W, (hist_len+1) * channel] if input is (H, W, channel)""" idx = (self._curr_pos + idx) % self._curr_size k = self.history_len + 1 if idx + k <= self._curr_...
[ "return", "a", "tuple", "of", "(", "s", "r", "a", "o", ")", "where", "s", "is", "of", "shape", "self", ".", "_output_shape", "which", "is", "[", "H", "W", "(", "hist_len", "+", "1", ")", "*", "channel", "]", "if", "input", "is", "(", "H", "W", ...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DeepQNetwork/expreplay.py#L66-L84
[ "def", "sample", "(", "self", ",", "idx", ")", ":", "idx", "=", "(", "self", ".", "_curr_pos", "+", "idx", ")", "%", "self", ".", "_curr_size", "k", "=", "self", ".", "history_len", "+", "1", "if", "idx", "+", "k", "<=", "self", ".", "_curr_size"...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
EnvRunner.step
Run the environment for one step. If the episode ends, store the entire episode to the replay memory.
examples/DeepQNetwork/expreplay.py
def step(self, exploration): """ Run the environment for one step. If the episode ends, store the entire episode to the replay memory. """ old_s = self._current_ob if self.rng.rand() <= exploration: act = self.rng.choice(range(self.num_actions)) else: ...
def step(self, exploration): """ Run the environment for one step. If the episode ends, store the entire episode to the replay memory. """ old_s = self._current_ob if self.rng.rand() <= exploration: act = self.rng.choice(range(self.num_actions)) else: ...
[ "Run", "the", "environment", "for", "one", "step", ".", "If", "the", "episode", "ends", "store", "the", "entire", "episode", "to", "the", "replay", "memory", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DeepQNetwork/expreplay.py#L143-L182
[ "def", "step", "(", "self", ",", "exploration", ")", ":", "old_s", "=", "self", ".", "_current_ob", "if", "self", ".", "rng", ".", "rand", "(", ")", "<=", "exploration", ":", "act", "=", "self", ".", "rng", ".", "choice", "(", "range", "(", "self",...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
EnvRunner.recent_state
Get the recent state (with stacked history) of the environment. Returns: a list of ``hist_len-1`` elements, each of shape ``self.state_shape``
examples/DeepQNetwork/expreplay.py
def recent_state(self): """ Get the recent state (with stacked history) of the environment. Returns: a list of ``hist_len-1`` elements, each of shape ``self.state_shape`` """ expected_len = self.history_len - 1 if len(self._current_episode) >= expected_len: ...
def recent_state(self): """ Get the recent state (with stacked history) of the environment. Returns: a list of ``hist_len-1`` elements, each of shape ``self.state_shape`` """ expected_len = self.history_len - 1 if len(self._current_episode) >= expected_len: ...
[ "Get", "the", "recent", "state", "(", "with", "stacked", "history", ")", "of", "the", "environment", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DeepQNetwork/expreplay.py#L184-L197
[ "def", "recent_state", "(", "self", ")", ":", "expected_len", "=", "self", ".", "history_len", "-", "1", "if", "len", "(", "self", ".", "_current_episode", ")", ">=", "expected_len", ":", "return", "[", "k", ".", "state", "for", "k", "in", "self", ".",...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
EnvRunnerManager.step
Execute one step in any of the runners.
examples/DeepQNetwork/expreplay.py
def step(self, exploration): """ Execute one step in any of the runners. """ if len(self._runners) > 1: self._populate_job_queue.put(exploration) else: self._runners[0].step(exploration)
def step(self, exploration): """ Execute one step in any of the runners. """ if len(self._runners) > 1: self._populate_job_queue.put(exploration) else: self._runners[0].step(exploration)
[ "Execute", "one", "step", "in", "any", "of", "the", "runners", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DeepQNetwork/expreplay.py#L233-L240
[ "def", "step", "(", "self", ",", "exploration", ")", ":", "if", "len", "(", "self", ".", "_runners", ")", ">", "1", ":", "self", ".", "_populate_job_queue", ".", "put", "(", "exploration", ")", "else", ":", "self", ".", "_runners", "[", "0", "]", "...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f