repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
tensorpack/tensorpack
tensorpack/models/nonlin.py
PReLU
def PReLU(x, init=0.001, name='output'): """ Parameterized ReLU as in the paper `Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification <http://arxiv.org/abs/1502.01852>`_. Args: x (tf.Tensor): input init (float): initial value for the learnable slope. name (str): name of the output. Variable Names: * ``alpha``: learnable slope. """ init = tfv1.constant_initializer(init) alpha = tfv1.get_variable('alpha', [], initializer=init) x = ((1 + alpha) * x + (1 - alpha) * tf.abs(x)) ret = tf.multiply(x, 0.5, name=name) ret.variables = VariableHolder(alpha=alpha) return ret
python
def PReLU(x, init=0.001, name='output'): """ Parameterized ReLU as in the paper `Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification <http://arxiv.org/abs/1502.01852>`_. Args: x (tf.Tensor): input init (float): initial value for the learnable slope. name (str): name of the output. Variable Names: * ``alpha``: learnable slope. """ init = tfv1.constant_initializer(init) alpha = tfv1.get_variable('alpha', [], initializer=init) x = ((1 + alpha) * x + (1 - alpha) * tf.abs(x)) ret = tf.multiply(x, 0.5, name=name) ret.variables = VariableHolder(alpha=alpha) return ret
[ "def", "PReLU", "(", "x", ",", "init", "=", "0.001", ",", "name", "=", "'output'", ")", ":", "init", "=", "tfv1", ".", "constant_initializer", "(", "init", ")", "alpha", "=", "tfv1", ".", "get_variable", "(", "'alpha'", ",", "[", "]", ",", "initializer", "=", "init", ")", "x", "=", "(", "(", "1", "+", "alpha", ")", "*", "x", "+", "(", "1", "-", "alpha", ")", "*", "tf", ".", "abs", "(", "x", ")", ")", "ret", "=", "tf", ".", "multiply", "(", "x", ",", "0.5", ",", "name", "=", "name", ")", "ret", ".", "variables", "=", "VariableHolder", "(", "alpha", "=", "alpha", ")", "return", "ret" ]
Parameterized ReLU as in the paper `Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification <http://arxiv.org/abs/1502.01852>`_. Args: x (tf.Tensor): input init (float): initial value for the learnable slope. name (str): name of the output. Variable Names: * ``alpha``: learnable slope.
[ "Parameterized", "ReLU", "as", "in", "the", "paper", "Delving", "Deep", "into", "Rectifiers", ":", "Surpassing", "Human", "-", "Level", "Performance", "on", "ImageNet", "Classification", "<http", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1502", ".", "01852", ">", "_", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/nonlin.py#L39-L60
train
tensorpack/tensorpack
tensorpack/models/nonlin.py
BNReLU
def BNReLU(x, name=None): """ A shorthand of BatchNormalization + ReLU. """ x = BatchNorm('bn', x) x = tf.nn.relu(x, name=name) return x
python
def BNReLU(x, name=None): """ A shorthand of BatchNormalization + ReLU. """ x = BatchNorm('bn', x) x = tf.nn.relu(x, name=name) return x
[ "def", "BNReLU", "(", "x", ",", "name", "=", "None", ")", ":", "x", "=", "BatchNorm", "(", "'bn'", ",", "x", ")", "x", "=", "tf", ".", "nn", ".", "relu", "(", "x", ",", "name", "=", "name", ")", "return", "x" ]
A shorthand of BatchNormalization + ReLU.
[ "A", "shorthand", "of", "BatchNormalization", "+", "ReLU", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/nonlin.py#L64-L70
train
tensorpack/tensorpack
examples/FasterRCNN/backbone.py
GroupNorm
def GroupNorm(x, group=32, gamma_initializer=tf.constant_initializer(1.)): """ More code that reproduces the paper can be found at https://github.com/ppwwyyxx/GroupNorm-reproduce/. """ shape = x.get_shape().as_list() ndims = len(shape) assert ndims == 4, shape chan = shape[1] assert chan % group == 0, chan group_size = chan // group orig_shape = tf.shape(x) h, w = orig_shape[2], orig_shape[3] x = tf.reshape(x, tf.stack([-1, group, group_size, h, w])) mean, var = tf.nn.moments(x, [2, 3, 4], keep_dims=True) new_shape = [1, group, group_size, 1, 1] beta = tf.get_variable('beta', [chan], initializer=tf.constant_initializer()) beta = tf.reshape(beta, new_shape) gamma = tf.get_variable('gamma', [chan], initializer=gamma_initializer) gamma = tf.reshape(gamma, new_shape) out = tf.nn.batch_normalization(x, mean, var, beta, gamma, 1e-5, name='output') return tf.reshape(out, orig_shape, name='output')
python
def GroupNorm(x, group=32, gamma_initializer=tf.constant_initializer(1.)): """ More code that reproduces the paper can be found at https://github.com/ppwwyyxx/GroupNorm-reproduce/. """ shape = x.get_shape().as_list() ndims = len(shape) assert ndims == 4, shape chan = shape[1] assert chan % group == 0, chan group_size = chan // group orig_shape = tf.shape(x) h, w = orig_shape[2], orig_shape[3] x = tf.reshape(x, tf.stack([-1, group, group_size, h, w])) mean, var = tf.nn.moments(x, [2, 3, 4], keep_dims=True) new_shape = [1, group, group_size, 1, 1] beta = tf.get_variable('beta', [chan], initializer=tf.constant_initializer()) beta = tf.reshape(beta, new_shape) gamma = tf.get_variable('gamma', [chan], initializer=gamma_initializer) gamma = tf.reshape(gamma, new_shape) out = tf.nn.batch_normalization(x, mean, var, beta, gamma, 1e-5, name='output') return tf.reshape(out, orig_shape, name='output')
[ "def", "GroupNorm", "(", "x", ",", "group", "=", "32", ",", "gamma_initializer", "=", "tf", ".", "constant_initializer", "(", "1.", ")", ")", ":", "shape", "=", "x", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "ndims", "=", "len", "(", "shape", ")", "assert", "ndims", "==", "4", ",", "shape", "chan", "=", "shape", "[", "1", "]", "assert", "chan", "%", "group", "==", "0", ",", "chan", "group_size", "=", "chan", "//", "group", "orig_shape", "=", "tf", ".", "shape", "(", "x", ")", "h", ",", "w", "=", "orig_shape", "[", "2", "]", ",", "orig_shape", "[", "3", "]", "x", "=", "tf", ".", "reshape", "(", "x", ",", "tf", ".", "stack", "(", "[", "-", "1", ",", "group", ",", "group_size", ",", "h", ",", "w", "]", ")", ")", "mean", ",", "var", "=", "tf", ".", "nn", ".", "moments", "(", "x", ",", "[", "2", ",", "3", ",", "4", "]", ",", "keep_dims", "=", "True", ")", "new_shape", "=", "[", "1", ",", "group", ",", "group_size", ",", "1", ",", "1", "]", "beta", "=", "tf", ".", "get_variable", "(", "'beta'", ",", "[", "chan", "]", ",", "initializer", "=", "tf", ".", "constant_initializer", "(", ")", ")", "beta", "=", "tf", ".", "reshape", "(", "beta", ",", "new_shape", ")", "gamma", "=", "tf", ".", "get_variable", "(", "'gamma'", ",", "[", "chan", "]", ",", "initializer", "=", "gamma_initializer", ")", "gamma", "=", "tf", ".", "reshape", "(", "gamma", ",", "new_shape", ")", "out", "=", "tf", ".", "nn", ".", "batch_normalization", "(", "x", ",", "mean", ",", "var", ",", "beta", ",", "gamma", ",", "1e-5", ",", "name", "=", "'output'", ")", "return", "tf", ".", "reshape", "(", "out", ",", "orig_shape", ",", "name", "=", "'output'", ")" ]
More code that reproduces the paper can be found at https://github.com/ppwwyyxx/GroupNorm-reproduce/.
[ "More", "code", "that", "reproduces", "the", "paper", "can", "be", "found", "at", "https", ":", "//", "github", ".", "com", "/", "ppwwyyxx", "/", "GroupNorm", "-", "reproduce", "/", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/backbone.py#L17-L44
train
tensorpack/tensorpack
examples/FasterRCNN/backbone.py
backbone_scope
def backbone_scope(freeze): """ Args: freeze (bool): whether to freeze all the variables under the scope """ def nonlin(x): x = get_norm()(x) return tf.nn.relu(x) with argscope([Conv2D, MaxPooling, BatchNorm], data_format='channels_first'), \ argscope(Conv2D, use_bias=False, activation=nonlin, kernel_initializer=tf.variance_scaling_initializer( scale=2.0, mode='fan_out')), \ ExitStack() as stack: if cfg.BACKBONE.NORM in ['FreezeBN', 'SyncBN']: if freeze or cfg.BACKBONE.NORM == 'FreezeBN': stack.enter_context(argscope(BatchNorm, training=False)) else: stack.enter_context(argscope( BatchNorm, sync_statistics='nccl' if cfg.TRAINER == 'replicated' else 'horovod')) if freeze: stack.enter_context(freeze_variables(stop_gradient=False, skip_collection=True)) else: # the layers are not completely freezed, but we may want to only freeze the affine if cfg.BACKBONE.FREEZE_AFFINE: stack.enter_context(custom_getter_scope(freeze_affine_getter)) yield
python
def backbone_scope(freeze): """ Args: freeze (bool): whether to freeze all the variables under the scope """ def nonlin(x): x = get_norm()(x) return tf.nn.relu(x) with argscope([Conv2D, MaxPooling, BatchNorm], data_format='channels_first'), \ argscope(Conv2D, use_bias=False, activation=nonlin, kernel_initializer=tf.variance_scaling_initializer( scale=2.0, mode='fan_out')), \ ExitStack() as stack: if cfg.BACKBONE.NORM in ['FreezeBN', 'SyncBN']: if freeze or cfg.BACKBONE.NORM == 'FreezeBN': stack.enter_context(argscope(BatchNorm, training=False)) else: stack.enter_context(argscope( BatchNorm, sync_statistics='nccl' if cfg.TRAINER == 'replicated' else 'horovod')) if freeze: stack.enter_context(freeze_variables(stop_gradient=False, skip_collection=True)) else: # the layers are not completely freezed, but we may want to only freeze the affine if cfg.BACKBONE.FREEZE_AFFINE: stack.enter_context(custom_getter_scope(freeze_affine_getter)) yield
[ "def", "backbone_scope", "(", "freeze", ")", ":", "def", "nonlin", "(", "x", ")", ":", "x", "=", "get_norm", "(", ")", "(", "x", ")", "return", "tf", ".", "nn", ".", "relu", "(", "x", ")", "with", "argscope", "(", "[", "Conv2D", ",", "MaxPooling", ",", "BatchNorm", "]", ",", "data_format", "=", "'channels_first'", ")", ",", "argscope", "(", "Conv2D", ",", "use_bias", "=", "False", ",", "activation", "=", "nonlin", ",", "kernel_initializer", "=", "tf", ".", "variance_scaling_initializer", "(", "scale", "=", "2.0", ",", "mode", "=", "'fan_out'", ")", ")", ",", "ExitStack", "(", ")", "as", "stack", ":", "if", "cfg", ".", "BACKBONE", ".", "NORM", "in", "[", "'FreezeBN'", ",", "'SyncBN'", "]", ":", "if", "freeze", "or", "cfg", ".", "BACKBONE", ".", "NORM", "==", "'FreezeBN'", ":", "stack", ".", "enter_context", "(", "argscope", "(", "BatchNorm", ",", "training", "=", "False", ")", ")", "else", ":", "stack", ".", "enter_context", "(", "argscope", "(", "BatchNorm", ",", "sync_statistics", "=", "'nccl'", "if", "cfg", ".", "TRAINER", "==", "'replicated'", "else", "'horovod'", ")", ")", "if", "freeze", ":", "stack", ".", "enter_context", "(", "freeze_variables", "(", "stop_gradient", "=", "False", ",", "skip_collection", "=", "True", ")", ")", "else", ":", "# the layers are not completely freezed, but we may want to only freeze the affine", "if", "cfg", ".", "BACKBONE", ".", "FREEZE_AFFINE", ":", "stack", ".", "enter_context", "(", "custom_getter_scope", "(", "freeze_affine_getter", ")", ")", "yield" ]
Args: freeze (bool): whether to freeze all the variables under the scope
[ "Args", ":", "freeze", "(", "bool", ")", ":", "whether", "to", "freeze", "all", "the", "variables", "under", "the", "scope" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/backbone.py#L66-L93
train
tensorpack/tensorpack
tensorpack/dataflow/dataset/mnist.py
extract_images
def extract_images(filename): """Extract the images into a 4D uint8 numpy array [index, y, x, depth].""" with gzip.open(filename) as bytestream: magic = _read32(bytestream) if magic != 2051: raise ValueError( 'Invalid magic number %d in MNIST image file: %s' % (magic, filename)) num_images = _read32(bytestream) rows = _read32(bytestream) cols = _read32(bytestream) buf = bytestream.read(rows * cols * num_images) data = numpy.frombuffer(buf, dtype=numpy.uint8) data = data.reshape(num_images, rows, cols, 1) data = data.astype('float32') / 255.0 return data
python
def extract_images(filename): """Extract the images into a 4D uint8 numpy array [index, y, x, depth].""" with gzip.open(filename) as bytestream: magic = _read32(bytestream) if magic != 2051: raise ValueError( 'Invalid magic number %d in MNIST image file: %s' % (magic, filename)) num_images = _read32(bytestream) rows = _read32(bytestream) cols = _read32(bytestream) buf = bytestream.read(rows * cols * num_images) data = numpy.frombuffer(buf, dtype=numpy.uint8) data = data.reshape(num_images, rows, cols, 1) data = data.astype('float32') / 255.0 return data
[ "def", "extract_images", "(", "filename", ")", ":", "with", "gzip", ".", "open", "(", "filename", ")", "as", "bytestream", ":", "magic", "=", "_read32", "(", "bytestream", ")", "if", "magic", "!=", "2051", ":", "raise", "ValueError", "(", "'Invalid magic number %d in MNIST image file: %s'", "%", "(", "magic", ",", "filename", ")", ")", "num_images", "=", "_read32", "(", "bytestream", ")", "rows", "=", "_read32", "(", "bytestream", ")", "cols", "=", "_read32", "(", "bytestream", ")", "buf", "=", "bytestream", ".", "read", "(", "rows", "*", "cols", "*", "num_images", ")", "data", "=", "numpy", ".", "frombuffer", "(", "buf", ",", "dtype", "=", "numpy", ".", "uint8", ")", "data", "=", "data", ".", "reshape", "(", "num_images", ",", "rows", ",", "cols", ",", "1", ")", "data", "=", "data", ".", "astype", "(", "'float32'", ")", "/", "255.0", "return", "data" ]
Extract the images into a 4D uint8 numpy array [index, y, x, depth].
[ "Extract", "the", "images", "into", "a", "4D", "uint8", "numpy", "array", "[", "index", "y", "x", "depth", "]", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/dataset/mnist.py#L32-L47
train
tensorpack/tensorpack
tensorpack/dataflow/dataset/mnist.py
extract_labels
def extract_labels(filename): """Extract the labels into a 1D uint8 numpy array [index].""" with gzip.open(filename) as bytestream: magic = _read32(bytestream) if magic != 2049: raise ValueError( 'Invalid magic number %d in MNIST label file: %s' % (magic, filename)) num_items = _read32(bytestream) buf = bytestream.read(num_items) labels = numpy.frombuffer(buf, dtype=numpy.uint8) return labels
python
def extract_labels(filename): """Extract the labels into a 1D uint8 numpy array [index].""" with gzip.open(filename) as bytestream: magic = _read32(bytestream) if magic != 2049: raise ValueError( 'Invalid magic number %d in MNIST label file: %s' % (magic, filename)) num_items = _read32(bytestream) buf = bytestream.read(num_items) labels = numpy.frombuffer(buf, dtype=numpy.uint8) return labels
[ "def", "extract_labels", "(", "filename", ")", ":", "with", "gzip", ".", "open", "(", "filename", ")", "as", "bytestream", ":", "magic", "=", "_read32", "(", "bytestream", ")", "if", "magic", "!=", "2049", ":", "raise", "ValueError", "(", "'Invalid magic number %d in MNIST label file: %s'", "%", "(", "magic", ",", "filename", ")", ")", "num_items", "=", "_read32", "(", "bytestream", ")", "buf", "=", "bytestream", ".", "read", "(", "num_items", ")", "labels", "=", "numpy", ".", "frombuffer", "(", "buf", ",", "dtype", "=", "numpy", ".", "uint8", ")", "return", "labels" ]
Extract the labels into a 1D uint8 numpy array [index].
[ "Extract", "the", "labels", "into", "a", "1D", "uint8", "numpy", "array", "[", "index", "]", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/dataset/mnist.py#L50-L61
train
tensorpack/tensorpack
tensorpack/utils/develop.py
create_dummy_class
def create_dummy_class(klass, dependency): """ When a dependency of a class is not available, create a dummy class which throws ImportError when used. Args: klass (str): name of the class. dependency (str): name of the dependency. Returns: class: a class object """ assert not building_rtfd() class _DummyMetaClass(type): # throw error on class attribute access def __getattr__(_, __): raise AttributeError("Cannot import '{}', therefore '{}' is not available".format(dependency, klass)) @six.add_metaclass(_DummyMetaClass) class _Dummy(object): # throw error on constructor def __init__(self, *args, **kwargs): raise ImportError("Cannot import '{}', therefore '{}' is not available".format(dependency, klass)) return _Dummy
python
def create_dummy_class(klass, dependency): """ When a dependency of a class is not available, create a dummy class which throws ImportError when used. Args: klass (str): name of the class. dependency (str): name of the dependency. Returns: class: a class object """ assert not building_rtfd() class _DummyMetaClass(type): # throw error on class attribute access def __getattr__(_, __): raise AttributeError("Cannot import '{}', therefore '{}' is not available".format(dependency, klass)) @six.add_metaclass(_DummyMetaClass) class _Dummy(object): # throw error on constructor def __init__(self, *args, **kwargs): raise ImportError("Cannot import '{}', therefore '{}' is not available".format(dependency, klass)) return _Dummy
[ "def", "create_dummy_class", "(", "klass", ",", "dependency", ")", ":", "assert", "not", "building_rtfd", "(", ")", "class", "_DummyMetaClass", "(", "type", ")", ":", "# throw error on class attribute access", "def", "__getattr__", "(", "_", ",", "__", ")", ":", "raise", "AttributeError", "(", "\"Cannot import '{}', therefore '{}' is not available\"", ".", "format", "(", "dependency", ",", "klass", ")", ")", "@", "six", ".", "add_metaclass", "(", "_DummyMetaClass", ")", "class", "_Dummy", "(", "object", ")", ":", "# throw error on constructor", "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "raise", "ImportError", "(", "\"Cannot import '{}', therefore '{}' is not available\"", ".", "format", "(", "dependency", ",", "klass", ")", ")", "return", "_Dummy" ]
When a dependency of a class is not available, create a dummy class which throws ImportError when used. Args: klass (str): name of the class. dependency (str): name of the dependency. Returns: class: a class object
[ "When", "a", "dependency", "of", "a", "class", "is", "not", "available", "create", "a", "dummy", "class", "which", "throws", "ImportError", "when", "used", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/develop.py#L21-L45
train
tensorpack/tensorpack
tensorpack/utils/develop.py
create_dummy_func
def create_dummy_func(func, dependency): """ When a dependency of a function is not available, create a dummy function which throws ImportError when used. Args: func (str): name of the function. dependency (str or list[str]): name(s) of the dependency. Returns: function: a function object """ assert not building_rtfd() if isinstance(dependency, (list, tuple)): dependency = ','.join(dependency) def _dummy(*args, **kwargs): raise ImportError("Cannot import '{}', therefore '{}' is not available".format(dependency, func)) return _dummy
python
def create_dummy_func(func, dependency): """ When a dependency of a function is not available, create a dummy function which throws ImportError when used. Args: func (str): name of the function. dependency (str or list[str]): name(s) of the dependency. Returns: function: a function object """ assert not building_rtfd() if isinstance(dependency, (list, tuple)): dependency = ','.join(dependency) def _dummy(*args, **kwargs): raise ImportError("Cannot import '{}', therefore '{}' is not available".format(dependency, func)) return _dummy
[ "def", "create_dummy_func", "(", "func", ",", "dependency", ")", ":", "assert", "not", "building_rtfd", "(", ")", "if", "isinstance", "(", "dependency", ",", "(", "list", ",", "tuple", ")", ")", ":", "dependency", "=", "','", ".", "join", "(", "dependency", ")", "def", "_dummy", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "raise", "ImportError", "(", "\"Cannot import '{}', therefore '{}' is not available\"", ".", "format", "(", "dependency", ",", "func", ")", ")", "return", "_dummy" ]
When a dependency of a function is not available, create a dummy function which throws ImportError when used. Args: func (str): name of the function. dependency (str or list[str]): name(s) of the dependency. Returns: function: a function object
[ "When", "a", "dependency", "of", "a", "function", "is", "not", "available", "create", "a", "dummy", "function", "which", "throws", "ImportError", "when", "used", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/develop.py#L48-L66
train
tensorpack/tensorpack
tensorpack/utils/develop.py
log_deprecated
def log_deprecated(name="", text="", eos=""): """ Log deprecation warning. Args: name (str): name of the deprecated item. text (str, optional): information about the deprecation. eos (str, optional): end of service date such as "YYYY-MM-DD". """ assert name or text if eos: eos = "after " + datetime(*map(int, eos.split("-"))).strftime("%d %b") if name: if eos: warn_msg = "%s will be deprecated %s. %s" % (name, eos, text) else: warn_msg = "%s was deprecated. %s" % (name, text) else: warn_msg = text if eos: warn_msg += " Legacy period ends %s" % eos logger.warn("[Deprecated] " + warn_msg)
python
def log_deprecated(name="", text="", eos=""): """ Log deprecation warning. Args: name (str): name of the deprecated item. text (str, optional): information about the deprecation. eos (str, optional): end of service date such as "YYYY-MM-DD". """ assert name or text if eos: eos = "after " + datetime(*map(int, eos.split("-"))).strftime("%d %b") if name: if eos: warn_msg = "%s will be deprecated %s. %s" % (name, eos, text) else: warn_msg = "%s was deprecated. %s" % (name, text) else: warn_msg = text if eos: warn_msg += " Legacy period ends %s" % eos logger.warn("[Deprecated] " + warn_msg)
[ "def", "log_deprecated", "(", "name", "=", "\"\"", ",", "text", "=", "\"\"", ",", "eos", "=", "\"\"", ")", ":", "assert", "name", "or", "text", "if", "eos", ":", "eos", "=", "\"after \"", "+", "datetime", "(", "*", "map", "(", "int", ",", "eos", ".", "split", "(", "\"-\"", ")", ")", ")", ".", "strftime", "(", "\"%d %b\"", ")", "if", "name", ":", "if", "eos", ":", "warn_msg", "=", "\"%s will be deprecated %s. %s\"", "%", "(", "name", ",", "eos", ",", "text", ")", "else", ":", "warn_msg", "=", "\"%s was deprecated. %s\"", "%", "(", "name", ",", "text", ")", "else", ":", "warn_msg", "=", "text", "if", "eos", ":", "warn_msg", "+=", "\" Legacy period ends %s\"", "%", "eos", "logger", ".", "warn", "(", "\"[Deprecated] \"", "+", "warn_msg", ")" ]
Log deprecation warning. Args: name (str): name of the deprecated item. text (str, optional): information about the deprecation. eos (str, optional): end of service date such as "YYYY-MM-DD".
[ "Log", "deprecation", "warning", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/develop.py#L78-L99
train
tensorpack/tensorpack
tensorpack/utils/develop.py
deprecated
def deprecated(text="", eos=""): """ Args: text, eos: same as :func:`log_deprecated`. Returns: a decorator which deprecates the function. Example: .. code-block:: python @deprecated("Explanation of what to do instead.", "2017-11-4") def foo(...): pass """ def get_location(): import inspect frame = inspect.currentframe() if frame: callstack = inspect.getouterframes(frame)[-1] return '%s:%i' % (callstack[1], callstack[2]) else: stack = inspect.stack(0) entry = stack[2] return '%s:%i' % (entry[1], entry[2]) def deprecated_inner(func): @functools.wraps(func) def new_func(*args, **kwargs): name = "{} [{}]".format(func.__name__, get_location()) log_deprecated(name, text, eos) return func(*args, **kwargs) return new_func return deprecated_inner
python
def deprecated(text="", eos=""): """ Args: text, eos: same as :func:`log_deprecated`. Returns: a decorator which deprecates the function. Example: .. code-block:: python @deprecated("Explanation of what to do instead.", "2017-11-4") def foo(...): pass """ def get_location(): import inspect frame = inspect.currentframe() if frame: callstack = inspect.getouterframes(frame)[-1] return '%s:%i' % (callstack[1], callstack[2]) else: stack = inspect.stack(0) entry = stack[2] return '%s:%i' % (entry[1], entry[2]) def deprecated_inner(func): @functools.wraps(func) def new_func(*args, **kwargs): name = "{} [{}]".format(func.__name__, get_location()) log_deprecated(name, text, eos) return func(*args, **kwargs) return new_func return deprecated_inner
[ "def", "deprecated", "(", "text", "=", "\"\"", ",", "eos", "=", "\"\"", ")", ":", "def", "get_location", "(", ")", ":", "import", "inspect", "frame", "=", "inspect", ".", "currentframe", "(", ")", "if", "frame", ":", "callstack", "=", "inspect", ".", "getouterframes", "(", "frame", ")", "[", "-", "1", "]", "return", "'%s:%i'", "%", "(", "callstack", "[", "1", "]", ",", "callstack", "[", "2", "]", ")", "else", ":", "stack", "=", "inspect", ".", "stack", "(", "0", ")", "entry", "=", "stack", "[", "2", "]", "return", "'%s:%i'", "%", "(", "entry", "[", "1", "]", ",", "entry", "[", "2", "]", ")", "def", "deprecated_inner", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "new_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "name", "=", "\"{} [{}]\"", ".", "format", "(", "func", ".", "__name__", ",", "get_location", "(", ")", ")", "log_deprecated", "(", "name", ",", "text", ",", "eos", ")", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "new_func", "return", "deprecated_inner" ]
Args: text, eos: same as :func:`log_deprecated`. Returns: a decorator which deprecates the function. Example: .. code-block:: python @deprecated("Explanation of what to do instead.", "2017-11-4") def foo(...): pass
[ "Args", ":", "text", "eos", ":", "same", "as", ":", "func", ":", "log_deprecated", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/develop.py#L102-L136
train
tensorpack/tensorpack
tensorpack/input_source/input_source.py
QueueInput.refill_queue
def refill_queue(self): """ Clear the queue, then call dataflow.__iter__() again and fill into the queue. """ self.thread.pause() # pause enqueue opt = tfv1.RunOptions() opt.timeout_in_ms = 2000 # 2s sess = tfv1.get_default_session() # dequeue until empty try: while True: sess.run(self._dequeue_op, options=opt) except tf.errors.DeadlineExceededError: pass # reset dataflow, start thread self.thread.reinitialize_dataflow() self.thread.resume()
python
def refill_queue(self): """ Clear the queue, then call dataflow.__iter__() again and fill into the queue. """ self.thread.pause() # pause enqueue opt = tfv1.RunOptions() opt.timeout_in_ms = 2000 # 2s sess = tfv1.get_default_session() # dequeue until empty try: while True: sess.run(self._dequeue_op, options=opt) except tf.errors.DeadlineExceededError: pass # reset dataflow, start thread self.thread.reinitialize_dataflow() self.thread.resume()
[ "def", "refill_queue", "(", "self", ")", ":", "self", ".", "thread", ".", "pause", "(", ")", "# pause enqueue", "opt", "=", "tfv1", ".", "RunOptions", "(", ")", "opt", ".", "timeout_in_ms", "=", "2000", "# 2s", "sess", "=", "tfv1", ".", "get_default_session", "(", ")", "# dequeue until empty", "try", ":", "while", "True", ":", "sess", ".", "run", "(", "self", ".", "_dequeue_op", ",", "options", "=", "opt", ")", "except", "tf", ".", "errors", ".", "DeadlineExceededError", ":", "pass", "# reset dataflow, start thread", "self", ".", "thread", ".", "reinitialize_dataflow", "(", ")", "self", ".", "thread", ".", "resume", "(", ")" ]
Clear the queue, then call dataflow.__iter__() again and fill into the queue.
[ "Clear", "the", "queue", "then", "call", "dataflow", ".", "__iter__", "()", "again", "and", "fill", "into", "the", "queue", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/input_source/input_source.py#L228-L246
train
tensorpack/tensorpack
tensorpack/input_source/input_source.py
QueueInput._create_ema_callback
def _create_ema_callback(self): """ Create a hook-only callback which maintain EMA of the queue size. Also tf.summary.scalar the EMA. """ with self.cached_name_scope(): # in TF there is no API to get queue capacity, so we can only summary the size size = tf.cast(self.queue.size(), tf.float32, name='queue_size') size_ema_op = add_moving_summary(size, collection=None, decay=0.5)[0].op ret = RunOp( lambda: size_ema_op, run_before=False, run_as_trigger=False, run_step=True) ret.name_scope = "InputSource/EMA" return ret
python
def _create_ema_callback(self): """ Create a hook-only callback which maintain EMA of the queue size. Also tf.summary.scalar the EMA. """ with self.cached_name_scope(): # in TF there is no API to get queue capacity, so we can only summary the size size = tf.cast(self.queue.size(), tf.float32, name='queue_size') size_ema_op = add_moving_summary(size, collection=None, decay=0.5)[0].op ret = RunOp( lambda: size_ema_op, run_before=False, run_as_trigger=False, run_step=True) ret.name_scope = "InputSource/EMA" return ret
[ "def", "_create_ema_callback", "(", "self", ")", ":", "with", "self", ".", "cached_name_scope", "(", ")", ":", "# in TF there is no API to get queue capacity, so we can only summary the size", "size", "=", "tf", ".", "cast", "(", "self", ".", "queue", ".", "size", "(", ")", ",", "tf", ".", "float32", ",", "name", "=", "'queue_size'", ")", "size_ema_op", "=", "add_moving_summary", "(", "size", ",", "collection", "=", "None", ",", "decay", "=", "0.5", ")", "[", "0", "]", ".", "op", "ret", "=", "RunOp", "(", "lambda", ":", "size_ema_op", ",", "run_before", "=", "False", ",", "run_as_trigger", "=", "False", ",", "run_step", "=", "True", ")", "ret", ".", "name_scope", "=", "\"InputSource/EMA\"", "return", "ret" ]
Create a hook-only callback which maintain EMA of the queue size. Also tf.summary.scalar the EMA.
[ "Create", "a", "hook", "-", "only", "callback", "which", "maintain", "EMA", "of", "the", "queue", "size", ".", "Also", "tf", ".", "summary", ".", "scalar", "the", "EMA", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/input_source/input_source.py#L248-L263
train
tensorpack/tensorpack
tensorpack/input_source/input_source.py
BatchQueueInput._setup
def _setup(self, inputs): logger.info("Setting up the queue for CPU prefetching ...") self.input_placehdrs = [build_or_reuse_placeholder(v) for v in inputs] assert len(self.input_placehdrs) > 0, \ "BatchQueueInput has to be used with some input signature!" # prepare placeholders without the first dimension placehdrs_nobatch = [] for p in self.input_placehdrs: placehdrs_nobatch.append(tfv1.placeholder( dtype=p.dtype, shape=p.get_shape().as_list()[1:], name=get_op_tensor_name(p.name)[0] + '-nobatch')) # dequeue_many requires fully-defined shapes shape_err = "Use of BatchQueueInput requires inputs to have fully-defined " "shapes except for the batch dimension" shapes = [] for p in placehdrs_nobatch: assert p.get_shape().is_fully_defined(), shape_err shapes.append(p.get_shape()) with self.cached_name_scope(): if self.queue is None: self.queue = tf.FIFOQueue( 3000, [x.dtype for x in self.input_placehdrs], shapes=shapes, name='input_queue') for shp in self.queue.shapes: assert shp.is_fully_defined(), shape_err self.thread = EnqueueThread(self.queue, self._inf_ds, placehdrs_nobatch)
python
def _setup(self, inputs): logger.info("Setting up the queue for CPU prefetching ...") self.input_placehdrs = [build_or_reuse_placeholder(v) for v in inputs] assert len(self.input_placehdrs) > 0, \ "BatchQueueInput has to be used with some input signature!" # prepare placeholders without the first dimension placehdrs_nobatch = [] for p in self.input_placehdrs: placehdrs_nobatch.append(tfv1.placeholder( dtype=p.dtype, shape=p.get_shape().as_list()[1:], name=get_op_tensor_name(p.name)[0] + '-nobatch')) # dequeue_many requires fully-defined shapes shape_err = "Use of BatchQueueInput requires inputs to have fully-defined " "shapes except for the batch dimension" shapes = [] for p in placehdrs_nobatch: assert p.get_shape().is_fully_defined(), shape_err shapes.append(p.get_shape()) with self.cached_name_scope(): if self.queue is None: self.queue = tf.FIFOQueue( 3000, [x.dtype for x in self.input_placehdrs], shapes=shapes, name='input_queue') for shp in self.queue.shapes: assert shp.is_fully_defined(), shape_err self.thread = EnqueueThread(self.queue, self._inf_ds, placehdrs_nobatch)
[ "def", "_setup", "(", "self", ",", "inputs", ")", ":", "logger", ".", "info", "(", "\"Setting up the queue for CPU prefetching ...\"", ")", "self", ".", "input_placehdrs", "=", "[", "build_or_reuse_placeholder", "(", "v", ")", "for", "v", "in", "inputs", "]", "assert", "len", "(", "self", ".", "input_placehdrs", ")", ">", "0", ",", "\"BatchQueueInput has to be used with some input signature!\"", "# prepare placeholders without the first dimension", "placehdrs_nobatch", "=", "[", "]", "for", "p", "in", "self", ".", "input_placehdrs", ":", "placehdrs_nobatch", ".", "append", "(", "tfv1", ".", "placeholder", "(", "dtype", "=", "p", ".", "dtype", ",", "shape", "=", "p", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "[", "1", ":", "]", ",", "name", "=", "get_op_tensor_name", "(", "p", ".", "name", ")", "[", "0", "]", "+", "'-nobatch'", ")", ")", "# dequeue_many requires fully-defined shapes", "shape_err", "=", "\"Use of BatchQueueInput requires inputs to have fully-defined \"", "shapes", "=", "[", "]", "for", "p", "in", "placehdrs_nobatch", ":", "assert", "p", ".", "get_shape", "(", ")", ".", "is_fully_defined", "(", ")", ",", "shape_err", "shapes", ".", "append", "(", "p", ".", "get_shape", "(", ")", ")", "with", "self", ".", "cached_name_scope", "(", ")", ":", "if", "self", ".", "queue", "is", "None", ":", "self", ".", "queue", "=", "tf", ".", "FIFOQueue", "(", "3000", ",", "[", "x", ".", "dtype", "for", "x", "in", "self", ".", "input_placehdrs", "]", ",", "shapes", "=", "shapes", ",", "name", "=", "'input_queue'", ")", "for", "shp", "in", "self", ".", "queue", ".", "shapes", ":", "assert", "shp", ".", "is_fully_defined", "(", ")", ",", "shape_err", "self", ".", "thread", "=", "EnqueueThread", "(", "self", ".", "queue", ",", "self", ".", "_inf_ds", ",", "placehdrs_nobatch", ")" ]
shapes except for the batch dimension
[ "shapes", "except", "for", "the", "batch", "dimension" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/input_source/input_source.py#L301-L331
train
tensorpack/tensorpack
tensorpack/input_source/input_source.py
TFDatasetInput.dataflow_to_dataset
def dataflow_to_dataset(df, types): """ Wrap a dataflow to tf.data.Dataset. This function will also reset the dataflow. If the dataflow itself is finite, the returned dataset is also finite. Therefore, if used for training, you'll need to add `.repeat()` on the returned dataset. Args: df (DataFlow): a dataflow which produces lists types([tf.DType]): list of types Returns: (tf.data.Dataset) """ # TODO theoretically it can support dict assert isinstance(df, DataFlow), df assert isinstance(types, (list, tuple)), types df = MapData(df, lambda dp: tuple(dp)) df.reset_state() ds = tf.data.Dataset.from_generator( df.get_data, tuple(types)) return ds
python
def dataflow_to_dataset(df, types): """ Wrap a dataflow to tf.data.Dataset. This function will also reset the dataflow. If the dataflow itself is finite, the returned dataset is also finite. Therefore, if used for training, you'll need to add `.repeat()` on the returned dataset. Args: df (DataFlow): a dataflow which produces lists types([tf.DType]): list of types Returns: (tf.data.Dataset) """ # TODO theoretically it can support dict assert isinstance(df, DataFlow), df assert isinstance(types, (list, tuple)), types df = MapData(df, lambda dp: tuple(dp)) df.reset_state() ds = tf.data.Dataset.from_generator( df.get_data, tuple(types)) return ds
[ "def", "dataflow_to_dataset", "(", "df", ",", "types", ")", ":", "# TODO theoretically it can support dict", "assert", "isinstance", "(", "df", ",", "DataFlow", ")", ",", "df", "assert", "isinstance", "(", "types", ",", "(", "list", ",", "tuple", ")", ")", ",", "types", "df", "=", "MapData", "(", "df", ",", "lambda", "dp", ":", "tuple", "(", "dp", ")", ")", "df", ".", "reset_state", "(", ")", "ds", "=", "tf", ".", "data", ".", "Dataset", ".", "from_generator", "(", "df", ".", "get_data", ",", "tuple", "(", "types", ")", ")", "return", "ds" ]
Wrap a dataflow to tf.data.Dataset. This function will also reset the dataflow. If the dataflow itself is finite, the returned dataset is also finite. Therefore, if used for training, you'll need to add `.repeat()` on the returned dataset. Args: df (DataFlow): a dataflow which produces lists types([tf.DType]): list of types Returns: (tf.data.Dataset)
[ "Wrap", "a", "dataflow", "to", "tf", ".", "data", ".", "Dataset", ".", "This", "function", "will", "also", "reset", "the", "dataflow", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/input_source/input_source.py#L496-L519
train
tensorpack/tensorpack
tensorpack/predict/multigpu.py
MultiTowerOfflinePredictor.get_predictor
def get_predictor(self, n): """ Returns: OnlinePredictor: the nth predictor on the nth tower. """ l = len(self.predictors) if n >= l: logger.warn("n > #towers, will assign predictor to GPU by round-robin") return [self.predictors[k % l] for k in range(n)]
python
def get_predictor(self, n): """ Returns: OnlinePredictor: the nth predictor on the nth tower. """ l = len(self.predictors) if n >= l: logger.warn("n > #towers, will assign predictor to GPU by round-robin") return [self.predictors[k % l] for k in range(n)]
[ "def", "get_predictor", "(", "self", ",", "n", ")", ":", "l", "=", "len", "(", "self", ".", "predictors", ")", "if", "n", ">=", "l", ":", "logger", ".", "warn", "(", "\"n > #towers, will assign predictor to GPU by round-robin\"", ")", "return", "[", "self", ".", "predictors", "[", "k", "%", "l", "]", "for", "k", "in", "range", "(", "n", ")", "]" ]
Returns: OnlinePredictor: the nth predictor on the nth tower.
[ "Returns", ":", "OnlinePredictor", ":", "the", "nth", "predictor", "on", "the", "nth", "tower", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/predict/multigpu.py#L62-L70
train
tensorpack/tensorpack
examples/FasterRCNN/utils/np_box_ops.py
intersection
def intersection(boxes1, boxes2): """Compute pairwise intersection areas between boxes. Args: boxes1: a numpy array with shape [N, 4] holding N boxes boxes2: a numpy array with shape [M, 4] holding M boxes Returns: a numpy array with shape [N*M] representing pairwise intersection area """ [y_min1, x_min1, y_max1, x_max1] = np.split(boxes1, 4, axis=1) [y_min2, x_min2, y_max2, x_max2] = np.split(boxes2, 4, axis=1) all_pairs_min_ymax = np.minimum(y_max1, np.transpose(y_max2)) all_pairs_max_ymin = np.maximum(y_min1, np.transpose(y_min2)) intersect_heights = np.maximum( np.zeros(all_pairs_max_ymin.shape, dtype='f4'), all_pairs_min_ymax - all_pairs_max_ymin) all_pairs_min_xmax = np.minimum(x_max1, np.transpose(x_max2)) all_pairs_max_xmin = np.maximum(x_min1, np.transpose(x_min2)) intersect_widths = np.maximum( np.zeros(all_pairs_max_xmin.shape, dtype='f4'), all_pairs_min_xmax - all_pairs_max_xmin) return intersect_heights * intersect_widths
python
def intersection(boxes1, boxes2): """Compute pairwise intersection areas between boxes. Args: boxes1: a numpy array with shape [N, 4] holding N boxes boxes2: a numpy array with shape [M, 4] holding M boxes Returns: a numpy array with shape [N*M] representing pairwise intersection area """ [y_min1, x_min1, y_max1, x_max1] = np.split(boxes1, 4, axis=1) [y_min2, x_min2, y_max2, x_max2] = np.split(boxes2, 4, axis=1) all_pairs_min_ymax = np.minimum(y_max1, np.transpose(y_max2)) all_pairs_max_ymin = np.maximum(y_min1, np.transpose(y_min2)) intersect_heights = np.maximum( np.zeros(all_pairs_max_ymin.shape, dtype='f4'), all_pairs_min_ymax - all_pairs_max_ymin) all_pairs_min_xmax = np.minimum(x_max1, np.transpose(x_max2)) all_pairs_max_xmin = np.maximum(x_min1, np.transpose(x_min2)) intersect_widths = np.maximum( np.zeros(all_pairs_max_xmin.shape, dtype='f4'), all_pairs_min_xmax - all_pairs_max_xmin) return intersect_heights * intersect_widths
[ "def", "intersection", "(", "boxes1", ",", "boxes2", ")", ":", "[", "y_min1", ",", "x_min1", ",", "y_max1", ",", "x_max1", "]", "=", "np", ".", "split", "(", "boxes1", ",", "4", ",", "axis", "=", "1", ")", "[", "y_min2", ",", "x_min2", ",", "y_max2", ",", "x_max2", "]", "=", "np", ".", "split", "(", "boxes2", ",", "4", ",", "axis", "=", "1", ")", "all_pairs_min_ymax", "=", "np", ".", "minimum", "(", "y_max1", ",", "np", ".", "transpose", "(", "y_max2", ")", ")", "all_pairs_max_ymin", "=", "np", ".", "maximum", "(", "y_min1", ",", "np", ".", "transpose", "(", "y_min2", ")", ")", "intersect_heights", "=", "np", ".", "maximum", "(", "np", ".", "zeros", "(", "all_pairs_max_ymin", ".", "shape", ",", "dtype", "=", "'f4'", ")", ",", "all_pairs_min_ymax", "-", "all_pairs_max_ymin", ")", "all_pairs_min_xmax", "=", "np", ".", "minimum", "(", "x_max1", ",", "np", ".", "transpose", "(", "x_max2", ")", ")", "all_pairs_max_xmin", "=", "np", ".", "maximum", "(", "x_min1", ",", "np", ".", "transpose", "(", "x_min2", ")", ")", "intersect_widths", "=", "np", ".", "maximum", "(", "np", ".", "zeros", "(", "all_pairs_max_xmin", ".", "shape", ",", "dtype", "=", "'f4'", ")", ",", "all_pairs_min_xmax", "-", "all_pairs_max_xmin", ")", "return", "intersect_heights", "*", "intersect_widths" ]
Compute pairwise intersection areas between boxes. Args: boxes1: a numpy array with shape [N, 4] holding N boxes boxes2: a numpy array with shape [M, 4] holding M boxes Returns: a numpy array with shape [N*M] representing pairwise intersection area
[ "Compute", "pairwise", "intersection", "areas", "between", "boxes", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/utils/np_box_ops.py#L37-L60
train
tensorpack/tensorpack
examples/FasterRCNN/utils/np_box_ops.py
iou
def iou(boxes1, boxes2): """Computes pairwise intersection-over-union between box collections. Args: boxes1: a numpy array with shape [N, 4] holding N boxes. boxes2: a numpy array with shape [M, 4] holding M boxes. Returns: a numpy array with shape [N, M] representing pairwise iou scores. """ intersect = intersection(boxes1, boxes2) area1 = area(boxes1) area2 = area(boxes2) union = np.expand_dims(area1, axis=1) + np.expand_dims( area2, axis=0) - intersect return intersect / union
python
def iou(boxes1, boxes2): """Computes pairwise intersection-over-union between box collections. Args: boxes1: a numpy array with shape [N, 4] holding N boxes. boxes2: a numpy array with shape [M, 4] holding M boxes. Returns: a numpy array with shape [N, M] representing pairwise iou scores. """ intersect = intersection(boxes1, boxes2) area1 = area(boxes1) area2 = area(boxes2) union = np.expand_dims(area1, axis=1) + np.expand_dims( area2, axis=0) - intersect return intersect / union
[ "def", "iou", "(", "boxes1", ",", "boxes2", ")", ":", "intersect", "=", "intersection", "(", "boxes1", ",", "boxes2", ")", "area1", "=", "area", "(", "boxes1", ")", "area2", "=", "area", "(", "boxes2", ")", "union", "=", "np", ".", "expand_dims", "(", "area1", ",", "axis", "=", "1", ")", "+", "np", ".", "expand_dims", "(", "area2", ",", "axis", "=", "0", ")", "-", "intersect", "return", "intersect", "/", "union" ]
Computes pairwise intersection-over-union between box collections. Args: boxes1: a numpy array with shape [N, 4] holding N boxes. boxes2: a numpy array with shape [M, 4] holding M boxes. Returns: a numpy array with shape [N, M] representing pairwise iou scores.
[ "Computes", "pairwise", "intersection", "-", "over", "-", "union", "between", "box", "collections", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/utils/np_box_ops.py#L63-L78
train
tensorpack/tensorpack
examples/FasterRCNN/utils/np_box_ops.py
ioa
def ioa(boxes1, boxes2): """Computes pairwise intersection-over-area between box collections. Intersection-over-area (ioa) between two boxes box1 and box2 is defined as their intersection area over box2's area. Note that ioa is not symmetric, that is, IOA(box1, box2) != IOA(box2, box1). Args: boxes1: a numpy array with shape [N, 4] holding N boxes. boxes2: a numpy array with shape [M, 4] holding N boxes. Returns: a numpy array with shape [N, M] representing pairwise ioa scores. """ intersect = intersection(boxes1, boxes2) inv_areas = np.expand_dims(1.0 / area(boxes2), axis=0) return intersect * inv_areas
python
def ioa(boxes1, boxes2): """Computes pairwise intersection-over-area between box collections. Intersection-over-area (ioa) between two boxes box1 and box2 is defined as their intersection area over box2's area. Note that ioa is not symmetric, that is, IOA(box1, box2) != IOA(box2, box1). Args: boxes1: a numpy array with shape [N, 4] holding N boxes. boxes2: a numpy array with shape [M, 4] holding N boxes. Returns: a numpy array with shape [N, M] representing pairwise ioa scores. """ intersect = intersection(boxes1, boxes2) inv_areas = np.expand_dims(1.0 / area(boxes2), axis=0) return intersect * inv_areas
[ "def", "ioa", "(", "boxes1", ",", "boxes2", ")", ":", "intersect", "=", "intersection", "(", "boxes1", ",", "boxes2", ")", "inv_areas", "=", "np", ".", "expand_dims", "(", "1.0", "/", "area", "(", "boxes2", ")", ",", "axis", "=", "0", ")", "return", "intersect", "*", "inv_areas" ]
Computes pairwise intersection-over-area between box collections. Intersection-over-area (ioa) between two boxes box1 and box2 is defined as their intersection area over box2's area. Note that ioa is not symmetric, that is, IOA(box1, box2) != IOA(box2, box1). Args: boxes1: a numpy array with shape [N, 4] holding N boxes. boxes2: a numpy array with shape [M, 4] holding N boxes. Returns: a numpy array with shape [N, M] representing pairwise ioa scores.
[ "Computes", "pairwise", "intersection", "-", "over", "-", "area", "between", "box", "collections", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/utils/np_box_ops.py#L81-L97
train
tensorpack/tensorpack
tensorpack/dataflow/dataset/caltech101.py
maybe_download
def maybe_download(url, work_directory): """Download the data from Marlin's website, unless it's already here.""" filename = url.split("/")[-1] filepath = os.path.join(work_directory, filename) if not os.path.exists(filepath): logger.info("Downloading to {}...".format(filepath)) download(url, work_directory) return filepath
python
def maybe_download(url, work_directory): """Download the data from Marlin's website, unless it's already here.""" filename = url.split("/")[-1] filepath = os.path.join(work_directory, filename) if not os.path.exists(filepath): logger.info("Downloading to {}...".format(filepath)) download(url, work_directory) return filepath
[ "def", "maybe_download", "(", "url", ",", "work_directory", ")", ":", "filename", "=", "url", ".", "split", "(", "\"/\"", ")", "[", "-", "1", "]", "filepath", "=", "os", ".", "path", ".", "join", "(", "work_directory", ",", "filename", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "filepath", ")", ":", "logger", ".", "info", "(", "\"Downloading to {}...\"", ".", "format", "(", "filepath", ")", ")", "download", "(", "url", ",", "work_directory", ")", "return", "filepath" ]
Download the data from Marlin's website, unless it's already here.
[ "Download", "the", "data", "from", "Marlin", "s", "website", "unless", "it", "s", "already", "here", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/dataset/caltech101.py#L15-L22
train
tensorpack/tensorpack
tensorpack/dataflow/dataset/ilsvrc.py
ILSVRCMeta.get_synset_1000
def get_synset_1000(self): """ Returns: dict: {cls_number: synset_id} """ fname = os.path.join(self.dir, 'synsets.txt') assert os.path.isfile(fname) lines = [x.strip() for x in open(fname).readlines()] return dict(enumerate(lines))
python
def get_synset_1000(self): """ Returns: dict: {cls_number: synset_id} """ fname = os.path.join(self.dir, 'synsets.txt') assert os.path.isfile(fname) lines = [x.strip() for x in open(fname).readlines()] return dict(enumerate(lines))
[ "def", "get_synset_1000", "(", "self", ")", ":", "fname", "=", "os", ".", "path", ".", "join", "(", "self", ".", "dir", ",", "'synsets.txt'", ")", "assert", "os", ".", "path", ".", "isfile", "(", "fname", ")", "lines", "=", "[", "x", ".", "strip", "(", ")", "for", "x", "in", "open", "(", "fname", ")", ".", "readlines", "(", ")", "]", "return", "dict", "(", "enumerate", "(", "lines", ")", ")" ]
Returns: dict: {cls_number: synset_id}
[ "Returns", ":", "dict", ":", "{", "cls_number", ":", "synset_id", "}" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/dataset/ilsvrc.py#L45-L53
train
tensorpack/tensorpack
tensorpack/dataflow/dataset/ilsvrc.py
ILSVRCMeta.get_image_list
def get_image_list(self, name, dir_structure='original'): """ Args: name (str): 'train' or 'val' or 'test' dir_structure (str): same as in :meth:`ILSVRC12.__init__()`. Returns: list: list of (image filename, label) """ assert name in ['train', 'val', 'test'] assert dir_structure in ['original', 'train'] add_label_to_fname = (name != 'train' and dir_structure != 'original') if add_label_to_fname: synset = self.get_synset_1000() fname = os.path.join(self.dir, name + '.txt') assert os.path.isfile(fname), fname with open(fname) as f: ret = [] for line in f.readlines(): name, cls = line.strip().split() cls = int(cls) if add_label_to_fname: name = os.path.join(synset[cls], name) ret.append((name.strip(), cls)) assert len(ret), fname return ret
python
def get_image_list(self, name, dir_structure='original'): """ Args: name (str): 'train' or 'val' or 'test' dir_structure (str): same as in :meth:`ILSVRC12.__init__()`. Returns: list: list of (image filename, label) """ assert name in ['train', 'val', 'test'] assert dir_structure in ['original', 'train'] add_label_to_fname = (name != 'train' and dir_structure != 'original') if add_label_to_fname: synset = self.get_synset_1000() fname = os.path.join(self.dir, name + '.txt') assert os.path.isfile(fname), fname with open(fname) as f: ret = [] for line in f.readlines(): name, cls = line.strip().split() cls = int(cls) if add_label_to_fname: name = os.path.join(synset[cls], name) ret.append((name.strip(), cls)) assert len(ret), fname return ret
[ "def", "get_image_list", "(", "self", ",", "name", ",", "dir_structure", "=", "'original'", ")", ":", "assert", "name", "in", "[", "'train'", ",", "'val'", ",", "'test'", "]", "assert", "dir_structure", "in", "[", "'original'", ",", "'train'", "]", "add_label_to_fname", "=", "(", "name", "!=", "'train'", "and", "dir_structure", "!=", "'original'", ")", "if", "add_label_to_fname", ":", "synset", "=", "self", ".", "get_synset_1000", "(", ")", "fname", "=", "os", ".", "path", ".", "join", "(", "self", ".", "dir", ",", "name", "+", "'.txt'", ")", "assert", "os", ".", "path", ".", "isfile", "(", "fname", ")", ",", "fname", "with", "open", "(", "fname", ")", "as", "f", ":", "ret", "=", "[", "]", "for", "line", "in", "f", ".", "readlines", "(", ")", ":", "name", ",", "cls", "=", "line", ".", "strip", "(", ")", ".", "split", "(", ")", "cls", "=", "int", "(", "cls", ")", "if", "add_label_to_fname", ":", "name", "=", "os", ".", "path", ".", "join", "(", "synset", "[", "cls", "]", ",", "name", ")", "ret", ".", "append", "(", "(", "name", ".", "strip", "(", ")", ",", "cls", ")", ")", "assert", "len", "(", "ret", ")", ",", "fname", "return", "ret" ]
Args: name (str): 'train' or 'val' or 'test' dir_structure (str): same as in :meth:`ILSVRC12.__init__()`. Returns: list: list of (image filename, label)
[ "Args", ":", "name", "(", "str", ")", ":", "train", "or", "val", "or", "test", "dir_structure", "(", "str", ")", ":", "same", "as", "in", ":", "meth", ":", "ILSVRC12", ".", "__init__", "()", ".", "Returns", ":", "list", ":", "list", "of", "(", "image", "filename", "label", ")" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/dataset/ilsvrc.py#L59-L86
train
tensorpack/tensorpack
tensorpack/dataflow/dataset/ilsvrc.py
ILSVRCMeta.get_per_pixel_mean
def get_per_pixel_mean(self, size=None): """ Args: size (tuple): image size in (h, w). Defaults to (256, 256). Returns: np.ndarray: per-pixel mean of shape (h, w, 3 (BGR)) in range [0, 255]. """ if self.caffepb is None: self.caffepb = get_caffe_pb() obj = self.caffepb.BlobProto() mean_file = os.path.join(self.dir, 'imagenet_mean.binaryproto') with open(mean_file, 'rb') as f: obj.ParseFromString(f.read()) arr = np.array(obj.data).reshape((3, 256, 256)).astype('float32') arr = np.transpose(arr, [1, 2, 0]) if size is not None: arr = cv2.resize(arr, size[::-1]) return arr
python
def get_per_pixel_mean(self, size=None): """ Args: size (tuple): image size in (h, w). Defaults to (256, 256). Returns: np.ndarray: per-pixel mean of shape (h, w, 3 (BGR)) in range [0, 255]. """ if self.caffepb is None: self.caffepb = get_caffe_pb() obj = self.caffepb.BlobProto() mean_file = os.path.join(self.dir, 'imagenet_mean.binaryproto') with open(mean_file, 'rb') as f: obj.ParseFromString(f.read()) arr = np.array(obj.data).reshape((3, 256, 256)).astype('float32') arr = np.transpose(arr, [1, 2, 0]) if size is not None: arr = cv2.resize(arr, size[::-1]) return arr
[ "def", "get_per_pixel_mean", "(", "self", ",", "size", "=", "None", ")", ":", "if", "self", ".", "caffepb", "is", "None", ":", "self", ".", "caffepb", "=", "get_caffe_pb", "(", ")", "obj", "=", "self", ".", "caffepb", ".", "BlobProto", "(", ")", "mean_file", "=", "os", ".", "path", ".", "join", "(", "self", ".", "dir", ",", "'imagenet_mean.binaryproto'", ")", "with", "open", "(", "mean_file", ",", "'rb'", ")", "as", "f", ":", "obj", ".", "ParseFromString", "(", "f", ".", "read", "(", ")", ")", "arr", "=", "np", ".", "array", "(", "obj", ".", "data", ")", ".", "reshape", "(", "(", "3", ",", "256", ",", "256", ")", ")", ".", "astype", "(", "'float32'", ")", "arr", "=", "np", ".", "transpose", "(", "arr", ",", "[", "1", ",", "2", ",", "0", "]", ")", "if", "size", "is", "not", "None", ":", "arr", "=", "cv2", ".", "resize", "(", "arr", ",", "size", "[", ":", ":", "-", "1", "]", ")", "return", "arr" ]
Args: size (tuple): image size in (h, w). Defaults to (256, 256). Returns: np.ndarray: per-pixel mean of shape (h, w, 3 (BGR)) in range [0, 255].
[ "Args", ":", "size", "(", "tuple", ")", ":", "image", "size", "in", "(", "h", "w", ")", ".", "Defaults", "to", "(", "256", "256", ")", ".", "Returns", ":", "np", ".", "ndarray", ":", "per", "-", "pixel", "mean", "of", "shape", "(", "h", "w", "3", "(", "BGR", "))", "in", "range", "[", "0", "255", "]", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/dataset/ilsvrc.py#L88-L106
train
tensorpack/tensorpack
tensorpack/dataflow/dataset/ilsvrc.py
ILSVRCMeta.guess_dir_structure
def guess_dir_structure(dir): """ Return the directory structure of "dir". Args: dir(str): something like '/path/to/imagenet/val' Returns: either 'train' or 'original' """ subdir = os.listdir(dir)[0] # find a subdir starting with 'n' if subdir.startswith('n') and \ os.path.isdir(os.path.join(dir, subdir)): dir_structure = 'train' else: dir_structure = 'original' logger.info( "[ILSVRC12] Assuming directory {} has '{}' structure.".format( dir, dir_structure)) return dir_structure
python
def guess_dir_structure(dir): """ Return the directory structure of "dir". Args: dir(str): something like '/path/to/imagenet/val' Returns: either 'train' or 'original' """ subdir = os.listdir(dir)[0] # find a subdir starting with 'n' if subdir.startswith('n') and \ os.path.isdir(os.path.join(dir, subdir)): dir_structure = 'train' else: dir_structure = 'original' logger.info( "[ILSVRC12] Assuming directory {} has '{}' structure.".format( dir, dir_structure)) return dir_structure
[ "def", "guess_dir_structure", "(", "dir", ")", ":", "subdir", "=", "os", ".", "listdir", "(", "dir", ")", "[", "0", "]", "# find a subdir starting with 'n'", "if", "subdir", ".", "startswith", "(", "'n'", ")", "and", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "join", "(", "dir", ",", "subdir", ")", ")", ":", "dir_structure", "=", "'train'", "else", ":", "dir_structure", "=", "'original'", "logger", ".", "info", "(", "\"[ILSVRC12] Assuming directory {} has '{}' structure.\"", ".", "format", "(", "dir", ",", "dir_structure", ")", ")", "return", "dir_structure" ]
Return the directory structure of "dir". Args: dir(str): something like '/path/to/imagenet/val' Returns: either 'train' or 'original'
[ "Return", "the", "directory", "structure", "of", "dir", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/dataset/ilsvrc.py#L109-L129
train
tensorpack/tensorpack
examples/FasterRCNN/dataset.py
COCODetection.print_coco_metrics
def print_coco_metrics(self, json_file): """ Args: json_file (str): path to the results json file in coco format Returns: dict: the evaluation metrics """ from pycocotools.cocoeval import COCOeval ret = {} cocoDt = self.coco.loadRes(json_file) cocoEval = COCOeval(self.coco, cocoDt, 'bbox') cocoEval.evaluate() cocoEval.accumulate() cocoEval.summarize() fields = ['IoU=0.5:0.95', 'IoU=0.5', 'IoU=0.75', 'small', 'medium', 'large'] for k in range(6): ret['mAP(bbox)/' + fields[k]] = cocoEval.stats[k] json_obj = json.load(open(json_file)) if len(json_obj) > 0 and 'segmentation' in json_obj[0]: cocoEval = COCOeval(self.coco, cocoDt, 'segm') cocoEval.evaluate() cocoEval.accumulate() cocoEval.summarize() for k in range(6): ret['mAP(segm)/' + fields[k]] = cocoEval.stats[k] return ret
python
def print_coco_metrics(self, json_file): """ Args: json_file (str): path to the results json file in coco format Returns: dict: the evaluation metrics """ from pycocotools.cocoeval import COCOeval ret = {} cocoDt = self.coco.loadRes(json_file) cocoEval = COCOeval(self.coco, cocoDt, 'bbox') cocoEval.evaluate() cocoEval.accumulate() cocoEval.summarize() fields = ['IoU=0.5:0.95', 'IoU=0.5', 'IoU=0.75', 'small', 'medium', 'large'] for k in range(6): ret['mAP(bbox)/' + fields[k]] = cocoEval.stats[k] json_obj = json.load(open(json_file)) if len(json_obj) > 0 and 'segmentation' in json_obj[0]: cocoEval = COCOeval(self.coco, cocoDt, 'segm') cocoEval.evaluate() cocoEval.accumulate() cocoEval.summarize() for k in range(6): ret['mAP(segm)/' + fields[k]] = cocoEval.stats[k] return ret
[ "def", "print_coco_metrics", "(", "self", ",", "json_file", ")", ":", "from", "pycocotools", ".", "cocoeval", "import", "COCOeval", "ret", "=", "{", "}", "cocoDt", "=", "self", ".", "coco", ".", "loadRes", "(", "json_file", ")", "cocoEval", "=", "COCOeval", "(", "self", ".", "coco", ",", "cocoDt", ",", "'bbox'", ")", "cocoEval", ".", "evaluate", "(", ")", "cocoEval", ".", "accumulate", "(", ")", "cocoEval", ".", "summarize", "(", ")", "fields", "=", "[", "'IoU=0.5:0.95'", ",", "'IoU=0.5'", ",", "'IoU=0.75'", ",", "'small'", ",", "'medium'", ",", "'large'", "]", "for", "k", "in", "range", "(", "6", ")", ":", "ret", "[", "'mAP(bbox)/'", "+", "fields", "[", "k", "]", "]", "=", "cocoEval", ".", "stats", "[", "k", "]", "json_obj", "=", "json", ".", "load", "(", "open", "(", "json_file", ")", ")", "if", "len", "(", "json_obj", ")", ">", "0", "and", "'segmentation'", "in", "json_obj", "[", "0", "]", ":", "cocoEval", "=", "COCOeval", "(", "self", ".", "coco", ",", "cocoDt", ",", "'segm'", ")", "cocoEval", ".", "evaluate", "(", ")", "cocoEval", ".", "accumulate", "(", ")", "cocoEval", ".", "summarize", "(", ")", "for", "k", "in", "range", "(", "6", ")", ":", "ret", "[", "'mAP(segm)/'", "+", "fields", "[", "k", "]", "]", "=", "cocoEval", ".", "stats", "[", "k", "]", "return", "ret" ]
Args: json_file (str): path to the results json file in coco format Returns: dict: the evaluation metrics
[ "Args", ":", "json_file", "(", "str", ")", ":", "path", "to", "the", "results", "json", "file", "in", "coco", "format", "Returns", ":", "dict", ":", "the", "evaluation", "metrics" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/dataset.py#L49-L75
train
tensorpack/tensorpack
examples/FasterRCNN/dataset.py
COCODetection.load
def load(self, add_gt=True, add_mask=False): """ Args: add_gt: whether to add ground truth bounding box annotations to the dicts add_mask: whether to also add ground truth mask Returns: a list of dict, each has keys including: 'image_id', 'file_name', and (if add_gt is True) 'boxes', 'class', 'is_crowd', and optionally 'segmentation'. """ if add_mask: assert add_gt with timed_operation('Load Groundtruth Boxes for {}'.format(self.name)): img_ids = self.coco.getImgIds() img_ids.sort() # list of dict, each has keys: height,width,id,file_name imgs = self.coco.loadImgs(img_ids) for img in tqdm.tqdm(imgs): img['image_id'] = img.pop('id') self._use_absolute_file_name(img) if add_gt: self._add_detection_gt(img, add_mask) return imgs
python
def load(self, add_gt=True, add_mask=False): """ Args: add_gt: whether to add ground truth bounding box annotations to the dicts add_mask: whether to also add ground truth mask Returns: a list of dict, each has keys including: 'image_id', 'file_name', and (if add_gt is True) 'boxes', 'class', 'is_crowd', and optionally 'segmentation'. """ if add_mask: assert add_gt with timed_operation('Load Groundtruth Boxes for {}'.format(self.name)): img_ids = self.coco.getImgIds() img_ids.sort() # list of dict, each has keys: height,width,id,file_name imgs = self.coco.loadImgs(img_ids) for img in tqdm.tqdm(imgs): img['image_id'] = img.pop('id') self._use_absolute_file_name(img) if add_gt: self._add_detection_gt(img, add_mask) return imgs
[ "def", "load", "(", "self", ",", "add_gt", "=", "True", ",", "add_mask", "=", "False", ")", ":", "if", "add_mask", ":", "assert", "add_gt", "with", "timed_operation", "(", "'Load Groundtruth Boxes for {}'", ".", "format", "(", "self", ".", "name", ")", ")", ":", "img_ids", "=", "self", ".", "coco", ".", "getImgIds", "(", ")", "img_ids", ".", "sort", "(", ")", "# list of dict, each has keys: height,width,id,file_name", "imgs", "=", "self", ".", "coco", ".", "loadImgs", "(", "img_ids", ")", "for", "img", "in", "tqdm", ".", "tqdm", "(", "imgs", ")", ":", "img", "[", "'image_id'", "]", "=", "img", ".", "pop", "(", "'id'", ")", "self", ".", "_use_absolute_file_name", "(", "img", ")", "if", "add_gt", ":", "self", ".", "_add_detection_gt", "(", "img", ",", "add_mask", ")", "return", "imgs" ]
Args: add_gt: whether to add ground truth bounding box annotations to the dicts add_mask: whether to also add ground truth mask Returns: a list of dict, each has keys including: 'image_id', 'file_name', and (if add_gt is True) 'boxes', 'class', 'is_crowd', and optionally 'segmentation'.
[ "Args", ":", "add_gt", ":", "whether", "to", "add", "ground", "truth", "bounding", "box", "annotations", "to", "the", "dicts", "add_mask", ":", "whether", "to", "also", "add", "ground", "truth", "mask" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/dataset.py#L77-L102
train
tensorpack/tensorpack
examples/FasterRCNN/dataset.py
COCODetection._use_absolute_file_name
def _use_absolute_file_name(self, img): """ Change relative filename to abosolute file name. """ img['file_name'] = os.path.join( self._imgdir, img['file_name']) assert os.path.isfile(img['file_name']), img['file_name']
python
def _use_absolute_file_name(self, img): """ Change relative filename to abosolute file name. """ img['file_name'] = os.path.join( self._imgdir, img['file_name']) assert os.path.isfile(img['file_name']), img['file_name']
[ "def", "_use_absolute_file_name", "(", "self", ",", "img", ")", ":", "img", "[", "'file_name'", "]", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_imgdir", ",", "img", "[", "'file_name'", "]", ")", "assert", "os", ".", "path", ".", "isfile", "(", "img", "[", "'file_name'", "]", ")", ",", "img", "[", "'file_name'", "]" ]
Change relative filename to abosolute file name.
[ "Change", "relative", "filename", "to", "abosolute", "file", "name", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/dataset.py#L104-L110
train
tensorpack/tensorpack
examples/FasterRCNN/dataset.py
COCODetection._add_detection_gt
def _add_detection_gt(self, img, add_mask): """ Add 'boxes', 'class', 'is_crowd' of this image to the dict, used by detection. If add_mask is True, also add 'segmentation' in coco poly format. """ # ann_ids = self.coco.getAnnIds(imgIds=img['image_id']) # objs = self.coco.loadAnns(ann_ids) objs = self.coco.imgToAnns[img['image_id']] # equivalent but faster than the above two lines # clean-up boxes valid_objs = [] width = img.pop('width') height = img.pop('height') for objid, obj in enumerate(objs): if obj.get('ignore', 0) == 1: continue x1, y1, w, h = obj['bbox'] # bbox is originally in float # x1/y1 means upper-left corner and w/h means true w/h. This can be verified by segmentation pixels. # But we do make an assumption here that (0.0, 0.0) is upper-left corner of the first pixel x1 = np.clip(float(x1), 0, width) y1 = np.clip(float(y1), 0, height) w = np.clip(float(x1 + w), 0, width) - x1 h = np.clip(float(y1 + h), 0, height) - y1 # Require non-zero seg area and more than 1x1 box size if obj['area'] > 1 and w > 0 and h > 0 and w * h >= 4: obj['bbox'] = [x1, y1, x1 + w, y1 + h] valid_objs.append(obj) if add_mask: segs = obj['segmentation'] if not isinstance(segs, list): assert obj['iscrowd'] == 1 obj['segmentation'] = None else: valid_segs = [np.asarray(p).reshape(-1, 2).astype('float32') for p in segs if len(p) >= 6] if len(valid_segs) == 0: logger.error("Object {} in image {} has no valid polygons!".format(objid, img['file_name'])) elif len(valid_segs) < len(segs): logger.warn("Object {} in image {} has invalid polygons!".format(objid, img['file_name'])) obj['segmentation'] = valid_segs # all geometrically-valid boxes are returned boxes = np.asarray([obj['bbox'] for obj in valid_objs], dtype='float32') # (n, 4) cls = np.asarray([ self.COCO_id_to_category_id[obj['category_id']] for obj in valid_objs], dtype='int32') # (n,) is_crowd = np.asarray([obj['iscrowd'] for obj in valid_objs], dtype='int8') # add the keys img['boxes'] = boxes # nx4 img['class'] = cls # n, always >0 img['is_crowd'] = is_crowd # n, if add_mask: # also required to be float32 img['segmentation'] = [ obj['segmentation'] for obj in valid_objs]
python
def _add_detection_gt(self, img, add_mask): """ Add 'boxes', 'class', 'is_crowd' of this image to the dict, used by detection. If add_mask is True, also add 'segmentation' in coco poly format. """ # ann_ids = self.coco.getAnnIds(imgIds=img['image_id']) # objs = self.coco.loadAnns(ann_ids) objs = self.coco.imgToAnns[img['image_id']] # equivalent but faster than the above two lines # clean-up boxes valid_objs = [] width = img.pop('width') height = img.pop('height') for objid, obj in enumerate(objs): if obj.get('ignore', 0) == 1: continue x1, y1, w, h = obj['bbox'] # bbox is originally in float # x1/y1 means upper-left corner and w/h means true w/h. This can be verified by segmentation pixels. # But we do make an assumption here that (0.0, 0.0) is upper-left corner of the first pixel x1 = np.clip(float(x1), 0, width) y1 = np.clip(float(y1), 0, height) w = np.clip(float(x1 + w), 0, width) - x1 h = np.clip(float(y1 + h), 0, height) - y1 # Require non-zero seg area and more than 1x1 box size if obj['area'] > 1 and w > 0 and h > 0 and w * h >= 4: obj['bbox'] = [x1, y1, x1 + w, y1 + h] valid_objs.append(obj) if add_mask: segs = obj['segmentation'] if not isinstance(segs, list): assert obj['iscrowd'] == 1 obj['segmentation'] = None else: valid_segs = [np.asarray(p).reshape(-1, 2).astype('float32') for p in segs if len(p) >= 6] if len(valid_segs) == 0: logger.error("Object {} in image {} has no valid polygons!".format(objid, img['file_name'])) elif len(valid_segs) < len(segs): logger.warn("Object {} in image {} has invalid polygons!".format(objid, img['file_name'])) obj['segmentation'] = valid_segs # all geometrically-valid boxes are returned boxes = np.asarray([obj['bbox'] for obj in valid_objs], dtype='float32') # (n, 4) cls = np.asarray([ self.COCO_id_to_category_id[obj['category_id']] for obj in valid_objs], dtype='int32') # (n,) is_crowd = np.asarray([obj['iscrowd'] for obj in valid_objs], dtype='int8') # add the keys img['boxes'] = boxes # nx4 img['class'] = cls # n, always >0 img['is_crowd'] = is_crowd # n, if add_mask: # also required to be float32 img['segmentation'] = [ obj['segmentation'] for obj in valid_objs]
[ "def", "_add_detection_gt", "(", "self", ",", "img", ",", "add_mask", ")", ":", "# ann_ids = self.coco.getAnnIds(imgIds=img['image_id'])", "# objs = self.coco.loadAnns(ann_ids)", "objs", "=", "self", ".", "coco", ".", "imgToAnns", "[", "img", "[", "'image_id'", "]", "]", "# equivalent but faster than the above two lines", "# clean-up boxes", "valid_objs", "=", "[", "]", "width", "=", "img", ".", "pop", "(", "'width'", ")", "height", "=", "img", ".", "pop", "(", "'height'", ")", "for", "objid", ",", "obj", "in", "enumerate", "(", "objs", ")", ":", "if", "obj", ".", "get", "(", "'ignore'", ",", "0", ")", "==", "1", ":", "continue", "x1", ",", "y1", ",", "w", ",", "h", "=", "obj", "[", "'bbox'", "]", "# bbox is originally in float", "# x1/y1 means upper-left corner and w/h means true w/h. This can be verified by segmentation pixels.", "# But we do make an assumption here that (0.0, 0.0) is upper-left corner of the first pixel", "x1", "=", "np", ".", "clip", "(", "float", "(", "x1", ")", ",", "0", ",", "width", ")", "y1", "=", "np", ".", "clip", "(", "float", "(", "y1", ")", ",", "0", ",", "height", ")", "w", "=", "np", ".", "clip", "(", "float", "(", "x1", "+", "w", ")", ",", "0", ",", "width", ")", "-", "x1", "h", "=", "np", ".", "clip", "(", "float", "(", "y1", "+", "h", ")", ",", "0", ",", "height", ")", "-", "y1", "# Require non-zero seg area and more than 1x1 box size", "if", "obj", "[", "'area'", "]", ">", "1", "and", "w", ">", "0", "and", "h", ">", "0", "and", "w", "*", "h", ">=", "4", ":", "obj", "[", "'bbox'", "]", "=", "[", "x1", ",", "y1", ",", "x1", "+", "w", ",", "y1", "+", "h", "]", "valid_objs", ".", "append", "(", "obj", ")", "if", "add_mask", ":", "segs", "=", "obj", "[", "'segmentation'", "]", "if", "not", "isinstance", "(", "segs", ",", "list", ")", ":", "assert", "obj", "[", "'iscrowd'", "]", "==", "1", "obj", "[", "'segmentation'", "]", "=", "None", "else", ":", "valid_segs", "=", "[", "np", ".", "asarray", "(", "p", ")", ".", "reshape", "(", "-", "1", ",", "2", ")", ".", "astype", "(", "'float32'", ")", "for", "p", "in", "segs", "if", "len", "(", "p", ")", ">=", "6", "]", "if", "len", "(", "valid_segs", ")", "==", "0", ":", "logger", ".", "error", "(", "\"Object {} in image {} has no valid polygons!\"", ".", "format", "(", "objid", ",", "img", "[", "'file_name'", "]", ")", ")", "elif", "len", "(", "valid_segs", ")", "<", "len", "(", "segs", ")", ":", "logger", ".", "warn", "(", "\"Object {} in image {} has invalid polygons!\"", ".", "format", "(", "objid", ",", "img", "[", "'file_name'", "]", ")", ")", "obj", "[", "'segmentation'", "]", "=", "valid_segs", "# all geometrically-valid boxes are returned", "boxes", "=", "np", ".", "asarray", "(", "[", "obj", "[", "'bbox'", "]", "for", "obj", "in", "valid_objs", "]", ",", "dtype", "=", "'float32'", ")", "# (n, 4)", "cls", "=", "np", ".", "asarray", "(", "[", "self", ".", "COCO_id_to_category_id", "[", "obj", "[", "'category_id'", "]", "]", "for", "obj", "in", "valid_objs", "]", ",", "dtype", "=", "'int32'", ")", "# (n,)", "is_crowd", "=", "np", ".", "asarray", "(", "[", "obj", "[", "'iscrowd'", "]", "for", "obj", "in", "valid_objs", "]", ",", "dtype", "=", "'int8'", ")", "# add the keys", "img", "[", "'boxes'", "]", "=", "boxes", "# nx4", "img", "[", "'class'", "]", "=", "cls", "# n, always >0", "img", "[", "'is_crowd'", "]", "=", "is_crowd", "# n,", "if", "add_mask", ":", "# also required to be float32", "img", "[", "'segmentation'", "]", "=", "[", "obj", "[", "'segmentation'", "]", "for", "obj", "in", "valid_objs", "]" ]
Add 'boxes', 'class', 'is_crowd' of this image to the dict, used by detection. If add_mask is True, also add 'segmentation' in coco poly format.
[ "Add", "boxes", "class", "is_crowd", "of", "this", "image", "to", "the", "dict", "used", "by", "detection", ".", "If", "add_mask", "is", "True", "also", "add", "segmentation", "in", "coco", "poly", "format", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/dataset.py#L112-L170
train
tensorpack/tensorpack
examples/FasterRCNN/dataset.py
COCODetection.load_many
def load_many(basedir, names, add_gt=True, add_mask=False): """ Load and merges several instance files together. Returns the same format as :meth:`COCODetection.load`. """ if not isinstance(names, (list, tuple)): names = [names] ret = [] for n in names: coco = COCODetection(basedir, n) ret.extend(coco.load(add_gt, add_mask=add_mask)) return ret
python
def load_many(basedir, names, add_gt=True, add_mask=False): """ Load and merges several instance files together. Returns the same format as :meth:`COCODetection.load`. """ if not isinstance(names, (list, tuple)): names = [names] ret = [] for n in names: coco = COCODetection(basedir, n) ret.extend(coco.load(add_gt, add_mask=add_mask)) return ret
[ "def", "load_many", "(", "basedir", ",", "names", ",", "add_gt", "=", "True", ",", "add_mask", "=", "False", ")", ":", "if", "not", "isinstance", "(", "names", ",", "(", "list", ",", "tuple", ")", ")", ":", "names", "=", "[", "names", "]", "ret", "=", "[", "]", "for", "n", "in", "names", ":", "coco", "=", "COCODetection", "(", "basedir", ",", "n", ")", "ret", ".", "extend", "(", "coco", ".", "load", "(", "add_gt", ",", "add_mask", "=", "add_mask", ")", ")", "return", "ret" ]
Load and merges several instance files together. Returns the same format as :meth:`COCODetection.load`.
[ "Load", "and", "merges", "several", "instance", "files", "together", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/dataset.py#L173-L185
train
tensorpack/tensorpack
examples/FasterRCNN/dataset.py
DetectionDataset.load_training_roidbs
def load_training_roidbs(self, names): """ Args: names (list[str]): name of the training datasets, e.g. ['train2014', 'valminusminival2014'] Returns: roidbs (list[dict]): Produce "roidbs" as a list of dict, each dict corresponds to one image with k>=0 instances. and the following keys are expected for training: file_name: str, full path to the image boxes: numpy array of kx4 floats, each row is [x1, y1, x2, y2] class: numpy array of k integers, in the range of [1, #categories], NOT [0, #categories) is_crowd: k booleans. Use k False if you don't know what it means. segmentation: k lists of numpy arrays (one for each instance). Each list of numpy arrays corresponds to the mask for one instance. Each numpy array in the list is a polygon of shape Nx2, because one mask can be represented by N polygons. If your segmentation annotations are originally masks rather than polygons, either convert it, or the augmentation will need to be changed or skipped accordingly. Include this field only if training Mask R-CNN. """ return COCODetection.load_many( cfg.DATA.BASEDIR, names, add_gt=True, add_mask=cfg.MODE_MASK)
python
def load_training_roidbs(self, names): """ Args: names (list[str]): name of the training datasets, e.g. ['train2014', 'valminusminival2014'] Returns: roidbs (list[dict]): Produce "roidbs" as a list of dict, each dict corresponds to one image with k>=0 instances. and the following keys are expected for training: file_name: str, full path to the image boxes: numpy array of kx4 floats, each row is [x1, y1, x2, y2] class: numpy array of k integers, in the range of [1, #categories], NOT [0, #categories) is_crowd: k booleans. Use k False if you don't know what it means. segmentation: k lists of numpy arrays (one for each instance). Each list of numpy arrays corresponds to the mask for one instance. Each numpy array in the list is a polygon of shape Nx2, because one mask can be represented by N polygons. If your segmentation annotations are originally masks rather than polygons, either convert it, or the augmentation will need to be changed or skipped accordingly. Include this field only if training Mask R-CNN. """ return COCODetection.load_many( cfg.DATA.BASEDIR, names, add_gt=True, add_mask=cfg.MODE_MASK)
[ "def", "load_training_roidbs", "(", "self", ",", "names", ")", ":", "return", "COCODetection", ".", "load_many", "(", "cfg", ".", "DATA", ".", "BASEDIR", ",", "names", ",", "add_gt", "=", "True", ",", "add_mask", "=", "cfg", ".", "MODE_MASK", ")" ]
Args: names (list[str]): name of the training datasets, e.g. ['train2014', 'valminusminival2014'] Returns: roidbs (list[dict]): Produce "roidbs" as a list of dict, each dict corresponds to one image with k>=0 instances. and the following keys are expected for training: file_name: str, full path to the image boxes: numpy array of kx4 floats, each row is [x1, y1, x2, y2] class: numpy array of k integers, in the range of [1, #categories], NOT [0, #categories) is_crowd: k booleans. Use k False if you don't know what it means. segmentation: k lists of numpy arrays (one for each instance). Each list of numpy arrays corresponds to the mask for one instance. Each numpy array in the list is a polygon of shape Nx2, because one mask can be represented by N polygons. If your segmentation annotations are originally masks rather than polygons, either convert it, or the augmentation will need to be changed or skipped accordingly. Include this field only if training Mask R-CNN.
[ "Args", ":", "names", "(", "list", "[", "str", "]", ")", ":", "name", "of", "the", "training", "datasets", "e", ".", "g", ".", "[", "train2014", "valminusminival2014", "]" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/dataset.py#L203-L229
train
tensorpack/tensorpack
examples/FasterRCNN/dataset.py
DetectionDataset.load_inference_roidbs
def load_inference_roidbs(self, name): """ Args: name (str): name of one inference dataset, e.g. 'minival2014' Returns: roidbs (list[dict]): Each dict corresponds to one image to run inference on. The following keys in the dict are expected: file_name (str): full path to the image image_id (str): an id for the image. The inference results will be stored with this id. """ return COCODetection.load_many(cfg.DATA.BASEDIR, name, add_gt=False)
python
def load_inference_roidbs(self, name): """ Args: name (str): name of one inference dataset, e.g. 'minival2014' Returns: roidbs (list[dict]): Each dict corresponds to one image to run inference on. The following keys in the dict are expected: file_name (str): full path to the image image_id (str): an id for the image. The inference results will be stored with this id. """ return COCODetection.load_many(cfg.DATA.BASEDIR, name, add_gt=False)
[ "def", "load_inference_roidbs", "(", "self", ",", "name", ")", ":", "return", "COCODetection", ".", "load_many", "(", "cfg", ".", "DATA", ".", "BASEDIR", ",", "name", ",", "add_gt", "=", "False", ")" ]
Args: name (str): name of one inference dataset, e.g. 'minival2014' Returns: roidbs (list[dict]): Each dict corresponds to one image to run inference on. The following keys in the dict are expected: file_name (str): full path to the image image_id (str): an id for the image. The inference results will be stored with this id.
[ "Args", ":", "name", "(", "str", ")", ":", "name", "of", "one", "inference", "dataset", "e", ".", "g", ".", "minival2014" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/dataset.py#L231-L245
train
tensorpack/tensorpack
examples/FasterRCNN/dataset.py
DetectionDataset.eval_or_save_inference_results
def eval_or_save_inference_results(self, results, dataset, output=None): """ Args: results (list[dict]): the inference results as dicts. Each dict corresponds to one __instance__. It contains the following keys: image_id (str): the id that matches `load_inference_roidbs`. category_id (int): the category prediction, in range [1, #category] bbox (list[float]): x1, y1, x2, y2 score (float): segmentation: the segmentation mask in COCO's rle format. dataset (str): the name of the dataset to evaluate. output (str): the output file to optionally save the results to. Returns: dict: the evaluation results. """ continuous_id_to_COCO_id = {v: k for k, v in COCODetection.COCO_id_to_category_id.items()} for res in results: # convert to COCO's incontinuous category id res['category_id'] = continuous_id_to_COCO_id[res['category_id']] # COCO expects results in xywh format box = res['bbox'] box[2] -= box[0] box[3] -= box[1] res['bbox'] = [round(float(x), 3) for x in box] assert output is not None, "COCO evaluation requires an output file!" with open(output, 'w') as f: json.dump(results, f) if len(results): # sometimes may crash if the results are empty? return COCODetection(cfg.DATA.BASEDIR, dataset).print_coco_metrics(output) else: return {}
python
def eval_or_save_inference_results(self, results, dataset, output=None): """ Args: results (list[dict]): the inference results as dicts. Each dict corresponds to one __instance__. It contains the following keys: image_id (str): the id that matches `load_inference_roidbs`. category_id (int): the category prediction, in range [1, #category] bbox (list[float]): x1, y1, x2, y2 score (float): segmentation: the segmentation mask in COCO's rle format. dataset (str): the name of the dataset to evaluate. output (str): the output file to optionally save the results to. Returns: dict: the evaluation results. """ continuous_id_to_COCO_id = {v: k for k, v in COCODetection.COCO_id_to_category_id.items()} for res in results: # convert to COCO's incontinuous category id res['category_id'] = continuous_id_to_COCO_id[res['category_id']] # COCO expects results in xywh format box = res['bbox'] box[2] -= box[0] box[3] -= box[1] res['bbox'] = [round(float(x), 3) for x in box] assert output is not None, "COCO evaluation requires an output file!" with open(output, 'w') as f: json.dump(results, f) if len(results): # sometimes may crash if the results are empty? return COCODetection(cfg.DATA.BASEDIR, dataset).print_coco_metrics(output) else: return {}
[ "def", "eval_or_save_inference_results", "(", "self", ",", "results", ",", "dataset", ",", "output", "=", "None", ")", ":", "continuous_id_to_COCO_id", "=", "{", "v", ":", "k", "for", "k", ",", "v", "in", "COCODetection", ".", "COCO_id_to_category_id", ".", "items", "(", ")", "}", "for", "res", "in", "results", ":", "# convert to COCO's incontinuous category id", "res", "[", "'category_id'", "]", "=", "continuous_id_to_COCO_id", "[", "res", "[", "'category_id'", "]", "]", "# COCO expects results in xywh format", "box", "=", "res", "[", "'bbox'", "]", "box", "[", "2", "]", "-=", "box", "[", "0", "]", "box", "[", "3", "]", "-=", "box", "[", "1", "]", "res", "[", "'bbox'", "]", "=", "[", "round", "(", "float", "(", "x", ")", ",", "3", ")", "for", "x", "in", "box", "]", "assert", "output", "is", "not", "None", ",", "\"COCO evaluation requires an output file!\"", "with", "open", "(", "output", ",", "'w'", ")", "as", "f", ":", "json", ".", "dump", "(", "results", ",", "f", ")", "if", "len", "(", "results", ")", ":", "# sometimes may crash if the results are empty?", "return", "COCODetection", "(", "cfg", ".", "DATA", ".", "BASEDIR", ",", "dataset", ")", ".", "print_coco_metrics", "(", "output", ")", "else", ":", "return", "{", "}" ]
Args: results (list[dict]): the inference results as dicts. Each dict corresponds to one __instance__. It contains the following keys: image_id (str): the id that matches `load_inference_roidbs`. category_id (int): the category prediction, in range [1, #category] bbox (list[float]): x1, y1, x2, y2 score (float): segmentation: the segmentation mask in COCO's rle format. dataset (str): the name of the dataset to evaluate. output (str): the output file to optionally save the results to. Returns: dict: the evaluation results.
[ "Args", ":", "results", "(", "list", "[", "dict", "]", ")", ":", "the", "inference", "results", "as", "dicts", ".", "Each", "dict", "corresponds", "to", "one", "__instance__", ".", "It", "contains", "the", "following", "keys", ":" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/dataset.py#L247-L282
train
tensorpack/tensorpack
tensorpack/utils/timer.py
timed_operation
def timed_operation(msg, log_start=False): """ Surround a context with a timer. Args: msg(str): the log to print. log_start(bool): whether to print also at the beginning. Example: .. code-block:: python with timed_operation('Good Stuff'): time.sleep(1) Will print: .. code-block:: python Good stuff finished, time:1sec. """ assert len(msg) if log_start: logger.info('Start {} ...'.format(msg)) start = timer() yield msg = msg[0].upper() + msg[1:] logger.info('{} finished, time:{:.4f} sec.'.format( msg, timer() - start))
python
def timed_operation(msg, log_start=False): """ Surround a context with a timer. Args: msg(str): the log to print. log_start(bool): whether to print also at the beginning. Example: .. code-block:: python with timed_operation('Good Stuff'): time.sleep(1) Will print: .. code-block:: python Good stuff finished, time:1sec. """ assert len(msg) if log_start: logger.info('Start {} ...'.format(msg)) start = timer() yield msg = msg[0].upper() + msg[1:] logger.info('{} finished, time:{:.4f} sec.'.format( msg, timer() - start))
[ "def", "timed_operation", "(", "msg", ",", "log_start", "=", "False", ")", ":", "assert", "len", "(", "msg", ")", "if", "log_start", ":", "logger", ".", "info", "(", "'Start {} ...'", ".", "format", "(", "msg", ")", ")", "start", "=", "timer", "(", ")", "yield", "msg", "=", "msg", "[", "0", "]", ".", "upper", "(", ")", "+", "msg", "[", "1", ":", "]", "logger", ".", "info", "(", "'{} finished, time:{:.4f} sec.'", ".", "format", "(", "msg", ",", "timer", "(", ")", "-", "start", ")", ")" ]
Surround a context with a timer. Args: msg(str): the log to print. log_start(bool): whether to print also at the beginning. Example: .. code-block:: python with timed_operation('Good Stuff'): time.sleep(1) Will print: .. code-block:: python Good stuff finished, time:1sec.
[ "Surround", "a", "context", "with", "a", "timer", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/timer.py#L23-L50
train
tensorpack/tensorpack
tensorpack/utils/timer.py
total_timer
def total_timer(msg): """ A context which add the time spent inside to TotalTimer. """ start = timer() yield t = timer() - start _TOTAL_TIMER_DATA[msg].feed(t)
python
def total_timer(msg): """ A context which add the time spent inside to TotalTimer. """ start = timer() yield t = timer() - start _TOTAL_TIMER_DATA[msg].feed(t)
[ "def", "total_timer", "(", "msg", ")", ":", "start", "=", "timer", "(", ")", "yield", "t", "=", "timer", "(", ")", "-", "start", "_TOTAL_TIMER_DATA", "[", "msg", "]", ".", "feed", "(", "t", ")" ]
A context which add the time spent inside to TotalTimer.
[ "A", "context", "which", "add", "the", "time", "spent", "inside", "to", "TotalTimer", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/timer.py#L57-L62
train
tensorpack/tensorpack
tensorpack/utils/timer.py
print_total_timer
def print_total_timer(): """ Print the content of the TotalTimer, if it's not empty. This function will automatically get called when program exits. """ if len(_TOTAL_TIMER_DATA) == 0: return for k, v in six.iteritems(_TOTAL_TIMER_DATA): logger.info("Total Time: {} -> {:.2f} sec, {} times, {:.3g} sec/time".format( k, v.sum, v.count, v.average))
python
def print_total_timer(): """ Print the content of the TotalTimer, if it's not empty. This function will automatically get called when program exits. """ if len(_TOTAL_TIMER_DATA) == 0: return for k, v in six.iteritems(_TOTAL_TIMER_DATA): logger.info("Total Time: {} -> {:.2f} sec, {} times, {:.3g} sec/time".format( k, v.sum, v.count, v.average))
[ "def", "print_total_timer", "(", ")", ":", "if", "len", "(", "_TOTAL_TIMER_DATA", ")", "==", "0", ":", "return", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "_TOTAL_TIMER_DATA", ")", ":", "logger", ".", "info", "(", "\"Total Time: {} -> {:.2f} sec, {} times, {:.3g} sec/time\"", ".", "format", "(", "k", ",", "v", ".", "sum", ",", "v", ".", "count", ",", "v", ".", "average", ")", ")" ]
Print the content of the TotalTimer, if it's not empty. This function will automatically get called when program exits.
[ "Print", "the", "content", "of", "the", "TotalTimer", "if", "it", "s", "not", "empty", ".", "This", "function", "will", "automatically", "get", "called", "when", "program", "exits", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/timer.py#L65-L74
train
tensorpack/tensorpack
tensorpack/dataflow/imgaug/base.py
AugmentorList.reset_state
def reset_state(self): """ Will reset state of each augmentor """ super(AugmentorList, self).reset_state() for a in self.augmentors: a.reset_state()
python
def reset_state(self): """ Will reset state of each augmentor """ super(AugmentorList, self).reset_state() for a in self.augmentors: a.reset_state()
[ "def", "reset_state", "(", "self", ")", ":", "super", "(", "AugmentorList", ",", "self", ")", ".", "reset_state", "(", ")", "for", "a", "in", "self", ".", "augmentors", ":", "a", ".", "reset_state", "(", ")" ]
Will reset state of each augmentor
[ "Will", "reset", "state", "of", "each", "augmentor" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/imgaug/base.py#L224-L228
train
tensorpack/tensorpack
tensorpack/utils/concurrency.py
ensure_proc_terminate
def ensure_proc_terminate(proc): """ Make sure processes terminate when main process exit. Args: proc (multiprocessing.Process or list) """ if isinstance(proc, list): for p in proc: ensure_proc_terminate(p) return def stop_proc_by_weak_ref(ref): proc = ref() if proc is None: return if not proc.is_alive(): return proc.terminate() proc.join() assert isinstance(proc, mp.Process) atexit.register(stop_proc_by_weak_ref, weakref.ref(proc))
python
def ensure_proc_terminate(proc): """ Make sure processes terminate when main process exit. Args: proc (multiprocessing.Process or list) """ if isinstance(proc, list): for p in proc: ensure_proc_terminate(p) return def stop_proc_by_weak_ref(ref): proc = ref() if proc is None: return if not proc.is_alive(): return proc.terminate() proc.join() assert isinstance(proc, mp.Process) atexit.register(stop_proc_by_weak_ref, weakref.ref(proc))
[ "def", "ensure_proc_terminate", "(", "proc", ")", ":", "if", "isinstance", "(", "proc", ",", "list", ")", ":", "for", "p", "in", "proc", ":", "ensure_proc_terminate", "(", "p", ")", "return", "def", "stop_proc_by_weak_ref", "(", "ref", ")", ":", "proc", "=", "ref", "(", ")", "if", "proc", "is", "None", ":", "return", "if", "not", "proc", ".", "is_alive", "(", ")", ":", "return", "proc", ".", "terminate", "(", ")", "proc", ".", "join", "(", ")", "assert", "isinstance", "(", "proc", ",", "mp", ".", "Process", ")", "atexit", ".", "register", "(", "stop_proc_by_weak_ref", ",", "weakref", ".", "ref", "(", "proc", ")", ")" ]
Make sure processes terminate when main process exit. Args: proc (multiprocessing.Process or list)
[ "Make", "sure", "processes", "terminate", "when", "main", "process", "exit", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/concurrency.py#L152-L174
train
tensorpack/tensorpack
tensorpack/utils/concurrency.py
enable_death_signal
def enable_death_signal(_warn=True): """ Set the "death signal" of the current process, so that the current process will be cleaned with guarantee in case the parent dies accidentally. """ if platform.system() != 'Linux': return try: import prctl # pip install python-prctl except ImportError: if _warn: log_once('"import prctl" failed! Install python-prctl so that processes can be cleaned with guarantee.', 'warn') return else: assert hasattr(prctl, 'set_pdeathsig'), \ "prctl.set_pdeathsig does not exist! Note that you need to install 'python-prctl' instead of 'prctl'." # is SIGHUP a good choice? prctl.set_pdeathsig(signal.SIGHUP)
python
def enable_death_signal(_warn=True): """ Set the "death signal" of the current process, so that the current process will be cleaned with guarantee in case the parent dies accidentally. """ if platform.system() != 'Linux': return try: import prctl # pip install python-prctl except ImportError: if _warn: log_once('"import prctl" failed! Install python-prctl so that processes can be cleaned with guarantee.', 'warn') return else: assert hasattr(prctl, 'set_pdeathsig'), \ "prctl.set_pdeathsig does not exist! Note that you need to install 'python-prctl' instead of 'prctl'." # is SIGHUP a good choice? prctl.set_pdeathsig(signal.SIGHUP)
[ "def", "enable_death_signal", "(", "_warn", "=", "True", ")", ":", "if", "platform", ".", "system", "(", ")", "!=", "'Linux'", ":", "return", "try", ":", "import", "prctl", "# pip install python-prctl", "except", "ImportError", ":", "if", "_warn", ":", "log_once", "(", "'\"import prctl\" failed! Install python-prctl so that processes can be cleaned with guarantee.'", ",", "'warn'", ")", "return", "else", ":", "assert", "hasattr", "(", "prctl", ",", "'set_pdeathsig'", ")", ",", "\"prctl.set_pdeathsig does not exist! Note that you need to install 'python-prctl' instead of 'prctl'.\"", "# is SIGHUP a good choice?", "prctl", ".", "set_pdeathsig", "(", "signal", ".", "SIGHUP", ")" ]
Set the "death signal" of the current process, so that the current process will be cleaned with guarantee in case the parent dies accidentally.
[ "Set", "the", "death", "signal", "of", "the", "current", "process", "so", "that", "the", "current", "process", "will", "be", "cleaned", "with", "guarantee", "in", "case", "the", "parent", "dies", "accidentally", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/concurrency.py#L177-L196
train
tensorpack/tensorpack
tensorpack/utils/concurrency.py
mask_sigint
def mask_sigint(): """ Returns: If called in main thread, returns a context where ``SIGINT`` is ignored, and yield True. Otherwise yield False. """ if is_main_thread(): sigint_handler = signal.signal(signal.SIGINT, signal.SIG_IGN) yield True signal.signal(signal.SIGINT, sigint_handler) else: yield False
python
def mask_sigint(): """ Returns: If called in main thread, returns a context where ``SIGINT`` is ignored, and yield True. Otherwise yield False. """ if is_main_thread(): sigint_handler = signal.signal(signal.SIGINT, signal.SIG_IGN) yield True signal.signal(signal.SIGINT, sigint_handler) else: yield False
[ "def", "mask_sigint", "(", ")", ":", "if", "is_main_thread", "(", ")", ":", "sigint_handler", "=", "signal", ".", "signal", "(", "signal", ".", "SIGINT", ",", "signal", ".", "SIG_IGN", ")", "yield", "True", "signal", ".", "signal", "(", "signal", ".", "SIGINT", ",", "sigint_handler", ")", "else", ":", "yield", "False" ]
Returns: If called in main thread, returns a context where ``SIGINT`` is ignored, and yield True. Otherwise yield False.
[ "Returns", ":", "If", "called", "in", "main", "thread", "returns", "a", "context", "where", "SIGINT", "is", "ignored", "and", "yield", "True", ".", "Otherwise", "yield", "False", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/concurrency.py#L208-L219
train
tensorpack/tensorpack
tensorpack/utils/concurrency.py
start_proc_mask_signal
def start_proc_mask_signal(proc): """ Start process(es) with SIGINT ignored. Args: proc: (mp.Process or list) Note: The signal mask is only applied when called from main thread. """ if not isinstance(proc, list): proc = [proc] with mask_sigint(): for p in proc: if isinstance(p, mp.Process): if sys.version_info < (3, 4) or mp.get_start_method() == 'fork': log_once( "Starting a process with 'fork' method is not safe and may consume unnecessary extra memory." " Use 'forkserver' method (available after Py3.4) instead if you run into any issues. " "See https://docs.python.org/3/library/multiprocessing.html#contexts-and-start-methods", 'warn') # noqa p.start()
python
def start_proc_mask_signal(proc): """ Start process(es) with SIGINT ignored. Args: proc: (mp.Process or list) Note: The signal mask is only applied when called from main thread. """ if not isinstance(proc, list): proc = [proc] with mask_sigint(): for p in proc: if isinstance(p, mp.Process): if sys.version_info < (3, 4) or mp.get_start_method() == 'fork': log_once( "Starting a process with 'fork' method is not safe and may consume unnecessary extra memory." " Use 'forkserver' method (available after Py3.4) instead if you run into any issues. " "See https://docs.python.org/3/library/multiprocessing.html#contexts-and-start-methods", 'warn') # noqa p.start()
[ "def", "start_proc_mask_signal", "(", "proc", ")", ":", "if", "not", "isinstance", "(", "proc", ",", "list", ")", ":", "proc", "=", "[", "proc", "]", "with", "mask_sigint", "(", ")", ":", "for", "p", "in", "proc", ":", "if", "isinstance", "(", "p", ",", "mp", ".", "Process", ")", ":", "if", "sys", ".", "version_info", "<", "(", "3", ",", "4", ")", "or", "mp", ".", "get_start_method", "(", ")", "==", "'fork'", ":", "log_once", "(", "\"Starting a process with 'fork' method is not safe and may consume unnecessary extra memory.\"", "\" Use 'forkserver' method (available after Py3.4) instead if you run into any issues. \"", "\"See https://docs.python.org/3/library/multiprocessing.html#contexts-and-start-methods\"", ",", "'warn'", ")", "# noqa", "p", ".", "start", "(", ")" ]
Start process(es) with SIGINT ignored. Args: proc: (mp.Process or list) Note: The signal mask is only applied when called from main thread.
[ "Start", "process", "(", "es", ")", "with", "SIGINT", "ignored", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/concurrency.py#L222-L244
train
tensorpack/tensorpack
tensorpack/utils/concurrency.py
subproc_call
def subproc_call(cmd, timeout=None): """ Execute a command with timeout, and return STDOUT and STDERR Args: cmd(str): the command to execute. timeout(float): timeout in seconds. Returns: output(bytes), retcode(int). If timeout, retcode is -1. """ try: output = subprocess.check_output( cmd, stderr=subprocess.STDOUT, shell=True, timeout=timeout) return output, 0 except subprocess.TimeoutExpired as e: logger.warn("Command '{}' timeout!".format(cmd)) logger.warn(e.output.decode('utf-8')) return e.output, -1 except subprocess.CalledProcessError as e: logger.warn("Command '{}' failed, return code={}".format(cmd, e.returncode)) logger.warn(e.output.decode('utf-8')) return e.output, e.returncode except Exception: logger.warn("Command '{}' failed to run.".format(cmd)) return "", -2
python
def subproc_call(cmd, timeout=None): """ Execute a command with timeout, and return STDOUT and STDERR Args: cmd(str): the command to execute. timeout(float): timeout in seconds. Returns: output(bytes), retcode(int). If timeout, retcode is -1. """ try: output = subprocess.check_output( cmd, stderr=subprocess.STDOUT, shell=True, timeout=timeout) return output, 0 except subprocess.TimeoutExpired as e: logger.warn("Command '{}' timeout!".format(cmd)) logger.warn(e.output.decode('utf-8')) return e.output, -1 except subprocess.CalledProcessError as e: logger.warn("Command '{}' failed, return code={}".format(cmd, e.returncode)) logger.warn(e.output.decode('utf-8')) return e.output, e.returncode except Exception: logger.warn("Command '{}' failed to run.".format(cmd)) return "", -2
[ "def", "subproc_call", "(", "cmd", ",", "timeout", "=", "None", ")", ":", "try", ":", "output", "=", "subprocess", ".", "check_output", "(", "cmd", ",", "stderr", "=", "subprocess", ".", "STDOUT", ",", "shell", "=", "True", ",", "timeout", "=", "timeout", ")", "return", "output", ",", "0", "except", "subprocess", ".", "TimeoutExpired", "as", "e", ":", "logger", ".", "warn", "(", "\"Command '{}' timeout!\"", ".", "format", "(", "cmd", ")", ")", "logger", ".", "warn", "(", "e", ".", "output", ".", "decode", "(", "'utf-8'", ")", ")", "return", "e", ".", "output", ",", "-", "1", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "logger", ".", "warn", "(", "\"Command '{}' failed, return code={}\"", ".", "format", "(", "cmd", ",", "e", ".", "returncode", ")", ")", "logger", ".", "warn", "(", "e", ".", "output", ".", "decode", "(", "'utf-8'", ")", ")", "return", "e", ".", "output", ",", "e", ".", "returncode", "except", "Exception", ":", "logger", ".", "warn", "(", "\"Command '{}' failed to run.\"", ".", "format", "(", "cmd", ")", ")", "return", "\"\"", ",", "-", "2" ]
Execute a command with timeout, and return STDOUT and STDERR Args: cmd(str): the command to execute. timeout(float): timeout in seconds. Returns: output(bytes), retcode(int). If timeout, retcode is -1.
[ "Execute", "a", "command", "with", "timeout", "and", "return", "STDOUT", "and", "STDERR" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/concurrency.py#L247-L273
train
tensorpack/tensorpack
tensorpack/utils/concurrency.py
StoppableThread.queue_put_stoppable
def queue_put_stoppable(self, q, obj): """ Put obj to queue, but will give up when the thread is stopped""" while not self.stopped(): try: q.put(obj, timeout=5) break except queue.Full: pass
python
def queue_put_stoppable(self, q, obj): """ Put obj to queue, but will give up when the thread is stopped""" while not self.stopped(): try: q.put(obj, timeout=5) break except queue.Full: pass
[ "def", "queue_put_stoppable", "(", "self", ",", "q", ",", "obj", ")", ":", "while", "not", "self", ".", "stopped", "(", ")", ":", "try", ":", "q", ".", "put", "(", "obj", ",", "timeout", "=", "5", ")", "break", "except", "queue", ".", "Full", ":", "pass" ]
Put obj to queue, but will give up when the thread is stopped
[ "Put", "obj", "to", "queue", "but", "will", "give", "up", "when", "the", "thread", "is", "stopped" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/concurrency.py#L59-L66
train
tensorpack/tensorpack
tensorpack/utils/concurrency.py
StoppableThread.queue_get_stoppable
def queue_get_stoppable(self, q): """ Take obj from queue, but will give up when the thread is stopped""" while not self.stopped(): try: return q.get(timeout=5) except queue.Empty: pass
python
def queue_get_stoppable(self, q): """ Take obj from queue, but will give up when the thread is stopped""" while not self.stopped(): try: return q.get(timeout=5) except queue.Empty: pass
[ "def", "queue_get_stoppable", "(", "self", ",", "q", ")", ":", "while", "not", "self", ".", "stopped", "(", ")", ":", "try", ":", "return", "q", ".", "get", "(", "timeout", "=", "5", ")", "except", "queue", ".", "Empty", ":", "pass" ]
Take obj from queue, but will give up when the thread is stopped
[ "Take", "obj", "from", "queue", "but", "will", "give", "up", "when", "the", "thread", "is", "stopped" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/concurrency.py#L68-L74
train
tensorpack/tensorpack
tensorpack/utils/concurrency.py
OrderedContainer.put
def put(self, rank, val): """ Args: rank(int): rank of th element. All elements must have different ranks. val: an object """ idx = bisect.bisect(self.ranks, rank) self.ranks.insert(idx, rank) self.data.insert(idx, val)
python
def put(self, rank, val): """ Args: rank(int): rank of th element. All elements must have different ranks. val: an object """ idx = bisect.bisect(self.ranks, rank) self.ranks.insert(idx, rank) self.data.insert(idx, val)
[ "def", "put", "(", "self", ",", "rank", ",", "val", ")", ":", "idx", "=", "bisect", ".", "bisect", "(", "self", ".", "ranks", ",", "rank", ")", "self", ".", "ranks", ".", "insert", "(", "idx", ",", "rank", ")", "self", ".", "data", ".", "insert", "(", "idx", ",", "val", ")" ]
Args: rank(int): rank of th element. All elements must have different ranks. val: an object
[ "Args", ":", "rank", "(", "int", ")", ":", "rank", "of", "th", "element", ".", "All", "elements", "must", "have", "different", "ranks", ".", "val", ":", "an", "object" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/concurrency.py#L294-L302
train
tensorpack/tensorpack
examples/basics/mnist-visualizations.py
visualize_conv_weights
def visualize_conv_weights(filters, name): """Visualize use weights in convolution filters. Args: filters: tensor containing the weights [H,W,Cin,Cout] name: label for tensorboard Returns: image of all weight """ with tf.name_scope('visualize_w_' + name): filters = tf.transpose(filters, (3, 2, 0, 1)) # [h, w, cin, cout] -> [cout, cin, h, w] filters = tf.unstack(filters) # --> cout * [cin, h, w] filters = tf.concat(filters, 1) # --> [cin, cout * h, w] filters = tf.unstack(filters) # --> cin * [cout * h, w] filters = tf.concat(filters, 1) # --> [cout * h, cin * w] filters = tf.expand_dims(filters, 0) filters = tf.expand_dims(filters, -1) tf.summary.image('visualize_w_' + name, filters)
python
def visualize_conv_weights(filters, name): """Visualize use weights in convolution filters. Args: filters: tensor containing the weights [H,W,Cin,Cout] name: label for tensorboard Returns: image of all weight """ with tf.name_scope('visualize_w_' + name): filters = tf.transpose(filters, (3, 2, 0, 1)) # [h, w, cin, cout] -> [cout, cin, h, w] filters = tf.unstack(filters) # --> cout * [cin, h, w] filters = tf.concat(filters, 1) # --> [cin, cout * h, w] filters = tf.unstack(filters) # --> cin * [cout * h, w] filters = tf.concat(filters, 1) # --> [cout * h, cin * w] filters = tf.expand_dims(filters, 0) filters = tf.expand_dims(filters, -1) tf.summary.image('visualize_w_' + name, filters)
[ "def", "visualize_conv_weights", "(", "filters", ",", "name", ")", ":", "with", "tf", ".", "name_scope", "(", "'visualize_w_'", "+", "name", ")", ":", "filters", "=", "tf", ".", "transpose", "(", "filters", ",", "(", "3", ",", "2", ",", "0", ",", "1", ")", ")", "# [h, w, cin, cout] -> [cout, cin, h, w]", "filters", "=", "tf", ".", "unstack", "(", "filters", ")", "# --> cout * [cin, h, w]", "filters", "=", "tf", ".", "concat", "(", "filters", ",", "1", ")", "# --> [cin, cout * h, w]", "filters", "=", "tf", ".", "unstack", "(", "filters", ")", "# --> cin * [cout * h, w]", "filters", "=", "tf", ".", "concat", "(", "filters", ",", "1", ")", "# --> [cout * h, cin * w]", "filters", "=", "tf", ".", "expand_dims", "(", "filters", ",", "0", ")", "filters", "=", "tf", ".", "expand_dims", "(", "filters", ",", "-", "1", ")", "tf", ".", "summary", ".", "image", "(", "'visualize_w_'", "+", "name", ",", "filters", ")" ]
Visualize use weights in convolution filters. Args: filters: tensor containing the weights [H,W,Cin,Cout] name: label for tensorboard Returns: image of all weight
[ "Visualize", "use", "weights", "in", "convolution", "filters", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/basics/mnist-visualizations.py#L17-L36
train
tensorpack/tensorpack
examples/basics/mnist-visualizations.py
visualize_conv_activations
def visualize_conv_activations(activation, name): """Visualize activations for convolution layers. Remarks: This tries to place all activations into a square. Args: activation: tensor with the activation [B,H,W,C] name: label for tensorboard Returns: image of almost all activations """ import math with tf.name_scope('visualize_act_' + name): _, h, w, c = activation.get_shape().as_list() rows = [] c_per_row = int(math.sqrt(c)) for y in range(0, c - c_per_row, c_per_row): row = activation[:, :, :, y:y + c_per_row] # [?, H, W, 32] --> [?, H, W, 5] cols = tf.unstack(row, axis=3) # [?, H, W, 5] --> 5 * [?, H, W] row = tf.concat(cols, 1) rows.append(row) viz = tf.concat(rows, 2) tf.summary.image('visualize_act_' + name, tf.expand_dims(viz, -1))
python
def visualize_conv_activations(activation, name): """Visualize activations for convolution layers. Remarks: This tries to place all activations into a square. Args: activation: tensor with the activation [B,H,W,C] name: label for tensorboard Returns: image of almost all activations """ import math with tf.name_scope('visualize_act_' + name): _, h, w, c = activation.get_shape().as_list() rows = [] c_per_row = int(math.sqrt(c)) for y in range(0, c - c_per_row, c_per_row): row = activation[:, :, :, y:y + c_per_row] # [?, H, W, 32] --> [?, H, W, 5] cols = tf.unstack(row, axis=3) # [?, H, W, 5] --> 5 * [?, H, W] row = tf.concat(cols, 1) rows.append(row) viz = tf.concat(rows, 2) tf.summary.image('visualize_act_' + name, tf.expand_dims(viz, -1))
[ "def", "visualize_conv_activations", "(", "activation", ",", "name", ")", ":", "import", "math", "with", "tf", ".", "name_scope", "(", "'visualize_act_'", "+", "name", ")", ":", "_", ",", "h", ",", "w", ",", "c", "=", "activation", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "rows", "=", "[", "]", "c_per_row", "=", "int", "(", "math", ".", "sqrt", "(", "c", ")", ")", "for", "y", "in", "range", "(", "0", ",", "c", "-", "c_per_row", ",", "c_per_row", ")", ":", "row", "=", "activation", "[", ":", ",", ":", ",", ":", ",", "y", ":", "y", "+", "c_per_row", "]", "# [?, H, W, 32] --> [?, H, W, 5]", "cols", "=", "tf", ".", "unstack", "(", "row", ",", "axis", "=", "3", ")", "# [?, H, W, 5] --> 5 * [?, H, W]", "row", "=", "tf", ".", "concat", "(", "cols", ",", "1", ")", "rows", ".", "append", "(", "row", ")", "viz", "=", "tf", ".", "concat", "(", "rows", ",", "2", ")", "tf", ".", "summary", ".", "image", "(", "'visualize_act_'", "+", "name", ",", "tf", ".", "expand_dims", "(", "viz", ",", "-", "1", ")", ")" ]
Visualize activations for convolution layers. Remarks: This tries to place all activations into a square. Args: activation: tensor with the activation [B,H,W,C] name: label for tensorboard Returns: image of almost all activations
[ "Visualize", "activations", "for", "convolution", "layers", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/basics/mnist-visualizations.py#L39-L64
train
tensorpack/tensorpack
examples/GAN/InfoGAN-mnist.py
shapeless_placeholder
def shapeless_placeholder(x, axis, name): """ Make the static shape of a tensor less specific. If you want to feed to a tensor, the shape of the feed value must match the tensor's static shape. This function creates a placeholder which defaults to x if not fed, but has a less specific static shape than x. See also `tensorflow#5680 <https://github.com/tensorflow/tensorflow/issues/5680>`_. Args: x: a tensor axis(int or list of ints): these axes of ``x.get_shape()`` will become None in the output. name(str): name of the output tensor Returns: a tensor equal to x, but shape information is partially cleared. """ shp = x.get_shape().as_list() if not isinstance(axis, list): axis = [axis] for a in axis: if shp[a] is None: raise ValueError("Axis {} of shape {} is already unknown!".format(a, shp)) shp[a] = None x = tf.placeholder_with_default(x, shape=shp, name=name) return x
python
def shapeless_placeholder(x, axis, name): """ Make the static shape of a tensor less specific. If you want to feed to a tensor, the shape of the feed value must match the tensor's static shape. This function creates a placeholder which defaults to x if not fed, but has a less specific static shape than x. See also `tensorflow#5680 <https://github.com/tensorflow/tensorflow/issues/5680>`_. Args: x: a tensor axis(int or list of ints): these axes of ``x.get_shape()`` will become None in the output. name(str): name of the output tensor Returns: a tensor equal to x, but shape information is partially cleared. """ shp = x.get_shape().as_list() if not isinstance(axis, list): axis = [axis] for a in axis: if shp[a] is None: raise ValueError("Axis {} of shape {} is already unknown!".format(a, shp)) shp[a] = None x = tf.placeholder_with_default(x, shape=shp, name=name) return x
[ "def", "shapeless_placeholder", "(", "x", ",", "axis", ",", "name", ")", ":", "shp", "=", "x", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "if", "not", "isinstance", "(", "axis", ",", "list", ")", ":", "axis", "=", "[", "axis", "]", "for", "a", "in", "axis", ":", "if", "shp", "[", "a", "]", "is", "None", ":", "raise", "ValueError", "(", "\"Axis {} of shape {} is already unknown!\"", ".", "format", "(", "a", ",", "shp", ")", ")", "shp", "[", "a", "]", "=", "None", "x", "=", "tf", ".", "placeholder_with_default", "(", "x", ",", "shape", "=", "shp", ",", "name", "=", "name", ")", "return", "x" ]
Make the static shape of a tensor less specific. If you want to feed to a tensor, the shape of the feed value must match the tensor's static shape. This function creates a placeholder which defaults to x if not fed, but has a less specific static shape than x. See also `tensorflow#5680 <https://github.com/tensorflow/tensorflow/issues/5680>`_. Args: x: a tensor axis(int or list of ints): these axes of ``x.get_shape()`` will become None in the output. name(str): name of the output tensor Returns: a tensor equal to x, but shape information is partially cleared.
[ "Make", "the", "static", "shape", "of", "a", "tensor", "less", "specific", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/InfoGAN-mnist.py#L40-L66
train
tensorpack/tensorpack
examples/GAN/InfoGAN-mnist.py
entropy_from_samples
def entropy_from_samples(samples, vec): """ Estimate H(x|s) ~= -E_{x \sim P(x|s)}[\log Q(x|s)], where x are samples, and Q is parameterized by vec. """ samples_cat = tf.argmax(samples[:, :NUM_CLASS], axis=1, output_type=tf.int32) samples_uniform = samples[:, NUM_CLASS:] cat, uniform = get_distributions(vec[:, :NUM_CLASS], vec[:, NUM_CLASS:]) def neg_logprob(dist, sample, name): nll = -dist.log_prob(sample) # average over batch return tf.reduce_sum(tf.reduce_mean(nll, axis=0), name=name) entropies = [neg_logprob(cat, samples_cat, 'nll_cat'), neg_logprob(uniform, samples_uniform, 'nll_uniform')] return entropies
python
def entropy_from_samples(samples, vec): """ Estimate H(x|s) ~= -E_{x \sim P(x|s)}[\log Q(x|s)], where x are samples, and Q is parameterized by vec. """ samples_cat = tf.argmax(samples[:, :NUM_CLASS], axis=1, output_type=tf.int32) samples_uniform = samples[:, NUM_CLASS:] cat, uniform = get_distributions(vec[:, :NUM_CLASS], vec[:, NUM_CLASS:]) def neg_logprob(dist, sample, name): nll = -dist.log_prob(sample) # average over batch return tf.reduce_sum(tf.reduce_mean(nll, axis=0), name=name) entropies = [neg_logprob(cat, samples_cat, 'nll_cat'), neg_logprob(uniform, samples_uniform, 'nll_uniform')] return entropies
[ "def", "entropy_from_samples", "(", "samples", ",", "vec", ")", ":", "samples_cat", "=", "tf", ".", "argmax", "(", "samples", "[", ":", ",", ":", "NUM_CLASS", "]", ",", "axis", "=", "1", ",", "output_type", "=", "tf", ".", "int32", ")", "samples_uniform", "=", "samples", "[", ":", ",", "NUM_CLASS", ":", "]", "cat", ",", "uniform", "=", "get_distributions", "(", "vec", "[", ":", ",", ":", "NUM_CLASS", "]", ",", "vec", "[", ":", ",", "NUM_CLASS", ":", "]", ")", "def", "neg_logprob", "(", "dist", ",", "sample", ",", "name", ")", ":", "nll", "=", "-", "dist", ".", "log_prob", "(", "sample", ")", "# average over batch", "return", "tf", ".", "reduce_sum", "(", "tf", ".", "reduce_mean", "(", "nll", ",", "axis", "=", "0", ")", ",", "name", "=", "name", ")", "entropies", "=", "[", "neg_logprob", "(", "cat", ",", "samples_cat", ",", "'nll_cat'", ")", ",", "neg_logprob", "(", "uniform", ",", "samples_uniform", ",", "'nll_uniform'", ")", "]", "return", "entropies" ]
Estimate H(x|s) ~= -E_{x \sim P(x|s)}[\log Q(x|s)], where x are samples, and Q is parameterized by vec.
[ "Estimate", "H", "(", "x|s", ")", "~", "=", "-", "E_", "{", "x", "\\", "sim", "P", "(", "x|s", ")", "}", "[", "\\", "log", "Q", "(", "x|s", ")", "]", "where", "x", "are", "samples", "and", "Q", "is", "parameterized", "by", "vec", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/InfoGAN-mnist.py#L75-L90
train
tensorpack/tensorpack
examples/GAN/InfoGAN-mnist.py
sample_prior
def sample_prior(batch_size): cat, _ = get_distributions(DIST_PRIOR_PARAM[:NUM_CLASS], DIST_PRIOR_PARAM[NUM_CLASS:]) sample_cat = tf.one_hot(cat.sample(batch_size), NUM_CLASS) """ OpenAI official code actually models the "uniform" latent code as a Gaussian distribution, but obtain the samples from a uniform distribution. """ sample_uni = tf.random_uniform([batch_size, NUM_UNIFORM], -1, 1) samples = tf.concat([sample_cat, sample_uni], axis=1) return samples
python
def sample_prior(batch_size): cat, _ = get_distributions(DIST_PRIOR_PARAM[:NUM_CLASS], DIST_PRIOR_PARAM[NUM_CLASS:]) sample_cat = tf.one_hot(cat.sample(batch_size), NUM_CLASS) """ OpenAI official code actually models the "uniform" latent code as a Gaussian distribution, but obtain the samples from a uniform distribution. """ sample_uni = tf.random_uniform([batch_size, NUM_UNIFORM], -1, 1) samples = tf.concat([sample_cat, sample_uni], axis=1) return samples
[ "def", "sample_prior", "(", "batch_size", ")", ":", "cat", ",", "_", "=", "get_distributions", "(", "DIST_PRIOR_PARAM", "[", ":", "NUM_CLASS", "]", ",", "DIST_PRIOR_PARAM", "[", "NUM_CLASS", ":", "]", ")", "sample_cat", "=", "tf", ".", "one_hot", "(", "cat", ".", "sample", "(", "batch_size", ")", ",", "NUM_CLASS", ")", "sample_uni", "=", "tf", ".", "random_uniform", "(", "[", "batch_size", ",", "NUM_UNIFORM", "]", ",", "-", "1", ",", "1", ")", "samples", "=", "tf", ".", "concat", "(", "[", "sample_cat", ",", "sample_uni", "]", ",", "axis", "=", "1", ")", "return", "samples" ]
OpenAI official code actually models the "uniform" latent code as a Gaussian distribution, but obtain the samples from a uniform distribution.
[ "OpenAI", "official", "code", "actually", "models", "the", "uniform", "latent", "code", "as", "a", "Gaussian", "distribution", "but", "obtain", "the", "samples", "from", "a", "uniform", "distribution", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/InfoGAN-mnist.py#L94-L104
train
tensorpack/tensorpack
examples/GAN/InfoGAN-mnist.py
Model.build_graph
def build_graph(self, real_sample): real_sample = tf.expand_dims(real_sample, -1) # sample the latent code: zc = shapeless_placeholder(sample_prior(BATCH), 0, name='z_code') z_noise = shapeless_placeholder( tf.random_uniform([BATCH, NOISE_DIM], -1, 1), 0, name='z_noise') z = tf.concat([zc, z_noise], 1, name='z') with argscope([Conv2D, Conv2DTranspose, FullyConnected], kernel_initializer=tf.truncated_normal_initializer(stddev=0.02)): with tf.variable_scope('gen'): fake_sample = self.generator(z) fake_sample_viz = tf.cast((fake_sample) * 255.0, tf.uint8, name='viz') tf.summary.image('gen', fake_sample_viz, max_outputs=30) # may need to investigate how bn stats should be updated across two discrim with tf.variable_scope('discrim'): real_pred, _ = self.discriminator(real_sample) fake_pred, dist_param = self.discriminator(fake_sample) """ Mutual information between x (i.e. zc in this case) and some information s (the generated samples in this case): I(x;s) = H(x) - H(x|s) = H(x) + E[\log P(x|s)] The distribution from which zc is sampled, in this case, is set to a fixed prior already. So the first term is a constant. For the second term, we can maximize its variational lower bound: E_{x \sim P(x|s)}[\log Q(x|s)] where Q(x|s) is a proposal distribution to approximate P(x|s). Here, Q(x|s) is assumed to be a distribution which shares the form of P, and whose parameters are predicted by the discriminator network. """ with tf.name_scope("mutual_information"): with tf.name_scope('prior_entropy'): cat, uni = get_distributions(DIST_PRIOR_PARAM[:NUM_CLASS], DIST_PRIOR_PARAM[NUM_CLASS:]) ents = [cat.entropy(name='cat_entropy'), tf.reduce_sum(uni.entropy(), name='uni_entropy')] entropy = tf.add_n(ents, name='total_entropy') # Note that the entropy of prior is a constant. The paper mentioned it but didn't use it. with tf.name_scope('conditional_entropy'): cond_ents = entropy_from_samples(zc, dist_param) cond_entropy = tf.add_n(cond_ents, name="total_entropy") MI = tf.subtract(entropy, cond_entropy, name='mutual_information') summary.add_moving_summary(entropy, cond_entropy, MI, *cond_ents) # default GAN objective self.build_losses(real_pred, fake_pred) # subtract mutual information for latent factors (we want to maximize them) self.g_loss = tf.subtract(self.g_loss, MI, name='total_g_loss') self.d_loss = tf.subtract(self.d_loss, MI, name='total_d_loss') summary.add_moving_summary(self.g_loss, self.d_loss) # distinguish between variables of generator and discriminator updates self.collect_variables()
python
def build_graph(self, real_sample): real_sample = tf.expand_dims(real_sample, -1) # sample the latent code: zc = shapeless_placeholder(sample_prior(BATCH), 0, name='z_code') z_noise = shapeless_placeholder( tf.random_uniform([BATCH, NOISE_DIM], -1, 1), 0, name='z_noise') z = tf.concat([zc, z_noise], 1, name='z') with argscope([Conv2D, Conv2DTranspose, FullyConnected], kernel_initializer=tf.truncated_normal_initializer(stddev=0.02)): with tf.variable_scope('gen'): fake_sample = self.generator(z) fake_sample_viz = tf.cast((fake_sample) * 255.0, tf.uint8, name='viz') tf.summary.image('gen', fake_sample_viz, max_outputs=30) # may need to investigate how bn stats should be updated across two discrim with tf.variable_scope('discrim'): real_pred, _ = self.discriminator(real_sample) fake_pred, dist_param = self.discriminator(fake_sample) """ Mutual information between x (i.e. zc in this case) and some information s (the generated samples in this case): I(x;s) = H(x) - H(x|s) = H(x) + E[\log P(x|s)] The distribution from which zc is sampled, in this case, is set to a fixed prior already. So the first term is a constant. For the second term, we can maximize its variational lower bound: E_{x \sim P(x|s)}[\log Q(x|s)] where Q(x|s) is a proposal distribution to approximate P(x|s). Here, Q(x|s) is assumed to be a distribution which shares the form of P, and whose parameters are predicted by the discriminator network. """ with tf.name_scope("mutual_information"): with tf.name_scope('prior_entropy'): cat, uni = get_distributions(DIST_PRIOR_PARAM[:NUM_CLASS], DIST_PRIOR_PARAM[NUM_CLASS:]) ents = [cat.entropy(name='cat_entropy'), tf.reduce_sum(uni.entropy(), name='uni_entropy')] entropy = tf.add_n(ents, name='total_entropy') # Note that the entropy of prior is a constant. The paper mentioned it but didn't use it. with tf.name_scope('conditional_entropy'): cond_ents = entropy_from_samples(zc, dist_param) cond_entropy = tf.add_n(cond_ents, name="total_entropy") MI = tf.subtract(entropy, cond_entropy, name='mutual_information') summary.add_moving_summary(entropy, cond_entropy, MI, *cond_ents) # default GAN objective self.build_losses(real_pred, fake_pred) # subtract mutual information for latent factors (we want to maximize them) self.g_loss = tf.subtract(self.g_loss, MI, name='total_g_loss') self.d_loss = tf.subtract(self.d_loss, MI, name='total_d_loss') summary.add_moving_summary(self.g_loss, self.d_loss) # distinguish between variables of generator and discriminator updates self.collect_variables()
[ "def", "build_graph", "(", "self", ",", "real_sample", ")", ":", "real_sample", "=", "tf", ".", "expand_dims", "(", "real_sample", ",", "-", "1", ")", "# sample the latent code:", "zc", "=", "shapeless_placeholder", "(", "sample_prior", "(", "BATCH", ")", ",", "0", ",", "name", "=", "'z_code'", ")", "z_noise", "=", "shapeless_placeholder", "(", "tf", ".", "random_uniform", "(", "[", "BATCH", ",", "NOISE_DIM", "]", ",", "-", "1", ",", "1", ")", ",", "0", ",", "name", "=", "'z_noise'", ")", "z", "=", "tf", ".", "concat", "(", "[", "zc", ",", "z_noise", "]", ",", "1", ",", "name", "=", "'z'", ")", "with", "argscope", "(", "[", "Conv2D", ",", "Conv2DTranspose", ",", "FullyConnected", "]", ",", "kernel_initializer", "=", "tf", ".", "truncated_normal_initializer", "(", "stddev", "=", "0.02", ")", ")", ":", "with", "tf", ".", "variable_scope", "(", "'gen'", ")", ":", "fake_sample", "=", "self", ".", "generator", "(", "z", ")", "fake_sample_viz", "=", "tf", ".", "cast", "(", "(", "fake_sample", ")", "*", "255.0", ",", "tf", ".", "uint8", ",", "name", "=", "'viz'", ")", "tf", ".", "summary", ".", "image", "(", "'gen'", ",", "fake_sample_viz", ",", "max_outputs", "=", "30", ")", "# may need to investigate how bn stats should be updated across two discrim", "with", "tf", ".", "variable_scope", "(", "'discrim'", ")", ":", "real_pred", ",", "_", "=", "self", ".", "discriminator", "(", "real_sample", ")", "fake_pred", ",", "dist_param", "=", "self", ".", "discriminator", "(", "fake_sample", ")", "with", "tf", ".", "name_scope", "(", "\"mutual_information\"", ")", ":", "with", "tf", ".", "name_scope", "(", "'prior_entropy'", ")", ":", "cat", ",", "uni", "=", "get_distributions", "(", "DIST_PRIOR_PARAM", "[", ":", "NUM_CLASS", "]", ",", "DIST_PRIOR_PARAM", "[", "NUM_CLASS", ":", "]", ")", "ents", "=", "[", "cat", ".", "entropy", "(", "name", "=", "'cat_entropy'", ")", ",", "tf", ".", "reduce_sum", "(", "uni", ".", "entropy", "(", ")", ",", "name", "=", "'uni_entropy'", ")", "]", "entropy", "=", "tf", ".", "add_n", "(", "ents", ",", "name", "=", "'total_entropy'", ")", "# Note that the entropy of prior is a constant. The paper mentioned it but didn't use it.", "with", "tf", ".", "name_scope", "(", "'conditional_entropy'", ")", ":", "cond_ents", "=", "entropy_from_samples", "(", "zc", ",", "dist_param", ")", "cond_entropy", "=", "tf", ".", "add_n", "(", "cond_ents", ",", "name", "=", "\"total_entropy\"", ")", "MI", "=", "tf", ".", "subtract", "(", "entropy", ",", "cond_entropy", ",", "name", "=", "'mutual_information'", ")", "summary", ".", "add_moving_summary", "(", "entropy", ",", "cond_entropy", ",", "MI", ",", "*", "cond_ents", ")", "# default GAN objective", "self", ".", "build_losses", "(", "real_pred", ",", "fake_pred", ")", "# subtract mutual information for latent factors (we want to maximize them)", "self", ".", "g_loss", "=", "tf", ".", "subtract", "(", "self", ".", "g_loss", ",", "MI", ",", "name", "=", "'total_g_loss'", ")", "self", ".", "d_loss", "=", "tf", ".", "subtract", "(", "self", ".", "d_loss", ",", "MI", ",", "name", "=", "'total_d_loss'", ")", "summary", ".", "add_moving_summary", "(", "self", ".", "g_loss", ",", "self", ".", "d_loss", ")", "# distinguish between variables of generator and discriminator updates", "self", ".", "collect_variables", "(", ")" ]
Mutual information between x (i.e. zc in this case) and some information s (the generated samples in this case): I(x;s) = H(x) - H(x|s) = H(x) + E[\log P(x|s)] The distribution from which zc is sampled, in this case, is set to a fixed prior already. So the first term is a constant. For the second term, we can maximize its variational lower bound: E_{x \sim P(x|s)}[\log Q(x|s)] where Q(x|s) is a proposal distribution to approximate P(x|s). Here, Q(x|s) is assumed to be a distribution which shares the form of P, and whose parameters are predicted by the discriminator network.
[ "Mutual", "information", "between", "x", "(", "i", ".", "e", ".", "zc", "in", "this", "case", ")", "and", "some", "information", "s", "(", "the", "generated", "samples", "in", "this", "case", ")", ":" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/InfoGAN-mnist.py#L141-L202
train
tensorpack/tensorpack
examples/DynamicFilterNetwork/steering-filter.py
DynamicConvFilter
def DynamicConvFilter(inputs, filters, out_channel, kernel_shape, stride=1, padding='SAME'): """ see "Dynamic Filter Networks" (NIPS 2016) by Bert De Brabandere*, Xu Jia*, Tinne Tuytelaars and Luc Van Gool Remarks: This is the convolution version of a dynamic filter. Args: inputs : unfiltered input [b, h, w, 1] only grayscale images. filters : learned filters of [b, k, k, 1] (dynamically generated by the network). out_channel (int): number of output channel. kernel_shape: (h, w) tuple or a int. stride: (h, w) tuple or a int. padding (str): 'valid' or 'same'. Case insensitive. Returns tf.Tensor named ``output``. """ # tf.unstack only works with known batch_size :-( batch_size, h, w, in_channel = inputs.get_shape().as_list() stride = shape4d(stride) inputs = tf.unstack(inputs) filters = tf.reshape(filters, [batch_size] + shape2d(kernel_shape) + [in_channel, out_channel]) filters = tf.unstack(filters) # this is ok as TF uses the cuda stream context rsl = [tf.nn.conv2d(tf.reshape(d, [1, h, w, in_channel]), tf.reshape(k, [kernel_shape, kernel_shape, in_channel, out_channel]), stride, padding="SAME") for d, k in zip(inputs, filters)] rsl = tf.concat(rsl, axis=0, name='output') return rsl
python
def DynamicConvFilter(inputs, filters, out_channel, kernel_shape, stride=1, padding='SAME'): """ see "Dynamic Filter Networks" (NIPS 2016) by Bert De Brabandere*, Xu Jia*, Tinne Tuytelaars and Luc Van Gool Remarks: This is the convolution version of a dynamic filter. Args: inputs : unfiltered input [b, h, w, 1] only grayscale images. filters : learned filters of [b, k, k, 1] (dynamically generated by the network). out_channel (int): number of output channel. kernel_shape: (h, w) tuple or a int. stride: (h, w) tuple or a int. padding (str): 'valid' or 'same'. Case insensitive. Returns tf.Tensor named ``output``. """ # tf.unstack only works with known batch_size :-( batch_size, h, w, in_channel = inputs.get_shape().as_list() stride = shape4d(stride) inputs = tf.unstack(inputs) filters = tf.reshape(filters, [batch_size] + shape2d(kernel_shape) + [in_channel, out_channel]) filters = tf.unstack(filters) # this is ok as TF uses the cuda stream context rsl = [tf.nn.conv2d(tf.reshape(d, [1, h, w, in_channel]), tf.reshape(k, [kernel_shape, kernel_shape, in_channel, out_channel]), stride, padding="SAME") for d, k in zip(inputs, filters)] rsl = tf.concat(rsl, axis=0, name='output') return rsl
[ "def", "DynamicConvFilter", "(", "inputs", ",", "filters", ",", "out_channel", ",", "kernel_shape", ",", "stride", "=", "1", ",", "padding", "=", "'SAME'", ")", ":", "# tf.unstack only works with known batch_size :-(", "batch_size", ",", "h", ",", "w", ",", "in_channel", "=", "inputs", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "stride", "=", "shape4d", "(", "stride", ")", "inputs", "=", "tf", ".", "unstack", "(", "inputs", ")", "filters", "=", "tf", ".", "reshape", "(", "filters", ",", "[", "batch_size", "]", "+", "shape2d", "(", "kernel_shape", ")", "+", "[", "in_channel", ",", "out_channel", "]", ")", "filters", "=", "tf", ".", "unstack", "(", "filters", ")", "# this is ok as TF uses the cuda stream context", "rsl", "=", "[", "tf", ".", "nn", ".", "conv2d", "(", "tf", ".", "reshape", "(", "d", ",", "[", "1", ",", "h", ",", "w", ",", "in_channel", "]", ")", ",", "tf", ".", "reshape", "(", "k", ",", "[", "kernel_shape", ",", "kernel_shape", ",", "in_channel", ",", "out_channel", "]", ")", ",", "stride", ",", "padding", "=", "\"SAME\"", ")", "for", "d", ",", "k", "in", "zip", "(", "inputs", ",", "filters", ")", "]", "rsl", "=", "tf", ".", "concat", "(", "rsl", ",", "axis", "=", "0", ",", "name", "=", "'output'", ")", "return", "rsl" ]
see "Dynamic Filter Networks" (NIPS 2016) by Bert De Brabandere*, Xu Jia*, Tinne Tuytelaars and Luc Van Gool Remarks: This is the convolution version of a dynamic filter. Args: inputs : unfiltered input [b, h, w, 1] only grayscale images. filters : learned filters of [b, k, k, 1] (dynamically generated by the network). out_channel (int): number of output channel. kernel_shape: (h, w) tuple or a int. stride: (h, w) tuple or a int. padding (str): 'valid' or 'same'. Case insensitive. Returns tf.Tensor named ``output``.
[ "see", "Dynamic", "Filter", "Networks", "(", "NIPS", "2016", ")", "by", "Bert", "De", "Brabandere", "*", "Xu", "Jia", "*", "Tinne", "Tuytelaars", "and", "Luc", "Van", "Gool" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DynamicFilterNetwork/steering-filter.py#L24-L59
train
tensorpack/tensorpack
examples/DynamicFilterNetwork/steering-filter.py
Model._parameter_net
def _parameter_net(self, theta, kernel_shape=9): """Estimate filters for convolution layers Args: theta: angle of filter kernel_shape: size of each filter Returns: learned filter as [B, k, k, 1] """ with argscope(FullyConnected, nl=tf.nn.leaky_relu): net = FullyConnected('fc1', theta, 64) net = FullyConnected('fc2', net, 128) pred_filter = FullyConnected('fc3', net, kernel_shape ** 2, nl=tf.identity) pred_filter = tf.reshape(pred_filter, [BATCH, kernel_shape, kernel_shape, 1], name="pred_filter") logger.info('Parameter net output: {}'.format(pred_filter.get_shape().as_list())) return pred_filter
python
def _parameter_net(self, theta, kernel_shape=9): """Estimate filters for convolution layers Args: theta: angle of filter kernel_shape: size of each filter Returns: learned filter as [B, k, k, 1] """ with argscope(FullyConnected, nl=tf.nn.leaky_relu): net = FullyConnected('fc1', theta, 64) net = FullyConnected('fc2', net, 128) pred_filter = FullyConnected('fc3', net, kernel_shape ** 2, nl=tf.identity) pred_filter = tf.reshape(pred_filter, [BATCH, kernel_shape, kernel_shape, 1], name="pred_filter") logger.info('Parameter net output: {}'.format(pred_filter.get_shape().as_list())) return pred_filter
[ "def", "_parameter_net", "(", "self", ",", "theta", ",", "kernel_shape", "=", "9", ")", ":", "with", "argscope", "(", "FullyConnected", ",", "nl", "=", "tf", ".", "nn", ".", "leaky_relu", ")", ":", "net", "=", "FullyConnected", "(", "'fc1'", ",", "theta", ",", "64", ")", "net", "=", "FullyConnected", "(", "'fc2'", ",", "net", ",", "128", ")", "pred_filter", "=", "FullyConnected", "(", "'fc3'", ",", "net", ",", "kernel_shape", "**", "2", ",", "nl", "=", "tf", ".", "identity", ")", "pred_filter", "=", "tf", ".", "reshape", "(", "pred_filter", ",", "[", "BATCH", ",", "kernel_shape", ",", "kernel_shape", ",", "1", "]", ",", "name", "=", "\"pred_filter\"", ")", "logger", ".", "info", "(", "'Parameter net output: {}'", ".", "format", "(", "pred_filter", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", ")", ")", "return", "pred_filter" ]
Estimate filters for convolution layers Args: theta: angle of filter kernel_shape: size of each filter Returns: learned filter as [B, k, k, 1]
[ "Estimate", "filters", "for", "convolution", "layers" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DynamicFilterNetwork/steering-filter.py#L103-L120
train
tensorpack/tensorpack
examples/DynamicFilterNetwork/steering-filter.py
ThetaImages.filter_with_theta
def filter_with_theta(image, theta, sigma=1., filter_size=9): """Implements a steerable Gaussian filter. This function can be used to evaluate the first directional derivative of an image, using the method outlined in W. T. Freeman and E. H. Adelson, "The Design and Use of Steerable Filters", IEEE PAMI, 1991. It evaluates the directional derivative of the input image I, oriented at THETA degrees with respect to the image rows. The standard deviation of the Gaussian kernel is given by SIGMA (assumed to be equal to unity by default). Args: image: any input image (only one channel) theta: orientation of filter [0, 2 * pi] sigma (float, optional): standard derivation of Gaussian filter_size (int, optional): filter support Returns: filtered image and the filter """ x = np.arange(-filter_size // 2 + 1, filter_size // 2 + 1) # 1D Gaussian g = np.array([np.exp(-(x**2) / (2 * sigma**2))]) # first-derivative of 1D Gaussian gp = np.array([-(x / sigma) * np.exp(-(x**2) / (2 * sigma**2))]) ix = convolve2d(image, -gp, mode='same', boundary='fill', fillvalue=0) ix = convolve2d(ix, g.T, mode='same', boundary='fill', fillvalue=0) iy = convolve2d(image, g, mode='same', boundary='fill', fillvalue=0) iy = convolve2d(iy, -gp.T, mode='same', boundary='fill', fillvalue=0) output = np.cos(theta) * ix + np.sin(theta) * iy # np.cos(theta) * np.matmul(g.T, gp) + np.sin(theta) * np.matmul(gp.T, g) gt_filter = np.matmul(g.T, gp) gt_filter = np.cos(theta) * gt_filter + np.sin(theta) * gt_filter.T return output, gt_filter
python
def filter_with_theta(image, theta, sigma=1., filter_size=9): """Implements a steerable Gaussian filter. This function can be used to evaluate the first directional derivative of an image, using the method outlined in W. T. Freeman and E. H. Adelson, "The Design and Use of Steerable Filters", IEEE PAMI, 1991. It evaluates the directional derivative of the input image I, oriented at THETA degrees with respect to the image rows. The standard deviation of the Gaussian kernel is given by SIGMA (assumed to be equal to unity by default). Args: image: any input image (only one channel) theta: orientation of filter [0, 2 * pi] sigma (float, optional): standard derivation of Gaussian filter_size (int, optional): filter support Returns: filtered image and the filter """ x = np.arange(-filter_size // 2 + 1, filter_size // 2 + 1) # 1D Gaussian g = np.array([np.exp(-(x**2) / (2 * sigma**2))]) # first-derivative of 1D Gaussian gp = np.array([-(x / sigma) * np.exp(-(x**2) / (2 * sigma**2))]) ix = convolve2d(image, -gp, mode='same', boundary='fill', fillvalue=0) ix = convolve2d(ix, g.T, mode='same', boundary='fill', fillvalue=0) iy = convolve2d(image, g, mode='same', boundary='fill', fillvalue=0) iy = convolve2d(iy, -gp.T, mode='same', boundary='fill', fillvalue=0) output = np.cos(theta) * ix + np.sin(theta) * iy # np.cos(theta) * np.matmul(g.T, gp) + np.sin(theta) * np.matmul(gp.T, g) gt_filter = np.matmul(g.T, gp) gt_filter = np.cos(theta) * gt_filter + np.sin(theta) * gt_filter.T return output, gt_filter
[ "def", "filter_with_theta", "(", "image", ",", "theta", ",", "sigma", "=", "1.", ",", "filter_size", "=", "9", ")", ":", "x", "=", "np", ".", "arange", "(", "-", "filter_size", "//", "2", "+", "1", ",", "filter_size", "//", "2", "+", "1", ")", "# 1D Gaussian", "g", "=", "np", ".", "array", "(", "[", "np", ".", "exp", "(", "-", "(", "x", "**", "2", ")", "/", "(", "2", "*", "sigma", "**", "2", ")", ")", "]", ")", "# first-derivative of 1D Gaussian", "gp", "=", "np", ".", "array", "(", "[", "-", "(", "x", "/", "sigma", ")", "*", "np", ".", "exp", "(", "-", "(", "x", "**", "2", ")", "/", "(", "2", "*", "sigma", "**", "2", ")", ")", "]", ")", "ix", "=", "convolve2d", "(", "image", ",", "-", "gp", ",", "mode", "=", "'same'", ",", "boundary", "=", "'fill'", ",", "fillvalue", "=", "0", ")", "ix", "=", "convolve2d", "(", "ix", ",", "g", ".", "T", ",", "mode", "=", "'same'", ",", "boundary", "=", "'fill'", ",", "fillvalue", "=", "0", ")", "iy", "=", "convolve2d", "(", "image", ",", "g", ",", "mode", "=", "'same'", ",", "boundary", "=", "'fill'", ",", "fillvalue", "=", "0", ")", "iy", "=", "convolve2d", "(", "iy", ",", "-", "gp", ".", "T", ",", "mode", "=", "'same'", ",", "boundary", "=", "'fill'", ",", "fillvalue", "=", "0", ")", "output", "=", "np", ".", "cos", "(", "theta", ")", "*", "ix", "+", "np", ".", "sin", "(", "theta", ")", "*", "iy", "# np.cos(theta) * np.matmul(g.T, gp) + np.sin(theta) * np.matmul(gp.T, g)", "gt_filter", "=", "np", ".", "matmul", "(", "g", ".", "T", ",", "gp", ")", "gt_filter", "=", "np", ".", "cos", "(", "theta", ")", "*", "gt_filter", "+", "np", ".", "sin", "(", "theta", ")", "*", "gt_filter", ".", "T", "return", "output", ",", "gt_filter" ]
Implements a steerable Gaussian filter. This function can be used to evaluate the first directional derivative of an image, using the method outlined in W. T. Freeman and E. H. Adelson, "The Design and Use of Steerable Filters", IEEE PAMI, 1991. It evaluates the directional derivative of the input image I, oriented at THETA degrees with respect to the image rows. The standard deviation of the Gaussian kernel is given by SIGMA (assumed to be equal to unity by default). Args: image: any input image (only one channel) theta: orientation of filter [0, 2 * pi] sigma (float, optional): standard derivation of Gaussian filter_size (int, optional): filter support Returns: filtered image and the filter
[ "Implements", "a", "steerable", "Gaussian", "filter", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DynamicFilterNetwork/steering-filter.py#L162-L204
train
tensorpack/tensorpack
examples/GAN/GAN.py
GANModelDesc.collect_variables
def collect_variables(self, g_scope='gen', d_scope='discrim'): """ Assign `self.g_vars` to the parameters under scope `g_scope`, and same with `self.d_vars`. """ self.g_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, g_scope) assert self.g_vars self.d_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, d_scope) assert self.d_vars
python
def collect_variables(self, g_scope='gen', d_scope='discrim'): """ Assign `self.g_vars` to the parameters under scope `g_scope`, and same with `self.d_vars`. """ self.g_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, g_scope) assert self.g_vars self.d_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, d_scope) assert self.d_vars
[ "def", "collect_variables", "(", "self", ",", "g_scope", "=", "'gen'", ",", "d_scope", "=", "'discrim'", ")", ":", "self", ".", "g_vars", "=", "tf", ".", "get_collection", "(", "tf", ".", "GraphKeys", ".", "TRAINABLE_VARIABLES", ",", "g_scope", ")", "assert", "self", ".", "g_vars", "self", ".", "d_vars", "=", "tf", ".", "get_collection", "(", "tf", ".", "GraphKeys", ".", "TRAINABLE_VARIABLES", ",", "d_scope", ")", "assert", "self", ".", "d_vars" ]
Assign `self.g_vars` to the parameters under scope `g_scope`, and same with `self.d_vars`.
[ "Assign", "self", ".", "g_vars", "to", "the", "parameters", "under", "scope", "g_scope", "and", "same", "with", "self", ".", "d_vars", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/GAN.py#L17-L25
train
tensorpack/tensorpack
examples/GAN/GAN.py
GANModelDesc.build_losses
def build_losses(self, logits_real, logits_fake): """ Build standard GAN loss and set `self.g_loss` and `self.d_loss`. D and G play two-player minimax game with value function V(G,D) min_G max _D V(D, G) = IE_{x ~ p_data} [log D(x)] + IE_{z ~ p_fake} [log (1 - D(G(z)))] Args: logits_real (tf.Tensor): discrim logits from real samples logits_fake (tf.Tensor): discrim logits from fake samples produced by generator """ with tf.name_scope("GAN_loss"): score_real = tf.sigmoid(logits_real) score_fake = tf.sigmoid(logits_fake) tf.summary.histogram('score-real', score_real) tf.summary.histogram('score-fake', score_fake) with tf.name_scope("discrim"): d_loss_pos = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits( logits=logits_real, labels=tf.ones_like(logits_real)), name='loss_real') d_loss_neg = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits( logits=logits_fake, labels=tf.zeros_like(logits_fake)), name='loss_fake') d_pos_acc = tf.reduce_mean(tf.cast(score_real > 0.5, tf.float32), name='accuracy_real') d_neg_acc = tf.reduce_mean(tf.cast(score_fake < 0.5, tf.float32), name='accuracy_fake') d_accuracy = tf.add(.5 * d_pos_acc, .5 * d_neg_acc, name='accuracy') self.d_loss = tf.add(.5 * d_loss_pos, .5 * d_loss_neg, name='loss') with tf.name_scope("gen"): self.g_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits( logits=logits_fake, labels=tf.ones_like(logits_fake)), name='loss') g_accuracy = tf.reduce_mean(tf.cast(score_fake > 0.5, tf.float32), name='accuracy') add_moving_summary(self.g_loss, self.d_loss, d_accuracy, g_accuracy)
python
def build_losses(self, logits_real, logits_fake): """ Build standard GAN loss and set `self.g_loss` and `self.d_loss`. D and G play two-player minimax game with value function V(G,D) min_G max _D V(D, G) = IE_{x ~ p_data} [log D(x)] + IE_{z ~ p_fake} [log (1 - D(G(z)))] Args: logits_real (tf.Tensor): discrim logits from real samples logits_fake (tf.Tensor): discrim logits from fake samples produced by generator """ with tf.name_scope("GAN_loss"): score_real = tf.sigmoid(logits_real) score_fake = tf.sigmoid(logits_fake) tf.summary.histogram('score-real', score_real) tf.summary.histogram('score-fake', score_fake) with tf.name_scope("discrim"): d_loss_pos = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits( logits=logits_real, labels=tf.ones_like(logits_real)), name='loss_real') d_loss_neg = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits( logits=logits_fake, labels=tf.zeros_like(logits_fake)), name='loss_fake') d_pos_acc = tf.reduce_mean(tf.cast(score_real > 0.5, tf.float32), name='accuracy_real') d_neg_acc = tf.reduce_mean(tf.cast(score_fake < 0.5, tf.float32), name='accuracy_fake') d_accuracy = tf.add(.5 * d_pos_acc, .5 * d_neg_acc, name='accuracy') self.d_loss = tf.add(.5 * d_loss_pos, .5 * d_loss_neg, name='loss') with tf.name_scope("gen"): self.g_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits( logits=logits_fake, labels=tf.ones_like(logits_fake)), name='loss') g_accuracy = tf.reduce_mean(tf.cast(score_fake > 0.5, tf.float32), name='accuracy') add_moving_summary(self.g_loss, self.d_loss, d_accuracy, g_accuracy)
[ "def", "build_losses", "(", "self", ",", "logits_real", ",", "logits_fake", ")", ":", "with", "tf", ".", "name_scope", "(", "\"GAN_loss\"", ")", ":", "score_real", "=", "tf", ".", "sigmoid", "(", "logits_real", ")", "score_fake", "=", "tf", ".", "sigmoid", "(", "logits_fake", ")", "tf", ".", "summary", ".", "histogram", "(", "'score-real'", ",", "score_real", ")", "tf", ".", "summary", ".", "histogram", "(", "'score-fake'", ",", "score_fake", ")", "with", "tf", ".", "name_scope", "(", "\"discrim\"", ")", ":", "d_loss_pos", "=", "tf", ".", "reduce_mean", "(", "tf", ".", "nn", ".", "sigmoid_cross_entropy_with_logits", "(", "logits", "=", "logits_real", ",", "labels", "=", "tf", ".", "ones_like", "(", "logits_real", ")", ")", ",", "name", "=", "'loss_real'", ")", "d_loss_neg", "=", "tf", ".", "reduce_mean", "(", "tf", ".", "nn", ".", "sigmoid_cross_entropy_with_logits", "(", "logits", "=", "logits_fake", ",", "labels", "=", "tf", ".", "zeros_like", "(", "logits_fake", ")", ")", ",", "name", "=", "'loss_fake'", ")", "d_pos_acc", "=", "tf", ".", "reduce_mean", "(", "tf", ".", "cast", "(", "score_real", ">", "0.5", ",", "tf", ".", "float32", ")", ",", "name", "=", "'accuracy_real'", ")", "d_neg_acc", "=", "tf", ".", "reduce_mean", "(", "tf", ".", "cast", "(", "score_fake", "<", "0.5", ",", "tf", ".", "float32", ")", ",", "name", "=", "'accuracy_fake'", ")", "d_accuracy", "=", "tf", ".", "add", "(", ".5", "*", "d_pos_acc", ",", ".5", "*", "d_neg_acc", ",", "name", "=", "'accuracy'", ")", "self", ".", "d_loss", "=", "tf", ".", "add", "(", ".5", "*", "d_loss_pos", ",", ".5", "*", "d_loss_neg", ",", "name", "=", "'loss'", ")", "with", "tf", ".", "name_scope", "(", "\"gen\"", ")", ":", "self", ".", "g_loss", "=", "tf", ".", "reduce_mean", "(", "tf", ".", "nn", ".", "sigmoid_cross_entropy_with_logits", "(", "logits", "=", "logits_fake", ",", "labels", "=", "tf", ".", "ones_like", "(", "logits_fake", ")", ")", ",", "name", "=", "'loss'", ")", "g_accuracy", "=", "tf", ".", "reduce_mean", "(", "tf", ".", "cast", "(", "score_fake", ">", "0.5", ",", "tf", ".", "float32", ")", ",", "name", "=", "'accuracy'", ")", "add_moving_summary", "(", "self", ".", "g_loss", ",", "self", ".", "d_loss", ",", "d_accuracy", ",", "g_accuracy", ")" ]
Build standard GAN loss and set `self.g_loss` and `self.d_loss`. D and G play two-player minimax game with value function V(G,D) min_G max _D V(D, G) = IE_{x ~ p_data} [log D(x)] + IE_{z ~ p_fake} [log (1 - D(G(z)))] Args: logits_real (tf.Tensor): discrim logits from real samples logits_fake (tf.Tensor): discrim logits from fake samples produced by generator
[ "Build", "standard", "GAN", "loss", "and", "set", "self", ".", "g_loss", "and", "self", ".", "d_loss", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/GAN.py#L27-L62
train
tensorpack/tensorpack
examples/GAN/GAN.py
GANTrainer._build_gan_trainer
def _build_gan_trainer(self, input, model): """ We need to set tower_func because it's a TowerTrainer, and only TowerTrainer supports automatic graph creation for inference during training. If we don't care about inference during training, using tower_func is not needed. Just calling model.build_graph directly is OK. """ # Build the graph self.tower_func = TowerFuncWrapper(model.build_graph, model.get_input_signature()) with TowerContext('', is_training=True): self.tower_func(*input.get_input_tensors()) opt = model.get_optimizer() # Define the training iteration # by default, run one d_min after one g_min with tf.name_scope('optimize'): g_min = opt.minimize(model.g_loss, var_list=model.g_vars, name='g_op') with tf.control_dependencies([g_min]): d_min = opt.minimize(model.d_loss, var_list=model.d_vars, name='d_op') self.train_op = d_min
python
def _build_gan_trainer(self, input, model): """ We need to set tower_func because it's a TowerTrainer, and only TowerTrainer supports automatic graph creation for inference during training. If we don't care about inference during training, using tower_func is not needed. Just calling model.build_graph directly is OK. """ # Build the graph self.tower_func = TowerFuncWrapper(model.build_graph, model.get_input_signature()) with TowerContext('', is_training=True): self.tower_func(*input.get_input_tensors()) opt = model.get_optimizer() # Define the training iteration # by default, run one d_min after one g_min with tf.name_scope('optimize'): g_min = opt.minimize(model.g_loss, var_list=model.g_vars, name='g_op') with tf.control_dependencies([g_min]): d_min = opt.minimize(model.d_loss, var_list=model.d_vars, name='d_op') self.train_op = d_min
[ "def", "_build_gan_trainer", "(", "self", ",", "input", ",", "model", ")", ":", "# Build the graph", "self", ".", "tower_func", "=", "TowerFuncWrapper", "(", "model", ".", "build_graph", ",", "model", ".", "get_input_signature", "(", ")", ")", "with", "TowerContext", "(", "''", ",", "is_training", "=", "True", ")", ":", "self", ".", "tower_func", "(", "*", "input", ".", "get_input_tensors", "(", ")", ")", "opt", "=", "model", ".", "get_optimizer", "(", ")", "# Define the training iteration", "# by default, run one d_min after one g_min", "with", "tf", ".", "name_scope", "(", "'optimize'", ")", ":", "g_min", "=", "opt", ".", "minimize", "(", "model", ".", "g_loss", ",", "var_list", "=", "model", ".", "g_vars", ",", "name", "=", "'g_op'", ")", "with", "tf", ".", "control_dependencies", "(", "[", "g_min", "]", ")", ":", "d_min", "=", "opt", ".", "minimize", "(", "model", ".", "d_loss", ",", "var_list", "=", "model", ".", "d_vars", ",", "name", "=", "'d_op'", ")", "self", ".", "train_op", "=", "d_min" ]
We need to set tower_func because it's a TowerTrainer, and only TowerTrainer supports automatic graph creation for inference during training. If we don't care about inference during training, using tower_func is not needed. Just calling model.build_graph directly is OK.
[ "We", "need", "to", "set", "tower_func", "because", "it", "s", "a", "TowerTrainer", "and", "only", "TowerTrainer", "supports", "automatic", "graph", "creation", "for", "inference", "during", "training", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/GAN.py#L99-L119
train
tensorpack/tensorpack
tensorpack/models/tflayer.py
convert_to_tflayer_args
def convert_to_tflayer_args(args_names, name_mapping): """ After applying this decorator: 1. data_format becomes tf.layers style 2. nl becomes activation 3. initializers are renamed 4. positional args are transformed to corresponding kwargs, according to args_names 5. kwargs are mapped to tf.layers names if needed, by name_mapping """ def decorator(func): @functools.wraps(func) def decorated_func(inputs, *args, **kwargs): kwargs = map_common_tfargs(kwargs) posarg_dic = {} assert len(args) <= len(args_names), \ "Please use kwargs instead of positional args to call this model, " \ "except for the following arguments: {}".format(', '.join(args_names)) for pos_arg, name in zip(args, args_names): posarg_dic[name] = pos_arg ret = {} for name, arg in six.iteritems(kwargs): newname = name_mapping.get(name, None) if newname is not None: assert newname not in kwargs, \ "Argument {} and {} conflicts!".format(name, newname) else: newname = name ret[newname] = arg ret.update(posarg_dic) # Let pos arg overwrite kw arg, for argscope to work return func(inputs, **ret) return decorated_func return decorator
python
def convert_to_tflayer_args(args_names, name_mapping): """ After applying this decorator: 1. data_format becomes tf.layers style 2. nl becomes activation 3. initializers are renamed 4. positional args are transformed to corresponding kwargs, according to args_names 5. kwargs are mapped to tf.layers names if needed, by name_mapping """ def decorator(func): @functools.wraps(func) def decorated_func(inputs, *args, **kwargs): kwargs = map_common_tfargs(kwargs) posarg_dic = {} assert len(args) <= len(args_names), \ "Please use kwargs instead of positional args to call this model, " \ "except for the following arguments: {}".format(', '.join(args_names)) for pos_arg, name in zip(args, args_names): posarg_dic[name] = pos_arg ret = {} for name, arg in six.iteritems(kwargs): newname = name_mapping.get(name, None) if newname is not None: assert newname not in kwargs, \ "Argument {} and {} conflicts!".format(name, newname) else: newname = name ret[newname] = arg ret.update(posarg_dic) # Let pos arg overwrite kw arg, for argscope to work return func(inputs, **ret) return decorated_func return decorator
[ "def", "convert_to_tflayer_args", "(", "args_names", ",", "name_mapping", ")", ":", "def", "decorator", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "decorated_func", "(", "inputs", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "map_common_tfargs", "(", "kwargs", ")", "posarg_dic", "=", "{", "}", "assert", "len", "(", "args", ")", "<=", "len", "(", "args_names", ")", ",", "\"Please use kwargs instead of positional args to call this model, \"", "\"except for the following arguments: {}\"", ".", "format", "(", "', '", ".", "join", "(", "args_names", ")", ")", "for", "pos_arg", ",", "name", "in", "zip", "(", "args", ",", "args_names", ")", ":", "posarg_dic", "[", "name", "]", "=", "pos_arg", "ret", "=", "{", "}", "for", "name", ",", "arg", "in", "six", ".", "iteritems", "(", "kwargs", ")", ":", "newname", "=", "name_mapping", ".", "get", "(", "name", ",", "None", ")", "if", "newname", "is", "not", "None", ":", "assert", "newname", "not", "in", "kwargs", ",", "\"Argument {} and {} conflicts!\"", ".", "format", "(", "name", ",", "newname", ")", "else", ":", "newname", "=", "name", "ret", "[", "newname", "]", "=", "arg", "ret", ".", "update", "(", "posarg_dic", ")", "# Let pos arg overwrite kw arg, for argscope to work", "return", "func", "(", "inputs", ",", "*", "*", "ret", ")", "return", "decorated_func", "return", "decorator" ]
After applying this decorator: 1. data_format becomes tf.layers style 2. nl becomes activation 3. initializers are renamed 4. positional args are transformed to corresponding kwargs, according to args_names 5. kwargs are mapped to tf.layers names if needed, by name_mapping
[ "After", "applying", "this", "decorator", ":", "1", ".", "data_format", "becomes", "tf", ".", "layers", "style", "2", ".", "nl", "becomes", "activation", "3", ".", "initializers", "are", "renamed", "4", ".", "positional", "args", "are", "transformed", "to", "corresponding", "kwargs", "according", "to", "args_names", "5", ".", "kwargs", "are", "mapped", "to", "tf", ".", "layers", "names", "if", "needed", "by", "name_mapping" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/tflayer.py#L33-L70
train
tensorpack/tensorpack
tensorpack/models/tflayer.py
rename_get_variable
def rename_get_variable(mapping): """ Args: mapping(dict): an old -> new mapping for variable basename. e.g. {'kernel': 'W'} Returns: A context where the variables are renamed. """ def custom_getter(getter, name, *args, **kwargs): splits = name.split('/') basename = splits[-1] if basename in mapping: basename = mapping[basename] splits[-1] = basename name = '/'.join(splits) return getter(name, *args, **kwargs) return custom_getter_scope(custom_getter)
python
def rename_get_variable(mapping): """ Args: mapping(dict): an old -> new mapping for variable basename. e.g. {'kernel': 'W'} Returns: A context where the variables are renamed. """ def custom_getter(getter, name, *args, **kwargs): splits = name.split('/') basename = splits[-1] if basename in mapping: basename = mapping[basename] splits[-1] = basename name = '/'.join(splits) return getter(name, *args, **kwargs) return custom_getter_scope(custom_getter)
[ "def", "rename_get_variable", "(", "mapping", ")", ":", "def", "custom_getter", "(", "getter", ",", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "splits", "=", "name", ".", "split", "(", "'/'", ")", "basename", "=", "splits", "[", "-", "1", "]", "if", "basename", "in", "mapping", ":", "basename", "=", "mapping", "[", "basename", "]", "splits", "[", "-", "1", "]", "=", "basename", "name", "=", "'/'", ".", "join", "(", "splits", ")", "return", "getter", "(", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "custom_getter_scope", "(", "custom_getter", ")" ]
Args: mapping(dict): an old -> new mapping for variable basename. e.g. {'kernel': 'W'} Returns: A context where the variables are renamed.
[ "Args", ":", "mapping", "(", "dict", ")", ":", "an", "old", "-", ">", "new", "mapping", "for", "variable", "basename", ".", "e", ".", "g", ".", "{", "kernel", ":", "W", "}" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/tflayer.py#L73-L89
train
tensorpack/tensorpack
tensorpack/models/regularize.py
regularize_cost
def regularize_cost(regex, func, name='regularize_cost'): """ Apply a regularizer on trainable variables matching the regex, and print the matched variables (only print once in multi-tower training). In replicated mode, it will only regularize variables within the current tower. If called under a TowerContext with `is_training==False`, this function returns a zero constant tensor. Args: regex (str): a regex to match variable names, e.g. "conv.*/W" func: the regularization function, which takes a tensor and returns a scalar tensor. E.g., ``tf.nn.l2_loss, tf.contrib.layers.l1_regularizer(0.001)``. Returns: tf.Tensor: a scalar, the total regularization cost. Example: .. code-block:: python cost = cost + regularize_cost("fc.*/W", l2_regularizer(1e-5)) """ assert len(regex) ctx = get_current_tower_context() if not ctx.is_training: # Currently cannot build the wd_cost correctly at inference, # because ths vs_name used in inference can be '', therefore the # variable filter will fail return tf.constant(0, dtype=tf.float32, name='empty_' + name) # If vars are shared, regularize all of them # If vars are replicated, only regularize those in the current tower if ctx.has_own_variables: params = ctx.get_collection_in_tower(tfv1.GraphKeys.TRAINABLE_VARIABLES) else: params = tfv1.trainable_variables() names = [] with tfv1.name_scope(name + '_internals'): costs = [] for p in params: para_name = p.op.name if re.search(regex, para_name): regloss = func(p) assert regloss.dtype.is_floating, regloss # Some variables may not be fp32, but it should # be fine to assume regularization in fp32 if regloss.dtype != tf.float32: regloss = tf.cast(regloss, tf.float32) costs.append(regloss) names.append(p.name) if not costs: return tf.constant(0, dtype=tf.float32, name='empty_' + name) # remove tower prefix from names, and print if len(ctx.vs_name): prefix = ctx.vs_name + '/' prefixlen = len(prefix) def f(name): if name.startswith(prefix): return name[prefixlen:] return name names = list(map(f, names)) logger.info("regularize_cost() found {} variables to regularize.".format(len(names))) _log_once("The following tensors will be regularized: {}".format(', '.join(names))) return tf.add_n(costs, name=name)
python
def regularize_cost(regex, func, name='regularize_cost'): """ Apply a regularizer on trainable variables matching the regex, and print the matched variables (only print once in multi-tower training). In replicated mode, it will only regularize variables within the current tower. If called under a TowerContext with `is_training==False`, this function returns a zero constant tensor. Args: regex (str): a regex to match variable names, e.g. "conv.*/W" func: the regularization function, which takes a tensor and returns a scalar tensor. E.g., ``tf.nn.l2_loss, tf.contrib.layers.l1_regularizer(0.001)``. Returns: tf.Tensor: a scalar, the total regularization cost. Example: .. code-block:: python cost = cost + regularize_cost("fc.*/W", l2_regularizer(1e-5)) """ assert len(regex) ctx = get_current_tower_context() if not ctx.is_training: # Currently cannot build the wd_cost correctly at inference, # because ths vs_name used in inference can be '', therefore the # variable filter will fail return tf.constant(0, dtype=tf.float32, name='empty_' + name) # If vars are shared, regularize all of them # If vars are replicated, only regularize those in the current tower if ctx.has_own_variables: params = ctx.get_collection_in_tower(tfv1.GraphKeys.TRAINABLE_VARIABLES) else: params = tfv1.trainable_variables() names = [] with tfv1.name_scope(name + '_internals'): costs = [] for p in params: para_name = p.op.name if re.search(regex, para_name): regloss = func(p) assert regloss.dtype.is_floating, regloss # Some variables may not be fp32, but it should # be fine to assume regularization in fp32 if regloss.dtype != tf.float32: regloss = tf.cast(regloss, tf.float32) costs.append(regloss) names.append(p.name) if not costs: return tf.constant(0, dtype=tf.float32, name='empty_' + name) # remove tower prefix from names, and print if len(ctx.vs_name): prefix = ctx.vs_name + '/' prefixlen = len(prefix) def f(name): if name.startswith(prefix): return name[prefixlen:] return name names = list(map(f, names)) logger.info("regularize_cost() found {} variables to regularize.".format(len(names))) _log_once("The following tensors will be regularized: {}".format(', '.join(names))) return tf.add_n(costs, name=name)
[ "def", "regularize_cost", "(", "regex", ",", "func", ",", "name", "=", "'regularize_cost'", ")", ":", "assert", "len", "(", "regex", ")", "ctx", "=", "get_current_tower_context", "(", ")", "if", "not", "ctx", ".", "is_training", ":", "# Currently cannot build the wd_cost correctly at inference,", "# because ths vs_name used in inference can be '', therefore the", "# variable filter will fail", "return", "tf", ".", "constant", "(", "0", ",", "dtype", "=", "tf", ".", "float32", ",", "name", "=", "'empty_'", "+", "name", ")", "# If vars are shared, regularize all of them", "# If vars are replicated, only regularize those in the current tower", "if", "ctx", ".", "has_own_variables", ":", "params", "=", "ctx", ".", "get_collection_in_tower", "(", "tfv1", ".", "GraphKeys", ".", "TRAINABLE_VARIABLES", ")", "else", ":", "params", "=", "tfv1", ".", "trainable_variables", "(", ")", "names", "=", "[", "]", "with", "tfv1", ".", "name_scope", "(", "name", "+", "'_internals'", ")", ":", "costs", "=", "[", "]", "for", "p", "in", "params", ":", "para_name", "=", "p", ".", "op", ".", "name", "if", "re", ".", "search", "(", "regex", ",", "para_name", ")", ":", "regloss", "=", "func", "(", "p", ")", "assert", "regloss", ".", "dtype", ".", "is_floating", ",", "regloss", "# Some variables may not be fp32, but it should", "# be fine to assume regularization in fp32", "if", "regloss", ".", "dtype", "!=", "tf", ".", "float32", ":", "regloss", "=", "tf", ".", "cast", "(", "regloss", ",", "tf", ".", "float32", ")", "costs", ".", "append", "(", "regloss", ")", "names", ".", "append", "(", "p", ".", "name", ")", "if", "not", "costs", ":", "return", "tf", ".", "constant", "(", "0", ",", "dtype", "=", "tf", ".", "float32", ",", "name", "=", "'empty_'", "+", "name", ")", "# remove tower prefix from names, and print", "if", "len", "(", "ctx", ".", "vs_name", ")", ":", "prefix", "=", "ctx", ".", "vs_name", "+", "'/'", "prefixlen", "=", "len", "(", "prefix", ")", "def", "f", "(", "name", ")", ":", "if", "name", ".", "startswith", "(", "prefix", ")", ":", "return", "name", "[", "prefixlen", ":", "]", "return", "name", "names", "=", "list", "(", "map", "(", "f", ",", "names", ")", ")", "logger", ".", "info", "(", "\"regularize_cost() found {} variables to regularize.\"", ".", "format", "(", "len", "(", "names", ")", ")", ")", "_log_once", "(", "\"The following tensors will be regularized: {}\"", ".", "format", "(", "', '", ".", "join", "(", "names", ")", ")", ")", "return", "tf", ".", "add_n", "(", "costs", ",", "name", "=", "name", ")" ]
Apply a regularizer on trainable variables matching the regex, and print the matched variables (only print once in multi-tower training). In replicated mode, it will only regularize variables within the current tower. If called under a TowerContext with `is_training==False`, this function returns a zero constant tensor. Args: regex (str): a regex to match variable names, e.g. "conv.*/W" func: the regularization function, which takes a tensor and returns a scalar tensor. E.g., ``tf.nn.l2_loss, tf.contrib.layers.l1_regularizer(0.001)``. Returns: tf.Tensor: a scalar, the total regularization cost. Example: .. code-block:: python cost = cost + regularize_cost("fc.*/W", l2_regularizer(1e-5))
[ "Apply", "a", "regularizer", "on", "trainable", "variables", "matching", "the", "regex", "and", "print", "the", "matched", "variables", "(", "only", "print", "once", "in", "multi", "-", "tower", "training", ")", ".", "In", "replicated", "mode", "it", "will", "only", "regularize", "variables", "within", "the", "current", "tower", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/regularize.py#L33-L100
train
tensorpack/tensorpack
tensorpack/models/regularize.py
regularize_cost_from_collection
def regularize_cost_from_collection(name='regularize_cost'): """ Get the cost from the regularizers in ``tf.GraphKeys.REGULARIZATION_LOSSES``. If in replicated mode, will only regularize variables created within the current tower. Args: name (str): the name of the returned tensor Returns: tf.Tensor: a scalar, the total regularization cost. """ ctx = get_current_tower_context() if not ctx.is_training: # TODO Currently cannot build the wd_cost correctly at inference, # because ths vs_name used in inference can be '', therefore the # variable filter will fail return tf.constant(0, dtype=tf.float32, name='empty_' + name) # NOTE: this collection doesn't always grow with towers. # It only grows with actual variable creation, but not get_variable call. if ctx.has_own_variables: # be careful of the first tower (name='') losses = ctx.get_collection_in_tower(tfv1.GraphKeys.REGULARIZATION_LOSSES) else: losses = tfv1.get_collection(tfv1.GraphKeys.REGULARIZATION_LOSSES) if len(losses) > 0: logger.info("regularize_cost_from_collection() found {} regularizers " "in REGULARIZATION_LOSSES collection.".format(len(losses))) def maploss(l): assert l.dtype.is_floating, l if l.dtype != tf.float32: l = tf.cast(l, tf.float32) return l losses = [maploss(l) for l in losses] reg_loss = tf.add_n(losses, name=name) return reg_loss else: return tf.constant(0, dtype=tf.float32, name='empty_' + name)
python
def regularize_cost_from_collection(name='regularize_cost'): """ Get the cost from the regularizers in ``tf.GraphKeys.REGULARIZATION_LOSSES``. If in replicated mode, will only regularize variables created within the current tower. Args: name (str): the name of the returned tensor Returns: tf.Tensor: a scalar, the total regularization cost. """ ctx = get_current_tower_context() if not ctx.is_training: # TODO Currently cannot build the wd_cost correctly at inference, # because ths vs_name used in inference can be '', therefore the # variable filter will fail return tf.constant(0, dtype=tf.float32, name='empty_' + name) # NOTE: this collection doesn't always grow with towers. # It only grows with actual variable creation, but not get_variable call. if ctx.has_own_variables: # be careful of the first tower (name='') losses = ctx.get_collection_in_tower(tfv1.GraphKeys.REGULARIZATION_LOSSES) else: losses = tfv1.get_collection(tfv1.GraphKeys.REGULARIZATION_LOSSES) if len(losses) > 0: logger.info("regularize_cost_from_collection() found {} regularizers " "in REGULARIZATION_LOSSES collection.".format(len(losses))) def maploss(l): assert l.dtype.is_floating, l if l.dtype != tf.float32: l = tf.cast(l, tf.float32) return l losses = [maploss(l) for l in losses] reg_loss = tf.add_n(losses, name=name) return reg_loss else: return tf.constant(0, dtype=tf.float32, name='empty_' + name)
[ "def", "regularize_cost_from_collection", "(", "name", "=", "'regularize_cost'", ")", ":", "ctx", "=", "get_current_tower_context", "(", ")", "if", "not", "ctx", ".", "is_training", ":", "# TODO Currently cannot build the wd_cost correctly at inference,", "# because ths vs_name used in inference can be '', therefore the", "# variable filter will fail", "return", "tf", ".", "constant", "(", "0", ",", "dtype", "=", "tf", ".", "float32", ",", "name", "=", "'empty_'", "+", "name", ")", "# NOTE: this collection doesn't always grow with towers.", "# It only grows with actual variable creation, but not get_variable call.", "if", "ctx", ".", "has_own_variables", ":", "# be careful of the first tower (name='')", "losses", "=", "ctx", ".", "get_collection_in_tower", "(", "tfv1", ".", "GraphKeys", ".", "REGULARIZATION_LOSSES", ")", "else", ":", "losses", "=", "tfv1", ".", "get_collection", "(", "tfv1", ".", "GraphKeys", ".", "REGULARIZATION_LOSSES", ")", "if", "len", "(", "losses", ")", ">", "0", ":", "logger", ".", "info", "(", "\"regularize_cost_from_collection() found {} regularizers \"", "\"in REGULARIZATION_LOSSES collection.\"", ".", "format", "(", "len", "(", "losses", ")", ")", ")", "def", "maploss", "(", "l", ")", ":", "assert", "l", ".", "dtype", ".", "is_floating", ",", "l", "if", "l", ".", "dtype", "!=", "tf", ".", "float32", ":", "l", "=", "tf", ".", "cast", "(", "l", ",", "tf", ".", "float32", ")", "return", "l", "losses", "=", "[", "maploss", "(", "l", ")", "for", "l", "in", "losses", "]", "reg_loss", "=", "tf", ".", "add_n", "(", "losses", ",", "name", "=", "name", ")", "return", "reg_loss", "else", ":", "return", "tf", ".", "constant", "(", "0", ",", "dtype", "=", "tf", ".", "float32", ",", "name", "=", "'empty_'", "+", "name", ")" ]
Get the cost from the regularizers in ``tf.GraphKeys.REGULARIZATION_LOSSES``. If in replicated mode, will only regularize variables created within the current tower. Args: name (str): the name of the returned tensor Returns: tf.Tensor: a scalar, the total regularization cost.
[ "Get", "the", "cost", "from", "the", "regularizers", "in", "tf", ".", "GraphKeys", ".", "REGULARIZATION_LOSSES", ".", "If", "in", "replicated", "mode", "will", "only", "regularize", "variables", "created", "within", "the", "current", "tower", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/regularize.py#L103-L141
train
tensorpack/tensorpack
tensorpack/models/regularize.py
Dropout
def Dropout(x, *args, **kwargs): """ Same as `tf.layers.dropout`. However, for historical reasons, the first positional argument is interpreted as keep_prob rather than drop_prob. Explicitly use `rate=` keyword arguments to ensure things are consistent. """ if 'is_training' in kwargs: kwargs['training'] = kwargs.pop('is_training') if len(args) > 0: if args[0] != 0.5: logger.warn( "The first positional argument to tensorpack.Dropout is the probability to keep, rather than to drop. " "This is different from the rate argument in tf.layers.Dropout due to historical reasons. " "To mimic tf.layers.Dropout, explicitly use keyword argument 'rate' instead") rate = 1 - args[0] elif 'keep_prob' in kwargs: assert 'rate' not in kwargs, "Cannot set both keep_prob and rate!" rate = 1 - kwargs.pop('keep_prob') elif 'rate' in kwargs: rate = kwargs.pop('rate') else: rate = 0.5 if kwargs.get('training', None) is None: kwargs['training'] = get_current_tower_context().is_training if get_tf_version_tuple() <= (1, 12): return tf.layers.dropout(x, rate=rate, **kwargs) else: return tf.nn.dropout(x, rate=rate if kwargs['training'] else 0.)
python
def Dropout(x, *args, **kwargs): """ Same as `tf.layers.dropout`. However, for historical reasons, the first positional argument is interpreted as keep_prob rather than drop_prob. Explicitly use `rate=` keyword arguments to ensure things are consistent. """ if 'is_training' in kwargs: kwargs['training'] = kwargs.pop('is_training') if len(args) > 0: if args[0] != 0.5: logger.warn( "The first positional argument to tensorpack.Dropout is the probability to keep, rather than to drop. " "This is different from the rate argument in tf.layers.Dropout due to historical reasons. " "To mimic tf.layers.Dropout, explicitly use keyword argument 'rate' instead") rate = 1 - args[0] elif 'keep_prob' in kwargs: assert 'rate' not in kwargs, "Cannot set both keep_prob and rate!" rate = 1 - kwargs.pop('keep_prob') elif 'rate' in kwargs: rate = kwargs.pop('rate') else: rate = 0.5 if kwargs.get('training', None) is None: kwargs['training'] = get_current_tower_context().is_training if get_tf_version_tuple() <= (1, 12): return tf.layers.dropout(x, rate=rate, **kwargs) else: return tf.nn.dropout(x, rate=rate if kwargs['training'] else 0.)
[ "def", "Dropout", "(", "x", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "'is_training'", "in", "kwargs", ":", "kwargs", "[", "'training'", "]", "=", "kwargs", ".", "pop", "(", "'is_training'", ")", "if", "len", "(", "args", ")", ">", "0", ":", "if", "args", "[", "0", "]", "!=", "0.5", ":", "logger", ".", "warn", "(", "\"The first positional argument to tensorpack.Dropout is the probability to keep, rather than to drop. \"", "\"This is different from the rate argument in tf.layers.Dropout due to historical reasons. \"", "\"To mimic tf.layers.Dropout, explicitly use keyword argument 'rate' instead\"", ")", "rate", "=", "1", "-", "args", "[", "0", "]", "elif", "'keep_prob'", "in", "kwargs", ":", "assert", "'rate'", "not", "in", "kwargs", ",", "\"Cannot set both keep_prob and rate!\"", "rate", "=", "1", "-", "kwargs", ".", "pop", "(", "'keep_prob'", ")", "elif", "'rate'", "in", "kwargs", ":", "rate", "=", "kwargs", ".", "pop", "(", "'rate'", ")", "else", ":", "rate", "=", "0.5", "if", "kwargs", ".", "get", "(", "'training'", ",", "None", ")", "is", "None", ":", "kwargs", "[", "'training'", "]", "=", "get_current_tower_context", "(", ")", ".", "is_training", "if", "get_tf_version_tuple", "(", ")", "<=", "(", "1", ",", "12", ")", ":", "return", "tf", ".", "layers", ".", "dropout", "(", "x", ",", "rate", "=", "rate", ",", "*", "*", "kwargs", ")", "else", ":", "return", "tf", ".", "nn", ".", "dropout", "(", "x", ",", "rate", "=", "rate", "if", "kwargs", "[", "'training'", "]", "else", "0.", ")" ]
Same as `tf.layers.dropout`. However, for historical reasons, the first positional argument is interpreted as keep_prob rather than drop_prob. Explicitly use `rate=` keyword arguments to ensure things are consistent.
[ "Same", "as", "tf", ".", "layers", ".", "dropout", ".", "However", "for", "historical", "reasons", "the", "first", "positional", "argument", "is", "interpreted", "as", "keep_prob", "rather", "than", "drop_prob", ".", "Explicitly", "use", "rate", "=", "keyword", "arguments", "to", "ensure", "things", "are", "consistent", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/regularize.py#L145-L175
train
tensorpack/tensorpack
tensorpack/dataflow/imgaug/paste.py
BackgroundFiller.fill
def fill(self, background_shape, img): """ Return a proper background image of background_shape, given img. Args: background_shape (tuple): a shape (h, w) img: an image Returns: a background image """ background_shape = tuple(background_shape) return self._fill(background_shape, img)
python
def fill(self, background_shape, img): """ Return a proper background image of background_shape, given img. Args: background_shape (tuple): a shape (h, w) img: an image Returns: a background image """ background_shape = tuple(background_shape) return self._fill(background_shape, img)
[ "def", "fill", "(", "self", ",", "background_shape", ",", "img", ")", ":", "background_shape", "=", "tuple", "(", "background_shape", ")", "return", "self", ".", "_fill", "(", "background_shape", ",", "img", ")" ]
Return a proper background image of background_shape, given img. Args: background_shape (tuple): a shape (h, w) img: an image Returns: a background image
[ "Return", "a", "proper", "background", "image", "of", "background_shape", "given", "img", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/imgaug/paste.py#L17-L28
train
tensorpack/tensorpack
tensorpack/models/linearwrap.py
LinearWrap.apply
def apply(self, func, *args, **kwargs): """ Apply a function on the wrapped tensor. Returns: LinearWrap: ``LinearWrap(func(self.tensor(), *args, **kwargs))``. """ ret = func(self._t, *args, **kwargs) return LinearWrap(ret)
python
def apply(self, func, *args, **kwargs): """ Apply a function on the wrapped tensor. Returns: LinearWrap: ``LinearWrap(func(self.tensor(), *args, **kwargs))``. """ ret = func(self._t, *args, **kwargs) return LinearWrap(ret)
[ "def", "apply", "(", "self", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "func", "(", "self", ".", "_t", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "LinearWrap", "(", "ret", ")" ]
Apply a function on the wrapped tensor. Returns: LinearWrap: ``LinearWrap(func(self.tensor(), *args, **kwargs))``.
[ "Apply", "a", "function", "on", "the", "wrapped", "tensor", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/linearwrap.py#L68-L76
train
tensorpack/tensorpack
tensorpack/models/linearwrap.py
LinearWrap.apply2
def apply2(self, func, *args, **kwargs): """ Apply a function on the wrapped tensor. The tensor will be the second argument of func. This is because many symbolic functions (such as tensorpack's layers) takes 'scope' as the first argument. Returns: LinearWrap: ``LinearWrap(func(args[0], self.tensor(), *args[1:], **kwargs))``. """ ret = func(args[0], self._t, *(args[1:]), **kwargs) return LinearWrap(ret)
python
def apply2(self, func, *args, **kwargs): """ Apply a function on the wrapped tensor. The tensor will be the second argument of func. This is because many symbolic functions (such as tensorpack's layers) takes 'scope' as the first argument. Returns: LinearWrap: ``LinearWrap(func(args[0], self.tensor(), *args[1:], **kwargs))``. """ ret = func(args[0], self._t, *(args[1:]), **kwargs) return LinearWrap(ret)
[ "def", "apply2", "(", "self", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "func", "(", "args", "[", "0", "]", ",", "self", ".", "_t", ",", "*", "(", "args", "[", "1", ":", "]", ")", ",", "*", "*", "kwargs", ")", "return", "LinearWrap", "(", "ret", ")" ]
Apply a function on the wrapped tensor. The tensor will be the second argument of func. This is because many symbolic functions (such as tensorpack's layers) takes 'scope' as the first argument. Returns: LinearWrap: ``LinearWrap(func(args[0], self.tensor(), *args[1:], **kwargs))``.
[ "Apply", "a", "function", "on", "the", "wrapped", "tensor", ".", "The", "tensor", "will", "be", "the", "second", "argument", "of", "func", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/linearwrap.py#L78-L90
train
tensorpack/tensorpack
examples/Saliency/saliency-maps.py
guided_relu
def guided_relu(): """ Returns: A context where the gradient of :meth:`tf.nn.relu` is replaced by guided back-propagation, as described in the paper: `Striving for Simplicity: The All Convolutional Net <https://arxiv.org/abs/1412.6806>`_ """ from tensorflow.python.ops import gen_nn_ops # noqa @tf.RegisterGradient("GuidedReLU") def GuidedReluGrad(op, grad): return tf.where(0. < grad, gen_nn_ops._relu_grad(grad, op.outputs[0]), tf.zeros(grad.get_shape())) g = tf.get_default_graph() with g.gradient_override_map({'Relu': 'GuidedReLU'}): yield
python
def guided_relu(): """ Returns: A context where the gradient of :meth:`tf.nn.relu` is replaced by guided back-propagation, as described in the paper: `Striving for Simplicity: The All Convolutional Net <https://arxiv.org/abs/1412.6806>`_ """ from tensorflow.python.ops import gen_nn_ops # noqa @tf.RegisterGradient("GuidedReLU") def GuidedReluGrad(op, grad): return tf.where(0. < grad, gen_nn_ops._relu_grad(grad, op.outputs[0]), tf.zeros(grad.get_shape())) g = tf.get_default_graph() with g.gradient_override_map({'Relu': 'GuidedReLU'}): yield
[ "def", "guided_relu", "(", ")", ":", "from", "tensorflow", ".", "python", ".", "ops", "import", "gen_nn_ops", "# noqa", "@", "tf", ".", "RegisterGradient", "(", "\"GuidedReLU\"", ")", "def", "GuidedReluGrad", "(", "op", ",", "grad", ")", ":", "return", "tf", ".", "where", "(", "0.", "<", "grad", ",", "gen_nn_ops", ".", "_relu_grad", "(", "grad", ",", "op", ".", "outputs", "[", "0", "]", ")", ",", "tf", ".", "zeros", "(", "grad", ".", "get_shape", "(", ")", ")", ")", "g", "=", "tf", ".", "get_default_graph", "(", ")", "with", "g", ".", "gradient_override_map", "(", "{", "'Relu'", ":", "'GuidedReLU'", "}", ")", ":", "yield" ]
Returns: A context where the gradient of :meth:`tf.nn.relu` is replaced by guided back-propagation, as described in the paper: `Striving for Simplicity: The All Convolutional Net <https://arxiv.org/abs/1412.6806>`_
[ "Returns", ":", "A", "context", "where", "the", "gradient", "of", ":", "meth", ":", "tf", ".", "nn", ".", "relu", "is", "replaced", "by", "guided", "back", "-", "propagation", "as", "described", "in", "the", "paper", ":", "Striving", "for", "Simplicity", ":", "The", "All", "Convolutional", "Net", "<https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1412", ".", "6806", ">", "_" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/Saliency/saliency-maps.py#L19-L37
train
tensorpack/tensorpack
examples/Saliency/saliency-maps.py
saliency_map
def saliency_map(output, input, name="saliency_map"): """ Produce a saliency map as described in the paper: `Deep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Maps <https://arxiv.org/abs/1312.6034>`_. The saliency map is the gradient of the max element in output w.r.t input. Returns: tf.Tensor: the saliency map. Has the same shape as input. """ max_outp = tf.reduce_max(output, 1) saliency_op = tf.gradients(max_outp, input)[:][0] return tf.identity(saliency_op, name=name)
python
def saliency_map(output, input, name="saliency_map"): """ Produce a saliency map as described in the paper: `Deep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Maps <https://arxiv.org/abs/1312.6034>`_. The saliency map is the gradient of the max element in output w.r.t input. Returns: tf.Tensor: the saliency map. Has the same shape as input. """ max_outp = tf.reduce_max(output, 1) saliency_op = tf.gradients(max_outp, input)[:][0] return tf.identity(saliency_op, name=name)
[ "def", "saliency_map", "(", "output", ",", "input", ",", "name", "=", "\"saliency_map\"", ")", ":", "max_outp", "=", "tf", ".", "reduce_max", "(", "output", ",", "1", ")", "saliency_op", "=", "tf", ".", "gradients", "(", "max_outp", ",", "input", ")", "[", ":", "]", "[", "0", "]", "return", "tf", ".", "identity", "(", "saliency_op", ",", "name", "=", "name", ")" ]
Produce a saliency map as described in the paper: `Deep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Maps <https://arxiv.org/abs/1312.6034>`_. The saliency map is the gradient of the max element in output w.r.t input. Returns: tf.Tensor: the saliency map. Has the same shape as input.
[ "Produce", "a", "saliency", "map", "as", "described", "in", "the", "paper", ":", "Deep", "Inside", "Convolutional", "Networks", ":", "Visualising", "Image", "Classification", "Models", "and", "Saliency", "Maps", "<https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1312", ".", "6034", ">", "_", ".", "The", "saliency", "map", "is", "the", "gradient", "of", "the", "max", "element", "in", "output", "w", ".", "r", ".", "t", "input", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/Saliency/saliency-maps.py#L40-L52
train
tensorpack/tensorpack
tensorpack/models/conv2d.py
Conv2D
def Conv2D( inputs, filters, kernel_size, strides=(1, 1), padding='same', data_format='channels_last', dilation_rate=(1, 1), activation=None, use_bias=True, kernel_initializer=None, bias_initializer=tf.zeros_initializer(), kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, split=1): """ A wrapper around `tf.layers.Conv2D`. Some differences to maintain backward-compatibility: 1. Default kernel initializer is variance_scaling_initializer(2.0). 2. Default padding is 'same'. 3. Support 'split' argument to do group conv. Note that this is not efficient. Variable Names: * ``W``: weights * ``b``: bias """ if kernel_initializer is None: if get_tf_version_tuple() <= (1, 12): kernel_initializer = tf.contrib.layers.variance_scaling_initializer(2.0) else: kernel_initializer = tf.keras.initializers.VarianceScaling(2.0, distribution='untruncated_normal') dilation_rate = shape2d(dilation_rate) if split == 1 and dilation_rate == [1, 1]: # tf.layers.Conv2D has bugs with dilations (https://github.com/tensorflow/tensorflow/issues/26797) with rename_get_variable({'kernel': 'W', 'bias': 'b'}): layer = tf.layers.Conv2D( filters, kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, activation=activation, use_bias=use_bias, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, kernel_regularizer=kernel_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, _reuse=tf.get_variable_scope().reuse) ret = layer.apply(inputs, scope=tf.get_variable_scope()) ret = tf.identity(ret, name='output') ret.variables = VariableHolder(W=layer.kernel) if use_bias: ret.variables.b = layer.bias else: # group conv implementation data_format = get_data_format(data_format, keras_mode=False) in_shape = inputs.get_shape().as_list() channel_axis = 3 if data_format == 'NHWC' else 1 in_channel = in_shape[channel_axis] assert in_channel is not None, "[Conv2D] Input cannot have unknown channel!" assert in_channel % split == 0 assert kernel_regularizer is None and bias_regularizer is None and activity_regularizer is None, \ "Not supported by group conv or dilated conv!" out_channel = filters assert out_channel % split == 0 assert dilation_rate == [1, 1] or get_tf_version_tuple() >= (1, 5), 'TF>=1.5 required for dilated conv.' kernel_shape = shape2d(kernel_size) filter_shape = kernel_shape + [in_channel / split, out_channel] stride = shape4d(strides, data_format=data_format) kwargs = dict(data_format=data_format) if get_tf_version_tuple() >= (1, 5): kwargs['dilations'] = shape4d(dilation_rate, data_format=data_format) W = tf.get_variable( 'W', filter_shape, initializer=kernel_initializer) if use_bias: b = tf.get_variable('b', [out_channel], initializer=bias_initializer) if split == 1: conv = tf.nn.conv2d(inputs, W, stride, padding.upper(), **kwargs) else: conv = None if get_tf_version_tuple() >= (1, 13): try: conv = tf.nn.conv2d(inputs, W, stride, padding.upper(), **kwargs) except ValueError: log_once("CUDNN group convolution support is only available with " "https://github.com/tensorflow/tensorflow/pull/25818 . " "Will fall back to a loop-based slow implementation instead!", 'warn') if conv is None: inputs = tf.split(inputs, split, channel_axis) kernels = tf.split(W, split, 3) outputs = [tf.nn.conv2d(i, k, stride, padding.upper(), **kwargs) for i, k in zip(inputs, kernels)] conv = tf.concat(outputs, channel_axis) ret = tf.nn.bias_add(conv, b, data_format=data_format) if use_bias else conv if activation is not None: ret = activation(ret) ret = tf.identity(ret, name='output') ret.variables = VariableHolder(W=W) if use_bias: ret.variables.b = b return ret
python
def Conv2D( inputs, filters, kernel_size, strides=(1, 1), padding='same', data_format='channels_last', dilation_rate=(1, 1), activation=None, use_bias=True, kernel_initializer=None, bias_initializer=tf.zeros_initializer(), kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, split=1): """ A wrapper around `tf.layers.Conv2D`. Some differences to maintain backward-compatibility: 1. Default kernel initializer is variance_scaling_initializer(2.0). 2. Default padding is 'same'. 3. Support 'split' argument to do group conv. Note that this is not efficient. Variable Names: * ``W``: weights * ``b``: bias """ if kernel_initializer is None: if get_tf_version_tuple() <= (1, 12): kernel_initializer = tf.contrib.layers.variance_scaling_initializer(2.0) else: kernel_initializer = tf.keras.initializers.VarianceScaling(2.0, distribution='untruncated_normal') dilation_rate = shape2d(dilation_rate) if split == 1 and dilation_rate == [1, 1]: # tf.layers.Conv2D has bugs with dilations (https://github.com/tensorflow/tensorflow/issues/26797) with rename_get_variable({'kernel': 'W', 'bias': 'b'}): layer = tf.layers.Conv2D( filters, kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, activation=activation, use_bias=use_bias, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, kernel_regularizer=kernel_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, _reuse=tf.get_variable_scope().reuse) ret = layer.apply(inputs, scope=tf.get_variable_scope()) ret = tf.identity(ret, name='output') ret.variables = VariableHolder(W=layer.kernel) if use_bias: ret.variables.b = layer.bias else: # group conv implementation data_format = get_data_format(data_format, keras_mode=False) in_shape = inputs.get_shape().as_list() channel_axis = 3 if data_format == 'NHWC' else 1 in_channel = in_shape[channel_axis] assert in_channel is not None, "[Conv2D] Input cannot have unknown channel!" assert in_channel % split == 0 assert kernel_regularizer is None and bias_regularizer is None and activity_regularizer is None, \ "Not supported by group conv or dilated conv!" out_channel = filters assert out_channel % split == 0 assert dilation_rate == [1, 1] or get_tf_version_tuple() >= (1, 5), 'TF>=1.5 required for dilated conv.' kernel_shape = shape2d(kernel_size) filter_shape = kernel_shape + [in_channel / split, out_channel] stride = shape4d(strides, data_format=data_format) kwargs = dict(data_format=data_format) if get_tf_version_tuple() >= (1, 5): kwargs['dilations'] = shape4d(dilation_rate, data_format=data_format) W = tf.get_variable( 'W', filter_shape, initializer=kernel_initializer) if use_bias: b = tf.get_variable('b', [out_channel], initializer=bias_initializer) if split == 1: conv = tf.nn.conv2d(inputs, W, stride, padding.upper(), **kwargs) else: conv = None if get_tf_version_tuple() >= (1, 13): try: conv = tf.nn.conv2d(inputs, W, stride, padding.upper(), **kwargs) except ValueError: log_once("CUDNN group convolution support is only available with " "https://github.com/tensorflow/tensorflow/pull/25818 . " "Will fall back to a loop-based slow implementation instead!", 'warn') if conv is None: inputs = tf.split(inputs, split, channel_axis) kernels = tf.split(W, split, 3) outputs = [tf.nn.conv2d(i, k, stride, padding.upper(), **kwargs) for i, k in zip(inputs, kernels)] conv = tf.concat(outputs, channel_axis) ret = tf.nn.bias_add(conv, b, data_format=data_format) if use_bias else conv if activation is not None: ret = activation(ret) ret = tf.identity(ret, name='output') ret.variables = VariableHolder(W=W) if use_bias: ret.variables.b = b return ret
[ "def", "Conv2D", "(", "inputs", ",", "filters", ",", "kernel_size", ",", "strides", "=", "(", "1", ",", "1", ")", ",", "padding", "=", "'same'", ",", "data_format", "=", "'channels_last'", ",", "dilation_rate", "=", "(", "1", ",", "1", ")", ",", "activation", "=", "None", ",", "use_bias", "=", "True", ",", "kernel_initializer", "=", "None", ",", "bias_initializer", "=", "tf", ".", "zeros_initializer", "(", ")", ",", "kernel_regularizer", "=", "None", ",", "bias_regularizer", "=", "None", ",", "activity_regularizer", "=", "None", ",", "split", "=", "1", ")", ":", "if", "kernel_initializer", "is", "None", ":", "if", "get_tf_version_tuple", "(", ")", "<=", "(", "1", ",", "12", ")", ":", "kernel_initializer", "=", "tf", ".", "contrib", ".", "layers", ".", "variance_scaling_initializer", "(", "2.0", ")", "else", ":", "kernel_initializer", "=", "tf", ".", "keras", ".", "initializers", ".", "VarianceScaling", "(", "2.0", ",", "distribution", "=", "'untruncated_normal'", ")", "dilation_rate", "=", "shape2d", "(", "dilation_rate", ")", "if", "split", "==", "1", "and", "dilation_rate", "==", "[", "1", ",", "1", "]", ":", "# tf.layers.Conv2D has bugs with dilations (https://github.com/tensorflow/tensorflow/issues/26797)", "with", "rename_get_variable", "(", "{", "'kernel'", ":", "'W'", ",", "'bias'", ":", "'b'", "}", ")", ":", "layer", "=", "tf", ".", "layers", ".", "Conv2D", "(", "filters", ",", "kernel_size", ",", "strides", "=", "strides", ",", "padding", "=", "padding", ",", "data_format", "=", "data_format", ",", "dilation_rate", "=", "dilation_rate", ",", "activation", "=", "activation", ",", "use_bias", "=", "use_bias", ",", "kernel_initializer", "=", "kernel_initializer", ",", "bias_initializer", "=", "bias_initializer", ",", "kernel_regularizer", "=", "kernel_regularizer", ",", "bias_regularizer", "=", "bias_regularizer", ",", "activity_regularizer", "=", "activity_regularizer", ",", "_reuse", "=", "tf", ".", "get_variable_scope", "(", ")", ".", "reuse", ")", "ret", "=", "layer", ".", "apply", "(", "inputs", ",", "scope", "=", "tf", ".", "get_variable_scope", "(", ")", ")", "ret", "=", "tf", ".", "identity", "(", "ret", ",", "name", "=", "'output'", ")", "ret", ".", "variables", "=", "VariableHolder", "(", "W", "=", "layer", ".", "kernel", ")", "if", "use_bias", ":", "ret", ".", "variables", ".", "b", "=", "layer", ".", "bias", "else", ":", "# group conv implementation", "data_format", "=", "get_data_format", "(", "data_format", ",", "keras_mode", "=", "False", ")", "in_shape", "=", "inputs", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "channel_axis", "=", "3", "if", "data_format", "==", "'NHWC'", "else", "1", "in_channel", "=", "in_shape", "[", "channel_axis", "]", "assert", "in_channel", "is", "not", "None", ",", "\"[Conv2D] Input cannot have unknown channel!\"", "assert", "in_channel", "%", "split", "==", "0", "assert", "kernel_regularizer", "is", "None", "and", "bias_regularizer", "is", "None", "and", "activity_regularizer", "is", "None", ",", "\"Not supported by group conv or dilated conv!\"", "out_channel", "=", "filters", "assert", "out_channel", "%", "split", "==", "0", "assert", "dilation_rate", "==", "[", "1", ",", "1", "]", "or", "get_tf_version_tuple", "(", ")", ">=", "(", "1", ",", "5", ")", ",", "'TF>=1.5 required for dilated conv.'", "kernel_shape", "=", "shape2d", "(", "kernel_size", ")", "filter_shape", "=", "kernel_shape", "+", "[", "in_channel", "/", "split", ",", "out_channel", "]", "stride", "=", "shape4d", "(", "strides", ",", "data_format", "=", "data_format", ")", "kwargs", "=", "dict", "(", "data_format", "=", "data_format", ")", "if", "get_tf_version_tuple", "(", ")", ">=", "(", "1", ",", "5", ")", ":", "kwargs", "[", "'dilations'", "]", "=", "shape4d", "(", "dilation_rate", ",", "data_format", "=", "data_format", ")", "W", "=", "tf", ".", "get_variable", "(", "'W'", ",", "filter_shape", ",", "initializer", "=", "kernel_initializer", ")", "if", "use_bias", ":", "b", "=", "tf", ".", "get_variable", "(", "'b'", ",", "[", "out_channel", "]", ",", "initializer", "=", "bias_initializer", ")", "if", "split", "==", "1", ":", "conv", "=", "tf", ".", "nn", ".", "conv2d", "(", "inputs", ",", "W", ",", "stride", ",", "padding", ".", "upper", "(", ")", ",", "*", "*", "kwargs", ")", "else", ":", "conv", "=", "None", "if", "get_tf_version_tuple", "(", ")", ">=", "(", "1", ",", "13", ")", ":", "try", ":", "conv", "=", "tf", ".", "nn", ".", "conv2d", "(", "inputs", ",", "W", ",", "stride", ",", "padding", ".", "upper", "(", ")", ",", "*", "*", "kwargs", ")", "except", "ValueError", ":", "log_once", "(", "\"CUDNN group convolution support is only available with \"", "\"https://github.com/tensorflow/tensorflow/pull/25818 . \"", "\"Will fall back to a loop-based slow implementation instead!\"", ",", "'warn'", ")", "if", "conv", "is", "None", ":", "inputs", "=", "tf", ".", "split", "(", "inputs", ",", "split", ",", "channel_axis", ")", "kernels", "=", "tf", ".", "split", "(", "W", ",", "split", ",", "3", ")", "outputs", "=", "[", "tf", ".", "nn", ".", "conv2d", "(", "i", ",", "k", ",", "stride", ",", "padding", ".", "upper", "(", ")", ",", "*", "*", "kwargs", ")", "for", "i", ",", "k", "in", "zip", "(", "inputs", ",", "kernels", ")", "]", "conv", "=", "tf", ".", "concat", "(", "outputs", ",", "channel_axis", ")", "ret", "=", "tf", ".", "nn", ".", "bias_add", "(", "conv", ",", "b", ",", "data_format", "=", "data_format", ")", "if", "use_bias", "else", "conv", "if", "activation", "is", "not", "None", ":", "ret", "=", "activation", "(", "ret", ")", "ret", "=", "tf", ".", "identity", "(", "ret", ",", "name", "=", "'output'", ")", "ret", ".", "variables", "=", "VariableHolder", "(", "W", "=", "W", ")", "if", "use_bias", ":", "ret", ".", "variables", ".", "b", "=", "b", "return", "ret" ]
A wrapper around `tf.layers.Conv2D`. Some differences to maintain backward-compatibility: 1. Default kernel initializer is variance_scaling_initializer(2.0). 2. Default padding is 'same'. 3. Support 'split' argument to do group conv. Note that this is not efficient. Variable Names: * ``W``: weights * ``b``: bias
[ "A", "wrapper", "around", "tf", ".", "layers", ".", "Conv2D", ".", "Some", "differences", "to", "maintain", "backward", "-", "compatibility", ":" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/conv2d.py#L23-L140
train
tensorpack/tensorpack
tensorpack/models/conv2d.py
Conv2DTranspose
def Conv2DTranspose( inputs, filters, kernel_size, strides=(1, 1), padding='same', data_format='channels_last', activation=None, use_bias=True, kernel_initializer=None, bias_initializer=tf.zeros_initializer(), kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None): """ A wrapper around `tf.layers.Conv2DTranspose`. Some differences to maintain backward-compatibility: 1. Default kernel initializer is variance_scaling_initializer(2.0). 2. Default padding is 'same' Variable Names: * ``W``: weights * ``b``: bias """ if kernel_initializer is None: if get_tf_version_tuple() <= (1, 12): kernel_initializer = tf.contrib.layers.variance_scaling_initializer(2.0) else: kernel_initializer = tf.keras.initializers.VarianceScaling(2.0, distribution='untruncated_normal') if get_tf_version_tuple() <= (1, 12): with rename_get_variable({'kernel': 'W', 'bias': 'b'}): layer = tf.layers.Conv2DTranspose( filters, kernel_size, strides=strides, padding=padding, data_format=data_format, activation=activation, use_bias=use_bias, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, kernel_regularizer=kernel_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, _reuse=tf.get_variable_scope().reuse) ret = layer.apply(inputs, scope=tf.get_variable_scope()) ret = tf.identity(ret, name='output') ret.variables = VariableHolder(W=layer.kernel) if use_bias: ret.variables.b = layer.bias else: # Our own implementation, to avoid Keras bugs. https://github.com/tensorflow/tensorflow/issues/25946 assert kernel_regularizer is None and bias_regularizer is None and activity_regularizer is None, \ "Unsupported arguments due to Keras bug in TensorFlow 1.13" data_format = get_data_format(data_format, keras_mode=False) shape_dyn = tf.shape(inputs) strides2d = shape2d(strides) channels_in = inputs.shape[1 if data_format == 'NCHW' else 3] if data_format == 'NCHW': channels_in = inputs.shape[1] out_shape_dyn = tf.stack( [shape_dyn[0], filters, shape_dyn[2] * strides2d[0], shape_dyn[3] * strides2d[1]]) out_shape3_sta = [filters, None if inputs.shape[2] is None else inputs.shape[2] * strides2d[0], None if inputs.shape[3] is None else inputs.shape[3] * strides2d[1]] else: channels_in = inputs.shape[-1] out_shape_dyn = tf.stack( [shape_dyn[0], shape_dyn[1] * strides2d[0], shape_dyn[2] * strides2d[1], filters]) out_shape3_sta = [None if inputs.shape[1] is None else inputs.shape[1] * strides2d[0], None if inputs.shape[2] is None else inputs.shape[2] * strides2d[1], filters] kernel_shape = shape2d(kernel_size) W = tf.get_variable('W', kernel_shape + [filters, channels_in], initializer=kernel_initializer) if use_bias: b = tf.get_variable('b', [filters], initializer=bias_initializer) conv = tf.nn.conv2d_transpose( inputs, W, out_shape_dyn, shape4d(strides, data_format=data_format), padding=padding.upper(), data_format=data_format) conv.set_shape(tf.TensorShape([None] + out_shape3_sta)) ret = tf.nn.bias_add(conv, b, data_format=data_format) if use_bias else conv if activation is not None: ret = activation(ret) ret = tf.identity(ret, name='output') ret.variables = VariableHolder(W=W) if use_bias: ret.variables.b = b return ret
python
def Conv2DTranspose( inputs, filters, kernel_size, strides=(1, 1), padding='same', data_format='channels_last', activation=None, use_bias=True, kernel_initializer=None, bias_initializer=tf.zeros_initializer(), kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None): """ A wrapper around `tf.layers.Conv2DTranspose`. Some differences to maintain backward-compatibility: 1. Default kernel initializer is variance_scaling_initializer(2.0). 2. Default padding is 'same' Variable Names: * ``W``: weights * ``b``: bias """ if kernel_initializer is None: if get_tf_version_tuple() <= (1, 12): kernel_initializer = tf.contrib.layers.variance_scaling_initializer(2.0) else: kernel_initializer = tf.keras.initializers.VarianceScaling(2.0, distribution='untruncated_normal') if get_tf_version_tuple() <= (1, 12): with rename_get_variable({'kernel': 'W', 'bias': 'b'}): layer = tf.layers.Conv2DTranspose( filters, kernel_size, strides=strides, padding=padding, data_format=data_format, activation=activation, use_bias=use_bias, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, kernel_regularizer=kernel_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, _reuse=tf.get_variable_scope().reuse) ret = layer.apply(inputs, scope=tf.get_variable_scope()) ret = tf.identity(ret, name='output') ret.variables = VariableHolder(W=layer.kernel) if use_bias: ret.variables.b = layer.bias else: # Our own implementation, to avoid Keras bugs. https://github.com/tensorflow/tensorflow/issues/25946 assert kernel_regularizer is None and bias_regularizer is None and activity_regularizer is None, \ "Unsupported arguments due to Keras bug in TensorFlow 1.13" data_format = get_data_format(data_format, keras_mode=False) shape_dyn = tf.shape(inputs) strides2d = shape2d(strides) channels_in = inputs.shape[1 if data_format == 'NCHW' else 3] if data_format == 'NCHW': channels_in = inputs.shape[1] out_shape_dyn = tf.stack( [shape_dyn[0], filters, shape_dyn[2] * strides2d[0], shape_dyn[3] * strides2d[1]]) out_shape3_sta = [filters, None if inputs.shape[2] is None else inputs.shape[2] * strides2d[0], None if inputs.shape[3] is None else inputs.shape[3] * strides2d[1]] else: channels_in = inputs.shape[-1] out_shape_dyn = tf.stack( [shape_dyn[0], shape_dyn[1] * strides2d[0], shape_dyn[2] * strides2d[1], filters]) out_shape3_sta = [None if inputs.shape[1] is None else inputs.shape[1] * strides2d[0], None if inputs.shape[2] is None else inputs.shape[2] * strides2d[1], filters] kernel_shape = shape2d(kernel_size) W = tf.get_variable('W', kernel_shape + [filters, channels_in], initializer=kernel_initializer) if use_bias: b = tf.get_variable('b', [filters], initializer=bias_initializer) conv = tf.nn.conv2d_transpose( inputs, W, out_shape_dyn, shape4d(strides, data_format=data_format), padding=padding.upper(), data_format=data_format) conv.set_shape(tf.TensorShape([None] + out_shape3_sta)) ret = tf.nn.bias_add(conv, b, data_format=data_format) if use_bias else conv if activation is not None: ret = activation(ret) ret = tf.identity(ret, name='output') ret.variables = VariableHolder(W=W) if use_bias: ret.variables.b = b return ret
[ "def", "Conv2DTranspose", "(", "inputs", ",", "filters", ",", "kernel_size", ",", "strides", "=", "(", "1", ",", "1", ")", ",", "padding", "=", "'same'", ",", "data_format", "=", "'channels_last'", ",", "activation", "=", "None", ",", "use_bias", "=", "True", ",", "kernel_initializer", "=", "None", ",", "bias_initializer", "=", "tf", ".", "zeros_initializer", "(", ")", ",", "kernel_regularizer", "=", "None", ",", "bias_regularizer", "=", "None", ",", "activity_regularizer", "=", "None", ")", ":", "if", "kernel_initializer", "is", "None", ":", "if", "get_tf_version_tuple", "(", ")", "<=", "(", "1", ",", "12", ")", ":", "kernel_initializer", "=", "tf", ".", "contrib", ".", "layers", ".", "variance_scaling_initializer", "(", "2.0", ")", "else", ":", "kernel_initializer", "=", "tf", ".", "keras", ".", "initializers", ".", "VarianceScaling", "(", "2.0", ",", "distribution", "=", "'untruncated_normal'", ")", "if", "get_tf_version_tuple", "(", ")", "<=", "(", "1", ",", "12", ")", ":", "with", "rename_get_variable", "(", "{", "'kernel'", ":", "'W'", ",", "'bias'", ":", "'b'", "}", ")", ":", "layer", "=", "tf", ".", "layers", ".", "Conv2DTranspose", "(", "filters", ",", "kernel_size", ",", "strides", "=", "strides", ",", "padding", "=", "padding", ",", "data_format", "=", "data_format", ",", "activation", "=", "activation", ",", "use_bias", "=", "use_bias", ",", "kernel_initializer", "=", "kernel_initializer", ",", "bias_initializer", "=", "bias_initializer", ",", "kernel_regularizer", "=", "kernel_regularizer", ",", "bias_regularizer", "=", "bias_regularizer", ",", "activity_regularizer", "=", "activity_regularizer", ",", "_reuse", "=", "tf", ".", "get_variable_scope", "(", ")", ".", "reuse", ")", "ret", "=", "layer", ".", "apply", "(", "inputs", ",", "scope", "=", "tf", ".", "get_variable_scope", "(", ")", ")", "ret", "=", "tf", ".", "identity", "(", "ret", ",", "name", "=", "'output'", ")", "ret", ".", "variables", "=", "VariableHolder", "(", "W", "=", "layer", ".", "kernel", ")", "if", "use_bias", ":", "ret", ".", "variables", ".", "b", "=", "layer", ".", "bias", "else", ":", "# Our own implementation, to avoid Keras bugs. https://github.com/tensorflow/tensorflow/issues/25946", "assert", "kernel_regularizer", "is", "None", "and", "bias_regularizer", "is", "None", "and", "activity_regularizer", "is", "None", ",", "\"Unsupported arguments due to Keras bug in TensorFlow 1.13\"", "data_format", "=", "get_data_format", "(", "data_format", ",", "keras_mode", "=", "False", ")", "shape_dyn", "=", "tf", ".", "shape", "(", "inputs", ")", "strides2d", "=", "shape2d", "(", "strides", ")", "channels_in", "=", "inputs", ".", "shape", "[", "1", "if", "data_format", "==", "'NCHW'", "else", "3", "]", "if", "data_format", "==", "'NCHW'", ":", "channels_in", "=", "inputs", ".", "shape", "[", "1", "]", "out_shape_dyn", "=", "tf", ".", "stack", "(", "[", "shape_dyn", "[", "0", "]", ",", "filters", ",", "shape_dyn", "[", "2", "]", "*", "strides2d", "[", "0", "]", ",", "shape_dyn", "[", "3", "]", "*", "strides2d", "[", "1", "]", "]", ")", "out_shape3_sta", "=", "[", "filters", ",", "None", "if", "inputs", ".", "shape", "[", "2", "]", "is", "None", "else", "inputs", ".", "shape", "[", "2", "]", "*", "strides2d", "[", "0", "]", ",", "None", "if", "inputs", ".", "shape", "[", "3", "]", "is", "None", "else", "inputs", ".", "shape", "[", "3", "]", "*", "strides2d", "[", "1", "]", "]", "else", ":", "channels_in", "=", "inputs", ".", "shape", "[", "-", "1", "]", "out_shape_dyn", "=", "tf", ".", "stack", "(", "[", "shape_dyn", "[", "0", "]", ",", "shape_dyn", "[", "1", "]", "*", "strides2d", "[", "0", "]", ",", "shape_dyn", "[", "2", "]", "*", "strides2d", "[", "1", "]", ",", "filters", "]", ")", "out_shape3_sta", "=", "[", "None", "if", "inputs", ".", "shape", "[", "1", "]", "is", "None", "else", "inputs", ".", "shape", "[", "1", "]", "*", "strides2d", "[", "0", "]", ",", "None", "if", "inputs", ".", "shape", "[", "2", "]", "is", "None", "else", "inputs", ".", "shape", "[", "2", "]", "*", "strides2d", "[", "1", "]", ",", "filters", "]", "kernel_shape", "=", "shape2d", "(", "kernel_size", ")", "W", "=", "tf", ".", "get_variable", "(", "'W'", ",", "kernel_shape", "+", "[", "filters", ",", "channels_in", "]", ",", "initializer", "=", "kernel_initializer", ")", "if", "use_bias", ":", "b", "=", "tf", ".", "get_variable", "(", "'b'", ",", "[", "filters", "]", ",", "initializer", "=", "bias_initializer", ")", "conv", "=", "tf", ".", "nn", ".", "conv2d_transpose", "(", "inputs", ",", "W", ",", "out_shape_dyn", ",", "shape4d", "(", "strides", ",", "data_format", "=", "data_format", ")", ",", "padding", "=", "padding", ".", "upper", "(", ")", ",", "data_format", "=", "data_format", ")", "conv", ".", "set_shape", "(", "tf", ".", "TensorShape", "(", "[", "None", "]", "+", "out_shape3_sta", ")", ")", "ret", "=", "tf", ".", "nn", ".", "bias_add", "(", "conv", ",", "b", ",", "data_format", "=", "data_format", ")", "if", "use_bias", "else", "conv", "if", "activation", "is", "not", "None", ":", "ret", "=", "activation", "(", "ret", ")", "ret", "=", "tf", ".", "identity", "(", "ret", ",", "name", "=", "'output'", ")", "ret", ".", "variables", "=", "VariableHolder", "(", "W", "=", "W", ")", "if", "use_bias", ":", "ret", ".", "variables", ".", "b", "=", "b", "return", "ret" ]
A wrapper around `tf.layers.Conv2DTranspose`. Some differences to maintain backward-compatibility: 1. Default kernel initializer is variance_scaling_initializer(2.0). 2. Default padding is 'same' Variable Names: * ``W``: weights * ``b``: bias
[ "A", "wrapper", "around", "tf", ".", "layers", ".", "Conv2DTranspose", ".", "Some", "differences", "to", "maintain", "backward", "-", "compatibility", ":" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/conv2d.py#L151-L252
train
tensorpack/tensorpack
tensorpack/callbacks/param.py
GraphVarParam.setup_graph
def setup_graph(self): """ Will setup the assign operator for that variable. """ all_vars = tfv1.global_variables() + tfv1.local_variables() for v in all_vars: if v.name == self.var_name: self.var = v break else: raise ValueError("{} is not a variable in the graph!".format(self.var_name))
python
def setup_graph(self): """ Will setup the assign operator for that variable. """ all_vars = tfv1.global_variables() + tfv1.local_variables() for v in all_vars: if v.name == self.var_name: self.var = v break else: raise ValueError("{} is not a variable in the graph!".format(self.var_name))
[ "def", "setup_graph", "(", "self", ")", ":", "all_vars", "=", "tfv1", ".", "global_variables", "(", ")", "+", "tfv1", ".", "local_variables", "(", ")", "for", "v", "in", "all_vars", ":", "if", "v", ".", "name", "==", "self", ".", "var_name", ":", "self", ".", "var", "=", "v", "break", "else", ":", "raise", "ValueError", "(", "\"{} is not a variable in the graph!\"", ".", "format", "(", "self", ".", "var_name", ")", ")" ]
Will setup the assign operator for that variable.
[ "Will", "setup", "the", "assign", "operator", "for", "that", "variable", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/param.py#L68-L76
train
tensorpack/tensorpack
tensorpack/callbacks/param.py
HyperParamSetter.get_value_to_set
def get_value_to_set(self): """ Returns: The value to assign to the variable. Note: Subclasses will implement the abstract method :meth:`_get_value_to_set`, which should return a new value to set, or return None to do nothing. """ ret = self._get_value_to_set() if ret is not None and ret != self._last_value: if self.epoch_num != self._last_epoch_set: # Print this message at most once every epoch if self._last_value is None: logger.info("[HyperParamSetter] At global_step={}, {} is set to {:.6f}".format( self.global_step, self.param.readable_name, ret)) else: logger.info("[HyperParamSetter] At global_step={}, {} changes from {:.6f} to {:.6f}".format( self.global_step, self.param.readable_name, self._last_value, ret)) self._last_epoch_set = self.epoch_num self._last_value = ret return ret
python
def get_value_to_set(self): """ Returns: The value to assign to the variable. Note: Subclasses will implement the abstract method :meth:`_get_value_to_set`, which should return a new value to set, or return None to do nothing. """ ret = self._get_value_to_set() if ret is not None and ret != self._last_value: if self.epoch_num != self._last_epoch_set: # Print this message at most once every epoch if self._last_value is None: logger.info("[HyperParamSetter] At global_step={}, {} is set to {:.6f}".format( self.global_step, self.param.readable_name, ret)) else: logger.info("[HyperParamSetter] At global_step={}, {} changes from {:.6f} to {:.6f}".format( self.global_step, self.param.readable_name, self._last_value, ret)) self._last_epoch_set = self.epoch_num self._last_value = ret return ret
[ "def", "get_value_to_set", "(", "self", ")", ":", "ret", "=", "self", ".", "_get_value_to_set", "(", ")", "if", "ret", "is", "not", "None", "and", "ret", "!=", "self", ".", "_last_value", ":", "if", "self", ".", "epoch_num", "!=", "self", ".", "_last_epoch_set", ":", "# Print this message at most once every epoch", "if", "self", ".", "_last_value", "is", "None", ":", "logger", ".", "info", "(", "\"[HyperParamSetter] At global_step={}, {} is set to {:.6f}\"", ".", "format", "(", "self", ".", "global_step", ",", "self", ".", "param", ".", "readable_name", ",", "ret", ")", ")", "else", ":", "logger", ".", "info", "(", "\"[HyperParamSetter] At global_step={}, {} changes from {:.6f} to {:.6f}\"", ".", "format", "(", "self", ".", "global_step", ",", "self", ".", "param", ".", "readable_name", ",", "self", ".", "_last_value", ",", "ret", ")", ")", "self", ".", "_last_epoch_set", "=", "self", ".", "epoch_num", "self", ".", "_last_value", "=", "ret", "return", "ret" ]
Returns: The value to assign to the variable. Note: Subclasses will implement the abstract method :meth:`_get_value_to_set`, which should return a new value to set, or return None to do nothing.
[ "Returns", ":", "The", "value", "to", "assign", "to", "the", "variable", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/param.py#L143-L164
train
tensorpack/tensorpack
tensorpack/callbacks/param.py
ScheduledHyperParamSetter._get_value_to_set_at_point
def _get_value_to_set_at_point(self, point): """ Using schedule, compute the value to be set at a given point. """ laste, lastv = None, None for e, v in self.schedule: if e == point: return v # meet the exact boundary, return directly if e > point: break laste, lastv = e, v if laste is None or laste == e: # hasn't reached the first scheduled point, or reached the end of all scheduled points return None if self.interp is None: # If no interpolation, nothing to do. return None v = (point - laste) * 1. / (e - laste) * (v - lastv) + lastv return v
python
def _get_value_to_set_at_point(self, point): """ Using schedule, compute the value to be set at a given point. """ laste, lastv = None, None for e, v in self.schedule: if e == point: return v # meet the exact boundary, return directly if e > point: break laste, lastv = e, v if laste is None or laste == e: # hasn't reached the first scheduled point, or reached the end of all scheduled points return None if self.interp is None: # If no interpolation, nothing to do. return None v = (point - laste) * 1. / (e - laste) * (v - lastv) + lastv return v
[ "def", "_get_value_to_set_at_point", "(", "self", ",", "point", ")", ":", "laste", ",", "lastv", "=", "None", ",", "None", "for", "e", ",", "v", "in", "self", ".", "schedule", ":", "if", "e", "==", "point", ":", "return", "v", "# meet the exact boundary, return directly", "if", "e", ">", "point", ":", "break", "laste", ",", "lastv", "=", "e", ",", "v", "if", "laste", "is", "None", "or", "laste", "==", "e", ":", "# hasn't reached the first scheduled point, or reached the end of all scheduled points", "return", "None", "if", "self", ".", "interp", "is", "None", ":", "# If no interpolation, nothing to do.", "return", "None", "v", "=", "(", "point", "-", "laste", ")", "*", "1.", "/", "(", "e", "-", "laste", ")", "*", "(", "v", "-", "lastv", ")", "+", "lastv", "return", "v" ]
Using schedule, compute the value to be set at a given point.
[ "Using", "schedule", "compute", "the", "value", "to", "be", "set", "at", "a", "given", "point", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/param.py#L283-L301
train
tensorpack/tensorpack
examples/basics/mnist-convnet.py
Model.build_graph
def build_graph(self, image, label): """This function should build the model which takes the input variables and return cost at the end""" # In tensorflow, inputs to convolution function are assumed to be # NHWC. Add a single channel here. image = tf.expand_dims(image, 3) image = image * 2 - 1 # center the pixels values at zero # The context manager `argscope` sets the default option for all the layers under # this context. Here we use 32 channel convolution with shape 3x3 with argscope(Conv2D, kernel_size=3, activation=tf.nn.relu, filters=32): logits = (LinearWrap(image) .Conv2D('conv0') .MaxPooling('pool0', 2) .Conv2D('conv1') .Conv2D('conv2') .MaxPooling('pool1', 2) .Conv2D('conv3') .FullyConnected('fc0', 512, activation=tf.nn.relu) .Dropout('dropout', rate=0.5) .FullyConnected('fc1', 10, activation=tf.identity)()) # a vector of length B with loss of each sample cost = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=label) cost = tf.reduce_mean(cost, name='cross_entropy_loss') # the average cross-entropy loss correct = tf.cast(tf.nn.in_top_k(predictions=logits, targets=label, k=1), tf.float32, name='correct') accuracy = tf.reduce_mean(correct, name='accuracy') # This will monitor training error & accuracy (in a moving average fashion). The value will be automatically # 1. written to tensosrboard # 2. written to stat.json # 3. printed after each epoch train_error = tf.reduce_mean(1 - correct, name='train_error') summary.add_moving_summary(train_error, accuracy) # Use a regex to find parameters to apply weight decay. # Here we apply a weight decay on all W (weight matrix) of all fc layers # If you don't like regex, you can certainly define the cost in any other methods. wd_cost = tf.multiply(1e-5, regularize_cost('fc.*/W', tf.nn.l2_loss), name='regularize_loss') total_cost = tf.add_n([wd_cost, cost], name='total_cost') summary.add_moving_summary(cost, wd_cost, total_cost) # monitor histogram of all weight (of conv and fc layers) in tensorboard summary.add_param_summary(('.*/W', ['histogram', 'rms'])) # the function should return the total cost to be optimized return total_cost
python
def build_graph(self, image, label): """This function should build the model which takes the input variables and return cost at the end""" # In tensorflow, inputs to convolution function are assumed to be # NHWC. Add a single channel here. image = tf.expand_dims(image, 3) image = image * 2 - 1 # center the pixels values at zero # The context manager `argscope` sets the default option for all the layers under # this context. Here we use 32 channel convolution with shape 3x3 with argscope(Conv2D, kernel_size=3, activation=tf.nn.relu, filters=32): logits = (LinearWrap(image) .Conv2D('conv0') .MaxPooling('pool0', 2) .Conv2D('conv1') .Conv2D('conv2') .MaxPooling('pool1', 2) .Conv2D('conv3') .FullyConnected('fc0', 512, activation=tf.nn.relu) .Dropout('dropout', rate=0.5) .FullyConnected('fc1', 10, activation=tf.identity)()) # a vector of length B with loss of each sample cost = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=label) cost = tf.reduce_mean(cost, name='cross_entropy_loss') # the average cross-entropy loss correct = tf.cast(tf.nn.in_top_k(predictions=logits, targets=label, k=1), tf.float32, name='correct') accuracy = tf.reduce_mean(correct, name='accuracy') # This will monitor training error & accuracy (in a moving average fashion). The value will be automatically # 1. written to tensosrboard # 2. written to stat.json # 3. printed after each epoch train_error = tf.reduce_mean(1 - correct, name='train_error') summary.add_moving_summary(train_error, accuracy) # Use a regex to find parameters to apply weight decay. # Here we apply a weight decay on all W (weight matrix) of all fc layers # If you don't like regex, you can certainly define the cost in any other methods. wd_cost = tf.multiply(1e-5, regularize_cost('fc.*/W', tf.nn.l2_loss), name='regularize_loss') total_cost = tf.add_n([wd_cost, cost], name='total_cost') summary.add_moving_summary(cost, wd_cost, total_cost) # monitor histogram of all weight (of conv and fc layers) in tensorboard summary.add_param_summary(('.*/W', ['histogram', 'rms'])) # the function should return the total cost to be optimized return total_cost
[ "def", "build_graph", "(", "self", ",", "image", ",", "label", ")", ":", "# In tensorflow, inputs to convolution function are assumed to be", "# NHWC. Add a single channel here.", "image", "=", "tf", ".", "expand_dims", "(", "image", ",", "3", ")", "image", "=", "image", "*", "2", "-", "1", "# center the pixels values at zero", "# The context manager `argscope` sets the default option for all the layers under", "# this context. Here we use 32 channel convolution with shape 3x3", "with", "argscope", "(", "Conv2D", ",", "kernel_size", "=", "3", ",", "activation", "=", "tf", ".", "nn", ".", "relu", ",", "filters", "=", "32", ")", ":", "logits", "=", "(", "LinearWrap", "(", "image", ")", ".", "Conv2D", "(", "'conv0'", ")", ".", "MaxPooling", "(", "'pool0'", ",", "2", ")", ".", "Conv2D", "(", "'conv1'", ")", ".", "Conv2D", "(", "'conv2'", ")", ".", "MaxPooling", "(", "'pool1'", ",", "2", ")", ".", "Conv2D", "(", "'conv3'", ")", ".", "FullyConnected", "(", "'fc0'", ",", "512", ",", "activation", "=", "tf", ".", "nn", ".", "relu", ")", ".", "Dropout", "(", "'dropout'", ",", "rate", "=", "0.5", ")", ".", "FullyConnected", "(", "'fc1'", ",", "10", ",", "activation", "=", "tf", ".", "identity", ")", "(", ")", ")", "# a vector of length B with loss of each sample", "cost", "=", "tf", ".", "nn", ".", "sparse_softmax_cross_entropy_with_logits", "(", "logits", "=", "logits", ",", "labels", "=", "label", ")", "cost", "=", "tf", ".", "reduce_mean", "(", "cost", ",", "name", "=", "'cross_entropy_loss'", ")", "# the average cross-entropy loss", "correct", "=", "tf", ".", "cast", "(", "tf", ".", "nn", ".", "in_top_k", "(", "predictions", "=", "logits", ",", "targets", "=", "label", ",", "k", "=", "1", ")", ",", "tf", ".", "float32", ",", "name", "=", "'correct'", ")", "accuracy", "=", "tf", ".", "reduce_mean", "(", "correct", ",", "name", "=", "'accuracy'", ")", "# This will monitor training error & accuracy (in a moving average fashion). The value will be automatically", "# 1. written to tensosrboard", "# 2. written to stat.json", "# 3. printed after each epoch", "train_error", "=", "tf", ".", "reduce_mean", "(", "1", "-", "correct", ",", "name", "=", "'train_error'", ")", "summary", ".", "add_moving_summary", "(", "train_error", ",", "accuracy", ")", "# Use a regex to find parameters to apply weight decay.", "# Here we apply a weight decay on all W (weight matrix) of all fc layers", "# If you don't like regex, you can certainly define the cost in any other methods.", "wd_cost", "=", "tf", ".", "multiply", "(", "1e-5", ",", "regularize_cost", "(", "'fc.*/W'", ",", "tf", ".", "nn", ".", "l2_loss", ")", ",", "name", "=", "'regularize_loss'", ")", "total_cost", "=", "tf", ".", "add_n", "(", "[", "wd_cost", ",", "cost", "]", ",", "name", "=", "'total_cost'", ")", "summary", ".", "add_moving_summary", "(", "cost", ",", "wd_cost", ",", "total_cost", ")", "# monitor histogram of all weight (of conv and fc layers) in tensorboard", "summary", ".", "add_param_summary", "(", "(", "'.*/W'", ",", "[", "'histogram'", ",", "'rms'", "]", ")", ")", "# the function should return the total cost to be optimized", "return", "total_cost" ]
This function should build the model which takes the input variables and return cost at the end
[ "This", "function", "should", "build", "the", "model", "which", "takes", "the", "input", "variables", "and", "return", "cost", "at", "the", "end" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/basics/mnist-convnet.py#L27-L76
train
tensorpack/tensorpack
examples/ResNet/load-resnet.py
name_conversion
def name_conversion(caffe_layer_name): """ Convert a caffe parameter name to a tensorflow parameter name as defined in the above model """ # beginning & end mapping NAME_MAP = {'bn_conv1/beta': 'conv0/bn/beta', 'bn_conv1/gamma': 'conv0/bn/gamma', 'bn_conv1/mean/EMA': 'conv0/bn/mean/EMA', 'bn_conv1/variance/EMA': 'conv0/bn/variance/EMA', 'conv1/W': 'conv0/W', 'conv1/b': 'conv0/b', 'fc1000/W': 'linear/W', 'fc1000/b': 'linear/b'} if caffe_layer_name in NAME_MAP: return NAME_MAP[caffe_layer_name] s = re.search('([a-z]+)([0-9]+)([a-z]+)_', caffe_layer_name) if s is None: s = re.search('([a-z]+)([0-9]+)([a-z]+)([0-9]+)_', caffe_layer_name) layer_block_part1 = s.group(3) layer_block_part2 = s.group(4) assert layer_block_part1 in ['a', 'b'] layer_block = 0 if layer_block_part1 == 'a' else int(layer_block_part2) else: layer_block = ord(s.group(3)) - ord('a') layer_type = s.group(1) layer_group = s.group(2) layer_branch = int(re.search('_branch([0-9])', caffe_layer_name).group(1)) assert layer_branch in [1, 2] if layer_branch == 2: layer_id = re.search('_branch[0-9]([a-z])/', caffe_layer_name).group(1) layer_id = ord(layer_id) - ord('a') + 1 TYPE_DICT = {'res': 'conv{}', 'bn': 'conv{}/bn'} layer_type = TYPE_DICT[layer_type].format(layer_id if layer_branch == 2 else 'shortcut') tf_name = caffe_layer_name[caffe_layer_name.index('/'):] tf_name = 'group{}/block{}/{}'.format( int(layer_group) - 2, layer_block, layer_type) + tf_name return tf_name
python
def name_conversion(caffe_layer_name): """ Convert a caffe parameter name to a tensorflow parameter name as defined in the above model """ # beginning & end mapping NAME_MAP = {'bn_conv1/beta': 'conv0/bn/beta', 'bn_conv1/gamma': 'conv0/bn/gamma', 'bn_conv1/mean/EMA': 'conv0/bn/mean/EMA', 'bn_conv1/variance/EMA': 'conv0/bn/variance/EMA', 'conv1/W': 'conv0/W', 'conv1/b': 'conv0/b', 'fc1000/W': 'linear/W', 'fc1000/b': 'linear/b'} if caffe_layer_name in NAME_MAP: return NAME_MAP[caffe_layer_name] s = re.search('([a-z]+)([0-9]+)([a-z]+)_', caffe_layer_name) if s is None: s = re.search('([a-z]+)([0-9]+)([a-z]+)([0-9]+)_', caffe_layer_name) layer_block_part1 = s.group(3) layer_block_part2 = s.group(4) assert layer_block_part1 in ['a', 'b'] layer_block = 0 if layer_block_part1 == 'a' else int(layer_block_part2) else: layer_block = ord(s.group(3)) - ord('a') layer_type = s.group(1) layer_group = s.group(2) layer_branch = int(re.search('_branch([0-9])', caffe_layer_name).group(1)) assert layer_branch in [1, 2] if layer_branch == 2: layer_id = re.search('_branch[0-9]([a-z])/', caffe_layer_name).group(1) layer_id = ord(layer_id) - ord('a') + 1 TYPE_DICT = {'res': 'conv{}', 'bn': 'conv{}/bn'} layer_type = TYPE_DICT[layer_type].format(layer_id if layer_branch == 2 else 'shortcut') tf_name = caffe_layer_name[caffe_layer_name.index('/'):] tf_name = 'group{}/block{}/{}'.format( int(layer_group) - 2, layer_block, layer_type) + tf_name return tf_name
[ "def", "name_conversion", "(", "caffe_layer_name", ")", ":", "# beginning & end mapping", "NAME_MAP", "=", "{", "'bn_conv1/beta'", ":", "'conv0/bn/beta'", ",", "'bn_conv1/gamma'", ":", "'conv0/bn/gamma'", ",", "'bn_conv1/mean/EMA'", ":", "'conv0/bn/mean/EMA'", ",", "'bn_conv1/variance/EMA'", ":", "'conv0/bn/variance/EMA'", ",", "'conv1/W'", ":", "'conv0/W'", ",", "'conv1/b'", ":", "'conv0/b'", ",", "'fc1000/W'", ":", "'linear/W'", ",", "'fc1000/b'", ":", "'linear/b'", "}", "if", "caffe_layer_name", "in", "NAME_MAP", ":", "return", "NAME_MAP", "[", "caffe_layer_name", "]", "s", "=", "re", ".", "search", "(", "'([a-z]+)([0-9]+)([a-z]+)_'", ",", "caffe_layer_name", ")", "if", "s", "is", "None", ":", "s", "=", "re", ".", "search", "(", "'([a-z]+)([0-9]+)([a-z]+)([0-9]+)_'", ",", "caffe_layer_name", ")", "layer_block_part1", "=", "s", ".", "group", "(", "3", ")", "layer_block_part2", "=", "s", ".", "group", "(", "4", ")", "assert", "layer_block_part1", "in", "[", "'a'", ",", "'b'", "]", "layer_block", "=", "0", "if", "layer_block_part1", "==", "'a'", "else", "int", "(", "layer_block_part2", ")", "else", ":", "layer_block", "=", "ord", "(", "s", ".", "group", "(", "3", ")", ")", "-", "ord", "(", "'a'", ")", "layer_type", "=", "s", ".", "group", "(", "1", ")", "layer_group", "=", "s", ".", "group", "(", "2", ")", "layer_branch", "=", "int", "(", "re", ".", "search", "(", "'_branch([0-9])'", ",", "caffe_layer_name", ")", ".", "group", "(", "1", ")", ")", "assert", "layer_branch", "in", "[", "1", ",", "2", "]", "if", "layer_branch", "==", "2", ":", "layer_id", "=", "re", ".", "search", "(", "'_branch[0-9]([a-z])/'", ",", "caffe_layer_name", ")", ".", "group", "(", "1", ")", "layer_id", "=", "ord", "(", "layer_id", ")", "-", "ord", "(", "'a'", ")", "+", "1", "TYPE_DICT", "=", "{", "'res'", ":", "'conv{}'", ",", "'bn'", ":", "'conv{}/bn'", "}", "layer_type", "=", "TYPE_DICT", "[", "layer_type", "]", ".", "format", "(", "layer_id", "if", "layer_branch", "==", "2", "else", "'shortcut'", ")", "tf_name", "=", "caffe_layer_name", "[", "caffe_layer_name", ".", "index", "(", "'/'", ")", ":", "]", "tf_name", "=", "'group{}/block{}/{}'", ".", "format", "(", "int", "(", "layer_group", ")", "-", "2", ",", "layer_block", ",", "layer_type", ")", "+", "tf_name", "return", "tf_name" ]
Convert a caffe parameter name to a tensorflow parameter name as defined in the above model
[ "Convert", "a", "caffe", "parameter", "name", "to", "a", "tensorflow", "parameter", "name", "as", "defined", "in", "the", "above", "model" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/ResNet/load-resnet.py#L101-L138
train
tensorpack/tensorpack
tensorpack/tfutils/varreplace.py
custom_getter_scope
def custom_getter_scope(custom_getter): """ Args: custom_getter: the same as in :func:`tf.get_variable` Returns: The current variable scope with a custom_getter. """ scope = tf.get_variable_scope() if get_tf_version_tuple() >= (1, 5): with tf.variable_scope( scope, custom_getter=custom_getter, auxiliary_name_scope=False): yield else: ns = tf.get_default_graph().get_name_scope() with tf.variable_scope( scope, custom_getter=custom_getter): with tf.name_scope(ns + '/' if ns else ''): yield
python
def custom_getter_scope(custom_getter): """ Args: custom_getter: the same as in :func:`tf.get_variable` Returns: The current variable scope with a custom_getter. """ scope = tf.get_variable_scope() if get_tf_version_tuple() >= (1, 5): with tf.variable_scope( scope, custom_getter=custom_getter, auxiliary_name_scope=False): yield else: ns = tf.get_default_graph().get_name_scope() with tf.variable_scope( scope, custom_getter=custom_getter): with tf.name_scope(ns + '/' if ns else ''): yield
[ "def", "custom_getter_scope", "(", "custom_getter", ")", ":", "scope", "=", "tf", ".", "get_variable_scope", "(", ")", "if", "get_tf_version_tuple", "(", ")", ">=", "(", "1", ",", "5", ")", ":", "with", "tf", ".", "variable_scope", "(", "scope", ",", "custom_getter", "=", "custom_getter", ",", "auxiliary_name_scope", "=", "False", ")", ":", "yield", "else", ":", "ns", "=", "tf", ".", "get_default_graph", "(", ")", ".", "get_name_scope", "(", ")", "with", "tf", ".", "variable_scope", "(", "scope", ",", "custom_getter", "=", "custom_getter", ")", ":", "with", "tf", ".", "name_scope", "(", "ns", "+", "'/'", "if", "ns", "else", "''", ")", ":", "yield" ]
Args: custom_getter: the same as in :func:`tf.get_variable` Returns: The current variable scope with a custom_getter.
[ "Args", ":", "custom_getter", ":", "the", "same", "as", "in", ":", "func", ":", "tf", ".", "get_variable" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/varreplace.py#L14-L33
train
tensorpack/tensorpack
tensorpack/tfutils/varreplace.py
remap_variables
def remap_variables(fn): """ Use fn to map the output of any variable getter. Args: fn (tf.Variable -> tf.Tensor) Returns: The current variable scope with a custom_getter that maps all the variables by fn. Example: .. code-block:: python with varreplace.remap_variables(lambda var: quantize(var)): x = FullyConnected('fc', x, 1000) # fc/{W,b} will be quantized """ def custom_getter(getter, *args, **kwargs): v = getter(*args, **kwargs) return fn(v) return custom_getter_scope(custom_getter)
python
def remap_variables(fn): """ Use fn to map the output of any variable getter. Args: fn (tf.Variable -> tf.Tensor) Returns: The current variable scope with a custom_getter that maps all the variables by fn. Example: .. code-block:: python with varreplace.remap_variables(lambda var: quantize(var)): x = FullyConnected('fc', x, 1000) # fc/{W,b} will be quantized """ def custom_getter(getter, *args, **kwargs): v = getter(*args, **kwargs) return fn(v) return custom_getter_scope(custom_getter)
[ "def", "remap_variables", "(", "fn", ")", ":", "def", "custom_getter", "(", "getter", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "v", "=", "getter", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "fn", "(", "v", ")", "return", "custom_getter_scope", "(", "custom_getter", ")" ]
Use fn to map the output of any variable getter. Args: fn (tf.Variable -> tf.Tensor) Returns: The current variable scope with a custom_getter that maps all the variables by fn. Example: .. code-block:: python with varreplace.remap_variables(lambda var: quantize(var)): x = FullyConnected('fc', x, 1000) # fc/{W,b} will be quantized
[ "Use", "fn", "to", "map", "the", "output", "of", "any", "variable", "getter", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/varreplace.py#L36-L56
train
tensorpack/tensorpack
tensorpack/tfutils/varreplace.py
freeze_variables
def freeze_variables(stop_gradient=True, skip_collection=False): """ Return a context to freeze variables, by wrapping ``tf.get_variable`` with a custom getter. It works by either applying ``tf.stop_gradient`` on the variables, or by keeping them out of the ``TRAINABLE_VARIABLES`` collection, or both. Example: .. code-block:: python with varreplace.freeze_variable(stop_gradient=False, skip_collection=True): x = FullyConnected('fc', x, 1000) # fc/* will not be trained Args: stop_gradient (bool): if True, variables returned from `get_variable` will be wrapped with `tf.stop_gradient` and therefore has no gradient when used later. Note that the created variables may still have gradient when accessed by other approaches (e.g. by name, or by collection). Also note that this makes `tf.get_variable` returns a Tensor instead of a Variable, which may break existing code. Therefore, it's recommended to use the `skip_collection` option instead. skip_collection (bool): if True, do not add the variable to ``TRAINABLE_VARIABLES`` collection, but to ``MODEL_VARIABLES`` collection. As a result they will not be trained by default. """ def custom_getter(getter, *args, **kwargs): trainable = kwargs.get('trainable', True) name = args[0] if len(args) else kwargs.get('name') if skip_collection: kwargs['trainable'] = False v = getter(*args, **kwargs) if skip_collection: tf.add_to_collection(tf.GraphKeys.MODEL_VARIABLES, v) if trainable and stop_gradient: v = tf.stop_gradient(v, name='freezed_' + name) return v return custom_getter_scope(custom_getter)
python
def freeze_variables(stop_gradient=True, skip_collection=False): """ Return a context to freeze variables, by wrapping ``tf.get_variable`` with a custom getter. It works by either applying ``tf.stop_gradient`` on the variables, or by keeping them out of the ``TRAINABLE_VARIABLES`` collection, or both. Example: .. code-block:: python with varreplace.freeze_variable(stop_gradient=False, skip_collection=True): x = FullyConnected('fc', x, 1000) # fc/* will not be trained Args: stop_gradient (bool): if True, variables returned from `get_variable` will be wrapped with `tf.stop_gradient` and therefore has no gradient when used later. Note that the created variables may still have gradient when accessed by other approaches (e.g. by name, or by collection). Also note that this makes `tf.get_variable` returns a Tensor instead of a Variable, which may break existing code. Therefore, it's recommended to use the `skip_collection` option instead. skip_collection (bool): if True, do not add the variable to ``TRAINABLE_VARIABLES`` collection, but to ``MODEL_VARIABLES`` collection. As a result they will not be trained by default. """ def custom_getter(getter, *args, **kwargs): trainable = kwargs.get('trainable', True) name = args[0] if len(args) else kwargs.get('name') if skip_collection: kwargs['trainable'] = False v = getter(*args, **kwargs) if skip_collection: tf.add_to_collection(tf.GraphKeys.MODEL_VARIABLES, v) if trainable and stop_gradient: v = tf.stop_gradient(v, name='freezed_' + name) return v return custom_getter_scope(custom_getter)
[ "def", "freeze_variables", "(", "stop_gradient", "=", "True", ",", "skip_collection", "=", "False", ")", ":", "def", "custom_getter", "(", "getter", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "trainable", "=", "kwargs", ".", "get", "(", "'trainable'", ",", "True", ")", "name", "=", "args", "[", "0", "]", "if", "len", "(", "args", ")", "else", "kwargs", ".", "get", "(", "'name'", ")", "if", "skip_collection", ":", "kwargs", "[", "'trainable'", "]", "=", "False", "v", "=", "getter", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "skip_collection", ":", "tf", ".", "add_to_collection", "(", "tf", ".", "GraphKeys", ".", "MODEL_VARIABLES", ",", "v", ")", "if", "trainable", "and", "stop_gradient", ":", "v", "=", "tf", ".", "stop_gradient", "(", "v", ",", "name", "=", "'freezed_'", "+", "name", ")", "return", "v", "return", "custom_getter_scope", "(", "custom_getter", ")" ]
Return a context to freeze variables, by wrapping ``tf.get_variable`` with a custom getter. It works by either applying ``tf.stop_gradient`` on the variables, or by keeping them out of the ``TRAINABLE_VARIABLES`` collection, or both. Example: .. code-block:: python with varreplace.freeze_variable(stop_gradient=False, skip_collection=True): x = FullyConnected('fc', x, 1000) # fc/* will not be trained Args: stop_gradient (bool): if True, variables returned from `get_variable` will be wrapped with `tf.stop_gradient` and therefore has no gradient when used later. Note that the created variables may still have gradient when accessed by other approaches (e.g. by name, or by collection). Also note that this makes `tf.get_variable` returns a Tensor instead of a Variable, which may break existing code. Therefore, it's recommended to use the `skip_collection` option instead. skip_collection (bool): if True, do not add the variable to ``TRAINABLE_VARIABLES`` collection, but to ``MODEL_VARIABLES`` collection. As a result they will not be trained by default.
[ "Return", "a", "context", "to", "freeze", "variables", "by", "wrapping", "tf", ".", "get_variable", "with", "a", "custom", "getter", ".", "It", "works", "by", "either", "applying", "tf", ".", "stop_gradient", "on", "the", "variables", "or", "by", "keeping", "them", "out", "of", "the", "TRAINABLE_VARIABLES", "collection", "or", "both", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/varreplace.py#L59-L97
train
tensorpack/tensorpack
tensorpack/utils/loadcaffe.py
load_caffe
def load_caffe(model_desc, model_file): """ Load a caffe model. You must be able to ``import caffe`` to use this function. Args: model_desc (str): path to caffe model description file (.prototxt). model_file (str): path to caffe model parameter file (.caffemodel). Returns: dict: the parameters. """ with change_env('GLOG_minloglevel', '2'): import caffe caffe.set_mode_cpu() net = caffe.Net(model_desc, model_file, caffe.TEST) param_dict = CaffeLayerProcessor(net).process() logger.info("Model loaded from caffe. Params: " + ", ".join(sorted(param_dict.keys()))) return param_dict
python
def load_caffe(model_desc, model_file): """ Load a caffe model. You must be able to ``import caffe`` to use this function. Args: model_desc (str): path to caffe model description file (.prototxt). model_file (str): path to caffe model parameter file (.caffemodel). Returns: dict: the parameters. """ with change_env('GLOG_minloglevel', '2'): import caffe caffe.set_mode_cpu() net = caffe.Net(model_desc, model_file, caffe.TEST) param_dict = CaffeLayerProcessor(net).process() logger.info("Model loaded from caffe. Params: " + ", ".join(sorted(param_dict.keys()))) return param_dict
[ "def", "load_caffe", "(", "model_desc", ",", "model_file", ")", ":", "with", "change_env", "(", "'GLOG_minloglevel'", ",", "'2'", ")", ":", "import", "caffe", "caffe", ".", "set_mode_cpu", "(", ")", "net", "=", "caffe", ".", "Net", "(", "model_desc", ",", "model_file", ",", "caffe", ".", "TEST", ")", "param_dict", "=", "CaffeLayerProcessor", "(", "net", ")", ".", "process", "(", ")", "logger", ".", "info", "(", "\"Model loaded from caffe. Params: \"", "+", "\", \"", ".", "join", "(", "sorted", "(", "param_dict", ".", "keys", "(", ")", ")", ")", ")", "return", "param_dict" ]
Load a caffe model. You must be able to ``import caffe`` to use this function. Args: model_desc (str): path to caffe model description file (.prototxt). model_file (str): path to caffe model parameter file (.caffemodel). Returns: dict: the parameters.
[ "Load", "a", "caffe", "model", ".", "You", "must", "be", "able", "to", "import", "caffe", "to", "use", "this", "function", ".", "Args", ":", "model_desc", "(", "str", ")", ":", "path", "to", "caffe", "model", "description", "file", "(", ".", "prototxt", ")", ".", "model_file", "(", "str", ")", ":", "path", "to", "caffe", "model", "parameter", "file", "(", ".", "caffemodel", ")", ".", "Returns", ":", "dict", ":", "the", "parameters", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/loadcaffe.py#L96-L113
train
tensorpack/tensorpack
tensorpack/utils/loadcaffe.py
get_caffe_pb
def get_caffe_pb(): """ Get caffe protobuf. Returns: The imported caffe protobuf module. """ dir = get_dataset_path('caffe') caffe_pb_file = os.path.join(dir, 'caffe_pb2.py') if not os.path.isfile(caffe_pb_file): download(CAFFE_PROTO_URL, dir) assert os.path.isfile(os.path.join(dir, 'caffe.proto')) if sys.version_info.major == 3: cmd = "protoc --version" version, ret = subproc_call(cmd, timeout=3) if ret != 0: sys.exit(1) try: version = version.decode('utf-8') version = float('.'.join(version.split(' ')[1].split('.')[:2])) assert version >= 2.7, "Require protoc>=2.7 for Python3" except Exception: logger.exception("protoc --version gives: " + str(version)) raise cmd = 'cd {} && protoc caffe.proto --python_out .'.format(dir) ret = os.system(cmd) assert ret == 0, \ "Command `{}` failed!".format(cmd) assert os.path.isfile(caffe_pb_file), caffe_pb_file import imp return imp.load_source('caffepb', caffe_pb_file)
python
def get_caffe_pb(): """ Get caffe protobuf. Returns: The imported caffe protobuf module. """ dir = get_dataset_path('caffe') caffe_pb_file = os.path.join(dir, 'caffe_pb2.py') if not os.path.isfile(caffe_pb_file): download(CAFFE_PROTO_URL, dir) assert os.path.isfile(os.path.join(dir, 'caffe.proto')) if sys.version_info.major == 3: cmd = "protoc --version" version, ret = subproc_call(cmd, timeout=3) if ret != 0: sys.exit(1) try: version = version.decode('utf-8') version = float('.'.join(version.split(' ')[1].split('.')[:2])) assert version >= 2.7, "Require protoc>=2.7 for Python3" except Exception: logger.exception("protoc --version gives: " + str(version)) raise cmd = 'cd {} && protoc caffe.proto --python_out .'.format(dir) ret = os.system(cmd) assert ret == 0, \ "Command `{}` failed!".format(cmd) assert os.path.isfile(caffe_pb_file), caffe_pb_file import imp return imp.load_source('caffepb', caffe_pb_file)
[ "def", "get_caffe_pb", "(", ")", ":", "dir", "=", "get_dataset_path", "(", "'caffe'", ")", "caffe_pb_file", "=", "os", ".", "path", ".", "join", "(", "dir", ",", "'caffe_pb2.py'", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "caffe_pb_file", ")", ":", "download", "(", "CAFFE_PROTO_URL", ",", "dir", ")", "assert", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "dir", ",", "'caffe.proto'", ")", ")", "if", "sys", ".", "version_info", ".", "major", "==", "3", ":", "cmd", "=", "\"protoc --version\"", "version", ",", "ret", "=", "subproc_call", "(", "cmd", ",", "timeout", "=", "3", ")", "if", "ret", "!=", "0", ":", "sys", ".", "exit", "(", "1", ")", "try", ":", "version", "=", "version", ".", "decode", "(", "'utf-8'", ")", "version", "=", "float", "(", "'.'", ".", "join", "(", "version", ".", "split", "(", "' '", ")", "[", "1", "]", ".", "split", "(", "'.'", ")", "[", ":", "2", "]", ")", ")", "assert", "version", ">=", "2.7", ",", "\"Require protoc>=2.7 for Python3\"", "except", "Exception", ":", "logger", ".", "exception", "(", "\"protoc --version gives: \"", "+", "str", "(", "version", ")", ")", "raise", "cmd", "=", "'cd {} && protoc caffe.proto --python_out .'", ".", "format", "(", "dir", ")", "ret", "=", "os", ".", "system", "(", "cmd", ")", "assert", "ret", "==", "0", ",", "\"Command `{}` failed!\"", ".", "format", "(", "cmd", ")", "assert", "os", ".", "path", ".", "isfile", "(", "caffe_pb_file", ")", ",", "caffe_pb_file", "import", "imp", "return", "imp", ".", "load_source", "(", "'caffepb'", ",", "caffe_pb_file", ")" ]
Get caffe protobuf. Returns: The imported caffe protobuf module.
[ "Get", "caffe", "protobuf", ".", "Returns", ":", "The", "imported", "caffe", "protobuf", "module", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/loadcaffe.py#L116-L147
train
tensorpack/tensorpack
examples/FasterRCNN/config.py
finalize_configs
def finalize_configs(is_training): """ Run some sanity checks, and populate some configs from others """ _C.freeze(False) # populate new keys now _C.DATA.NUM_CLASS = _C.DATA.NUM_CATEGORY + 1 # +1 background _C.DATA.BASEDIR = os.path.expanduser(_C.DATA.BASEDIR) if isinstance(_C.DATA.VAL, six.string_types): # support single string (the typical case) as well _C.DATA.VAL = (_C.DATA.VAL, ) assert _C.BACKBONE.NORM in ['FreezeBN', 'SyncBN', 'GN', 'None'], _C.BACKBONE.NORM if _C.BACKBONE.NORM != 'FreezeBN': assert not _C.BACKBONE.FREEZE_AFFINE assert _C.BACKBONE.FREEZE_AT in [0, 1, 2] _C.RPN.NUM_ANCHOR = len(_C.RPN.ANCHOR_SIZES) * len(_C.RPN.ANCHOR_RATIOS) assert len(_C.FPN.ANCHOR_STRIDES) == len(_C.RPN.ANCHOR_SIZES) # image size into the backbone has to be multiple of this number _C.FPN.RESOLUTION_REQUIREMENT = _C.FPN.ANCHOR_STRIDES[3] # [3] because we build FPN with features r2,r3,r4,r5 if _C.MODE_FPN: size_mult = _C.FPN.RESOLUTION_REQUIREMENT * 1. _C.PREPROC.MAX_SIZE = np.ceil(_C.PREPROC.MAX_SIZE / size_mult) * size_mult assert _C.FPN.PROPOSAL_MODE in ['Level', 'Joint'] assert _C.FPN.FRCNN_HEAD_FUNC.endswith('_head') assert _C.FPN.MRCNN_HEAD_FUNC.endswith('_head') assert _C.FPN.NORM in ['None', 'GN'] if _C.FPN.CASCADE: # the first threshold is the proposal sampling threshold assert _C.CASCADE.IOUS[0] == _C.FRCNN.FG_THRESH assert len(_C.CASCADE.BBOX_REG_WEIGHTS) == len(_C.CASCADE.IOUS) if is_training: train_scales = _C.PREPROC.TRAIN_SHORT_EDGE_SIZE if isinstance(train_scales, (list, tuple)) and train_scales[1] - train_scales[0] > 100: # don't autotune if augmentation is on os.environ['TF_CUDNN_USE_AUTOTUNE'] = '0' os.environ['TF_AUTOTUNE_THRESHOLD'] = '1' assert _C.TRAINER in ['horovod', 'replicated'], _C.TRAINER # setup NUM_GPUS if _C.TRAINER == 'horovod': import horovod.tensorflow as hvd ngpu = hvd.size() if ngpu == hvd.local_size(): logger.warn("It's not recommended to use horovod for single-machine training. " "Replicated trainer is more stable and has the same efficiency.") else: assert 'OMPI_COMM_WORLD_SIZE' not in os.environ ngpu = get_num_gpu() assert ngpu > 0, "Has to train with GPU!" assert ngpu % 8 == 0 or 8 % ngpu == 0, "Can only train with 1,2,4 or >=8 GPUs, but found {} GPUs".format(ngpu) else: # autotune is too slow for inference os.environ['TF_CUDNN_USE_AUTOTUNE'] = '0' ngpu = get_num_gpu() if _C.TRAIN.NUM_GPUS is None: _C.TRAIN.NUM_GPUS = ngpu else: if _C.TRAINER == 'horovod': assert _C.TRAIN.NUM_GPUS == ngpu else: assert _C.TRAIN.NUM_GPUS <= ngpu _C.freeze() logger.info("Config: ------------------------------------------\n" + str(_C))
python
def finalize_configs(is_training): """ Run some sanity checks, and populate some configs from others """ _C.freeze(False) # populate new keys now _C.DATA.NUM_CLASS = _C.DATA.NUM_CATEGORY + 1 # +1 background _C.DATA.BASEDIR = os.path.expanduser(_C.DATA.BASEDIR) if isinstance(_C.DATA.VAL, six.string_types): # support single string (the typical case) as well _C.DATA.VAL = (_C.DATA.VAL, ) assert _C.BACKBONE.NORM in ['FreezeBN', 'SyncBN', 'GN', 'None'], _C.BACKBONE.NORM if _C.BACKBONE.NORM != 'FreezeBN': assert not _C.BACKBONE.FREEZE_AFFINE assert _C.BACKBONE.FREEZE_AT in [0, 1, 2] _C.RPN.NUM_ANCHOR = len(_C.RPN.ANCHOR_SIZES) * len(_C.RPN.ANCHOR_RATIOS) assert len(_C.FPN.ANCHOR_STRIDES) == len(_C.RPN.ANCHOR_SIZES) # image size into the backbone has to be multiple of this number _C.FPN.RESOLUTION_REQUIREMENT = _C.FPN.ANCHOR_STRIDES[3] # [3] because we build FPN with features r2,r3,r4,r5 if _C.MODE_FPN: size_mult = _C.FPN.RESOLUTION_REQUIREMENT * 1. _C.PREPROC.MAX_SIZE = np.ceil(_C.PREPROC.MAX_SIZE / size_mult) * size_mult assert _C.FPN.PROPOSAL_MODE in ['Level', 'Joint'] assert _C.FPN.FRCNN_HEAD_FUNC.endswith('_head') assert _C.FPN.MRCNN_HEAD_FUNC.endswith('_head') assert _C.FPN.NORM in ['None', 'GN'] if _C.FPN.CASCADE: # the first threshold is the proposal sampling threshold assert _C.CASCADE.IOUS[0] == _C.FRCNN.FG_THRESH assert len(_C.CASCADE.BBOX_REG_WEIGHTS) == len(_C.CASCADE.IOUS) if is_training: train_scales = _C.PREPROC.TRAIN_SHORT_EDGE_SIZE if isinstance(train_scales, (list, tuple)) and train_scales[1] - train_scales[0] > 100: # don't autotune if augmentation is on os.environ['TF_CUDNN_USE_AUTOTUNE'] = '0' os.environ['TF_AUTOTUNE_THRESHOLD'] = '1' assert _C.TRAINER in ['horovod', 'replicated'], _C.TRAINER # setup NUM_GPUS if _C.TRAINER == 'horovod': import horovod.tensorflow as hvd ngpu = hvd.size() if ngpu == hvd.local_size(): logger.warn("It's not recommended to use horovod for single-machine training. " "Replicated trainer is more stable and has the same efficiency.") else: assert 'OMPI_COMM_WORLD_SIZE' not in os.environ ngpu = get_num_gpu() assert ngpu > 0, "Has to train with GPU!" assert ngpu % 8 == 0 or 8 % ngpu == 0, "Can only train with 1,2,4 or >=8 GPUs, but found {} GPUs".format(ngpu) else: # autotune is too slow for inference os.environ['TF_CUDNN_USE_AUTOTUNE'] = '0' ngpu = get_num_gpu() if _C.TRAIN.NUM_GPUS is None: _C.TRAIN.NUM_GPUS = ngpu else: if _C.TRAINER == 'horovod': assert _C.TRAIN.NUM_GPUS == ngpu else: assert _C.TRAIN.NUM_GPUS <= ngpu _C.freeze() logger.info("Config: ------------------------------------------\n" + str(_C))
[ "def", "finalize_configs", "(", "is_training", ")", ":", "_C", ".", "freeze", "(", "False", ")", "# populate new keys now", "_C", ".", "DATA", ".", "NUM_CLASS", "=", "_C", ".", "DATA", ".", "NUM_CATEGORY", "+", "1", "# +1 background", "_C", ".", "DATA", ".", "BASEDIR", "=", "os", ".", "path", ".", "expanduser", "(", "_C", ".", "DATA", ".", "BASEDIR", ")", "if", "isinstance", "(", "_C", ".", "DATA", ".", "VAL", ",", "six", ".", "string_types", ")", ":", "# support single string (the typical case) as well", "_C", ".", "DATA", ".", "VAL", "=", "(", "_C", ".", "DATA", ".", "VAL", ",", ")", "assert", "_C", ".", "BACKBONE", ".", "NORM", "in", "[", "'FreezeBN'", ",", "'SyncBN'", ",", "'GN'", ",", "'None'", "]", ",", "_C", ".", "BACKBONE", ".", "NORM", "if", "_C", ".", "BACKBONE", ".", "NORM", "!=", "'FreezeBN'", ":", "assert", "not", "_C", ".", "BACKBONE", ".", "FREEZE_AFFINE", "assert", "_C", ".", "BACKBONE", ".", "FREEZE_AT", "in", "[", "0", ",", "1", ",", "2", "]", "_C", ".", "RPN", ".", "NUM_ANCHOR", "=", "len", "(", "_C", ".", "RPN", ".", "ANCHOR_SIZES", ")", "*", "len", "(", "_C", ".", "RPN", ".", "ANCHOR_RATIOS", ")", "assert", "len", "(", "_C", ".", "FPN", ".", "ANCHOR_STRIDES", ")", "==", "len", "(", "_C", ".", "RPN", ".", "ANCHOR_SIZES", ")", "# image size into the backbone has to be multiple of this number", "_C", ".", "FPN", ".", "RESOLUTION_REQUIREMENT", "=", "_C", ".", "FPN", ".", "ANCHOR_STRIDES", "[", "3", "]", "# [3] because we build FPN with features r2,r3,r4,r5", "if", "_C", ".", "MODE_FPN", ":", "size_mult", "=", "_C", ".", "FPN", ".", "RESOLUTION_REQUIREMENT", "*", "1.", "_C", ".", "PREPROC", ".", "MAX_SIZE", "=", "np", ".", "ceil", "(", "_C", ".", "PREPROC", ".", "MAX_SIZE", "/", "size_mult", ")", "*", "size_mult", "assert", "_C", ".", "FPN", ".", "PROPOSAL_MODE", "in", "[", "'Level'", ",", "'Joint'", "]", "assert", "_C", ".", "FPN", ".", "FRCNN_HEAD_FUNC", ".", "endswith", "(", "'_head'", ")", "assert", "_C", ".", "FPN", ".", "MRCNN_HEAD_FUNC", ".", "endswith", "(", "'_head'", ")", "assert", "_C", ".", "FPN", ".", "NORM", "in", "[", "'None'", ",", "'GN'", "]", "if", "_C", ".", "FPN", ".", "CASCADE", ":", "# the first threshold is the proposal sampling threshold", "assert", "_C", ".", "CASCADE", ".", "IOUS", "[", "0", "]", "==", "_C", ".", "FRCNN", ".", "FG_THRESH", "assert", "len", "(", "_C", ".", "CASCADE", ".", "BBOX_REG_WEIGHTS", ")", "==", "len", "(", "_C", ".", "CASCADE", ".", "IOUS", ")", "if", "is_training", ":", "train_scales", "=", "_C", ".", "PREPROC", ".", "TRAIN_SHORT_EDGE_SIZE", "if", "isinstance", "(", "train_scales", ",", "(", "list", ",", "tuple", ")", ")", "and", "train_scales", "[", "1", "]", "-", "train_scales", "[", "0", "]", ">", "100", ":", "# don't autotune if augmentation is on", "os", ".", "environ", "[", "'TF_CUDNN_USE_AUTOTUNE'", "]", "=", "'0'", "os", ".", "environ", "[", "'TF_AUTOTUNE_THRESHOLD'", "]", "=", "'1'", "assert", "_C", ".", "TRAINER", "in", "[", "'horovod'", ",", "'replicated'", "]", ",", "_C", ".", "TRAINER", "# setup NUM_GPUS", "if", "_C", ".", "TRAINER", "==", "'horovod'", ":", "import", "horovod", ".", "tensorflow", "as", "hvd", "ngpu", "=", "hvd", ".", "size", "(", ")", "if", "ngpu", "==", "hvd", ".", "local_size", "(", ")", ":", "logger", ".", "warn", "(", "\"It's not recommended to use horovod for single-machine training. \"", "\"Replicated trainer is more stable and has the same efficiency.\"", ")", "else", ":", "assert", "'OMPI_COMM_WORLD_SIZE'", "not", "in", "os", ".", "environ", "ngpu", "=", "get_num_gpu", "(", ")", "assert", "ngpu", ">", "0", ",", "\"Has to train with GPU!\"", "assert", "ngpu", "%", "8", "==", "0", "or", "8", "%", "ngpu", "==", "0", ",", "\"Can only train with 1,2,4 or >=8 GPUs, but found {} GPUs\"", ".", "format", "(", "ngpu", ")", "else", ":", "# autotune is too slow for inference", "os", ".", "environ", "[", "'TF_CUDNN_USE_AUTOTUNE'", "]", "=", "'0'", "ngpu", "=", "get_num_gpu", "(", ")", "if", "_C", ".", "TRAIN", ".", "NUM_GPUS", "is", "None", ":", "_C", ".", "TRAIN", ".", "NUM_GPUS", "=", "ngpu", "else", ":", "if", "_C", ".", "TRAINER", "==", "'horovod'", ":", "assert", "_C", ".", "TRAIN", ".", "NUM_GPUS", "==", "ngpu", "else", ":", "assert", "_C", ".", "TRAIN", ".", "NUM_GPUS", "<=", "ngpu", "_C", ".", "freeze", "(", ")", "logger", ".", "info", "(", "\"Config: ------------------------------------------\\n\"", "+", "str", "(", "_C", ")", ")" ]
Run some sanity checks, and populate some configs from others
[ "Run", "some", "sanity", "checks", "and", "populate", "some", "configs", "from", "others" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/config.py#L214-L282
train
tensorpack/tensorpack
examples/FasterRCNN/config.py
AttrDict.to_dict
def to_dict(self): """Convert to a nested dict. """ return {k: v.to_dict() if isinstance(v, AttrDict) else v for k, v in self.__dict__.items() if not k.startswith('_')}
python
def to_dict(self): """Convert to a nested dict. """ return {k: v.to_dict() if isinstance(v, AttrDict) else v for k, v in self.__dict__.items() if not k.startswith('_')}
[ "def", "to_dict", "(", "self", ")", ":", "return", "{", "k", ":", "v", ".", "to_dict", "(", ")", "if", "isinstance", "(", "v", ",", "AttrDict", ")", "else", "v", "for", "k", ",", "v", "in", "self", ".", "__dict__", ".", "items", "(", ")", "if", "not", "k", ".", "startswith", "(", "'_'", ")", "}" ]
Convert to a nested dict.
[ "Convert", "to", "a", "nested", "dict", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/config.py#L41-L44
train
tensorpack/tensorpack
examples/FasterRCNN/config.py
AttrDict.update_args
def update_args(self, args): """Update from command line args. """ for cfg in args: keys, v = cfg.split('=', maxsplit=1) keylist = keys.split('.') dic = self for i, k in enumerate(keylist[:-1]): assert k in dir(dic), "Unknown config key: {}".format(keys) dic = getattr(dic, k) key = keylist[-1] oldv = getattr(dic, key) if not isinstance(oldv, str): v = eval(v) setattr(dic, key, v)
python
def update_args(self, args): """Update from command line args. """ for cfg in args: keys, v = cfg.split('=', maxsplit=1) keylist = keys.split('.') dic = self for i, k in enumerate(keylist[:-1]): assert k in dir(dic), "Unknown config key: {}".format(keys) dic = getattr(dic, k) key = keylist[-1] oldv = getattr(dic, key) if not isinstance(oldv, str): v = eval(v) setattr(dic, key, v)
[ "def", "update_args", "(", "self", ",", "args", ")", ":", "for", "cfg", "in", "args", ":", "keys", ",", "v", "=", "cfg", ".", "split", "(", "'='", ",", "maxsplit", "=", "1", ")", "keylist", "=", "keys", ".", "split", "(", "'.'", ")", "dic", "=", "self", "for", "i", ",", "k", "in", "enumerate", "(", "keylist", "[", ":", "-", "1", "]", ")", ":", "assert", "k", "in", "dir", "(", "dic", ")", ",", "\"Unknown config key: {}\"", ".", "format", "(", "keys", ")", "dic", "=", "getattr", "(", "dic", ",", "k", ")", "key", "=", "keylist", "[", "-", "1", "]", "oldv", "=", "getattr", "(", "dic", ",", "key", ")", "if", "not", "isinstance", "(", "oldv", ",", "str", ")", ":", "v", "=", "eval", "(", "v", ")", "setattr", "(", "dic", ",", "key", ",", "v", ")" ]
Update from command line args.
[ "Update", "from", "command", "line", "args", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/config.py#L46-L61
train
tensorpack/tensorpack
tensorpack/tfutils/sessinit.py
get_model_loader
def get_model_loader(filename): """ Get a corresponding model loader by looking at the file name. Returns: SessInit: either a :class:`DictRestore` (if name ends with 'npy/npz') or :class:`SaverRestore` (otherwise). """ assert isinstance(filename, six.string_types), filename filename = os.path.expanduser(filename) if filename.endswith('.npy'): assert tf.gfile.Exists(filename), filename return DictRestore(np.load(filename, encoding='latin1').item()) elif filename.endswith('.npz'): assert tf.gfile.Exists(filename), filename obj = np.load(filename) return DictRestore(dict(obj)) else: return SaverRestore(filename)
python
def get_model_loader(filename): """ Get a corresponding model loader by looking at the file name. Returns: SessInit: either a :class:`DictRestore` (if name ends with 'npy/npz') or :class:`SaverRestore` (otherwise). """ assert isinstance(filename, six.string_types), filename filename = os.path.expanduser(filename) if filename.endswith('.npy'): assert tf.gfile.Exists(filename), filename return DictRestore(np.load(filename, encoding='latin1').item()) elif filename.endswith('.npz'): assert tf.gfile.Exists(filename), filename obj = np.load(filename) return DictRestore(dict(obj)) else: return SaverRestore(filename)
[ "def", "get_model_loader", "(", "filename", ")", ":", "assert", "isinstance", "(", "filename", ",", "six", ".", "string_types", ")", ",", "filename", "filename", "=", "os", ".", "path", ".", "expanduser", "(", "filename", ")", "if", "filename", ".", "endswith", "(", "'.npy'", ")", ":", "assert", "tf", ".", "gfile", ".", "Exists", "(", "filename", ")", ",", "filename", "return", "DictRestore", "(", "np", ".", "load", "(", "filename", ",", "encoding", "=", "'latin1'", ")", ".", "item", "(", ")", ")", "elif", "filename", ".", "endswith", "(", "'.npz'", ")", ":", "assert", "tf", ".", "gfile", ".", "Exists", "(", "filename", ")", ",", "filename", "obj", "=", "np", ".", "load", "(", "filename", ")", "return", "DictRestore", "(", "dict", "(", "obj", ")", ")", "else", ":", "return", "SaverRestore", "(", "filename", ")" ]
Get a corresponding model loader by looking at the file name. Returns: SessInit: either a :class:`DictRestore` (if name ends with 'npy/npz') or :class:`SaverRestore` (otherwise).
[ "Get", "a", "corresponding", "model", "loader", "by", "looking", "at", "the", "file", "name", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/sessinit.py#L245-L263
train
tensorpack/tensorpack
tensorpack/tfutils/sessinit.py
SaverRestore._read_checkpoint_vars
def _read_checkpoint_vars(model_path): """ return a set of strings """ reader = tf.train.NewCheckpointReader(model_path) reader = CheckpointReaderAdapter(reader) # use an adapter to standardize the name ckpt_vars = reader.get_variable_to_shape_map().keys() return reader, set(ckpt_vars)
python
def _read_checkpoint_vars(model_path): """ return a set of strings """ reader = tf.train.NewCheckpointReader(model_path) reader = CheckpointReaderAdapter(reader) # use an adapter to standardize the name ckpt_vars = reader.get_variable_to_shape_map().keys() return reader, set(ckpt_vars)
[ "def", "_read_checkpoint_vars", "(", "model_path", ")", ":", "reader", "=", "tf", ".", "train", ".", "NewCheckpointReader", "(", "model_path", ")", "reader", "=", "CheckpointReaderAdapter", "(", "reader", ")", "# use an adapter to standardize the name", "ckpt_vars", "=", "reader", ".", "get_variable_to_shape_map", "(", ")", ".", "keys", "(", ")", "return", "reader", ",", "set", "(", "ckpt_vars", ")" ]
return a set of strings
[ "return", "a", "set", "of", "strings" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/sessinit.py#L118-L123
train
tensorpack/tensorpack
tensorpack/tfutils/argscope.py
argscope
def argscope(layers, **kwargs): """ Args: layers (list or layer): layer or list of layers to apply the arguments. Returns: a context where all appearance of these layer will by default have the arguments specified by kwargs. Example: .. code-block:: python with argscope(Conv2D, kernel_shape=3, nl=tf.nn.relu, out_channel=32): x = Conv2D('conv0', x) x = Conv2D('conv1', x) x = Conv2D('conv2', x, out_channel=64) # override argscope """ if not isinstance(layers, list): layers = [layers] # def _check_args_exist(l): # args = inspect.getargspec(l).args # for k, v in six.iteritems(kwargs): # assert k in args, "No argument {} in {}".format(k, l.__name__) for l in layers: assert hasattr(l, 'symbolic_function'), "{} is not a registered layer".format(l.__name__) # _check_args_exist(l.symbolic_function) new_scope = copy.copy(get_arg_scope()) for l in layers: new_scope[l.__name__].update(kwargs) _ArgScopeStack.append(new_scope) yield del _ArgScopeStack[-1]
python
def argscope(layers, **kwargs): """ Args: layers (list or layer): layer or list of layers to apply the arguments. Returns: a context where all appearance of these layer will by default have the arguments specified by kwargs. Example: .. code-block:: python with argscope(Conv2D, kernel_shape=3, nl=tf.nn.relu, out_channel=32): x = Conv2D('conv0', x) x = Conv2D('conv1', x) x = Conv2D('conv2', x, out_channel=64) # override argscope """ if not isinstance(layers, list): layers = [layers] # def _check_args_exist(l): # args = inspect.getargspec(l).args # for k, v in six.iteritems(kwargs): # assert k in args, "No argument {} in {}".format(k, l.__name__) for l in layers: assert hasattr(l, 'symbolic_function'), "{} is not a registered layer".format(l.__name__) # _check_args_exist(l.symbolic_function) new_scope = copy.copy(get_arg_scope()) for l in layers: new_scope[l.__name__].update(kwargs) _ArgScopeStack.append(new_scope) yield del _ArgScopeStack[-1]
[ "def", "argscope", "(", "layers", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "layers", ",", "list", ")", ":", "layers", "=", "[", "layers", "]", "# def _check_args_exist(l):", "# args = inspect.getargspec(l).args", "# for k, v in six.iteritems(kwargs):", "# assert k in args, \"No argument {} in {}\".format(k, l.__name__)", "for", "l", "in", "layers", ":", "assert", "hasattr", "(", "l", ",", "'symbolic_function'", ")", ",", "\"{} is not a registered layer\"", ".", "format", "(", "l", ".", "__name__", ")", "# _check_args_exist(l.symbolic_function)", "new_scope", "=", "copy", ".", "copy", "(", "get_arg_scope", "(", ")", ")", "for", "l", "in", "layers", ":", "new_scope", "[", "l", ".", "__name__", "]", ".", "update", "(", "kwargs", ")", "_ArgScopeStack", ".", "append", "(", "new_scope", ")", "yield", "del", "_ArgScopeStack", "[", "-", "1", "]" ]
Args: layers (list or layer): layer or list of layers to apply the arguments. Returns: a context where all appearance of these layer will by default have the arguments specified by kwargs. Example: .. code-block:: python with argscope(Conv2D, kernel_shape=3, nl=tf.nn.relu, out_channel=32): x = Conv2D('conv0', x) x = Conv2D('conv1', x) x = Conv2D('conv2', x, out_channel=64) # override argscope
[ "Args", ":", "layers", "(", "list", "or", "layer", ")", ":", "layer", "or", "list", "of", "layers", "to", "apply", "the", "arguments", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/argscope.py#L22-L57
train
tensorpack/tensorpack
tensorpack/tfutils/argscope.py
enable_argscope_for_function
def enable_argscope_for_function(func, log_shape=True): """Decorator for function to support argscope Example: .. code-block:: python from mylib import myfunc myfunc = enable_argscope_for_function(myfunc) Args: func: A function mapping one or multiple tensors to one or multiple tensors. log_shape (bool): Specify whether the first input resp. output tensor shape should be printed once. Remarks: If the function ``func`` returns multiple input or output tensors, only the first input/output tensor shape is displayed during logging. Returns: The decorated function. """ assert callable(func), "func should be a callable" @wraps(func) def wrapped_func(*args, **kwargs): actual_args = copy.copy(get_arg_scope()[func.__name__]) actual_args.update(kwargs) out_tensor = func(*args, **actual_args) in_tensor = args[0] ctx = get_current_tower_context() name = func.__name__ if 'name' not in kwargs else kwargs['name'] if log_shape: if ('tower' not in ctx.ns_name.lower()) or ctx.is_main_training_tower: # we assume the first parameter is the most interesting if isinstance(out_tensor, tuple): out_tensor_descr = out_tensor[0] else: out_tensor_descr = out_tensor logger.info('%20s: %20s -> %20s' % (name, in_tensor.shape.as_list(), out_tensor_descr.shape.as_list())) return out_tensor # argscope requires this property wrapped_func.symbolic_function = None return wrapped_func
python
def enable_argscope_for_function(func, log_shape=True): """Decorator for function to support argscope Example: .. code-block:: python from mylib import myfunc myfunc = enable_argscope_for_function(myfunc) Args: func: A function mapping one or multiple tensors to one or multiple tensors. log_shape (bool): Specify whether the first input resp. output tensor shape should be printed once. Remarks: If the function ``func`` returns multiple input or output tensors, only the first input/output tensor shape is displayed during logging. Returns: The decorated function. """ assert callable(func), "func should be a callable" @wraps(func) def wrapped_func(*args, **kwargs): actual_args = copy.copy(get_arg_scope()[func.__name__]) actual_args.update(kwargs) out_tensor = func(*args, **actual_args) in_tensor = args[0] ctx = get_current_tower_context() name = func.__name__ if 'name' not in kwargs else kwargs['name'] if log_shape: if ('tower' not in ctx.ns_name.lower()) or ctx.is_main_training_tower: # we assume the first parameter is the most interesting if isinstance(out_tensor, tuple): out_tensor_descr = out_tensor[0] else: out_tensor_descr = out_tensor logger.info('%20s: %20s -> %20s' % (name, in_tensor.shape.as_list(), out_tensor_descr.shape.as_list())) return out_tensor # argscope requires this property wrapped_func.symbolic_function = None return wrapped_func
[ "def", "enable_argscope_for_function", "(", "func", ",", "log_shape", "=", "True", ")", ":", "assert", "callable", "(", "func", ")", ",", "\"func should be a callable\"", "@", "wraps", "(", "func", ")", "def", "wrapped_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "actual_args", "=", "copy", ".", "copy", "(", "get_arg_scope", "(", ")", "[", "func", ".", "__name__", "]", ")", "actual_args", ".", "update", "(", "kwargs", ")", "out_tensor", "=", "func", "(", "*", "args", ",", "*", "*", "actual_args", ")", "in_tensor", "=", "args", "[", "0", "]", "ctx", "=", "get_current_tower_context", "(", ")", "name", "=", "func", ".", "__name__", "if", "'name'", "not", "in", "kwargs", "else", "kwargs", "[", "'name'", "]", "if", "log_shape", ":", "if", "(", "'tower'", "not", "in", "ctx", ".", "ns_name", ".", "lower", "(", ")", ")", "or", "ctx", ".", "is_main_training_tower", ":", "# we assume the first parameter is the most interesting", "if", "isinstance", "(", "out_tensor", ",", "tuple", ")", ":", "out_tensor_descr", "=", "out_tensor", "[", "0", "]", "else", ":", "out_tensor_descr", "=", "out_tensor", "logger", ".", "info", "(", "'%20s: %20s -> %20s'", "%", "(", "name", ",", "in_tensor", ".", "shape", ".", "as_list", "(", ")", ",", "out_tensor_descr", ".", "shape", ".", "as_list", "(", ")", ")", ")", "return", "out_tensor", "# argscope requires this property", "wrapped_func", ".", "symbolic_function", "=", "None", "return", "wrapped_func" ]
Decorator for function to support argscope Example: .. code-block:: python from mylib import myfunc myfunc = enable_argscope_for_function(myfunc) Args: func: A function mapping one or multiple tensors to one or multiple tensors. log_shape (bool): Specify whether the first input resp. output tensor shape should be printed once. Remarks: If the function ``func`` returns multiple input or output tensors, only the first input/output tensor shape is displayed during logging. Returns: The decorated function.
[ "Decorator", "for", "function", "to", "support", "argscope" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/argscope.py#L73-L123
train
tensorpack/tensorpack
tensorpack/tfutils/argscope.py
enable_argscope_for_module
def enable_argscope_for_module(module, log_shape=True): """ Overwrite all functions of a given module to support argscope. Note that this function monkey-patches the module and therefore could have unexpected consequences. It has been only tested to work well with ``tf.layers`` module. Example: .. code-block:: python import tensorflow as tf enable_argscope_for_module(tf.layers) Args: log_shape (bool): print input/output shapes of each function. """ if is_tfv2() and module == tf.layers: module = tf.compat.v1.layers for name, obj in getmembers(module): if isfunction(obj): setattr(module, name, enable_argscope_for_function(obj, log_shape=log_shape))
python
def enable_argscope_for_module(module, log_shape=True): """ Overwrite all functions of a given module to support argscope. Note that this function monkey-patches the module and therefore could have unexpected consequences. It has been only tested to work well with ``tf.layers`` module. Example: .. code-block:: python import tensorflow as tf enable_argscope_for_module(tf.layers) Args: log_shape (bool): print input/output shapes of each function. """ if is_tfv2() and module == tf.layers: module = tf.compat.v1.layers for name, obj in getmembers(module): if isfunction(obj): setattr(module, name, enable_argscope_for_function(obj, log_shape=log_shape))
[ "def", "enable_argscope_for_module", "(", "module", ",", "log_shape", "=", "True", ")", ":", "if", "is_tfv2", "(", ")", "and", "module", "==", "tf", ".", "layers", ":", "module", "=", "tf", ".", "compat", ".", "v1", ".", "layers", "for", "name", ",", "obj", "in", "getmembers", "(", "module", ")", ":", "if", "isfunction", "(", "obj", ")", ":", "setattr", "(", "module", ",", "name", ",", "enable_argscope_for_function", "(", "obj", ",", "log_shape", "=", "log_shape", ")", ")" ]
Overwrite all functions of a given module to support argscope. Note that this function monkey-patches the module and therefore could have unexpected consequences. It has been only tested to work well with ``tf.layers`` module. Example: .. code-block:: python import tensorflow as tf enable_argscope_for_module(tf.layers) Args: log_shape (bool): print input/output shapes of each function.
[ "Overwrite", "all", "functions", "of", "a", "given", "module", "to", "support", "argscope", ".", "Note", "that", "this", "function", "monkey", "-", "patches", "the", "module", "and", "therefore", "could", "have", "unexpected", "consequences", ".", "It", "has", "been", "only", "tested", "to", "work", "well", "with", "tf", ".", "layers", "module", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/argscope.py#L126-L148
train
tensorpack/tensorpack
examples/GAN/Image2Image.py
visualize_tensors
def visualize_tensors(name, imgs, scale_func=lambda x: (x + 1.) * 128., max_outputs=1): """Generate tensor for TensorBoard (casting, clipping) Args: name: name for visualization operation *imgs: multiple tensors as list scale_func: scale input tensors to fit range [0, 255] Example: visualize_tensors('viz1', [img1]) visualize_tensors('viz2', [img1, img2, img3], max_outputs=max(30, BATCH)) """ xy = scale_func(tf.concat(imgs, axis=2)) xy = tf.cast(tf.clip_by_value(xy, 0, 255), tf.uint8, name='viz') tf.summary.image(name, xy, max_outputs=30)
python
def visualize_tensors(name, imgs, scale_func=lambda x: (x + 1.) * 128., max_outputs=1): """Generate tensor for TensorBoard (casting, clipping) Args: name: name for visualization operation *imgs: multiple tensors as list scale_func: scale input tensors to fit range [0, 255] Example: visualize_tensors('viz1', [img1]) visualize_tensors('viz2', [img1, img2, img3], max_outputs=max(30, BATCH)) """ xy = scale_func(tf.concat(imgs, axis=2)) xy = tf.cast(tf.clip_by_value(xy, 0, 255), tf.uint8, name='viz') tf.summary.image(name, xy, max_outputs=30)
[ "def", "visualize_tensors", "(", "name", ",", "imgs", ",", "scale_func", "=", "lambda", "x", ":", "(", "x", "+", "1.", ")", "*", "128.", ",", "max_outputs", "=", "1", ")", ":", "xy", "=", "scale_func", "(", "tf", ".", "concat", "(", "imgs", ",", "axis", "=", "2", ")", ")", "xy", "=", "tf", ".", "cast", "(", "tf", ".", "clip_by_value", "(", "xy", ",", "0", ",", "255", ")", ",", "tf", ".", "uint8", ",", "name", "=", "'viz'", ")", "tf", ".", "summary", ".", "image", "(", "name", ",", "xy", ",", "max_outputs", "=", "30", ")" ]
Generate tensor for TensorBoard (casting, clipping) Args: name: name for visualization operation *imgs: multiple tensors as list scale_func: scale input tensors to fit range [0, 255] Example: visualize_tensors('viz1', [img1]) visualize_tensors('viz2', [img1, img2, img3], max_outputs=max(30, BATCH))
[ "Generate", "tensor", "for", "TensorBoard", "(", "casting", "clipping", ")" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/Image2Image.py#L46-L60
train
tensorpack/tensorpack
examples/GAN/Image2Image.py
split_input
def split_input(img): """ img: an RGB image of shape (s, 2s, 3). :return: [input, output] """ # split the image into left + right pairs s = img.shape[0] assert img.shape[1] == 2 * s input, output = img[:, :s, :], img[:, s:, :] if args.mode == 'BtoA': input, output = output, input if IN_CH == 1: input = cv2.cvtColor(input, cv2.COLOR_RGB2GRAY)[:, :, np.newaxis] if OUT_CH == 1: output = cv2.cvtColor(output, cv2.COLOR_RGB2GRAY)[:, :, np.newaxis] return [input, output]
python
def split_input(img): """ img: an RGB image of shape (s, 2s, 3). :return: [input, output] """ # split the image into left + right pairs s = img.shape[0] assert img.shape[1] == 2 * s input, output = img[:, :s, :], img[:, s:, :] if args.mode == 'BtoA': input, output = output, input if IN_CH == 1: input = cv2.cvtColor(input, cv2.COLOR_RGB2GRAY)[:, :, np.newaxis] if OUT_CH == 1: output = cv2.cvtColor(output, cv2.COLOR_RGB2GRAY)[:, :, np.newaxis] return [input, output]
[ "def", "split_input", "(", "img", ")", ":", "# split the image into left + right pairs", "s", "=", "img", ".", "shape", "[", "0", "]", "assert", "img", ".", "shape", "[", "1", "]", "==", "2", "*", "s", "input", ",", "output", "=", "img", "[", ":", ",", ":", "s", ",", ":", "]", ",", "img", "[", ":", ",", "s", ":", ",", ":", "]", "if", "args", ".", "mode", "==", "'BtoA'", ":", "input", ",", "output", "=", "output", ",", "input", "if", "IN_CH", "==", "1", ":", "input", "=", "cv2", ".", "cvtColor", "(", "input", ",", "cv2", ".", "COLOR_RGB2GRAY", ")", "[", ":", ",", ":", ",", "np", ".", "newaxis", "]", "if", "OUT_CH", "==", "1", ":", "output", "=", "cv2", ".", "cvtColor", "(", "output", ",", "cv2", ".", "COLOR_RGB2GRAY", ")", "[", ":", ",", ":", ",", "np", ".", "newaxis", "]", "return", "[", "input", ",", "output", "]" ]
img: an RGB image of shape (s, 2s, 3). :return: [input, output]
[ "img", ":", "an", "RGB", "image", "of", "shape", "(", "s", "2s", "3", ")", ".", ":", "return", ":", "[", "input", "output", "]" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/Image2Image.py#L149-L164
train
tensorpack/tensorpack
examples/GAN/Image2Image.py
Model.discriminator
def discriminator(self, inputs, outputs): """ return a (b, 1) logits""" l = tf.concat([inputs, outputs], 3) with argscope(Conv2D, kernel_size=4, strides=2, activation=BNLReLU): l = (LinearWrap(l) .Conv2D('conv0', NF, activation=tf.nn.leaky_relu) .Conv2D('conv1', NF * 2) .Conv2D('conv2', NF * 4) .Conv2D('conv3', NF * 8, strides=1, padding='VALID') .Conv2D('convlast', 1, strides=1, padding='VALID', activation=tf.identity)()) return l
python
def discriminator(self, inputs, outputs): """ return a (b, 1) logits""" l = tf.concat([inputs, outputs], 3) with argscope(Conv2D, kernel_size=4, strides=2, activation=BNLReLU): l = (LinearWrap(l) .Conv2D('conv0', NF, activation=tf.nn.leaky_relu) .Conv2D('conv1', NF * 2) .Conv2D('conv2', NF * 4) .Conv2D('conv3', NF * 8, strides=1, padding='VALID') .Conv2D('convlast', 1, strides=1, padding='VALID', activation=tf.identity)()) return l
[ "def", "discriminator", "(", "self", ",", "inputs", ",", "outputs", ")", ":", "l", "=", "tf", ".", "concat", "(", "[", "inputs", ",", "outputs", "]", ",", "3", ")", "with", "argscope", "(", "Conv2D", ",", "kernel_size", "=", "4", ",", "strides", "=", "2", ",", "activation", "=", "BNLReLU", ")", ":", "l", "=", "(", "LinearWrap", "(", "l", ")", ".", "Conv2D", "(", "'conv0'", ",", "NF", ",", "activation", "=", "tf", ".", "nn", ".", "leaky_relu", ")", ".", "Conv2D", "(", "'conv1'", ",", "NF", "*", "2", ")", ".", "Conv2D", "(", "'conv2'", ",", "NF", "*", "4", ")", ".", "Conv2D", "(", "'conv3'", ",", "NF", "*", "8", ",", "strides", "=", "1", ",", "padding", "=", "'VALID'", ")", ".", "Conv2D", "(", "'convlast'", ",", "1", ",", "strides", "=", "1", ",", "padding", "=", "'VALID'", ",", "activation", "=", "tf", ".", "identity", ")", "(", ")", ")", "return", "l" ]
return a (b, 1) logits
[ "return", "a", "(", "b", "1", ")", "logits" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/Image2Image.py#L106-L116
train
tensorpack/tensorpack
tensorpack/tfutils/symbolic_functions.py
print_stat
def print_stat(x, message=None): """ A simple print Op that might be easier to use than :meth:`tf.Print`. Use it like: ``x = print_stat(x, message='This is x')``. """ if message is None: message = x.op.name lst = [tf.shape(x), tf.reduce_mean(x)] if x.dtype.is_floating: lst.append(rms(x)) return tf.Print(x, lst + [x], summarize=20, message=message, name='print_' + x.op.name)
python
def print_stat(x, message=None): """ A simple print Op that might be easier to use than :meth:`tf.Print`. Use it like: ``x = print_stat(x, message='This is x')``. """ if message is None: message = x.op.name lst = [tf.shape(x), tf.reduce_mean(x)] if x.dtype.is_floating: lst.append(rms(x)) return tf.Print(x, lst + [x], summarize=20, message=message, name='print_' + x.op.name)
[ "def", "print_stat", "(", "x", ",", "message", "=", "None", ")", ":", "if", "message", "is", "None", ":", "message", "=", "x", ".", "op", ".", "name", "lst", "=", "[", "tf", ".", "shape", "(", "x", ")", ",", "tf", ".", "reduce_mean", "(", "x", ")", "]", "if", "x", ".", "dtype", ".", "is_floating", ":", "lst", ".", "append", "(", "rms", "(", "x", ")", ")", "return", "tf", ".", "Print", "(", "x", ",", "lst", "+", "[", "x", "]", ",", "summarize", "=", "20", ",", "message", "=", "message", ",", "name", "=", "'print_'", "+", "x", ".", "op", ".", "name", ")" ]
A simple print Op that might be easier to use than :meth:`tf.Print`. Use it like: ``x = print_stat(x, message='This is x')``.
[ "A", "simple", "print", "Op", "that", "might", "be", "easier", "to", "use", "than", ":", "meth", ":", "tf", ".", "Print", ".", "Use", "it", "like", ":", "x", "=", "print_stat", "(", "x", "message", "=", "This", "is", "x", ")", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/symbolic_functions.py#L13-L23
train
tensorpack/tensorpack
tensorpack/tfutils/symbolic_functions.py
rms
def rms(x, name=None): """ Returns: root mean square of tensor x. """ if name is None: name = x.op.name + '/rms' with tfv1.name_scope(None): # name already contains the scope return tf.sqrt(tf.reduce_mean(tf.square(x)), name=name) return tf.sqrt(tf.reduce_mean(tf.square(x)), name=name)
python
def rms(x, name=None): """ Returns: root mean square of tensor x. """ if name is None: name = x.op.name + '/rms' with tfv1.name_scope(None): # name already contains the scope return tf.sqrt(tf.reduce_mean(tf.square(x)), name=name) return tf.sqrt(tf.reduce_mean(tf.square(x)), name=name)
[ "def", "rms", "(", "x", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "x", ".", "op", ".", "name", "+", "'/rms'", "with", "tfv1", ".", "name_scope", "(", "None", ")", ":", "# name already contains the scope", "return", "tf", ".", "sqrt", "(", "tf", ".", "reduce_mean", "(", "tf", ".", "square", "(", "x", ")", ")", ",", "name", "=", "name", ")", "return", "tf", ".", "sqrt", "(", "tf", ".", "reduce_mean", "(", "tf", ".", "square", "(", "x", ")", ")", ",", "name", "=", "name", ")" ]
Returns: root mean square of tensor x.
[ "Returns", ":", "root", "mean", "square", "of", "tensor", "x", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/symbolic_functions.py#L27-L36
train
tensorpack/tensorpack
tensorpack/tfutils/symbolic_functions.py
psnr
def psnr(prediction, ground_truth, maxp=None, name='psnr'): """`Peek Signal to Noise Ratio <https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio>`_. .. math:: PSNR = 20 \cdot \log_{10}(MAX_p) - 10 \cdot \log_{10}(MSE) Args: prediction: a :class:`tf.Tensor` representing the prediction signal. ground_truth: another :class:`tf.Tensor` with the same shape. maxp: maximum possible pixel value of the image (255 in in 8bit images) Returns: A scalar tensor representing the PSNR """ maxp = float(maxp) def log10(x): with tf.name_scope("log10"): numerator = tf.log(x) denominator = tf.log(tf.constant(10, dtype=numerator.dtype)) return numerator / denominator mse = tf.reduce_mean(tf.square(prediction - ground_truth)) if maxp is None: psnr = tf.multiply(log10(mse), -10., name=name) else: psnr = tf.multiply(log10(mse), -10.) psnr = tf.add(tf.multiply(20., log10(maxp)), psnr, name=name) return psnr
python
def psnr(prediction, ground_truth, maxp=None, name='psnr'): """`Peek Signal to Noise Ratio <https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio>`_. .. math:: PSNR = 20 \cdot \log_{10}(MAX_p) - 10 \cdot \log_{10}(MSE) Args: prediction: a :class:`tf.Tensor` representing the prediction signal. ground_truth: another :class:`tf.Tensor` with the same shape. maxp: maximum possible pixel value of the image (255 in in 8bit images) Returns: A scalar tensor representing the PSNR """ maxp = float(maxp) def log10(x): with tf.name_scope("log10"): numerator = tf.log(x) denominator = tf.log(tf.constant(10, dtype=numerator.dtype)) return numerator / denominator mse = tf.reduce_mean(tf.square(prediction - ground_truth)) if maxp is None: psnr = tf.multiply(log10(mse), -10., name=name) else: psnr = tf.multiply(log10(mse), -10.) psnr = tf.add(tf.multiply(20., log10(maxp)), psnr, name=name) return psnr
[ "def", "psnr", "(", "prediction", ",", "ground_truth", ",", "maxp", "=", "None", ",", "name", "=", "'psnr'", ")", ":", "maxp", "=", "float", "(", "maxp", ")", "def", "log10", "(", "x", ")", ":", "with", "tf", ".", "name_scope", "(", "\"log10\"", ")", ":", "numerator", "=", "tf", ".", "log", "(", "x", ")", "denominator", "=", "tf", ".", "log", "(", "tf", ".", "constant", "(", "10", ",", "dtype", "=", "numerator", ".", "dtype", ")", ")", "return", "numerator", "/", "denominator", "mse", "=", "tf", ".", "reduce_mean", "(", "tf", ".", "square", "(", "prediction", "-", "ground_truth", ")", ")", "if", "maxp", "is", "None", ":", "psnr", "=", "tf", ".", "multiply", "(", "log10", "(", "mse", ")", ",", "-", "10.", ",", "name", "=", "name", ")", "else", ":", "psnr", "=", "tf", ".", "multiply", "(", "log10", "(", "mse", ")", ",", "-", "10.", ")", "psnr", "=", "tf", ".", "add", "(", "tf", ".", "multiply", "(", "20.", ",", "log10", "(", "maxp", ")", ")", ",", "psnr", ",", "name", "=", "name", ")", "return", "psnr" ]
`Peek Signal to Noise Ratio <https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio>`_. .. math:: PSNR = 20 \cdot \log_{10}(MAX_p) - 10 \cdot \log_{10}(MSE) Args: prediction: a :class:`tf.Tensor` representing the prediction signal. ground_truth: another :class:`tf.Tensor` with the same shape. maxp: maximum possible pixel value of the image (255 in in 8bit images) Returns: A scalar tensor representing the PSNR
[ "Peek", "Signal", "to", "Noise", "Ratio", "<https", ":", "//", "en", ".", "wikipedia", ".", "org", "/", "wiki", "/", "Peak_signal", "-", "to", "-", "noise_ratio", ">", "_", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/symbolic_functions.py#L41-L72
train
tensorpack/tensorpack
tensorpack/dataflow/imgaug/deform.py
GaussianMap.get_gaussian_weight
def get_gaussian_weight(self, anchor): """ Args: anchor: coordinate of the center """ ret = np.zeros(self.shape, dtype='float32') y, x = np.mgrid[:self.shape[0], :self.shape[1]] y = y.astype('float32') / ret.shape[0] - anchor[0] x = x.astype('float32') / ret.shape[1] - anchor[1] g = np.exp(-(x**2 + y ** 2) / self.sigma) # cv2.imshow(" ", g) # cv2.waitKey() return g
python
def get_gaussian_weight(self, anchor): """ Args: anchor: coordinate of the center """ ret = np.zeros(self.shape, dtype='float32') y, x = np.mgrid[:self.shape[0], :self.shape[1]] y = y.astype('float32') / ret.shape[0] - anchor[0] x = x.astype('float32') / ret.shape[1] - anchor[1] g = np.exp(-(x**2 + y ** 2) / self.sigma) # cv2.imshow(" ", g) # cv2.waitKey() return g
[ "def", "get_gaussian_weight", "(", "self", ",", "anchor", ")", ":", "ret", "=", "np", ".", "zeros", "(", "self", ".", "shape", ",", "dtype", "=", "'float32'", ")", "y", ",", "x", "=", "np", ".", "mgrid", "[", ":", "self", ".", "shape", "[", "0", "]", ",", ":", "self", ".", "shape", "[", "1", "]", "]", "y", "=", "y", ".", "astype", "(", "'float32'", ")", "/", "ret", ".", "shape", "[", "0", "]", "-", "anchor", "[", "0", "]", "x", "=", "x", ".", "astype", "(", "'float32'", ")", "/", "ret", ".", "shape", "[", "1", "]", "-", "anchor", "[", "1", "]", "g", "=", "np", ".", "exp", "(", "-", "(", "x", "**", "2", "+", "y", "**", "2", ")", "/", "self", ".", "sigma", ")", "# cv2.imshow(\" \", g)", "# cv2.waitKey()", "return", "g" ]
Args: anchor: coordinate of the center
[ "Args", ":", "anchor", ":", "coordinate", "of", "the", "center" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/imgaug/deform.py#L26-L39
train
tensorpack/tensorpack
examples/OpticalFlow/flownet_models.py
pad
def pad(x, p=3): """Pad tensor in H, W Remarks: TensorFlow uses "ceil(input_spatial_shape[i] / strides[i])" rather than explicit padding like Caffe, pyTorch does. Hence, we need to pad here beforehand. Args: x (tf.tensor): incoming tensor p (int, optional): padding for H, W Returns: tf.tensor: padded tensor """ return tf.pad(x, [[0, 0], [0, 0], [p, p], [p, p]])
python
def pad(x, p=3): """Pad tensor in H, W Remarks: TensorFlow uses "ceil(input_spatial_shape[i] / strides[i])" rather than explicit padding like Caffe, pyTorch does. Hence, we need to pad here beforehand. Args: x (tf.tensor): incoming tensor p (int, optional): padding for H, W Returns: tf.tensor: padded tensor """ return tf.pad(x, [[0, 0], [0, 0], [p, p], [p, p]])
[ "def", "pad", "(", "x", ",", "p", "=", "3", ")", ":", "return", "tf", ".", "pad", "(", "x", ",", "[", "[", "0", ",", "0", "]", ",", "[", "0", ",", "0", "]", ",", "[", "p", ",", "p", "]", ",", "[", "p", ",", "p", "]", "]", ")" ]
Pad tensor in H, W Remarks: TensorFlow uses "ceil(input_spatial_shape[i] / strides[i])" rather than explicit padding like Caffe, pyTorch does. Hence, we need to pad here beforehand. Args: x (tf.tensor): incoming tensor p (int, optional): padding for H, W Returns: tf.tensor: padded tensor
[ "Pad", "tensor", "in", "H", "W" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/OpticalFlow/flownet_models.py#L17-L31
train
tensorpack/tensorpack
examples/OpticalFlow/flownet_models.py
correlation
def correlation(ina, inb, kernel_size, max_displacement, stride_1, stride_2, pad, data_format): """ Correlation Cost Volume computation. This is a fallback Python-only implementation, specialized just for FlowNet2. It takes a lot of memory and is slow. If you know to compile a custom op yourself, it's better to use the cuda implementation here: https://github.com/PatWie/tensorflow-recipes/tree/master/OpticalFlow/user_ops """ assert pad == max_displacement assert kernel_size == 1 assert data_format == 'NCHW' assert max_displacement % stride_2 == 0 assert stride_1 == 1 D = int(max_displacement / stride_2 * 2) + 1 # D^2 == number of correlations per spatial location b, c, h, w = ina.shape.as_list() inb = tf.pad(inb, [[0, 0], [0, 0], [pad, pad], [pad, pad]]) res = [] for k1 in range(0, D): start_h = k1 * stride_2 for k2 in range(0, D): start_w = k2 * stride_2 s = tf.slice(inb, [0, 0, start_h, start_w], [-1, -1, h, w]) ans = tf.reduce_mean(ina * s, axis=1, keepdims=True) res.append(ans) res = tf.concat(res, axis=1) # ND^2HW return res
python
def correlation(ina, inb, kernel_size, max_displacement, stride_1, stride_2, pad, data_format): """ Correlation Cost Volume computation. This is a fallback Python-only implementation, specialized just for FlowNet2. It takes a lot of memory and is slow. If you know to compile a custom op yourself, it's better to use the cuda implementation here: https://github.com/PatWie/tensorflow-recipes/tree/master/OpticalFlow/user_ops """ assert pad == max_displacement assert kernel_size == 1 assert data_format == 'NCHW' assert max_displacement % stride_2 == 0 assert stride_1 == 1 D = int(max_displacement / stride_2 * 2) + 1 # D^2 == number of correlations per spatial location b, c, h, w = ina.shape.as_list() inb = tf.pad(inb, [[0, 0], [0, 0], [pad, pad], [pad, pad]]) res = [] for k1 in range(0, D): start_h = k1 * stride_2 for k2 in range(0, D): start_w = k2 * stride_2 s = tf.slice(inb, [0, 0, start_h, start_w], [-1, -1, h, w]) ans = tf.reduce_mean(ina * s, axis=1, keepdims=True) res.append(ans) res = tf.concat(res, axis=1) # ND^2HW return res
[ "def", "correlation", "(", "ina", ",", "inb", ",", "kernel_size", ",", "max_displacement", ",", "stride_1", ",", "stride_2", ",", "pad", ",", "data_format", ")", ":", "assert", "pad", "==", "max_displacement", "assert", "kernel_size", "==", "1", "assert", "data_format", "==", "'NCHW'", "assert", "max_displacement", "%", "stride_2", "==", "0", "assert", "stride_1", "==", "1", "D", "=", "int", "(", "max_displacement", "/", "stride_2", "*", "2", ")", "+", "1", "# D^2 == number of correlations per spatial location", "b", ",", "c", ",", "h", ",", "w", "=", "ina", ".", "shape", ".", "as_list", "(", ")", "inb", "=", "tf", ".", "pad", "(", "inb", ",", "[", "[", "0", ",", "0", "]", ",", "[", "0", ",", "0", "]", ",", "[", "pad", ",", "pad", "]", ",", "[", "pad", ",", "pad", "]", "]", ")", "res", "=", "[", "]", "for", "k1", "in", "range", "(", "0", ",", "D", ")", ":", "start_h", "=", "k1", "*", "stride_2", "for", "k2", "in", "range", "(", "0", ",", "D", ")", ":", "start_w", "=", "k2", "*", "stride_2", "s", "=", "tf", ".", "slice", "(", "inb", ",", "[", "0", ",", "0", ",", "start_h", ",", "start_w", "]", ",", "[", "-", "1", ",", "-", "1", ",", "h", ",", "w", "]", ")", "ans", "=", "tf", ".", "reduce_mean", "(", "ina", "*", "s", ",", "axis", "=", "1", ",", "keepdims", "=", "True", ")", "res", ".", "append", "(", "ans", ")", "res", "=", "tf", ".", "concat", "(", "res", ",", "axis", "=", "1", ")", "# ND^2HW", "return", "res" ]
Correlation Cost Volume computation. This is a fallback Python-only implementation, specialized just for FlowNet2. It takes a lot of memory and is slow. If you know to compile a custom op yourself, it's better to use the cuda implementation here: https://github.com/PatWie/tensorflow-recipes/tree/master/OpticalFlow/user_ops
[ "Correlation", "Cost", "Volume", "computation", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/OpticalFlow/flownet_models.py#L38-L72
train
tensorpack/tensorpack
examples/OpticalFlow/flownet_models.py
resize
def resize(x, mode, factor=4): """Resize input tensor with unkown input-shape by a factor Args: x (tf.Tensor): tensor NCHW factor (int, optional): resize factor for H, W Note: Differences here against Caffe have huge impacts on the quality of the predictions. Returns: tf.Tensor: resized tensor NCHW """ assert mode in ['bilinear', 'nearest'], mode shp = tf.shape(x)[2:] * factor # NCHW -> NHWC x = tf.transpose(x, [0, 2, 3, 1]) if mode == 'bilinear': x = tf.image.resize_bilinear(x, shp, align_corners=True) else: # better approximation of what Caffe is doing x = tf.image.resize_nearest_neighbor(x, shp, align_corners=False) # NHWC -> NCHW return tf.transpose(x, [0, 3, 1, 2])
python
def resize(x, mode, factor=4): """Resize input tensor with unkown input-shape by a factor Args: x (tf.Tensor): tensor NCHW factor (int, optional): resize factor for H, W Note: Differences here against Caffe have huge impacts on the quality of the predictions. Returns: tf.Tensor: resized tensor NCHW """ assert mode in ['bilinear', 'nearest'], mode shp = tf.shape(x)[2:] * factor # NCHW -> NHWC x = tf.transpose(x, [0, 2, 3, 1]) if mode == 'bilinear': x = tf.image.resize_bilinear(x, shp, align_corners=True) else: # better approximation of what Caffe is doing x = tf.image.resize_nearest_neighbor(x, shp, align_corners=False) # NHWC -> NCHW return tf.transpose(x, [0, 3, 1, 2])
[ "def", "resize", "(", "x", ",", "mode", ",", "factor", "=", "4", ")", ":", "assert", "mode", "in", "[", "'bilinear'", ",", "'nearest'", "]", ",", "mode", "shp", "=", "tf", ".", "shape", "(", "x", ")", "[", "2", ":", "]", "*", "factor", "# NCHW -> NHWC", "x", "=", "tf", ".", "transpose", "(", "x", ",", "[", "0", ",", "2", ",", "3", ",", "1", "]", ")", "if", "mode", "==", "'bilinear'", ":", "x", "=", "tf", ".", "image", ".", "resize_bilinear", "(", "x", ",", "shp", ",", "align_corners", "=", "True", ")", "else", ":", "# better approximation of what Caffe is doing", "x", "=", "tf", ".", "image", ".", "resize_nearest_neighbor", "(", "x", ",", "shp", ",", "align_corners", "=", "False", ")", "# NHWC -> NCHW", "return", "tf", ".", "transpose", "(", "x", ",", "[", "0", ",", "3", ",", "1", ",", "2", "]", ")" ]
Resize input tensor with unkown input-shape by a factor Args: x (tf.Tensor): tensor NCHW factor (int, optional): resize factor for H, W Note: Differences here against Caffe have huge impacts on the quality of the predictions. Returns: tf.Tensor: resized tensor NCHW
[ "Resize", "input", "tensor", "with", "unkown", "input", "-", "shape", "by", "a", "factor" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/OpticalFlow/flownet_models.py#L115-L139
train
tensorpack/tensorpack
examples/OpticalFlow/flownet_models.py
FlowNet2.flownet2_fusion
def flownet2_fusion(self, x): """ Architecture in Table 4 of FlowNet 2.0. Args: x: NCHW tensor, where C=11 is the concatenation of 7 items of [3, 2, 2, 1, 1, 1, 1] channels. """ with argscope([tf.layers.conv2d], activation=lambda x: tf.nn.leaky_relu(x, 0.1), padding='valid', strides=2, kernel_size=3, data_format='channels_first'), \ argscope([tf.layers.conv2d_transpose], padding='same', activation=tf.identity, data_format='channels_first', strides=2, kernel_size=4): conv0 = tf.layers.conv2d(pad(x, 1), 64, name='conv0', strides=1) x = tf.layers.conv2d(pad(conv0, 1), 64, name='conv1') conv1 = tf.layers.conv2d(pad(x, 1), 128, name='conv1_1', strides=1) x = tf.layers.conv2d(pad(conv1, 1), 128, name='conv2') conv2 = tf.layers.conv2d(pad(x, 1), 128, name='conv2_1', strides=1) flow2 = tf.layers.conv2d(pad(conv2, 1), 2, name='predict_flow2', strides=1, activation=tf.identity) flow2_up = tf.layers.conv2d_transpose(flow2, 2, name='upsampled_flow2_to_1') x = tf.layers.conv2d_transpose(conv2, 32, name='deconv1', activation=lambda x: tf.nn.leaky_relu(x, 0.1)) concat1 = tf.concat([conv1, x, flow2_up], axis=1, name='concat1') interconv1 = tf.layers.conv2d(pad(concat1, 1), 32, strides=1, name='inter_conv1', activation=tf.identity) flow1 = tf.layers.conv2d(pad(interconv1, 1), 2, name='predict_flow1', strides=1, activation=tf.identity) flow1_up = tf.layers.conv2d_transpose(flow1, 2, name='upsampled_flow1_to_0') x = tf.layers.conv2d_transpose(concat1, 16, name='deconv0', activation=lambda x: tf.nn.leaky_relu(x, 0.1)) concat0 = tf.concat([conv0, x, flow1_up], axis=1, name='concat0') interconv0 = tf.layers.conv2d(pad(concat0, 1), 16, strides=1, name='inter_conv0', activation=tf.identity) flow0 = tf.layers.conv2d(pad(interconv0, 1), 2, name='predict_flow0', strides=1, activation=tf.identity) return tf.identity(flow0, name='flow2')
python
def flownet2_fusion(self, x): """ Architecture in Table 4 of FlowNet 2.0. Args: x: NCHW tensor, where C=11 is the concatenation of 7 items of [3, 2, 2, 1, 1, 1, 1] channels. """ with argscope([tf.layers.conv2d], activation=lambda x: tf.nn.leaky_relu(x, 0.1), padding='valid', strides=2, kernel_size=3, data_format='channels_first'), \ argscope([tf.layers.conv2d_transpose], padding='same', activation=tf.identity, data_format='channels_first', strides=2, kernel_size=4): conv0 = tf.layers.conv2d(pad(x, 1), 64, name='conv0', strides=1) x = tf.layers.conv2d(pad(conv0, 1), 64, name='conv1') conv1 = tf.layers.conv2d(pad(x, 1), 128, name='conv1_1', strides=1) x = tf.layers.conv2d(pad(conv1, 1), 128, name='conv2') conv2 = tf.layers.conv2d(pad(x, 1), 128, name='conv2_1', strides=1) flow2 = tf.layers.conv2d(pad(conv2, 1), 2, name='predict_flow2', strides=1, activation=tf.identity) flow2_up = tf.layers.conv2d_transpose(flow2, 2, name='upsampled_flow2_to_1') x = tf.layers.conv2d_transpose(conv2, 32, name='deconv1', activation=lambda x: tf.nn.leaky_relu(x, 0.1)) concat1 = tf.concat([conv1, x, flow2_up], axis=1, name='concat1') interconv1 = tf.layers.conv2d(pad(concat1, 1), 32, strides=1, name='inter_conv1', activation=tf.identity) flow1 = tf.layers.conv2d(pad(interconv1, 1), 2, name='predict_flow1', strides=1, activation=tf.identity) flow1_up = tf.layers.conv2d_transpose(flow1, 2, name='upsampled_flow1_to_0') x = tf.layers.conv2d_transpose(concat1, 16, name='deconv0', activation=lambda x: tf.nn.leaky_relu(x, 0.1)) concat0 = tf.concat([conv0, x, flow1_up], axis=1, name='concat0') interconv0 = tf.layers.conv2d(pad(concat0, 1), 16, strides=1, name='inter_conv0', activation=tf.identity) flow0 = tf.layers.conv2d(pad(interconv0, 1), 2, name='predict_flow0', strides=1, activation=tf.identity) return tf.identity(flow0, name='flow2')
[ "def", "flownet2_fusion", "(", "self", ",", "x", ")", ":", "with", "argscope", "(", "[", "tf", ".", "layers", ".", "conv2d", "]", ",", "activation", "=", "lambda", "x", ":", "tf", ".", "nn", ".", "leaky_relu", "(", "x", ",", "0.1", ")", ",", "padding", "=", "'valid'", ",", "strides", "=", "2", ",", "kernel_size", "=", "3", ",", "data_format", "=", "'channels_first'", ")", ",", "argscope", "(", "[", "tf", ".", "layers", ".", "conv2d_transpose", "]", ",", "padding", "=", "'same'", ",", "activation", "=", "tf", ".", "identity", ",", "data_format", "=", "'channels_first'", ",", "strides", "=", "2", ",", "kernel_size", "=", "4", ")", ":", "conv0", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "x", ",", "1", ")", ",", "64", ",", "name", "=", "'conv0'", ",", "strides", "=", "1", ")", "x", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "conv0", ",", "1", ")", ",", "64", ",", "name", "=", "'conv1'", ")", "conv1", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "x", ",", "1", ")", ",", "128", ",", "name", "=", "'conv1_1'", ",", "strides", "=", "1", ")", "x", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "conv1", ",", "1", ")", ",", "128", ",", "name", "=", "'conv2'", ")", "conv2", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "x", ",", "1", ")", ",", "128", ",", "name", "=", "'conv2_1'", ",", "strides", "=", "1", ")", "flow2", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "conv2", ",", "1", ")", ",", "2", ",", "name", "=", "'predict_flow2'", ",", "strides", "=", "1", ",", "activation", "=", "tf", ".", "identity", ")", "flow2_up", "=", "tf", ".", "layers", ".", "conv2d_transpose", "(", "flow2", ",", "2", ",", "name", "=", "'upsampled_flow2_to_1'", ")", "x", "=", "tf", ".", "layers", ".", "conv2d_transpose", "(", "conv2", ",", "32", ",", "name", "=", "'deconv1'", ",", "activation", "=", "lambda", "x", ":", "tf", ".", "nn", ".", "leaky_relu", "(", "x", ",", "0.1", ")", ")", "concat1", "=", "tf", ".", "concat", "(", "[", "conv1", ",", "x", ",", "flow2_up", "]", ",", "axis", "=", "1", ",", "name", "=", "'concat1'", ")", "interconv1", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "concat1", ",", "1", ")", ",", "32", ",", "strides", "=", "1", ",", "name", "=", "'inter_conv1'", ",", "activation", "=", "tf", ".", "identity", ")", "flow1", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "interconv1", ",", "1", ")", ",", "2", ",", "name", "=", "'predict_flow1'", ",", "strides", "=", "1", ",", "activation", "=", "tf", ".", "identity", ")", "flow1_up", "=", "tf", ".", "layers", ".", "conv2d_transpose", "(", "flow1", ",", "2", ",", "name", "=", "'upsampled_flow1_to_0'", ")", "x", "=", "tf", ".", "layers", ".", "conv2d_transpose", "(", "concat1", ",", "16", ",", "name", "=", "'deconv0'", ",", "activation", "=", "lambda", "x", ":", "tf", ".", "nn", ".", "leaky_relu", "(", "x", ",", "0.1", ")", ")", "concat0", "=", "tf", ".", "concat", "(", "[", "conv0", ",", "x", ",", "flow1_up", "]", ",", "axis", "=", "1", ",", "name", "=", "'concat0'", ")", "interconv0", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "concat0", ",", "1", ")", ",", "16", ",", "strides", "=", "1", ",", "name", "=", "'inter_conv0'", ",", "activation", "=", "tf", ".", "identity", ")", "flow0", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "interconv0", ",", "1", ")", ",", "2", ",", "name", "=", "'predict_flow0'", ",", "strides", "=", "1", ",", "activation", "=", "tf", ".", "identity", ")", "return", "tf", ".", "identity", "(", "flow0", ",", "name", "=", "'flow2'", ")" ]
Architecture in Table 4 of FlowNet 2.0. Args: x: NCHW tensor, where C=11 is the concatenation of 7 items of [3, 2, 2, 1, 1, 1, 1] channels.
[ "Architecture", "in", "Table", "4", "of", "FlowNet", "2", ".", "0", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/OpticalFlow/flownet_models.py#L230-L264
train
tensorpack/tensorpack
examples/OpticalFlow/flownet_models.py
FlowNet2.flownet2_sd
def flownet2_sd(self, x): """ Architecture in Table 3 of FlowNet 2.0. Args: x: concatenation of two inputs, of shape [1, 2xC, H, W] """ with argscope([tf.layers.conv2d], activation=lambda x: tf.nn.leaky_relu(x, 0.1), padding='valid', strides=2, kernel_size=3, data_format='channels_first'), \ argscope([tf.layers.conv2d_transpose], padding='same', activation=tf.identity, data_format='channels_first', strides=2, kernel_size=4): x = tf.layers.conv2d(pad(x, 1), 64, name='conv0', strides=1) x = tf.layers.conv2d(pad(x, 1), 64, name='conv1') conv1 = tf.layers.conv2d(pad(x, 1), 128, name='conv1_1', strides=1) x = tf.layers.conv2d(pad(conv1, 1), 128, name='conv2') conv2 = tf.layers.conv2d(pad(x, 1), 128, name='conv2_1', strides=1) x = tf.layers.conv2d(pad(conv2, 1), 256, name='conv3') conv3 = tf.layers.conv2d(pad(x, 1), 256, name='conv3_1', strides=1) x = tf.layers.conv2d(pad(conv3, 1), 512, name='conv4') conv4 = tf.layers.conv2d(pad(x, 1), 512, name='conv4_1', strides=1) x = tf.layers.conv2d(pad(conv4, 1), 512, name='conv5') conv5 = tf.layers.conv2d(pad(x, 1), 512, name='conv5_1', strides=1) x = tf.layers.conv2d(pad(conv5, 1), 1024, name='conv6') conv6 = tf.layers.conv2d(pad(x, 1), 1024, name='conv6_1', strides=1) flow6 = tf.layers.conv2d(pad(conv6, 1), 2, name='predict_flow6', strides=1, activation=tf.identity) flow6_up = tf.layers.conv2d_transpose(flow6, 2, name='upsampled_flow6_to_5') x = tf.layers.conv2d_transpose(conv6, 512, name='deconv5', activation=lambda x: tf.nn.leaky_relu(x, 0.1)) concat5 = tf.concat([conv5, x, flow6_up], axis=1, name='concat5') interconv5 = tf.layers.conv2d(pad(concat5, 1), 512, strides=1, name='inter_conv5', activation=tf.identity) flow5 = tf.layers.conv2d(pad(interconv5, 1), 2, name='predict_flow5', strides=1, activation=tf.identity) flow5_up = tf.layers.conv2d_transpose(flow5, 2, name='upsampled_flow5_to_4') x = tf.layers.conv2d_transpose(concat5, 256, name='deconv4', activation=lambda x: tf.nn.leaky_relu(x, 0.1)) concat4 = tf.concat([conv4, x, flow5_up], axis=1, name='concat4') interconv4 = tf.layers.conv2d(pad(concat4, 1), 256, strides=1, name='inter_conv4', activation=tf.identity) flow4 = tf.layers.conv2d(pad(interconv4, 1), 2, name='predict_flow4', strides=1, activation=tf.identity) flow4_up = tf.layers.conv2d_transpose(flow4, 2, name='upsampled_flow4_to_3') x = tf.layers.conv2d_transpose(concat4, 128, name='deconv3', activation=lambda x: tf.nn.leaky_relu(x, 0.1)) concat3 = tf.concat([conv3, x, flow4_up], axis=1, name='concat3') interconv3 = tf.layers.conv2d(pad(concat3, 1), 128, strides=1, name='inter_conv3', activation=tf.identity) flow3 = tf.layers.conv2d(pad(interconv3, 1), 2, name='predict_flow3', strides=1, activation=tf.identity) flow3_up = tf.layers.conv2d_transpose(flow3, 2, name='upsampled_flow3_to_2') x = tf.layers.conv2d_transpose(concat3, 64, name='deconv2', activation=lambda x: tf.nn.leaky_relu(x, 0.1)) concat2 = tf.concat([conv2, x, flow3_up], axis=1, name='concat2') interconv2 = tf.layers.conv2d(pad(concat2, 1), 64, strides=1, name='inter_conv2', activation=tf.identity) flow2 = tf.layers.conv2d(pad(interconv2, 1), 2, name='predict_flow2', strides=1, activation=tf.identity) return resize(flow2 / DISP_SCALE, mode='nearest')
python
def flownet2_sd(self, x): """ Architecture in Table 3 of FlowNet 2.0. Args: x: concatenation of two inputs, of shape [1, 2xC, H, W] """ with argscope([tf.layers.conv2d], activation=lambda x: tf.nn.leaky_relu(x, 0.1), padding='valid', strides=2, kernel_size=3, data_format='channels_first'), \ argscope([tf.layers.conv2d_transpose], padding='same', activation=tf.identity, data_format='channels_first', strides=2, kernel_size=4): x = tf.layers.conv2d(pad(x, 1), 64, name='conv0', strides=1) x = tf.layers.conv2d(pad(x, 1), 64, name='conv1') conv1 = tf.layers.conv2d(pad(x, 1), 128, name='conv1_1', strides=1) x = tf.layers.conv2d(pad(conv1, 1), 128, name='conv2') conv2 = tf.layers.conv2d(pad(x, 1), 128, name='conv2_1', strides=1) x = tf.layers.conv2d(pad(conv2, 1), 256, name='conv3') conv3 = tf.layers.conv2d(pad(x, 1), 256, name='conv3_1', strides=1) x = tf.layers.conv2d(pad(conv3, 1), 512, name='conv4') conv4 = tf.layers.conv2d(pad(x, 1), 512, name='conv4_1', strides=1) x = tf.layers.conv2d(pad(conv4, 1), 512, name='conv5') conv5 = tf.layers.conv2d(pad(x, 1), 512, name='conv5_1', strides=1) x = tf.layers.conv2d(pad(conv5, 1), 1024, name='conv6') conv6 = tf.layers.conv2d(pad(x, 1), 1024, name='conv6_1', strides=1) flow6 = tf.layers.conv2d(pad(conv6, 1), 2, name='predict_flow6', strides=1, activation=tf.identity) flow6_up = tf.layers.conv2d_transpose(flow6, 2, name='upsampled_flow6_to_5') x = tf.layers.conv2d_transpose(conv6, 512, name='deconv5', activation=lambda x: tf.nn.leaky_relu(x, 0.1)) concat5 = tf.concat([conv5, x, flow6_up], axis=1, name='concat5') interconv5 = tf.layers.conv2d(pad(concat5, 1), 512, strides=1, name='inter_conv5', activation=tf.identity) flow5 = tf.layers.conv2d(pad(interconv5, 1), 2, name='predict_flow5', strides=1, activation=tf.identity) flow5_up = tf.layers.conv2d_transpose(flow5, 2, name='upsampled_flow5_to_4') x = tf.layers.conv2d_transpose(concat5, 256, name='deconv4', activation=lambda x: tf.nn.leaky_relu(x, 0.1)) concat4 = tf.concat([conv4, x, flow5_up], axis=1, name='concat4') interconv4 = tf.layers.conv2d(pad(concat4, 1), 256, strides=1, name='inter_conv4', activation=tf.identity) flow4 = tf.layers.conv2d(pad(interconv4, 1), 2, name='predict_flow4', strides=1, activation=tf.identity) flow4_up = tf.layers.conv2d_transpose(flow4, 2, name='upsampled_flow4_to_3') x = tf.layers.conv2d_transpose(concat4, 128, name='deconv3', activation=lambda x: tf.nn.leaky_relu(x, 0.1)) concat3 = tf.concat([conv3, x, flow4_up], axis=1, name='concat3') interconv3 = tf.layers.conv2d(pad(concat3, 1), 128, strides=1, name='inter_conv3', activation=tf.identity) flow3 = tf.layers.conv2d(pad(interconv3, 1), 2, name='predict_flow3', strides=1, activation=tf.identity) flow3_up = tf.layers.conv2d_transpose(flow3, 2, name='upsampled_flow3_to_2') x = tf.layers.conv2d_transpose(concat3, 64, name='deconv2', activation=lambda x: tf.nn.leaky_relu(x, 0.1)) concat2 = tf.concat([conv2, x, flow3_up], axis=1, name='concat2') interconv2 = tf.layers.conv2d(pad(concat2, 1), 64, strides=1, name='inter_conv2', activation=tf.identity) flow2 = tf.layers.conv2d(pad(interconv2, 1), 2, name='predict_flow2', strides=1, activation=tf.identity) return resize(flow2 / DISP_SCALE, mode='nearest')
[ "def", "flownet2_sd", "(", "self", ",", "x", ")", ":", "with", "argscope", "(", "[", "tf", ".", "layers", ".", "conv2d", "]", ",", "activation", "=", "lambda", "x", ":", "tf", ".", "nn", ".", "leaky_relu", "(", "x", ",", "0.1", ")", ",", "padding", "=", "'valid'", ",", "strides", "=", "2", ",", "kernel_size", "=", "3", ",", "data_format", "=", "'channels_first'", ")", ",", "argscope", "(", "[", "tf", ".", "layers", ".", "conv2d_transpose", "]", ",", "padding", "=", "'same'", ",", "activation", "=", "tf", ".", "identity", ",", "data_format", "=", "'channels_first'", ",", "strides", "=", "2", ",", "kernel_size", "=", "4", ")", ":", "x", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "x", ",", "1", ")", ",", "64", ",", "name", "=", "'conv0'", ",", "strides", "=", "1", ")", "x", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "x", ",", "1", ")", ",", "64", ",", "name", "=", "'conv1'", ")", "conv1", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "x", ",", "1", ")", ",", "128", ",", "name", "=", "'conv1_1'", ",", "strides", "=", "1", ")", "x", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "conv1", ",", "1", ")", ",", "128", ",", "name", "=", "'conv2'", ")", "conv2", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "x", ",", "1", ")", ",", "128", ",", "name", "=", "'conv2_1'", ",", "strides", "=", "1", ")", "x", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "conv2", ",", "1", ")", ",", "256", ",", "name", "=", "'conv3'", ")", "conv3", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "x", ",", "1", ")", ",", "256", ",", "name", "=", "'conv3_1'", ",", "strides", "=", "1", ")", "x", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "conv3", ",", "1", ")", ",", "512", ",", "name", "=", "'conv4'", ")", "conv4", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "x", ",", "1", ")", ",", "512", ",", "name", "=", "'conv4_1'", ",", "strides", "=", "1", ")", "x", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "conv4", ",", "1", ")", ",", "512", ",", "name", "=", "'conv5'", ")", "conv5", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "x", ",", "1", ")", ",", "512", ",", "name", "=", "'conv5_1'", ",", "strides", "=", "1", ")", "x", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "conv5", ",", "1", ")", ",", "1024", ",", "name", "=", "'conv6'", ")", "conv6", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "x", ",", "1", ")", ",", "1024", ",", "name", "=", "'conv6_1'", ",", "strides", "=", "1", ")", "flow6", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "conv6", ",", "1", ")", ",", "2", ",", "name", "=", "'predict_flow6'", ",", "strides", "=", "1", ",", "activation", "=", "tf", ".", "identity", ")", "flow6_up", "=", "tf", ".", "layers", ".", "conv2d_transpose", "(", "flow6", ",", "2", ",", "name", "=", "'upsampled_flow6_to_5'", ")", "x", "=", "tf", ".", "layers", ".", "conv2d_transpose", "(", "conv6", ",", "512", ",", "name", "=", "'deconv5'", ",", "activation", "=", "lambda", "x", ":", "tf", ".", "nn", ".", "leaky_relu", "(", "x", ",", "0.1", ")", ")", "concat5", "=", "tf", ".", "concat", "(", "[", "conv5", ",", "x", ",", "flow6_up", "]", ",", "axis", "=", "1", ",", "name", "=", "'concat5'", ")", "interconv5", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "concat5", ",", "1", ")", ",", "512", ",", "strides", "=", "1", ",", "name", "=", "'inter_conv5'", ",", "activation", "=", "tf", ".", "identity", ")", "flow5", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "interconv5", ",", "1", ")", ",", "2", ",", "name", "=", "'predict_flow5'", ",", "strides", "=", "1", ",", "activation", "=", "tf", ".", "identity", ")", "flow5_up", "=", "tf", ".", "layers", ".", "conv2d_transpose", "(", "flow5", ",", "2", ",", "name", "=", "'upsampled_flow5_to_4'", ")", "x", "=", "tf", ".", "layers", ".", "conv2d_transpose", "(", "concat5", ",", "256", ",", "name", "=", "'deconv4'", ",", "activation", "=", "lambda", "x", ":", "tf", ".", "nn", ".", "leaky_relu", "(", "x", ",", "0.1", ")", ")", "concat4", "=", "tf", ".", "concat", "(", "[", "conv4", ",", "x", ",", "flow5_up", "]", ",", "axis", "=", "1", ",", "name", "=", "'concat4'", ")", "interconv4", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "concat4", ",", "1", ")", ",", "256", ",", "strides", "=", "1", ",", "name", "=", "'inter_conv4'", ",", "activation", "=", "tf", ".", "identity", ")", "flow4", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "interconv4", ",", "1", ")", ",", "2", ",", "name", "=", "'predict_flow4'", ",", "strides", "=", "1", ",", "activation", "=", "tf", ".", "identity", ")", "flow4_up", "=", "tf", ".", "layers", ".", "conv2d_transpose", "(", "flow4", ",", "2", ",", "name", "=", "'upsampled_flow4_to_3'", ")", "x", "=", "tf", ".", "layers", ".", "conv2d_transpose", "(", "concat4", ",", "128", ",", "name", "=", "'deconv3'", ",", "activation", "=", "lambda", "x", ":", "tf", ".", "nn", ".", "leaky_relu", "(", "x", ",", "0.1", ")", ")", "concat3", "=", "tf", ".", "concat", "(", "[", "conv3", ",", "x", ",", "flow4_up", "]", ",", "axis", "=", "1", ",", "name", "=", "'concat3'", ")", "interconv3", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "concat3", ",", "1", ")", ",", "128", ",", "strides", "=", "1", ",", "name", "=", "'inter_conv3'", ",", "activation", "=", "tf", ".", "identity", ")", "flow3", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "interconv3", ",", "1", ")", ",", "2", ",", "name", "=", "'predict_flow3'", ",", "strides", "=", "1", ",", "activation", "=", "tf", ".", "identity", ")", "flow3_up", "=", "tf", ".", "layers", ".", "conv2d_transpose", "(", "flow3", ",", "2", ",", "name", "=", "'upsampled_flow3_to_2'", ")", "x", "=", "tf", ".", "layers", ".", "conv2d_transpose", "(", "concat3", ",", "64", ",", "name", "=", "'deconv2'", ",", "activation", "=", "lambda", "x", ":", "tf", ".", "nn", ".", "leaky_relu", "(", "x", ",", "0.1", ")", ")", "concat2", "=", "tf", ".", "concat", "(", "[", "conv2", ",", "x", ",", "flow3_up", "]", ",", "axis", "=", "1", ",", "name", "=", "'concat2'", ")", "interconv2", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "concat2", ",", "1", ")", ",", "64", ",", "strides", "=", "1", ",", "name", "=", "'inter_conv2'", ",", "activation", "=", "tf", ".", "identity", ")", "flow2", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "interconv2", ",", "1", ")", ",", "2", ",", "name", "=", "'predict_flow2'", ",", "strides", "=", "1", ",", "activation", "=", "tf", ".", "identity", ")", "return", "resize", "(", "flow2", "/", "DISP_SCALE", ",", "mode", "=", "'nearest'", ")" ]
Architecture in Table 3 of FlowNet 2.0. Args: x: concatenation of two inputs, of shape [1, 2xC, H, W]
[ "Architecture", "in", "Table", "3", "of", "FlowNet", "2", ".", "0", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/OpticalFlow/flownet_models.py#L266-L320
train
tensorpack/tensorpack
examples/OpticalFlow/flownet_models.py
FlowNet2S.graph_structure
def graph_structure(self, x, standalone=True): """ Architecture of FlowNetSimple in Figure 2 of FlowNet 1.0. Args: x: 2CHW if standalone==True, else NCHW where C=12 is a concatenation of 5 tensors of [3, 3, 3, 2, 1] channels. standalone: If True, this model is used to predict flow from two inputs. If False, this model is used as part of the FlowNet2. """ if standalone: x = tf.concat(tf.split(x, 2, axis=0), axis=1) with argscope([tf.layers.conv2d], activation=lambda x: tf.nn.leaky_relu(x, 0.1), padding='valid', strides=2, kernel_size=3, data_format='channels_first'), \ argscope([tf.layers.conv2d_transpose], padding='same', activation=tf.identity, data_format='channels_first', strides=2, kernel_size=4): x = tf.layers.conv2d(pad(x, 3), 64, kernel_size=7, name='conv1') conv2 = tf.layers.conv2d(pad(x, 2), 128, kernel_size=5, name='conv2') x = tf.layers.conv2d(pad(conv2, 2), 256, kernel_size=5, name='conv3') conv3 = tf.layers.conv2d(pad(x, 1), 256, name='conv3_1', strides=1) x = tf.layers.conv2d(pad(conv3, 1), 512, name='conv4') conv4 = tf.layers.conv2d(pad(x, 1), 512, name='conv4_1', strides=1) x = tf.layers.conv2d(pad(conv4, 1), 512, name='conv5') conv5 = tf.layers.conv2d(pad(x, 1), 512, name='conv5_1', strides=1) x = tf.layers.conv2d(pad(conv5, 1), 1024, name='conv6') conv6 = tf.layers.conv2d(pad(x, 1), 1024, name='conv6_1', strides=1) flow6 = tf.layers.conv2d(pad(conv6, 1), 2, name='predict_flow6', strides=1, activation=tf.identity) flow6_up = tf.layers.conv2d_transpose(flow6, 2, name='upsampled_flow6_to_5', use_bias=False) x = tf.layers.conv2d_transpose(conv6, 512, name='deconv5', activation=lambda x: tf.nn.leaky_relu(x, 0.1)) concat5 = tf.concat([conv5, x, flow6_up], axis=1, name='concat5') flow5 = tf.layers.conv2d(pad(concat5, 1), 2, name='predict_flow5', strides=1, activation=tf.identity) flow5_up = tf.layers.conv2d_transpose(flow5, 2, name='upsampled_flow5_to_4', use_bias=False) x = tf.layers.conv2d_transpose(concat5, 256, name='deconv4', activation=lambda x: tf.nn.leaky_relu(x, 0.1)) concat4 = tf.concat([conv4, x, flow5_up], axis=1, name='concat4') flow4 = tf.layers.conv2d(pad(concat4, 1), 2, name='predict_flow4', strides=1, activation=tf.identity) flow4_up = tf.layers.conv2d_transpose(flow4, 2, name='upsampled_flow4_to_3', use_bias=False) x = tf.layers.conv2d_transpose(concat4, 128, name='deconv3', activation=lambda x: tf.nn.leaky_relu(x, 0.1)) concat3 = tf.concat([conv3, x, flow4_up], axis=1, name='concat3') flow3 = tf.layers.conv2d(pad(concat3, 1), 2, name='predict_flow3', strides=1, activation=tf.identity) flow3_up = tf.layers.conv2d_transpose(flow3, 2, name='upsampled_flow3_to_2', use_bias=False) x = tf.layers.conv2d_transpose(concat3, 64, name='deconv2', activation=lambda x: tf.nn.leaky_relu(x, 0.1)) concat2 = tf.concat([conv2, x, flow3_up], axis=1, name='concat2') flow2 = tf.layers.conv2d(pad(concat2, 1), 2, name='predict_flow2', strides=1, activation=tf.identity) return tf.identity(flow2, name='flow2')
python
def graph_structure(self, x, standalone=True): """ Architecture of FlowNetSimple in Figure 2 of FlowNet 1.0. Args: x: 2CHW if standalone==True, else NCHW where C=12 is a concatenation of 5 tensors of [3, 3, 3, 2, 1] channels. standalone: If True, this model is used to predict flow from two inputs. If False, this model is used as part of the FlowNet2. """ if standalone: x = tf.concat(tf.split(x, 2, axis=0), axis=1) with argscope([tf.layers.conv2d], activation=lambda x: tf.nn.leaky_relu(x, 0.1), padding='valid', strides=2, kernel_size=3, data_format='channels_first'), \ argscope([tf.layers.conv2d_transpose], padding='same', activation=tf.identity, data_format='channels_first', strides=2, kernel_size=4): x = tf.layers.conv2d(pad(x, 3), 64, kernel_size=7, name='conv1') conv2 = tf.layers.conv2d(pad(x, 2), 128, kernel_size=5, name='conv2') x = tf.layers.conv2d(pad(conv2, 2), 256, kernel_size=5, name='conv3') conv3 = tf.layers.conv2d(pad(x, 1), 256, name='conv3_1', strides=1) x = tf.layers.conv2d(pad(conv3, 1), 512, name='conv4') conv4 = tf.layers.conv2d(pad(x, 1), 512, name='conv4_1', strides=1) x = tf.layers.conv2d(pad(conv4, 1), 512, name='conv5') conv5 = tf.layers.conv2d(pad(x, 1), 512, name='conv5_1', strides=1) x = tf.layers.conv2d(pad(conv5, 1), 1024, name='conv6') conv6 = tf.layers.conv2d(pad(x, 1), 1024, name='conv6_1', strides=1) flow6 = tf.layers.conv2d(pad(conv6, 1), 2, name='predict_flow6', strides=1, activation=tf.identity) flow6_up = tf.layers.conv2d_transpose(flow6, 2, name='upsampled_flow6_to_5', use_bias=False) x = tf.layers.conv2d_transpose(conv6, 512, name='deconv5', activation=lambda x: tf.nn.leaky_relu(x, 0.1)) concat5 = tf.concat([conv5, x, flow6_up], axis=1, name='concat5') flow5 = tf.layers.conv2d(pad(concat5, 1), 2, name='predict_flow5', strides=1, activation=tf.identity) flow5_up = tf.layers.conv2d_transpose(flow5, 2, name='upsampled_flow5_to_4', use_bias=False) x = tf.layers.conv2d_transpose(concat5, 256, name='deconv4', activation=lambda x: tf.nn.leaky_relu(x, 0.1)) concat4 = tf.concat([conv4, x, flow5_up], axis=1, name='concat4') flow4 = tf.layers.conv2d(pad(concat4, 1), 2, name='predict_flow4', strides=1, activation=tf.identity) flow4_up = tf.layers.conv2d_transpose(flow4, 2, name='upsampled_flow4_to_3', use_bias=False) x = tf.layers.conv2d_transpose(concat4, 128, name='deconv3', activation=lambda x: tf.nn.leaky_relu(x, 0.1)) concat3 = tf.concat([conv3, x, flow4_up], axis=1, name='concat3') flow3 = tf.layers.conv2d(pad(concat3, 1), 2, name='predict_flow3', strides=1, activation=tf.identity) flow3_up = tf.layers.conv2d_transpose(flow3, 2, name='upsampled_flow3_to_2', use_bias=False) x = tf.layers.conv2d_transpose(concat3, 64, name='deconv2', activation=lambda x: tf.nn.leaky_relu(x, 0.1)) concat2 = tf.concat([conv2, x, flow3_up], axis=1, name='concat2') flow2 = tf.layers.conv2d(pad(concat2, 1), 2, name='predict_flow2', strides=1, activation=tf.identity) return tf.identity(flow2, name='flow2')
[ "def", "graph_structure", "(", "self", ",", "x", ",", "standalone", "=", "True", ")", ":", "if", "standalone", ":", "x", "=", "tf", ".", "concat", "(", "tf", ".", "split", "(", "x", ",", "2", ",", "axis", "=", "0", ")", ",", "axis", "=", "1", ")", "with", "argscope", "(", "[", "tf", ".", "layers", ".", "conv2d", "]", ",", "activation", "=", "lambda", "x", ":", "tf", ".", "nn", ".", "leaky_relu", "(", "x", ",", "0.1", ")", ",", "padding", "=", "'valid'", ",", "strides", "=", "2", ",", "kernel_size", "=", "3", ",", "data_format", "=", "'channels_first'", ")", ",", "argscope", "(", "[", "tf", ".", "layers", ".", "conv2d_transpose", "]", ",", "padding", "=", "'same'", ",", "activation", "=", "tf", ".", "identity", ",", "data_format", "=", "'channels_first'", ",", "strides", "=", "2", ",", "kernel_size", "=", "4", ")", ":", "x", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "x", ",", "3", ")", ",", "64", ",", "kernel_size", "=", "7", ",", "name", "=", "'conv1'", ")", "conv2", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "x", ",", "2", ")", ",", "128", ",", "kernel_size", "=", "5", ",", "name", "=", "'conv2'", ")", "x", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "conv2", ",", "2", ")", ",", "256", ",", "kernel_size", "=", "5", ",", "name", "=", "'conv3'", ")", "conv3", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "x", ",", "1", ")", ",", "256", ",", "name", "=", "'conv3_1'", ",", "strides", "=", "1", ")", "x", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "conv3", ",", "1", ")", ",", "512", ",", "name", "=", "'conv4'", ")", "conv4", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "x", ",", "1", ")", ",", "512", ",", "name", "=", "'conv4_1'", ",", "strides", "=", "1", ")", "x", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "conv4", ",", "1", ")", ",", "512", ",", "name", "=", "'conv5'", ")", "conv5", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "x", ",", "1", ")", ",", "512", ",", "name", "=", "'conv5_1'", ",", "strides", "=", "1", ")", "x", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "conv5", ",", "1", ")", ",", "1024", ",", "name", "=", "'conv6'", ")", "conv6", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "x", ",", "1", ")", ",", "1024", ",", "name", "=", "'conv6_1'", ",", "strides", "=", "1", ")", "flow6", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "conv6", ",", "1", ")", ",", "2", ",", "name", "=", "'predict_flow6'", ",", "strides", "=", "1", ",", "activation", "=", "tf", ".", "identity", ")", "flow6_up", "=", "tf", ".", "layers", ".", "conv2d_transpose", "(", "flow6", ",", "2", ",", "name", "=", "'upsampled_flow6_to_5'", ",", "use_bias", "=", "False", ")", "x", "=", "tf", ".", "layers", ".", "conv2d_transpose", "(", "conv6", ",", "512", ",", "name", "=", "'deconv5'", ",", "activation", "=", "lambda", "x", ":", "tf", ".", "nn", ".", "leaky_relu", "(", "x", ",", "0.1", ")", ")", "concat5", "=", "tf", ".", "concat", "(", "[", "conv5", ",", "x", ",", "flow6_up", "]", ",", "axis", "=", "1", ",", "name", "=", "'concat5'", ")", "flow5", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "concat5", ",", "1", ")", ",", "2", ",", "name", "=", "'predict_flow5'", ",", "strides", "=", "1", ",", "activation", "=", "tf", ".", "identity", ")", "flow5_up", "=", "tf", ".", "layers", ".", "conv2d_transpose", "(", "flow5", ",", "2", ",", "name", "=", "'upsampled_flow5_to_4'", ",", "use_bias", "=", "False", ")", "x", "=", "tf", ".", "layers", ".", "conv2d_transpose", "(", "concat5", ",", "256", ",", "name", "=", "'deconv4'", ",", "activation", "=", "lambda", "x", ":", "tf", ".", "nn", ".", "leaky_relu", "(", "x", ",", "0.1", ")", ")", "concat4", "=", "tf", ".", "concat", "(", "[", "conv4", ",", "x", ",", "flow5_up", "]", ",", "axis", "=", "1", ",", "name", "=", "'concat4'", ")", "flow4", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "concat4", ",", "1", ")", ",", "2", ",", "name", "=", "'predict_flow4'", ",", "strides", "=", "1", ",", "activation", "=", "tf", ".", "identity", ")", "flow4_up", "=", "tf", ".", "layers", ".", "conv2d_transpose", "(", "flow4", ",", "2", ",", "name", "=", "'upsampled_flow4_to_3'", ",", "use_bias", "=", "False", ")", "x", "=", "tf", ".", "layers", ".", "conv2d_transpose", "(", "concat4", ",", "128", ",", "name", "=", "'deconv3'", ",", "activation", "=", "lambda", "x", ":", "tf", ".", "nn", ".", "leaky_relu", "(", "x", ",", "0.1", ")", ")", "concat3", "=", "tf", ".", "concat", "(", "[", "conv3", ",", "x", ",", "flow4_up", "]", ",", "axis", "=", "1", ",", "name", "=", "'concat3'", ")", "flow3", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "concat3", ",", "1", ")", ",", "2", ",", "name", "=", "'predict_flow3'", ",", "strides", "=", "1", ",", "activation", "=", "tf", ".", "identity", ")", "flow3_up", "=", "tf", ".", "layers", ".", "conv2d_transpose", "(", "flow3", ",", "2", ",", "name", "=", "'upsampled_flow3_to_2'", ",", "use_bias", "=", "False", ")", "x", "=", "tf", ".", "layers", ".", "conv2d_transpose", "(", "concat3", ",", "64", ",", "name", "=", "'deconv2'", ",", "activation", "=", "lambda", "x", ":", "tf", ".", "nn", ".", "leaky_relu", "(", "x", ",", "0.1", ")", ")", "concat2", "=", "tf", ".", "concat", "(", "[", "conv2", ",", "x", ",", "flow3_up", "]", ",", "axis", "=", "1", ",", "name", "=", "'concat2'", ")", "flow2", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "concat2", ",", "1", ")", ",", "2", ",", "name", "=", "'predict_flow2'", ",", "strides", "=", "1", ",", "activation", "=", "tf", ".", "identity", ")", "return", "tf", ".", "identity", "(", "flow2", ",", "name", "=", "'flow2'", ")" ]
Architecture of FlowNetSimple in Figure 2 of FlowNet 1.0. Args: x: 2CHW if standalone==True, else NCHW where C=12 is a concatenation of 5 tensors of [3, 3, 3, 2, 1] channels. standalone: If True, this model is used to predict flow from two inputs. If False, this model is used as part of the FlowNet2.
[ "Architecture", "of", "FlowNetSimple", "in", "Figure", "2", "of", "FlowNet", "1", ".", "0", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/OpticalFlow/flownet_models.py#L324-L375
train
tensorpack/tensorpack
examples/OpticalFlow/flownet_models.py
FlowNet2C.graph_structure
def graph_structure(self, x1x2): """ Architecture of FlowNetCorr in Figure 2 of FlowNet 1.0. Args: x: 2CHW. """ with argscope([tf.layers.conv2d], activation=lambda x: tf.nn.leaky_relu(x, 0.1), padding='valid', strides=2, kernel_size=3, data_format='channels_first'), \ argscope([tf.layers.conv2d_transpose], padding='same', activation=tf.identity, data_format='channels_first', strides=2, kernel_size=4): # extract features x = tf.layers.conv2d(pad(x1x2, 3), 64, kernel_size=7, name='conv1') conv2 = tf.layers.conv2d(pad(x, 2), 128, kernel_size=5, name='conv2') conv3 = tf.layers.conv2d(pad(conv2, 2), 256, kernel_size=5, name='conv3') conv2a, _ = tf.split(conv2, 2, axis=0) conv3a, conv3b = tf.split(conv3, 2, axis=0) corr = correlation(conv3a, conv3b, kernel_size=1, max_displacement=20, stride_1=1, stride_2=2, pad=20, data_format='NCHW') corr = tf.nn.leaky_relu(corr, 0.1) conv_redir = tf.layers.conv2d(conv3a, 32, kernel_size=1, strides=1, name='conv_redir') in_conv3_1 = tf.concat([conv_redir, corr], axis=1, name='in_conv3_1') conv3_1 = tf.layers.conv2d(pad(in_conv3_1, 1), 256, name='conv3_1', strides=1) x = tf.layers.conv2d(pad(conv3_1, 1), 512, name='conv4') conv4 = tf.layers.conv2d(pad(x, 1), 512, name='conv4_1', strides=1) x = tf.layers.conv2d(pad(conv4, 1), 512, name='conv5') conv5 = tf.layers.conv2d(pad(x, 1), 512, name='conv5_1', strides=1) x = tf.layers.conv2d(pad(conv5, 1), 1024, name='conv6') conv6 = tf.layers.conv2d(pad(x, 1), 1024, name='conv6_1', strides=1) flow6 = tf.layers.conv2d(pad(conv6, 1), 2, name='predict_flow6', strides=1, activation=tf.identity) flow6_up = tf.layers.conv2d_transpose(flow6, 2, name='upsampled_flow6_to_5') x = tf.layers.conv2d_transpose(conv6, 512, name='deconv5', activation=lambda x: tf.nn.leaky_relu(x, 0.1)) # return flow6 concat5 = tf.concat([conv5, x, flow6_up], axis=1, name='concat5') flow5 = tf.layers.conv2d(pad(concat5, 1), 2, name='predict_flow5', strides=1, activation=tf.identity) flow5_up = tf.layers.conv2d_transpose(flow5, 2, name='upsampled_flow5_to_4') x = tf.layers.conv2d_transpose(concat5, 256, name='deconv4', activation=lambda x: tf.nn.leaky_relu(x, 0.1)) concat4 = tf.concat([conv4, x, flow5_up], axis=1, name='concat4') flow4 = tf.layers.conv2d(pad(concat4, 1), 2, name='predict_flow4', strides=1, activation=tf.identity) flow4_up = tf.layers.conv2d_transpose(flow4, 2, name='upsampled_flow4_to_3') x = tf.layers.conv2d_transpose(concat4, 128, name='deconv3', activation=lambda x: tf.nn.leaky_relu(x, 0.1)) concat3 = tf.concat([conv3_1, x, flow4_up], axis=1, name='concat3') flow3 = tf.layers.conv2d(pad(concat3, 1), 2, name='predict_flow3', strides=1, activation=tf.identity) flow3_up = tf.layers.conv2d_transpose(flow3, 2, name='upsampled_flow3_to_2') x = tf.layers.conv2d_transpose(concat3, 64, name='deconv2', activation=lambda x: tf.nn.leaky_relu(x, 0.1)) concat2 = tf.concat([conv2a, x, flow3_up], axis=1, name='concat2') flow2 = tf.layers.conv2d(pad(concat2, 1), 2, name='predict_flow2', strides=1, activation=tf.identity) return tf.identity(flow2, name='flow2')
python
def graph_structure(self, x1x2): """ Architecture of FlowNetCorr in Figure 2 of FlowNet 1.0. Args: x: 2CHW. """ with argscope([tf.layers.conv2d], activation=lambda x: tf.nn.leaky_relu(x, 0.1), padding='valid', strides=2, kernel_size=3, data_format='channels_first'), \ argscope([tf.layers.conv2d_transpose], padding='same', activation=tf.identity, data_format='channels_first', strides=2, kernel_size=4): # extract features x = tf.layers.conv2d(pad(x1x2, 3), 64, kernel_size=7, name='conv1') conv2 = tf.layers.conv2d(pad(x, 2), 128, kernel_size=5, name='conv2') conv3 = tf.layers.conv2d(pad(conv2, 2), 256, kernel_size=5, name='conv3') conv2a, _ = tf.split(conv2, 2, axis=0) conv3a, conv3b = tf.split(conv3, 2, axis=0) corr = correlation(conv3a, conv3b, kernel_size=1, max_displacement=20, stride_1=1, stride_2=2, pad=20, data_format='NCHW') corr = tf.nn.leaky_relu(corr, 0.1) conv_redir = tf.layers.conv2d(conv3a, 32, kernel_size=1, strides=1, name='conv_redir') in_conv3_1 = tf.concat([conv_redir, corr], axis=1, name='in_conv3_1') conv3_1 = tf.layers.conv2d(pad(in_conv3_1, 1), 256, name='conv3_1', strides=1) x = tf.layers.conv2d(pad(conv3_1, 1), 512, name='conv4') conv4 = tf.layers.conv2d(pad(x, 1), 512, name='conv4_1', strides=1) x = tf.layers.conv2d(pad(conv4, 1), 512, name='conv5') conv5 = tf.layers.conv2d(pad(x, 1), 512, name='conv5_1', strides=1) x = tf.layers.conv2d(pad(conv5, 1), 1024, name='conv6') conv6 = tf.layers.conv2d(pad(x, 1), 1024, name='conv6_1', strides=1) flow6 = tf.layers.conv2d(pad(conv6, 1), 2, name='predict_flow6', strides=1, activation=tf.identity) flow6_up = tf.layers.conv2d_transpose(flow6, 2, name='upsampled_flow6_to_5') x = tf.layers.conv2d_transpose(conv6, 512, name='deconv5', activation=lambda x: tf.nn.leaky_relu(x, 0.1)) # return flow6 concat5 = tf.concat([conv5, x, flow6_up], axis=1, name='concat5') flow5 = tf.layers.conv2d(pad(concat5, 1), 2, name='predict_flow5', strides=1, activation=tf.identity) flow5_up = tf.layers.conv2d_transpose(flow5, 2, name='upsampled_flow5_to_4') x = tf.layers.conv2d_transpose(concat5, 256, name='deconv4', activation=lambda x: tf.nn.leaky_relu(x, 0.1)) concat4 = tf.concat([conv4, x, flow5_up], axis=1, name='concat4') flow4 = tf.layers.conv2d(pad(concat4, 1), 2, name='predict_flow4', strides=1, activation=tf.identity) flow4_up = tf.layers.conv2d_transpose(flow4, 2, name='upsampled_flow4_to_3') x = tf.layers.conv2d_transpose(concat4, 128, name='deconv3', activation=lambda x: tf.nn.leaky_relu(x, 0.1)) concat3 = tf.concat([conv3_1, x, flow4_up], axis=1, name='concat3') flow3 = tf.layers.conv2d(pad(concat3, 1), 2, name='predict_flow3', strides=1, activation=tf.identity) flow3_up = tf.layers.conv2d_transpose(flow3, 2, name='upsampled_flow3_to_2') x = tf.layers.conv2d_transpose(concat3, 64, name='deconv2', activation=lambda x: tf.nn.leaky_relu(x, 0.1)) concat2 = tf.concat([conv2a, x, flow3_up], axis=1, name='concat2') flow2 = tf.layers.conv2d(pad(concat2, 1), 2, name='predict_flow2', strides=1, activation=tf.identity) return tf.identity(flow2, name='flow2')
[ "def", "graph_structure", "(", "self", ",", "x1x2", ")", ":", "with", "argscope", "(", "[", "tf", ".", "layers", ".", "conv2d", "]", ",", "activation", "=", "lambda", "x", ":", "tf", ".", "nn", ".", "leaky_relu", "(", "x", ",", "0.1", ")", ",", "padding", "=", "'valid'", ",", "strides", "=", "2", ",", "kernel_size", "=", "3", ",", "data_format", "=", "'channels_first'", ")", ",", "argscope", "(", "[", "tf", ".", "layers", ".", "conv2d_transpose", "]", ",", "padding", "=", "'same'", ",", "activation", "=", "tf", ".", "identity", ",", "data_format", "=", "'channels_first'", ",", "strides", "=", "2", ",", "kernel_size", "=", "4", ")", ":", "# extract features", "x", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "x1x2", ",", "3", ")", ",", "64", ",", "kernel_size", "=", "7", ",", "name", "=", "'conv1'", ")", "conv2", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "x", ",", "2", ")", ",", "128", ",", "kernel_size", "=", "5", ",", "name", "=", "'conv2'", ")", "conv3", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "conv2", ",", "2", ")", ",", "256", ",", "kernel_size", "=", "5", ",", "name", "=", "'conv3'", ")", "conv2a", ",", "_", "=", "tf", ".", "split", "(", "conv2", ",", "2", ",", "axis", "=", "0", ")", "conv3a", ",", "conv3b", "=", "tf", ".", "split", "(", "conv3", ",", "2", ",", "axis", "=", "0", ")", "corr", "=", "correlation", "(", "conv3a", ",", "conv3b", ",", "kernel_size", "=", "1", ",", "max_displacement", "=", "20", ",", "stride_1", "=", "1", ",", "stride_2", "=", "2", ",", "pad", "=", "20", ",", "data_format", "=", "'NCHW'", ")", "corr", "=", "tf", ".", "nn", ".", "leaky_relu", "(", "corr", ",", "0.1", ")", "conv_redir", "=", "tf", ".", "layers", ".", "conv2d", "(", "conv3a", ",", "32", ",", "kernel_size", "=", "1", ",", "strides", "=", "1", ",", "name", "=", "'conv_redir'", ")", "in_conv3_1", "=", "tf", ".", "concat", "(", "[", "conv_redir", ",", "corr", "]", ",", "axis", "=", "1", ",", "name", "=", "'in_conv3_1'", ")", "conv3_1", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "in_conv3_1", ",", "1", ")", ",", "256", ",", "name", "=", "'conv3_1'", ",", "strides", "=", "1", ")", "x", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "conv3_1", ",", "1", ")", ",", "512", ",", "name", "=", "'conv4'", ")", "conv4", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "x", ",", "1", ")", ",", "512", ",", "name", "=", "'conv4_1'", ",", "strides", "=", "1", ")", "x", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "conv4", ",", "1", ")", ",", "512", ",", "name", "=", "'conv5'", ")", "conv5", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "x", ",", "1", ")", ",", "512", ",", "name", "=", "'conv5_1'", ",", "strides", "=", "1", ")", "x", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "conv5", ",", "1", ")", ",", "1024", ",", "name", "=", "'conv6'", ")", "conv6", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "x", ",", "1", ")", ",", "1024", ",", "name", "=", "'conv6_1'", ",", "strides", "=", "1", ")", "flow6", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "conv6", ",", "1", ")", ",", "2", ",", "name", "=", "'predict_flow6'", ",", "strides", "=", "1", ",", "activation", "=", "tf", ".", "identity", ")", "flow6_up", "=", "tf", ".", "layers", ".", "conv2d_transpose", "(", "flow6", ",", "2", ",", "name", "=", "'upsampled_flow6_to_5'", ")", "x", "=", "tf", ".", "layers", ".", "conv2d_transpose", "(", "conv6", ",", "512", ",", "name", "=", "'deconv5'", ",", "activation", "=", "lambda", "x", ":", "tf", ".", "nn", ".", "leaky_relu", "(", "x", ",", "0.1", ")", ")", "# return flow6", "concat5", "=", "tf", ".", "concat", "(", "[", "conv5", ",", "x", ",", "flow6_up", "]", ",", "axis", "=", "1", ",", "name", "=", "'concat5'", ")", "flow5", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "concat5", ",", "1", ")", ",", "2", ",", "name", "=", "'predict_flow5'", ",", "strides", "=", "1", ",", "activation", "=", "tf", ".", "identity", ")", "flow5_up", "=", "tf", ".", "layers", ".", "conv2d_transpose", "(", "flow5", ",", "2", ",", "name", "=", "'upsampled_flow5_to_4'", ")", "x", "=", "tf", ".", "layers", ".", "conv2d_transpose", "(", "concat5", ",", "256", ",", "name", "=", "'deconv4'", ",", "activation", "=", "lambda", "x", ":", "tf", ".", "nn", ".", "leaky_relu", "(", "x", ",", "0.1", ")", ")", "concat4", "=", "tf", ".", "concat", "(", "[", "conv4", ",", "x", ",", "flow5_up", "]", ",", "axis", "=", "1", ",", "name", "=", "'concat4'", ")", "flow4", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "concat4", ",", "1", ")", ",", "2", ",", "name", "=", "'predict_flow4'", ",", "strides", "=", "1", ",", "activation", "=", "tf", ".", "identity", ")", "flow4_up", "=", "tf", ".", "layers", ".", "conv2d_transpose", "(", "flow4", ",", "2", ",", "name", "=", "'upsampled_flow4_to_3'", ")", "x", "=", "tf", ".", "layers", ".", "conv2d_transpose", "(", "concat4", ",", "128", ",", "name", "=", "'deconv3'", ",", "activation", "=", "lambda", "x", ":", "tf", ".", "nn", ".", "leaky_relu", "(", "x", ",", "0.1", ")", ")", "concat3", "=", "tf", ".", "concat", "(", "[", "conv3_1", ",", "x", ",", "flow4_up", "]", ",", "axis", "=", "1", ",", "name", "=", "'concat3'", ")", "flow3", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "concat3", ",", "1", ")", ",", "2", ",", "name", "=", "'predict_flow3'", ",", "strides", "=", "1", ",", "activation", "=", "tf", ".", "identity", ")", "flow3_up", "=", "tf", ".", "layers", ".", "conv2d_transpose", "(", "flow3", ",", "2", ",", "name", "=", "'upsampled_flow3_to_2'", ")", "x", "=", "tf", ".", "layers", ".", "conv2d_transpose", "(", "concat3", ",", "64", ",", "name", "=", "'deconv2'", ",", "activation", "=", "lambda", "x", ":", "tf", ".", "nn", ".", "leaky_relu", "(", "x", ",", "0.1", ")", ")", "concat2", "=", "tf", ".", "concat", "(", "[", "conv2a", ",", "x", ",", "flow3_up", "]", ",", "axis", "=", "1", ",", "name", "=", "'concat2'", ")", "flow2", "=", "tf", ".", "layers", ".", "conv2d", "(", "pad", "(", "concat2", ",", "1", ")", ",", "2", ",", "name", "=", "'predict_flow2'", ",", "strides", "=", "1", ",", "activation", "=", "tf", ".", "identity", ")", "return", "tf", ".", "identity", "(", "flow2", ",", "name", "=", "'flow2'", ")" ]
Architecture of FlowNetCorr in Figure 2 of FlowNet 1.0. Args: x: 2CHW.
[ "Architecture", "of", "FlowNetCorr", "in", "Figure", "2", "of", "FlowNet", "1", ".", "0", ".", "Args", ":", "x", ":", "2CHW", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/OpticalFlow/flownet_models.py#L379-L442
train
tensorpack/tensorpack
examples/FasterRCNN/viz.py
draw_annotation
def draw_annotation(img, boxes, klass, is_crowd=None): """Will not modify img""" labels = [] assert len(boxes) == len(klass) if is_crowd is not None: assert len(boxes) == len(is_crowd) for cls, crd in zip(klass, is_crowd): clsname = cfg.DATA.CLASS_NAMES[cls] if crd == 1: clsname += ';Crowd' labels.append(clsname) else: for cls in klass: labels.append(cfg.DATA.CLASS_NAMES[cls]) img = viz.draw_boxes(img, boxes, labels) return img
python
def draw_annotation(img, boxes, klass, is_crowd=None): """Will not modify img""" labels = [] assert len(boxes) == len(klass) if is_crowd is not None: assert len(boxes) == len(is_crowd) for cls, crd in zip(klass, is_crowd): clsname = cfg.DATA.CLASS_NAMES[cls] if crd == 1: clsname += ';Crowd' labels.append(clsname) else: for cls in klass: labels.append(cfg.DATA.CLASS_NAMES[cls]) img = viz.draw_boxes(img, boxes, labels) return img
[ "def", "draw_annotation", "(", "img", ",", "boxes", ",", "klass", ",", "is_crowd", "=", "None", ")", ":", "labels", "=", "[", "]", "assert", "len", "(", "boxes", ")", "==", "len", "(", "klass", ")", "if", "is_crowd", "is", "not", "None", ":", "assert", "len", "(", "boxes", ")", "==", "len", "(", "is_crowd", ")", "for", "cls", ",", "crd", "in", "zip", "(", "klass", ",", "is_crowd", ")", ":", "clsname", "=", "cfg", ".", "DATA", ".", "CLASS_NAMES", "[", "cls", "]", "if", "crd", "==", "1", ":", "clsname", "+=", "';Crowd'", "labels", ".", "append", "(", "clsname", ")", "else", ":", "for", "cls", "in", "klass", ":", "labels", ".", "append", "(", "cfg", ".", "DATA", ".", "CLASS_NAMES", "[", "cls", "]", ")", "img", "=", "viz", ".", "draw_boxes", "(", "img", ",", "boxes", ",", "labels", ")", "return", "img" ]
Will not modify img
[ "Will", "not", "modify", "img" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/viz.py#L15-L30
train