Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function: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_pe... | [
"Visualize activations for convolution layers.\n\n Remarks:\n This tries to place all activations into a square.\n\n Args:\n activation: tensor with the activation [B,H,W,C]\n name: label for tensorboard\n\n Returns:\n image of almost all activations\n "
] |
Please provide a description of the function: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))
... | [
"\n Make the static shape of a tensor less specific.\n\n If you want to feed to a tensor, the shape of the feed value must match\n the tensor's static shape. This function creates a placeholder which\n defaults to x if not fed, but has a less specific static shape than x.\n See also `tensorflow#5680 ... |
Please provide a description of the function: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,... | [
"\n Estimate H(x|s) ~= -E_{x \\sim P(x|s)}[\\log Q(x|s)], where x are samples, and Q is parameterized by vec.\n "
] |
Please provide a description of the function: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... | [
"\n OpenAI official code actually models the \"uniform\" latent code as\n a Gaussian distribution, but obtain the samples from a uniform distribution.\n "
] |
Please provide a description of the function: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([BATC... | [
"\n Mutual information between x (i.e. zc in this case) and some\n information s (the generated samples in this case):\n\n I(x;s) = H(x) - H(x|s)\n = H(x) + E[\\log P(x|s)]\n\n The distribution from which zc is sampled, in this case, is set to a fixe... |
Please provide a description of the function: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... | [
" see \"Dynamic Filter Networks\" (NIPS 2016)\n by Bert De Brabandere*, Xu Jia*, Tinne Tuytelaars and Luc Van Gool\n\n Remarks:\n This is the convolution version of a dynamic filter.\n\n Args:\n inputs : unfiltered input [b, h, w, 1] only grayscale images.\n filters : learned filte... |
Please provide a description of the function: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... | [
"Estimate filters for convolution layers\n\n Args:\n theta: angle of filter\n kernel_shape: size of each filter\n\n Returns:\n learned filter as [B, k, k, 1]\n "
] |
Please provide a description of the function: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.... | [
"Implements a steerable Gaussian filter.\n\n This function can be used to evaluate the first\n directional derivative of an image, using the\n method outlined in\n\n W. T. Freeman and E. H. Adelson, \"The Design\n and Use of Steerable Filters\", IEEE PAMI, 1991.\n\n ... |
Please provide a description of the function: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)
as... | [
"\n Assign `self.g_vars` to the parameters under scope `g_scope`,\n and same with `self.d_vars`.\n "
] |
Please provide a description of the function: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.summ... | [
"\n Build standard GAN loss and set `self.g_loss` and `self.d_loss`.\n\n D and G play two-player minimax game with value function V(G,D)\n\n min_G max _D V(D, G) = IE_{x ~ p_data} [log D(x)] + IE_{z ~ p_fake} [log (1 - D(G(z)))]\n\n Args:\n logits_real (tf.Tensor): discrim l... |
Please provide a description of the function: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())
... | [
"\n We need to set tower_func because it's a TowerTrainer,\n and only TowerTrainer supports automatic graph creation for inference during training.\n\n If we don't care about inference during training, using tower_func is\n not needed. Just calling model.build_graph directly is OK.\n ... |
Please provide a description of the function: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) ... | [
"\n After applying this decorator:\n 1. data_format becomes tf.layers style\n 2. nl becomes activation\n 3. initializers are renamed\n 4. positional args are transformed to corresponding kwargs, according to args_names\n 5. kwargs are mapped to tf.layers names if needed, by name_mapping\n "
] |
Please provide a description of the function: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
... | [
"\n Args:\n mapping(dict): an old -> new mapping for variable basename. e.g. {'kernel': 'W'}\n\n Returns:\n A context where the variables are renamed.\n "
] |
Please provide a description of the function: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 ... | [
"\n Apply a regularizer on trainable variables matching the regex, and print\n the matched variables (only print once in multi-tower training).\n In replicated mode, it will only regularize variables within the current tower.\n\n If called under a TowerContext with `is_training==False`, this function re... |
Please provide a description of the function: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 ... | [
"\n Get the cost from the regularizers in ``tf.GraphKeys.REGULARIZATION_LOSSES``.\n If in replicated mode, will only regularize variables created within the current tower.\n\n Args:\n name (str): the name of the returned tensor\n\n Returns:\n tf.Tensor: a scalar, the total regularization c... |
Please provide a description of the function: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 ... | [
"\n Same as `tf.layers.dropout`.\n However, for historical reasons, the first positional argument is\n interpreted as keep_prob rather than drop_prob.\n Explicitly use `rate=` keyword arguments to ensure things are consistent.\n "
] |
Please provide a description of the function:def fill(self, background_shape, img):
background_shape = tuple(background_shape)
return self._fill(background_shape, img) | [
"\n Return a proper background image of background_shape, given img.\n\n Args:\n background_shape (tuple): a shape (h, w)\n img: an image\n Returns:\n a background image\n "
] |
Please provide a description of the function:def apply(self, func, *args, **kwargs):
ret = func(self._t, *args, **kwargs)
return LinearWrap(ret) | [
"\n Apply a function on the wrapped tensor.\n\n Returns:\n LinearWrap: ``LinearWrap(func(self.tensor(), *args, **kwargs))``.\n "
] |
Please provide a description of the function:def apply2(self, func, *args, **kwargs):
ret = func(args[0], self._t, *(args[1:]), **kwargs)
return LinearWrap(ret) | [
"\n Apply a function on the wrapped tensor. The tensor\n will be the second argument of func.\n\n This is because many symbolic functions\n (such as tensorpack's layers) takes 'scope' as the first argument.\n\n Returns:\n LinearWrap: ``LinearWrap(func(args[0], self.tens... |
Please provide a description of the function: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]),
... | [
"\n Returns:\n A context where the gradient of :meth:`tf.nn.relu` is replaced by\n guided back-propagation, as described in the paper:\n `Striving for Simplicity: The All Convolutional Net\n <https://arxiv.org/abs/1412.6806>`_\n "
] |
Please provide a description of the function: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) | [
"\n Produce a saliency map as described in the paper:\n `Deep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Maps\n <https://arxiv.org/abs/1312.6034>`_.\n The saliency map is the gradient of the max element in output w.r.t input.\n\n Returns:\n tf.Tensor: t... |
Please provide a description of the function: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_... | [
"\n A wrapper around `tf.layers.Conv2D`.\n Some differences to maintain backward-compatibility:\n\n 1. Default kernel initializer is variance_scaling_initializer(2.0).\n 2. Default padding is 'same'.\n 3. Support 'split' argument to do group conv. Note that this is not efficient.\n\n Variable Name... |
Please provide a description of the function: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_... | [
"\n A wrapper around `tf.layers.Conv2DTranspose`.\n Some differences to maintain backward-compatibility:\n\n 1. Default kernel initializer is variance_scaling_initializer(2.0).\n 2. Default padding is 'same'\n\n Variable Names:\n\n * ``W``: weights\n * ``b``: bias\n "
] |
Please provide a description of the function: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 v... | [
" Will setup the assign operator for that variable. "
] |
Please provide a description of the function: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 No... | [
"\n Returns:\n The value to assign to the variable.\n\n Note:\n Subclasses will implement the abstract method\n :meth:`_get_value_to_set`, which should return a new value to\n set, or return None to do nothing.\n "
] |
Please provide a description of the function: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
... | [
"\n Using schedule, compute the value to be set at a given point.\n "
] |
Please provide a description of the function: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
... | [
"This function should build the model which takes the input variables\n and return cost at the end"
] |
Please provide a description of the function: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': ... | [
" Convert a caffe parameter name to a tensorflow parameter name as\n defined in the above model "
] |
Please provide a description of the function: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
el... | [
"\n Args:\n custom_getter: the same as in :func:`tf.get_variable`\n\n Returns:\n The current variable scope with a custom_getter.\n "
] |
Please provide a description of the function:def remap_variables(fn):
def custom_getter(getter, *args, **kwargs):
v = getter(*args, **kwargs)
return fn(v)
return custom_getter_scope(custom_getter) | [
"\n Use fn to map the output of any variable getter.\n\n Args:\n fn (tf.Variable -> tf.Tensor)\n\n Returns:\n The current variable scope with a custom_getter that maps\n all the variables by fn.\n\n Example:\n .. code-block:: python\n\n with varreplace.remap_variab... |
Please provide a description of the function: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[... | [
"\n Return a context to freeze variables,\n by wrapping ``tf.get_variable`` with a custom getter.\n It works by either applying ``tf.stop_gradient`` on the variables,\n or by keeping them out of the ``TRAINABLE_VARIABLES`` collection, or\n both.\n\n Example:\n .. code-block:: python\n\n ... |
Please provide a description of the function: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... | [
"\n Load a caffe model. You must be able to ``import caffe`` to use this\n function.\n Args:\n model_desc (str): path to caffe model description file (.prototxt).\n model_file (str): path to caffe model parameter file (.caffemodel).\n Returns:\n dict: the parameters.\n "
] |
Please provide a description of the function: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... | [
"\n Get caffe protobuf.\n Returns:\n The imported caffe protobuf module.\n "
] |
Please provide a description of the function: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. "
] |
Please provide a description of the function: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 confi... | [
"Update from command line args. "
] |
Please provide a description of the function: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, enco... | [
"\n Get a corresponding model loader by looking at the file name.\n\n Returns:\n SessInit: either a :class:`DictRestore` (if name ends with 'npy/npz') or\n :class:`SaverRestore` (otherwise).\n "
] |
Please provide a description of the function: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... | [
" return a set of strings "
] |
Please provide a description of the function: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 {}... | [
"\n Args:\n layers (list or layer): layer or list of layers to apply the arguments.\n\n Returns:\n a context where all appearance of these layer will by default have the\n arguments specified by kwargs.\n\n Example:\n .. code-block:: python\n\n with argscope(Conv2D, k... |
Please provide a description of the function: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)
... | [
"Decorator for function to support argscope\n\n Example:\n\n .. code-block:: python\n\n from mylib import myfunc\n myfunc = enable_argscope_for_function(myfunc)\n\n Args:\n func: A function mapping one or multiple tensors to one or multiple\n tensors.\n lo... |
Please provide a description of the function: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... | [
"\n Overwrite all functions of a given module to support argscope.\n Note that this function monkey-patches the module and therefore could\n have unexpected consequences.\n It has been only tested to work well with ``tf.layers`` module.\n\n Example:\n\n .. code-block:: python\n\n im... |
Please provide a description of the function: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)\n\n Args:\n name: name for visualization operation\n *imgs: multiple tensors as list\n scale_func: scale input tensors to fit range [0, 255]\n\n Example:\n visualize_tensors('viz1', [img1])\n visualize_tensors('viz2', [img... |
Please provide a description of the function: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 ... | [
"\n img: an RGB image of shape (s, 2s, 3).\n :return: [input, output]\n "
] |
Please provide a description of the function: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)
... | [
" return a (b, 1) logits"
] |
Please provide a description of the function: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, na... | [
" A simple print Op that might be easier to use than :meth:`tf.Print`.\n Use it like: ``x = print_stat(x, message='This is x')``.\n "
] |
Please provide a description of the function: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)), nam... | [
"\n Returns:\n root mean square of tensor x.\n "
] |
Please provide a description of the function: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 nume... | [
"`Peek Signal to Noise Ratio <https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio>`_.\n\n .. math::\n\n PSNR = 20 \\cdot \\log_{10}(MAX_p) - 10 \\cdot \\log_{10}(MSE)\n\n Args:\n prediction: a :class:`tf.Tensor` representing the prediction signal.\n ground_truth: another :class:`tf.T... |
Please provide a description of the function: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]
... | [
"\n Args:\n anchor: coordinate of the center\n "
] |
Please provide a description of the function:def pad(x, p=3):
return tf.pad(x, [[0, 0], [0, 0], [p, p], [p, p]]) | [
"Pad tensor in H, W\n\n Remarks:\n TensorFlow uses \"ceil(input_spatial_shape[i] / strides[i])\" rather than explicit padding\n like Caffe, pyTorch does. Hence, we need to pad here beforehand.\n\n Args:\n x (tf.tensor): incoming tensor\n p (int, optional): padding for H, W\n\n R... |
Please provide a description of the function: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 % ... | [
"\n Correlation Cost Volume computation.\n\n This is a fallback Python-only implementation, specialized just for FlowNet2.\n It takes a lot of memory and is slow.\n\n If you know to compile a custom op yourself, it's better to use the cuda implementation here:\n https://github.com/PatWie/tensorflow-r... |
Please provide a description of the function: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)
el... | [
"Resize input tensor with unkown input-shape by a factor\n\n Args:\n x (tf.Tensor): tensor NCHW\n factor (int, optional): resize factor for H, W\n\n Note:\n Differences here against Caffe have huge impacts on the\n quality of the predictions.\n\n Returns:\n tf.Tensor: res... |
Please provide a description of the function: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.la... | [
"\n Architecture in Table 4 of FlowNet 2.0.\n\n Args:\n x: NCHW tensor, where C=11 is the concatenation of 7 items of [3, 2, 2, 1, 1, 1, 1] channels.\n "
] |
Please provide a description of the function: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... | [
"\n Architecture in Table 3 of FlowNet 2.0.\n\n Args:\n x: concatenation of two inputs, of shape [1, 2xC, H, W]\n "
] |
Please provide a description of the function: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... | [
"\n Architecture of FlowNetSimple in Figure 2 of FlowNet 1.0.\n\n Args:\n x: 2CHW if standalone==True, else NCHW where C=12 is a concatenation\n of 5 tensors of [3, 3, 3, 2, 1] channels.\n standalone: If True, this model is used to predict flow from two inputs.\n ... |
Please provide a description of the function: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... | [
"\n Architecture of FlowNetCorr in Figure 2 of FlowNet 1.0.\n Args:\n x: 2CHW.\n "
] |
Please provide a description of the function: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[cl... | [
"Will not modify img"
] |
Please provide a description of the function:def draw_proposal_recall(img, proposals, proposal_scores, gt_boxes):
box_ious = np_iou(gt_boxes, proposals) # ng x np
box_ious_argsort = np.argsort(-box_ious, axis=1)
good_proposals_ind = box_ious_argsort[:, :3] # for each gt, find 3 best proposals
... | [
"\n Draw top3 proposals for each gt.\n Args:\n proposals: NPx4\n proposal_scores: NP\n gt_boxes: NG\n "
] |
Please provide a description of the function:def draw_predictions(img, boxes, scores):
if len(boxes) == 0:
return img
labels = scores.argmax(axis=1)
scores = scores.max(axis=1)
tags = ["{},{:.2f}".format(cfg.DATA.CLASS_NAMES[lb], score) for lb, score in zip(labels, scores)]
return viz.d... | [
"\n Args:\n boxes: kx4\n scores: kxC\n "
] |
Please provide a description of the function:def draw_final_outputs(img, results):
if len(results) == 0:
return img
# Display in largest to smallest order to reduce occlusion
boxes = np.asarray([r.box for r in results])
areas = np_area(boxes)
sorted_inds = np.argsort(-areas)
ret =... | [
"\n Args:\n results: [DetectionResult]\n "
] |
Please provide a description of the function:def draw_mask(im, mask, alpha=0.5, color=None):
if color is None:
color = PALETTE_RGB[np.random.choice(len(PALETTE_RGB))][::-1]
im = np.where(np.repeat((mask > 0)[:, :, None], 3, axis=2),
im * (1 - alpha) + color * alpha, im)
im = i... | [
"\n Overlay a mask on top of the image.\n\n Args:\n im: a 3-channel uint8 image in BGR\n mask: a binary 1-channel image of the same size\n color: if None, will choose automatically\n "
] |
Please provide a description of the function:def send_dataflow_zmq(df, addr, hwm=50, format=None, bind=False):
assert format in [None, 'zmq_op', 'zmq_ops']
if format is None:
dump_fn = dumps
else:
from zmq_ops import dump_arrays
dump_fn = dump_arrays
ctx = zmq.Context()
... | [
"\n Run DataFlow and send data to a ZMQ socket addr.\n It will serialize and send each datapoint to this address with a PUSH socket.\n This function never returns.\n\n Args:\n df (DataFlow): Will infinitely loop over the DataFlow.\n addr: a ZMQ socket endpoint.\n hwm (int): ZMQ high... |
Please provide a description of the function:def dump_dataflow_to_process_queue(df, size, nr_consumer):
q = mp.Queue(size)
class EnqueProc(mp.Process):
def __init__(self, df, q, nr_consumer):
super(EnqueProc, self).__init__()
self.df = df
self.q = q
de... | [
"\n Convert a DataFlow to a :class:`multiprocessing.Queue`.\n The DataFlow will only be reset in the spawned process.\n\n Args:\n df (DataFlow): the DataFlow to dump.\n size (int): size of the queue\n nr_consumer (int): number of consumer of the queue.\n The producer will ad... |
Please provide a description of the function:def _grab_raw_image(self):
m = self.ale.getScreenRGB()
return m.reshape((self.height, self.width, 3)) | [
"\n :returns: the current 3-channel image\n "
] |
Please provide a description of the function:def _current_state(self):
ret = self._grab_raw_image()
# max-pooled over the last screen
ret = np.maximum(ret, self.last_raw_screen)
if self.viz:
if isinstance(self.viz, float):
cv2.imshow(self.windowname, ... | [
"\n :returns: a gray-scale (h, w) uint8 image\n "
] |
Please provide a description of the function:def clip_boxes(boxes, window, name=None):
boxes = tf.maximum(boxes, 0.0)
m = tf.tile(tf.reverse(window, [0]), [2]) # (4,)
boxes = tf.minimum(boxes, tf.cast(m, tf.float32), name=name)
return boxes | [
"\n Args:\n boxes: nx4, xyxy\n window: [h, w]\n "
] |
Please provide a description of the function:def decode_bbox_target(box_predictions, anchors):
orig_shape = tf.shape(anchors)
box_pred_txtytwth = tf.reshape(box_predictions, (-1, 2, 2))
box_pred_txty, box_pred_twth = tf.split(box_pred_txtytwth, 2, axis=1)
# each is (...)x1x2
anchors_x1y1x2y2 = ... | [
"\n Args:\n box_predictions: (..., 4), logits\n anchors: (..., 4), floatbox. Must have the same shape\n\n Returns:\n box_decoded: (..., 4), float32. With the same shape.\n "
] |
Please provide a description of the function:def encode_bbox_target(boxes, anchors):
anchors_x1y1x2y2 = tf.reshape(anchors, (-1, 2, 2))
anchors_x1y1, anchors_x2y2 = tf.split(anchors_x1y1x2y2, 2, axis=1)
waha = anchors_x2y2 - anchors_x1y1
xaya = (anchors_x2y2 + anchors_x1y1) * 0.5
boxes_x1y1x2y... | [
"\n Args:\n boxes: (..., 4), float32\n anchors: (..., 4), float32\n\n Returns:\n box_encoded: (..., 4), float32 with the same shape.\n "
] |
Please provide a description of the function:def crop_and_resize(image, boxes, box_ind, crop_size, pad_border=True):
assert isinstance(crop_size, int), crop_size
boxes = tf.stop_gradient(boxes)
# TF's crop_and_resize produces zeros on border
if pad_border:
# this can be quite slow
... | [
"\n Aligned version of tf.image.crop_and_resize, following our definition of floating point boxes.\n\n Args:\n image: NCHW\n boxes: nx4, x1y1x2y2\n box_ind: (n,)\n crop_size (int):\n Returns:\n n,C,size,size\n ",
"\n The way tf.image.crop_and_resize works (wit... |
Please provide a description of the function:def roi_align(featuremap, boxes, resolution):
# sample 4 locations per roi bin
ret = crop_and_resize(
featuremap, boxes,
tf.zeros([tf.shape(boxes)[0]], dtype=tf.int32),
resolution * 2)
ret = tf.nn.avg_pool(ret, [1, 1, 2, 2], [1, 1, 2,... | [
"\n Args:\n featuremap: 1xCxHxW\n boxes: Nx4 floatbox\n resolution: output spatial resolution\n\n Returns:\n NxCx res x res\n "
] |
Please provide a description of the function:def narrow_to(self, featuremap):
shape2d = tf.shape(featuremap)[2:] # h,w
slice3d = tf.concat([shape2d, [-1]], axis=0)
slice4d = tf.concat([shape2d, [-1, -1]], axis=0)
boxes = tf.slice(self.boxes, [0, 0, 0, 0], slice4d)
gt_la... | [
"\n Slice anchors to the spatial size of this featuremap.\n "
] |
Please provide a description of the function:def colorize(img, heatmap):
heatmap = viz.intensity_to_rgb(heatmap, cmap='jet')[:, :, ::-1]
return img * 0.5 + heatmap * 0.5 | [
" img: bgr, [0,255]\n heatmap: [0,1]\n "
] |
Please provide a description of the function:def _get_augment_params(self, img):
center = img.shape[1::-1] * self._rand_range(
self.center_range[0], self.center_range[1], (2,))
deg = self._rand_range(-self.max_deg, self.max_deg)
if self.step_deg:
deg = deg // self.step_de... | [
"\n The correct center is shape*0.5-0.5. This can be verified by:\n\n SHAPE = 7\n arr = np.random.rand(SHAPE, SHAPE)\n orig = arr\n c = SHAPE * 0.5 - 0.5\n c = (c, c)\n for k in range(4):\n mat = cv2.getRotationMatrix2D(c, 90, 1)\n arr = cv2.war... |
Please provide a description of the function:def largest_rotated_rect(w, h, angle):
angle = angle / 180.0 * math.pi
if w <= 0 or h <= 0:
return 0, 0
width_is_longer = w >= h
side_long, side_short = (w, h) if width_is_longer else (h, w)
# since the solutions... | [
"\n Get largest rectangle after rotation.\n http://stackoverflow.com/questions/16702966/rotate-image-and-crop-out-black-borders\n "
] |
Please provide a description of the function:def map_arg(**maps):
def deco(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if six.PY2:
argmap = inspect.getcallargs(func, *args, **kwargs)
else:
# getcallargs was deprecated since... | [
"\n Apply a mapping on certain argument before calling the original function.\n\n Args:\n maps (dict): {argument_name: map_func}\n "
] |
Please provide a description of the function:def graph_memoized(func):
# TODO it keeps the graph alive
from ..compat import tfv1
GRAPH_ARG_NAME = '__IMPOSSIBLE_NAME_FOR_YOU__'
@memoized
def func_with_graph_arg(*args, **kwargs):
kwargs.pop(GRAPH_ARG_NAME)
return func(*args, **k... | [
"\n Like memoized, but keep one cache per default graph.\n "
] |
Please provide a description of the function:def memoized_ignoreargs(func):
def wrapper(*args, **kwargs):
if func not in _MEMOIZED_NOARGS:
res = func(*args, **kwargs)
_MEMOIZED_NOARGS[func] = res
return res
return _MEMOIZED_NOARGS[func]
return wrapper | [
"\n A decorator. It performs memoization ignoring the arguments used to call\n the function.\n "
] |
Please provide a description of the function:def shape2d(a):
if type(a) == int:
return [a, a]
if isinstance(a, (list, tuple)):
assert len(a) == 2
return list(a)
raise RuntimeError("Illegal shape: {}".format(a)) | [
"\n Ensure a 2D shape.\n\n Args:\n a: a int or tuple/list of length 2\n\n Returns:\n list: of length 2. if ``a`` is a int, return ``[a, a]``.\n "
] |
Please provide a description of the function:def shape4d(a, data_format='NHWC'):
s2d = shape2d(a)
if get_data_format(data_format, False) == 'NHWC':
return [1] + s2d + [1]
else:
return [1, 1] + s2d | [
"\n Ensuer a 4D shape, to use with 4D symbolic functions.\n\n Args:\n a: a int or tuple/list of length 2\n\n Returns:\n list: of length 4. if ``a`` is a int, return ``[1, a, a, 1]``\n or ``[1, 1, a, a]`` depending on data_format.\n "
] |
Please provide a description of the function:def call_only_once(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
self = args[0]
# cannot use hasattr here, because hasattr tries to getattr, which
# fails if func is a property
assert func.__name__ in dir(self), "cal... | [
"\n Decorate a method or property of a class, so that this method can only\n be called once for every instance.\n Calling it more than once will result in exception.\n "
] |
Please provide a description of the function:def memoized_method(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
self = args[0]
assert func.__name__ in dir(self), "memoized_method can only be used on method!"
if not hasattr(self, '_MEMOIZED_CACHE'):
cache =... | [
"\n A decorator that performs memoization on methods. It stores the cache on the object instance itself.\n "
] |
Please provide a description of the function:def auto_reuse_variable_scope(func):
used_scope = set()
@functools.wraps(func)
def wrapper(*args, **kwargs):
scope = tf.get_variable_scope()
h = hash((tf.get_default_graph(), scope.name))
# print("Entering " + scope.name + " reuse: "... | [
"\n A decorator which automatically reuses the current variable scope if the\n function has been called with the same variable scope before.\n\n Example:\n\n .. code-block:: python\n\n @auto_reuse_variable_scope\n def myfunc(x):\n return tf.layers.conv2d(x, 128, 3)\n\n my... |
Please provide a description of the function:def under_name_scope(name_scope=None):
def _impl(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
scopename = kwargs.pop('name_scope', name_scope)
if scopename is None:
scopename = func.__name__
... | [
"\n Args:\n name_scope(str): the default scope to use. If None, will use the name of the function.\n\n Returns:\n A decorator which makes the function run under a name scope.\n The name scope is obtained by the following:\n 1. The 'name_scope' keyword argument when the decorated fu... |
Please provide a description of the function:def under_variable_scope():
def _impl(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
name = func.__name__
with tf.variable_scope(name):
return func(*args, **kwargs)
return wrapper
retu... | [
"\n Returns:\n A decorator which makes the function happen under a variable scope,\n which is named by the function itself.\n\n Example:\n\n .. code-block:: python\n\n @under_variable_scope()\n def mid_level(x):\n with argscope(Conv2D, kernel_shape=3, nl=BNReLU):\n ... |
Please provide a description of the function:def cached_name_scope(name, top_level=True):
if not top_level:
current_ns = tf.get_default_graph().get_name_scope()
if current_ns:
name = current_ns + '/' + name
ns = _get_cached_ns(name)
with tf.name_scope(ns):
yield ns | [
"\n Return a context which either opens and caches a new name scope,\n or reenter an existing one.\n\n Args:\n top_level(bool): if True, the name scope will always be top-level.\n It will not be nested under any existing name scope of the caller.\n "
] |
Please provide a description of the function:def _check_grad_list(grad_list):
nvars = [len(k) for k in grad_list]
def basename(x):
return re.sub('tower[0-9]+/', '', x.op.name)
if len(set(nvars)) != 1:
names_per_gpu = [set([basename(k[1]) for k in grad_and_vars]... | [
"\n Args:\n grad_list: list of list of tuples, shape is Ngpu x Nvar x 2\n "
] |
Please provide a description of the function:def call_for_each_tower(
towers, func, devices=None, use_vs=None):
ret = []
if devices is not None:
assert len(devices) == len(towers)
if use_vs is not None:
assert len(use_vs) == len(towers)
towe... | [
"\n Run `func` on all GPUs (towers) and return the results.\n\n Args:\n towers (list[int]): a list of GPU id.\n func: a lambda to be called inside each tower\n devices: a list of devices to be used. By default will use '/gpu:{tower}'\n use_vs (list[bool]): l... |
Please provide a description of the function:def build(self, grad_list, get_opt_fn):
assert len(grad_list) == len(self.towers)
DataParallelBuilder._check_grad_list(grad_list)
# debug tower performance (without update):
# ops = [k[0] for k in grad_list[1]] + [k[0] for k in grad_... | [
"\n Reduce the gradients, apply them with the optimizer,\n and set self.grads to a list of (g, v), containing the averaged gradients.\n\n Args:\n grad_list ([[(grad, var), ...], ...]): #GPU lists to be reduced. Each is the gradients computed on each GPU.\n get_opt_fn (-> t... |
Please provide a description of the function:def call_for_each_tower(self, tower_fn):
# if tower_fn returns [(grad, var), ...], this returns #GPU x #VAR x 2
return DataParallelBuilder.build_on_towers(
self.towers,
tower_fn,
# use no variable scope for the fir... | [
"\n Call the function `tower_fn` under :class:`TowerContext` for each tower.\n\n Returns:\n a list, contains the return values of `tower_fn` on each tower.\n "
] |
Please provide a description of the function:def build(self, grad_list, get_opt_fn):
assert len(grad_list) == len(self.towers)
raw_devices = ['/gpu:{}'.format(k) for k in self.towers]
DataParallelBuilder._check_grad_list(grad_list)
dtypes = set([x[0].dtype.base_dtype for x in ... | [
"\n Reduce the gradients, apply them with the optimizer,\n and set self.grads to #GPU number of lists of (g, v), containing the all-reduced gradients on each device.\n\n Args:\n grad_list ([[(grad, var), ...], ...]): #GPU lists to be reduced. Each is the gradients computed on each GP... |
Please provide a description of the function:def get_post_init_ops():
# literally all variables, because it's better to sync optimizer-internal variables as well
all_vars = tf.global_variables() + tf.local_variables()
var_by_name = dict([(v.name, v) for v in all_vars])
trainable... | [
"\n Copy values of variables on GPU 0 to other GPUs.\n "
] |
Please provide a description of the function:def call_for_each_tower(self, tower_fn):
ps_device = 'cpu' if len(self.towers) >= 4 else 'gpu'
raw_devices = ['/gpu:{}'.format(k) for k in self.towers]
if ps_device == 'gpu':
devices = [LeastLoadedDeviceSetter(d, raw_devices) for... | [
"\n Call the function `tower_fn` under :class:`TowerContext` for each tower.\n\n Returns:\n a list, contains the return values of `tower_fn` on each tower.\n "
] |
Please provide a description of the function:def build(self, grad_list, get_opt_fn):
assert len(grad_list) == len(self.towers)
DataParallelBuilder._check_grad_list(grad_list)
if self._scale_gradient and len(self.towers) > 1:
# pretend to average the grads, in order to make ... | [
"\n Args:\n grad_list ([[(grad, var), ...], ...]): #GPU lists to be reduced. Each is the gradients computed on each GPU.\n get_opt_fn (-> tf.train.Optimizer): callable which returns an optimizer\n\n Returns:\n tf.Operation: the training op\n "
] |
Please provide a description of the function:def humanize_time_delta(sec):
if sec < 0:
logger.warn("humanize_time_delta() obtains negative seconds!")
return "{:.3g} seconds".format(sec)
if sec == 0:
return "0 second"
time = datetime(2000, 1, 1) + timedelta(seconds=int(sec))
... | [
"Humanize timedelta given in seconds\n\n Args:\n sec (float): time difference in seconds. Must be positive.\n\n Returns:\n str - time difference as a readable string\n\n Example:\n\n .. code-block:: python\n\n print(humanize_time_delta(1)) # 1 secon... |
Please provide a description of the function:def change_env(name, val):
oldval = os.environ.get(name, None)
os.environ[name] = val
yield
if oldval is None:
del os.environ[name]
else:
os.environ[name] = oldval | [
"\n Args:\n name(str), val(str):\n\n Returns:\n a context where the environment variable ``name`` being set to\n ``val``. It will be set back after the context exits.\n "
] |
Please provide a description of the function:def get_rng(obj=None):
seed = (id(obj) + os.getpid() +
int(datetime.now().strftime("%Y%m%d%H%M%S%f"))) % 4294967295
if _RNG_SEED is not None:
seed = _RNG_SEED
return np.random.RandomState(seed) | [
"\n Get a good RNG seeded with time, pid and the object.\n\n Args:\n obj: some object to use to generate random seed.\n Returns:\n np.random.RandomState: the RNG.\n "
] |
Please provide a description of the function:def execute_only_once():
f = inspect.currentframe().f_back
ident = (f.f_code.co_filename, f.f_lineno)
if ident in _EXECUTE_HISTORY:
return False
_EXECUTE_HISTORY.add(ident)
return True | [
"\n Each called in the code to this function is guaranteed to return True the\n first time and False afterwards.\n\n Returns:\n bool: whether this is the first time this function gets called from this line of code.\n\n Example:\n .. code-block:: python\n\n if execute_only_once()... |
Please provide a description of the function:def get_tqdm_kwargs(**kwargs):
default = dict(
smoothing=0.5,
dynamic_ncols=True,
ascii=True,
bar_format='{l_bar}{bar}|{n_fmt}/{total_fmt}[{elapsed}<{remaining},{rate_noinv_fmt}]'
)
try:
# Use this env var to override... | [
"\n Return default arguments to be used with tqdm.\n\n Args:\n kwargs: extra arguments to be used.\n Returns:\n dict:\n "
] |
Please provide a description of the function:def find_library_full_path(name):
from ctypes.util import find_library
if os.name == "posix" and sys.platform == "darwin":
# on Mac, ctypes already returns full path
return find_library(name)
def _use_proc_maps(name):
procm... | [
"\n Similar to `from ctypes.util import find_library`, but try\n to return full path if possible.\n ",
"\n Find so from /proc/pid/maps\n Only works with libraries that has already been loaded.\n But this is the most accurate method -- it finds the exact library that's being used.\n ... |
Please provide a description of the function:def save(df, path, write_frequency=5000):
assert isinstance(df, DataFlow), type(df)
isdir = os.path.isdir(path)
if isdir:
assert not os.path.isfile(os.path.join(path, 'data.mdb')), "LMDB file exists!"
else:
ass... | [
"\n Args:\n df (DataFlow): the DataFlow to serialize.\n path (str): output path. Either a directory or an lmdb file.\n write_frequency (int): the frequency to write back data to disk.\n "
] |
Please provide a description of the function:def load(path, shuffle=True):
df = LMDBData(path, shuffle=shuffle)
return MapData(df, lambda dp: loads(dp[1])) | [
"\n Note:\n If you found deserialization being the bottleneck, you can use :class:`LMDBData` as the reader\n and run deserialization as a mapper in parallel.\n "
] |
Please provide a description of the function:def save(df, path):
buffer = []
size = _reset_df_and_get_size(df)
with get_tqdm(total=size) as pbar:
for dp in df:
buffer.append(dp)
pbar.update()
np.savez_compressed(path, buffer=np.asarray... | [
"\n Args:\n df (DataFlow): the DataFlow to serialize.\n path (str): output npz file.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.