code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
for required in ['amount', 'currency', 'name']: if required not in params: raise ValueError("Missing required parameter: %s" % required) response = self._post('v2', 'checkouts', data=params) return self._make_api_object(response, Checkout)
def create_checkout(self, **params)
https://developers.coinbase.com/api/v2#create-checkout
4.063786
3.034607
1.339148
response = self._get('v2', 'checkouts', checkout_id, 'orders', params=params) return self._make_api_object(response, Order)
def get_checkout_orders(self, checkout_id, **params)
https://developers.coinbase.com/api/v2#list-checkout39s-orders
4.611726
3.314097
1.391548
response = self._post('v2', 'checkouts', checkout_id, 'orders', data=params) return self._make_api_object(response, Order)
def create_checkout_order(self, checkout_id, **params)
https://developers.coinbase.com/api/v2#create-a-new-order-for-a-checkout
5.157991
3.742291
1.378298
params = { 'grant_type': 'refresh_token', 'refresh_token': self.refresh_token } response = self._post('oauth', 'token', params=params) response = self._handle_response(response) blob = response.json() self.access_token = blob.get('access_t...
def refresh(self)
Attempt to refresh the current access token / refresh token pair. If successful, the relevant attributes of this client will be updated automatically and the dict of token values and information given by the Coinbase OAuth server will be returned to the caller.
2.650947
2.403126
1.103124
cur_module = sys.modules[__name__] my_globals = dict(globals()) # Import here so that it doesn't get added to the global namespace or deleted. # pylint: disable=g-import-not-at-top from prettytensor.pretty_tensor_class import PrettyTensor for name, _ in six.iteritems(my_globals): if not hasattr(Prett...
def _remove_non_methods()
Removes any object in dict that is not a registered method.
4.643218
4.413956
1.05194
regex = re.compile(name_filter) def fn(var_name, variable, phase): if phase is pt.Phase.train and regex.search(var_name): with tf.name_scope(None, name, [variable]): loss = regularization_fn(variable) if loss is not None: tf.add_to_collection(tf.GraphKeys.REGULARIZATION_LOSSES, lo...
def regularizer(name, regularization_fn, name_filter='weights')
Wraps a regularizer in a parameter-function. Args: name: The name scope for this regularizer. regularization_fn: A function with signature: fn(variable) -> loss `Tensor` or `None`. name_filter: A regex that will be used to filter variables by name. Returns: A parameter modification function ...
3.036838
3.182219
0.954315
return regularizer( 'l2_regularizer', lambda x: tf.nn.l2_loss(x) * decay, name_filter=name_filter)
def l2_regularizer(decay, name_filter='weights')
Create an l2 regularizer.
2.715991
2.763239
0.982901
return regularizer( 'l1_regularizer', lambda x: tf.reduce_sum(tf.abs(x)) * decay, name_filter=name_filter)
def l1_regularizer(decay, name_filter='weights')
Create an l1 regularizer.
3.176126
3.255552
0.975603
def composed_fn(var_name, variable, phase): for fn in parameter_functions: variable = fn(var_name, variable, phase) return variable return composed_fn
def compose(*parameter_functions)
Composes multiple modification functions in order. Args: *parameter_functions: The functions to compose. Returns: A parameter modification function that consists of applying all the provided functions.
3.842652
4.42581
0.868237
with tf.name_scope(name, 'l1_regression', [y, target]) as scope: y = tf.convert_to_tensor(y, name='y') target = tf.convert_to_tensor(target, name='target') return reduce_batch_sum(tf.abs(y - target), name=scope)
def l1_regression_loss(y, target, name=None)
Calculates the sum of absolute errors between y and target. Args: y: the calculated values. target: the desired values. name: the name for this op, defaults to l1_regression Returns: A tensorflow op.
2.032358
2.028594
1.001856
with tf.name_scope(name, 'l2_regression_sq', [y, target]) as scope: y = tf.convert_to_tensor(y, name='y') target = tf.convert_to_tensor(target, name='target') return reduce_batch_sum(tf.square(y - target), name=scope)
def l2_regression_sq_loss(y, target, name=None)
Calculates the sum of squared errors between y and target. Args: y: the calculated values. target: the desired values. name: the name for this op, defaults to l2_regression Returns: A tensorflow op.
1.988531
2.026319
0.981351
with tf.name_scope(name, 'l2_regression', [y, target]) as scope: y = tf.convert_to_tensor(y, name='y') target = tf.convert_to_tensor(target, name='target') return tf.sqrt(l2_regression_sq_loss(y, target, name=scope))
def l2_regression_loss(y, target, name=None)
Calculates the square root of the SSE between y and target. Args: y: the calculated values. target: the desired values. name: the name for this op, defaults to l2_regression Returns: A tensorflow op.
1.960092
1.920979
1.020361
with tf.name_scope(name, 'binary_cross_entropy_with_logits', [x, target]) as scope: x.get_shape().assert_is_compatible_with(target.get_shape()) neg_softplus = -tf.nn.softplus(-x) return -tf.add(tf.multiply(target, neg_softplus), tf.multiply(1 - target, -x + neg_s...
def binary_cross_entropy_loss_with_logits(x, target, name=None)
Calculates the binary cross entropy between sigmoid(x) and target. Expects unscaled logits. Do not pass in results of sigmoid operation. Args: x: the calculated pre-sigmoid values target: the desired values. name: the name for this op, defaults to binary_cross_entropy_with_logits Returns: -(targ...
2.209963
1.981374
1.115369
with tf.name_scope(name, 'cos_distance', [t1, t2]) as scope: t1 = tf.convert_to_tensor(t1, name='t1') t2 = tf.convert_to_tensor(t2, name='t2') x_inv_norm = tf.rsqrt(tf.maximum(length_squared(t1) * length_squared(t2), epsilon)) return tf.subtract(1.0, dot_product...
def cos_distance(t1, t2, epsilon=1e-12, name=None)
Cos distance between t1 and t2 and caps the gradient of the Square Root. Args: t1: A tensor t2: A tensor that can be multiplied by t1. epsilon: A lower bound value for the distance. The square root is used as the normalizer. name: Optional name for this op. Returns: The cos distance betwe...
2.000915
2.033155
0.984143
with tf.name_scope(name, 'dot_distance', [t1, t2]) as scope: return -dot_product(t1, t2, name=scope)
def dot_distance(t1, t2, name=None)
dot "distance" between t1 and t2. Args: t1: A tensor. t2: A tensor that is the same size as t1. name: Optional name for this op. Returns: The dot distance between t1 and t2.
2.732437
2.802855
0.974876
with tf.name_scope(name, 'l2_distance_sq', [t1, t2]) as scope: t1 = tf.convert_to_tensor(t1, name='t1') t2 = tf.convert_to_tensor(t2, name='t2') return length_squared(tf.subtract(t1, t2), name=scope)
def l2_distance_sq(t1, t2, name=None)
Square of l2 distance between t1 and t2. Args: t1: A tensor. t2: A tensor that is the same size as t1. name: Optional name for this op. Returns: The l2 distance between t1 and t2.
1.705119
1.76793
0.964472
with tf.name_scope(name, 'l2_distance', [t1, t2]) as scope: t1 = tf.convert_to_tensor(t1, name='t1') t2 = tf.convert_to_tensor(t2, name='t2') return tf.sqrt(tf.maximum(l2_distance_sq(t1, t2, scope), epsilon))
def l2_distance(t1, t2, epsilon=1e-12, name=None)
l2 distance between t1 and t2 and caps the gradient of the Square Root. Args: t1: A tensor. t2: A tensor that is the same size as t1. epsilon: A lower bound for distance, useful to avoid sqrt of very small values that can blow up gradients. name: Optional name for this op. Returns: The l2...
1.741586
1.804558
0.965104
with tf.name_scope(name, 'l1_distance', [t1, t2]) as scope: t1 = tf.convert_to_tensor(t1, name='t1') t2 = tf.convert_to_tensor(t2, name='t2') sub = tf.subtract(t1, t2) reduction_dim = _last_index(sub, 1) return tf.reduce_sum(tf.abs(sub), reduction_dim, name=scope)
def l1_distance(t1, t2, name=None)
l1 distance between t1 and t2. Args: t1: A tensor. t2: A tensor that is the same size as t1. name: Optional name for this op. Returns: The l1 distance between t1 and t2.
1.951599
1.977814
0.986746
with tf.name_scope(name, 'leaky_relu', [x]) as scope: x = tf.convert_to_tensor(x, name='x') return tf.where(tf.less(x, 0.0), 0.01 * x, x, name=scope)
def leaky_relu(x, name=None)
Creates a leaky_relu. This is an alternate non-linearity to relu. The leaky part of the relu may prevent dead Neurons in a model since the gradient doesn't go completely to 0. Args: x: The input tensor. name: Optional name for this op. Returns: x if x > 0 otherwise 0.01 * x.
1.888477
1.645091
1.147947
if scale == 1: return tf.nn.softplus(x) else: with tf.name_scope(name, 'softplus', [x]): scale = tf.convert_to_tensor(scale, dtype=x.dtype.base_dtype) return tf.nn.softplus(x * scale) / scale
def softplus(x, scale=1.0, name=None)
Computes softplus with a scale factor to sharpen of the hinge. This is an alternate non-linearity to relu. It has a similar shape, but it has a smooth transition from the linear part to 0. Args: x: A tensor. scale: A float that sharpens the curve. name: Optional name. Returns: y = log(1 + exp(...
1.912133
2.071963
0.922861
with tf.name_scope(name, 'l1_normalize', [x]) as scope: x = tf.convert_to_tensor(x, name='x') x = tf.verify_tensor_all_finite(x, 'Error at input %s' % scope) x_norm = tf.maximum(tf.reduce_sum(tf.abs(x), [dim], keep_dims=True), epsilon) return tf.div(x, x_norm, name=scope)
def l1_normalize(x, dim, epsilon=1e-12, name=None)
l1 normalizes x. Args: x: The tensor to normalize. dim: The dimension to normalize along. epsilon: Lower bound on the norm, used to avoid exploding gradients as the norm approaches 0. name: Optional name for this op. Returns: x normalized along dim.
2.330895
2.36452
0.98578
with tf.name_scope(name, 'every_other', [x]) as scope: x = tf.convert_to_tensor(x, name='x') return tf.reshape( tf.slice( tf.reshape(x, [-1, 2]), [0, 0], [-1, 1]), [-1], name=scope)
def every_other(x, name=None)
Drops every other value from the tensor and returns a 1D tensor. This is useful if you are running multiple inputs through a model tower before splitting them and you want to line it up with some other data. Args: x: the target tensor. name: the name for this op, defaults to every_other Returns: A...
2.031235
2.08835
0.972651
with tf.name_scope(name, 'dot', [t1, t2]) as scope: t1 = tf.convert_to_tensor(t1, name='t1') t2 = tf.convert_to_tensor(t2, name='t2') mul = tf.multiply(t1, t2) if not reduction_dim: reduction_dim = _last_index(mul, 1) return tf.reduce_sum(mul, reduction_dim, name=scope, keep_dims=keep_dim...
def dot_product(t1, t2, keep_dims=False, name=None, reduction_dim=None)
Computes the dot product of t1 and t2. Args: t1: A rank 2 tensor. t2: A tensor that is the same size as t1. keep_dims: If true, reduction does not change the rank of the input. name: Optional name for this op. reduction_dim: The dimension to reduce, by default choose the last one and if no ...
2.008996
1.943277
1.033819
with tf.name_scope(name, 'length_squared', [x]) as scope: x = tf.convert_to_tensor(x, name='x') if not reduction_dim: reduction_dim = _last_index(x, 1) return tf.reduce_sum( tf.square(x), reduction_dim, keep_dims=keep_dims, name=scope)
def length_squared(x, keep_dims=False, name=None, reduction_dim=None)
Computes the squared length of x. Args: x: A tensor. keep_dims: If true, reduction does not change the rank of the input. name: Optional name for this op. reduction_dim: The dimension to reduce, by default choose the last one and if no shape is specified guess 1. Returns: The squared leng...
2.102573
2.007888
1.047156
with tf.name_scope(name, 'unzip', [x]) as scope: x = tf.convert_to_tensor(x, name='x') # There is probably a more efficient way to do this. all_splits = tf.split( value=x, num_or_size_splits=current_length, axis=split_dim, name=scope) splits = [[] for _ in xrange(num_splits)] for i in x...
def unzip(x, split_dim, current_length, num_splits=2, name=None)
Splits a tensor by unzipping along the split_dim. For example the following array split into 2 would be: [1, 2, 3, 4, 5, 6] -> [1, 3, 5], [2, 4, 6] and by 3: [1, 2, 3, 4] -> [1, 4], [2], [3] Args: x: The tensor to split. split_dim: The dimension to split along. current_length: Current le...
2.120952
2.040165
1.039598
if x.get_shape().ndims is not None: return len(x.get_shape()) - 1 else: return default_dim
def _last_index(x, default_dim)
Returns the last dimension's index or default_dim if x has no shape.
2.779133
2.251405
1.234399
if x.get_shape().ndims is not None: return list(xrange(x.get_shape().ndims)) else: return default_dims
def _all_dims(x, default_dims=None)
Returns a list of dims in x or default_dims if the rank is unknown.
3.586012
2.708518
1.323976
if activation is None: return x if activation_kwargs is None: activation_kwargs = {} y = activation(x, *activation_args, **activation_kwargs) if activation in (tf.nn.relu, functions.leaky_relu, functions.softplus): books.add_scalar_summary( tf.reduce_mean(tf.cast(tf.less(x, 0.0), tf.float...
def apply_activation( books, x, activation, activation_args=(), activation_kwargs=None)
Returns activation(x, *activation_args, **activation_kwargs). This applies the given activation and adds useful summaries specific to the activation. Args: books: The bookkeeper. x: The tensor to apply activation to. activation: An activation function. activation_args: Optional additional argume...
1.771771
1.73351
1.022071
def in_relu_family(activation_fn): if isinstance(activation_fn, collections.Sequence): activation_fn = activation_fn[0] return activation_fn in (tf.nn.relu, tf.nn.relu6) if in_relu_family(activation_fn): stddev = math.sqrt(2.0 / n_inputs) # TODO(): Evaluates truncated_normal_initializer. ...
def he_init(n_inputs, n_outputs, activation_fn, uniform=True)
Sets the parameter initialization using the method described. This method is designed to keep the scale of the gradients roughly the same in all layers with ReLU activations. He et al. (2015): Delving deep into rectifiers: surpassing human-level performance on imageNet classification. Inte...
3.44711
3.202583
1.076353
if uniform: # 6 was used in the paper. init_range = math.sqrt(6.0 / (n_inputs + n_outputs)) return tf.random_uniform_initializer(-init_range, init_range) else: # 3 gives us approximately the same limits as above since this repicks # values greater than 2 standard deviations from the mean. ...
def xavier_init(n_inputs, n_outputs, uniform=True)
Set the parameter initialization using the method described. This method is designed to keep the scale of the gradients roughly the same in all layers. Xavier Glorot and Yoshua Bengio (2010): Understanding the difficulty of training deep feedforward neural networks. International conferenc...
2.934972
2.919369
1.005345
return tf.cast(tf.reduce_all(tf.less_equal(x, 0.0), [0, 1, 2]), tf.float32)
def spatial_slice_zeros(x)
Experimental summary that shows how many planes are unused for a batch.
3.441586
3.182309
1.081475
input_layer.get_shape().assert_has_rank(4) if input_layer.get_shape().ndims not in (None, 4): raise ValueError('Pooling requires a rank 4 tensor: %s' % input_layer.get_shape()) kernel = _kernel(kernel) stride = _stride(stride) size = [1, kernel[0], kernel[1], 1] new_head = pool_...
def _pool(input_layer, pool_fn, kernel, stride, edges, name)
Applies a pooling function.
3.046906
3.000553
1.015448
return _pool(input_layer, tf.nn.avg_pool, kernel, stride, edges, name)
def average_pool(input_layer, kernel, stride, edges=PAD_SAME, name=PROVIDED)
Performs average pooling. `kernel` is the patch that will be pooled and it describes the pooling along each of the 4 dimensions. `stride` is how big to take each step. Because more often than not, pooling is only done on the width and height of the image, the following shorthands are supported: * scalar (...
3.211773
6.458923
0.497261
return _pool(input_layer, tf.nn.max_pool, kernel, stride, edges, name)
def max_pool(input_layer, kernel, stride, edges=PAD_SAME, name=PROVIDED)
Performs max pooling. `kernel` is the patch that will be pooled and it describes the pooling along each of the 4 dimensions. `stride` is how big to take each step. Because more often than not, pooling is only done on the width and height of the image, the following shorthands are supported: * scalar (e.g....
3.138916
6.54707
0.479438
input_layer.get_shape().assert_has_rank(4) return _interpolate(im=input_layer, x=x, y=y, name=name)
def bilinear_sampling(input_layer, x, y, name=PROVIDED)
Performs bilinear sampling. This must be a rank 4 Tensor. Implements the differentiable sampling mechanism with bilinear kernel in https://arxiv.org/abs/1506.02025. Given (x, y) coordinates for each output pixel, use bilinear sampling on the input_layer to fill the output. Args: input_layer: The chaina...
3.573716
5.810504
0.615044
if isinstance(kernel_spec, tf.compat.integral_types): return [kernel_spec, kernel_spec] elif len(kernel_spec) == 1: return [kernel_spec[0], kernel_spec[0]] else: assert len(kernel_spec) == 2 return kernel_spec
def _kernel(kernel_spec)
Expands the kernel spec into a length 2 list. Args: kernel_spec: An integer or a length 1 or 2 sequence that is expanded to a list. Returns: A length 2 list.
2.550742
2.116071
1.205414
if stride_spec is None: return [1, 1, 1, 1] elif isinstance(stride_spec, tf.compat.integral_types): return [1, stride_spec, stride_spec, 1] elif len(stride_spec) == 1: return [1, stride_spec[0], stride_spec[0], 1] elif len(stride_spec) == 2: return [1, stride_spec[0], stride_spec[1], 1] els...
def _stride(stride_spec)
Expands the stride spec into a length 4 list. Args: stride_spec: If length 0, 1 or 2 then assign the inner dimensions, otherwise return stride_spec if it is length 4. Returns: A length 4 list.
1.61754
1.5458
1.04641
if shape is not None: try: tensor.set_shape(shape) except ValueError: raise ValueError("Requested shape does not match tensor's shape: %s vs %s" % (shape, tensor.get_shape())) elif tensor.get_shape().ndims is None: raise ValueError('Unknown shape on tensor: %s' % te...
def _set_shape_on_tensor(tensor, shape)
Convenience to set a shape or check it.
2.813461
2.486033
1.131707
while isinstance(tensor, (PrettyTensor, Loss)): tensor = tensor.tensor return tensor
def unwrap(tensor)
Returns the underlying tensor if tensor is wrapped or tensor. Args: tensor: The tensor to unwrap. Returns: Tensor or if it is a pretty tensor, the unwrapped version. Raises: ValueError: if tensor holds a sequence.
11.785985
14.499908
0.812832
if books is None: books = bookkeeper.for_default_graph() if isinstance(tensor, PrettyTensor): return tensor.as_layer() elif isinstance(tensor, UnboundVariable): def set_input_from_unbound_var(data): if data is not None: return wrap(data, books) else: return None ...
def wrap(tensor, books=None, tensor_shape=None)
Creates an input layer representing the given tensor. Args: tensor: The tensor. books: The bookkeeper; this is usually not required unless you are building multiple `tf.Graphs.` tensor_shape: An optional shape that will be set on the Tensor or verified to match the tensor. Returns: A la...
4.461468
3.99203
1.117594
if books is None: books = bookkeeper.for_default_graph() def set_input_from_unbound_var(data): if data is not None: return wrap(data, books) else: return None if optional: data = UnboundVariable(key=key, default=None) else: data = UnboundVariable(key=key) return _Defe...
def template(key, books=None, optional=False)
Starts a Pretty Tensor graph template. ## Template Mode Templates allow you to define a graph with some unknown values. The most common use case is to leave the input undefined and then define a graph normally. The variables are only defined once the first time the graph is constructed. For example: ...
6.280037
4.869882
1.289567
if books is None: books = bookkeeper.for_default_graph() my_sequence = [ wrap(t, books=books, tensor_shape=tensor_shape) for t in sequence] return Layer(books, sequence=my_sequence, name=my_sequence[0].name)
def wrap_sequence(sequence, books=None, tensor_shape=None)
Creates an input layer representing the given sequence of tensors. Args: sequence: A sequence of tensors. books: The bookkeeper. tensor_shape: An optional shape that will be set on the Tensor or verified to match the tensor. Returns: A layer.
5.336442
4.194368
1.272287
_assert_value_not_string('summary_collections', kwargs) _assert_value_not_string('variable_collections', kwargs) _check_defaults(kwargs) global _defaults old_defaults = _defaults _defaults = chain_dict.ChainDict(_defaults) _defaults.update(kwargs) # Special logic to support summary_collections. #...
def defaults_scope(**kwargs)
Creates a scope for the defaults that are used in a `with` block. Note: `defaults_scope` supports nesting where later defaults can be overridden. Also, an explicitly given keyword argument on a method always takes precedence. In addition to setting defaults for some methods, this also can control: * `summa...
6.727983
5.834562
1.153126
with sequential.g.as_default(), scopes.var_and_name_scope((name, None)): branches = [] for i in xrange(branch_count): branches.append(SequentialLayerBuilder(copy=sequential) .with_name('l%d' % i)) yield tuple(branches) layers = [b.as_layer() for b in branches] sequen...
def _subdivide_context(sequential, branch_count, join_function, name)
Creates a context so that branches/joins can be done using 'with'.
6.328384
6.017441
1.051674
if not tensors: raise ValueError('pretty_tensors must be a non-empty sequence.') with output.g.name_scope(name): if join_function is None: # Use depth concat last_dim = len(tensors[0].shape) - 1 return output.with_tensor(tf.concat(tensors, last_dim)) else: return output.with_t...
def join_pretty_tensors(tensors, output, join_function=None, name='join')
Joins the list of pretty_tensors and sets head of output_pretty_tensor. Args: tensors: A sequence of Layers or SequentialLayerBuilders to join. output: A pretty_tensor to set the head with the result. join_function: A function to join the tensors, defaults to concat on the last dimension. name:...
4.034982
3.119059
1.293654
for k, v in six.iteritems(src): if dst.get(k, v) != v: trace1 = ''.join(scopes.skip_common_stack_elements(v.stacktrace, dst[ k].stacktrace)) trace2 = ''.join( scopes.skip_common_stack_elements(dst[k].stacktrace, v.stacktrace)) raise ValueError('Key conflict: %s\nDefined At...
def _merge_unbound_var_dicts(src, dst)
Merges src into dst and throws an exception if a value is incompatible.
4.29699
4.254027
1.010099
context = {} for key, value in six.iteritems(unbound_var_values): if key not in unbound_vars: raise ValueError('unexpected key: %s. Legal values are: %s' % (key, list(six.iterkeys(unbound_vars)))) context[unbound_vars[key]] = value unspecified = [] for unbound_var in six....
def _assign_values_to_unbound_vars(unbound_vars, unbound_var_values)
Assigns values to the vars and raises ValueError if one is missing.
2.20437
2.17015
1.015768
def _merge_dicts(src, dst): for k, v in six.iteritems(src): if dst.get(k, v) != v: raise ValueError('Conflicting values bound for %s: %s and %s' % (k, v, dst[k])) else: dst[k] = v # pylint: disable=protected-access all_unbound_vars = {} context = {} ...
def construct_all(templates, **unbound_var_values)
Constructs all the given templates in a single pass without redundancy. This is useful when the templates have a common substructure and you want the smallest possible graph. Args: templates: A sequence of templates. **unbound_var_values: The unbound_var values to replace. Returns: A list of resul...
3.257173
3.167998
1.028149
# pylint: disable=protected-access if isinstance(result, (PrettyTensor, Loss)): if result.is_sequence(): for tensor in result.sequence: _strip_unnecessary_contents_from_stack(tensor, processed) return else: result = result.tensor if hasattr(result, 'op'): result = result...
def _strip_unnecessary_contents_from_stack(result, processed)
Remove the distracting lines from the stored tracebacks. This also reduces memory overhead by removing the frame contents. This is very important when doing long unrolls. Args: result: The result to process. processed: A set of already processed nodes, used to stop early.
4.728741
4.752854
0.994927
magic_string = '%s(' % func.__name__ if defaults: default_offset = len(args) - len(defaults) else: default_offset = len(args) for i, value in enumerate(args): if i >= default_offset: magic_string += '%s=%s, ' % (value, defaults[i - default_offset]) else: magic_string += '%s, ' % ...
def _gen_ipython_string(func, args, defaults, original_doc)
Provides auto-complete hint to ipython. If the first line in a docstring is fn(arg1=, arg2=) then they are added to auto-complete. This cannot be called on an instance method. Args: func: The function that will be modified. args: The arguments that this function takes in order. defaults: The defaul...
1.983139
2.004046
0.989568
for arg in itertools.chain([input_layer], args, six.itervalues(kwargs)): if isinstance(arg, (_DeferredLayer, UnboundVariable)): return True elif (isinstance(arg, collections.Sequence) and not isinstance(arg, six.string_types)): if _should_defer(None, arg, {}): return True ...
def _should_defer(input_layer, args, kwargs)
Checks to see if any of the args are templates.
2.598641
2.553782
1.017565
global _in_method_scope # pylint: disable=protected-access with input_layer.g.as_default(), \ scopes.var_and_name_scope( None if _in_method_scope else input_layer._scope), \ scopes.var_and_name_scope((name, None)) as (scope, var_scope): was_in_method_scope = _in_method_scope y...
def _method_scope(input_layer, name)
Creates a nested set of name and id scopes and avoids repeats.
3.983314
3.817358
1.043474
# Ignore as_ref to not create backward compatibility issues. _ = name, as_ref t = pt_wrapper.tensor if dtype and not dtype.is_compatible_with(t.dtype): raise ValueError( 'Tensor conversion requested dtype %s for Tensor with dtype %s: %r' % (dtype, t.dtype, t)) return t
def _conversion_function(pt_wrapper, dtype=None, name=None, as_ref=False)
Allows PrettyTensors and Loss to work as a tensor.
5.07891
5.354172
0.948589
found_vars = set() result = [] for layer in self.flatten(): if isinstance(layer, _DeferredLayer): var_keys = {var.key for var in six.itervalues(layer.unbound_vars)} layers_bindings = { k: v for k, v in six.iteritems(bindings) if k in var_keys } ...
def bind(self, **bindings)
Makes the bindings to each item in this and returns a new tuple.
3.026676
2.95852
1.023037
if len(binding_order) != len(self.unbound_vars): raise ValueError('All vars must be specified.') for arg in binding_order: if arg not in self.unbound_vars: raise ValueError('Unknown binding: %s' % arg) def func(*args, **kwargs): if len(binding_order) != len(args): ...
def as_fn(self, *binding_order)
Creates a function by binding the arguments in the given order. Args: *binding_order: The unbound variables. This must include all values. Returns: A function that takes the arguments of binding_order. Raises: ValueError: If the bindings are missing values or include unknown values.
3.580328
3.265564
1.096389
if isinstance(result, (PrettyTensor, Loss, PrettyTensorTupleMixin)): return result elif (isinstance(result, collections.Sequence) and not isinstance(result, six.string_types)): return self.with_sequence(result) else: return self.with_tensor(result)
def _method_complete(self, result)
Called after a registered method with the result.
5.908747
5.845192
1.010873
self.bookkeeper.add_loss(loss, name=name) return Loss(self.bookkeeper, tensor=loss, name=name)
def add_loss(self, loss, name=None)
Adds a loss and returns a wrapper for that loss.
5.031477
4.310886
1.167156
if _args is None: _args = six.iterkeys(kwargs) my_defaults = self.defaults for k in _args: if k not in kwargs: if k in my_defaults: kwargs[k] = my_defaults[k] elif k in _defaults: kwargs[k] = _defaults[k] return kwargs
def _replace_args_with_defaults(self, _args=None, **kwargs)
Internal method to fill absent values in the kwargs with the defaults. Args: _args: A list of arguments to replace if a subset is required. Name chosen to prevent conflicts with kwargs. **kwargs: The arguments to replace with defaults. Returns: A map with the same fields as kwargs, b...
2.601328
2.472976
1.051902
if _key in unbound_var_values: raise ValueError('%s specified twice.' % _key) unbound_var_values[_key] = self return _template.as_layer().construct(**unbound_var_values)
def attach_template(self, _template, _key, **unbound_var_values)
Attaches the template to this such that _key=this layer. Note: names were chosen to avoid conflicts with any likely unbound_var keys. Args: _template: The template to construct. _key: The key that this layer should replace. **unbound_var_values: The values for the unbound_vars. Returns: ...
4.852769
3.685182
1.316833
if self.is_sequence(): raise TypeError('A Pretty Tensor that holds a sequence cannot be ' 'represented as a graph element.') else: # Self might be holding something else that isn't a true tensor, so # if the 'tensor' can behave like a graph element, look for its ...
def _as_graph_element(self)
Returns the underlying graph element if possible.
8.544353
8.178834
1.044691
with self.g.as_default(), scopes.var_and_name_scope((name, None)) as ( name_scope, var_scope): return Layer(copy=self, name=self._name, scope=(name_scope, var_scope))
def with_name(self, name)
Sets the name scope for future operations.
8.505048
8.096175
1.050502
if self not in tf.get_collection(bookkeeper.GraphKeys.MARKED_LOSSES): tf.add_to_collection(bookkeeper.GraphKeys.MARKED_LOSSES, self)
def mark_as_required(self)
Adds this loss to the MARKED_LOSSES collection.
5.931551
2.83131
2.094984
if isinstance(arg, UnboundVariable): return context[arg] elif isinstance(arg, _DeferredLayer): # pylint: disable=protected-access return arg._construct(context) elif isinstance(arg, tuple): return tuple((self._replace_deferred(x, context) for x in arg)) elif (isinstance(arg,...
def _replace_deferred(self, arg, context)
This replaces all deferred nodes (UnboundVariables and _DeferredLayers). If arg is a sequence or a dict, then it's deferred values are also replaced. Args: arg: The argument to replace. If a list or a dict, then all items are also replaced. context: The context for this replacement. Re...
2.108767
1.827173
1.154115
with self.g.as_default(): if self._pass_through: # pylint: disable=protected-access return self._pass_through._construct(context) current_value = context.get(self, None) assert current_value is not _unspecified, 'Circular dependency' if current_value is not None: ...
def _construct(self, context)
Constructs this by calling the deferred method. This assumes that all unbound_vars have been specified in context and if this layer has already been computed in this context, then the previously constructed value will be returned. Args: context: A dict of UnboundVariables/_DeferredLayers to thei...
3.885334
3.652841
1.063647
new_context = dict(self._partial_context) unknown_keys = [] for k, v in six.iteritems(bindings): if k not in self._unbound_vars: unknown_keys.append(k) new_context[self._unbound_vars[k]] = v if unknown_keys: raise ValueError( 'The following keys are not associate...
def bind(self, **bindings)
Creates a new template with the given unbound variables bound. Args: **bindings: Arguments for every deferred parameter. Returns: A new template with the given bindings. Raises: ValueError: If any of the bindings do not correspond to unbound variables.
4.325163
4.01024
1.07853
context = _assign_values_to_unbound_vars(self._unbound_vars, bindings) context.update(self._partial_context) return self._construct(context)
def construct(self, **bindings)
Constructs the graph and returns either a tensor or a sequence. Args: **bindings: Arguments for every deferred parameter. Returns: The value that is placed into this.
7.047052
8.201215
0.859269
with self.g.as_default(), tf.variable_scope(name) as var_scope: name_scope = scopes.get_current_name_scope() return _DeferredLayer(self.bookkeeper, None, (), {}, scope=(name_scope, var_sc...
def with_name(self, name)
Sets the name scope for future operations.
7.447027
6.864188
1.08491
if _key in unbound_var_values: raise ValueError('%s specified twice.' % _key) unbound_var_values[_key] = self return _DeferredLayer(self.bookkeeper, _template.as_layer().construct, [], unbound_var_values, ...
def attach_template(self, _template, _key, **unbound_var_values)
Attaches the template to this with the _key is supplied with this layer. Note: names were chosen to avoid conflicts. Args: _template: The template to construct. _key: The key that this layer should replace. **unbound_var_values: The values for the unbound_vars. Returns: A new layer...
5.853882
4.883995
1.198585
if hasattr(self._head, 'construct'): return self._head.construct(**bindings) else: raise ValueError( 'Cannot call construct on a non-template: %s' % type(self._head))
def construct(self, **bindings)
Constructs the graph and returns either a tensor or a sequence. Note: This method requires that this SequentialLayerBuilder holds a template. Args: **bindings: Arguments for every deferred parameter. Returns: The value that is placed into this. Raises: ValueError: if this doesn't...
4.781151
4.172677
1.145823
if isinstance(result, PrettyTensor): self._head = result return self elif isinstance(result, Loss): return result elif isinstance(result, PrettyTensorTupleMixin): self._head = result[0] return result else: self._head = self._head.with_tensor(result) return ...
def _method_complete(self, result)
Called after an extention method with the result.
5.294488
5.227982
1.012721
return _subdivide_context(self, branches, join_function, name)
def subdivide_with(self, branches, join_function, name='mixed')
Branches this pretty tensor and uses an explicit join function. This should be used in a with statement, for example to fork and join with a sum: with pt.subdivide_with(2, tf.add_n) as [a, b]: a... b... Args: branches: The number of branches. join_function: A funct...
7.975374
15.196217
0.524826
self._head = self._head.with_name(name) return self
def with_name(self, name)
Sets the name scope for future operations.
5.55898
6.415658
0.866471
# Make sure it is a TF dtype and convert it into a base dtype. dt = tf.as_dtype(dt).base_dtype if var_name in self.vars: v = self.vars[var_name] if v.get_shape() != shape: raise ValueError( 'Shape mismatch: %s vs %s. Perhaps a UnboundVariable had ' 'incompati...
def variable(self, var_name, shape, init, dt=tf.float32, train=None)
Adds a named variable to this bookkeeper or returns an existing one. Variables marked train are returned by the training_variables method. If the requested name already exists and it is compatible (same shape, dt and train) then it is returned. In case of an incompatible type, an exception is thrown. ...
2.468302
2.437573
1.012606
return input_layer._replace_args_with_defaults(_args=self._assign_defaults, **kwargs)
def fill_kwargs(self, input_layer, kwargs)
Applies name_suffix and defaults to kwargs and returns the result.
26.083399
22.258608
1.171834
my_defaults = _defaults def _with_method_complete(*args, **kwargs): input_layer = args[0] with input_layer.g.as_default(), defaults_scope(**my_defaults), \ tf.name_scope(name): return input_layer._method_complete(func(*args, **kwargs)) # The deferred layer passes on the s...
def create_deferred(self, func, input_layer, deferred_args, deferred_kwargs, name)
Creates a deferred node with captured scope. Args: func: The original function to call. input_layer: The input_layer. deferred_args: The arguments that will be used bythe deferred function. deferred_kwargs: The keyword args for the deferred function. name: The name of this layer. ...
5.64601
5.479845
1.030323
# pylint: disable=missing-docstring @functools.wraps(func) def method(input_layer, *args, **kwargs): return func(input_layer, *args, **self.fill_kwargs(input_layer, kwargs)) return method
def create_method(self, func)
Creates the method.
4.006195
3.747191
1.069119
if isinstance(x, prettytensor.PrettyTensor): if x.is_sequence(): return tuple(x.sequence) else: return (x.tensor,) elif isinstance(x, tuple): return x elif (isinstance(x, collections.Sequence) and not isinstance(x, six.string_types)): return tuple(x) else: return (x,)
def _make_tuple(x)
TF has an obnoxious habit of being lenient with single vs tuple.
2.627048
2.400863
1.09421
return cls( lambda: input_queue.dequeue_many(batch_size), replay_size, batch_size=batch_size)
def build_from_queue(cls, input_queue, replay_size, batch_size)
Builds a `ReplayableQueue` that draws from a regular `input_queue`. Args: input_queue: The queue to draw from. replay_size: The size of the replay buffer. batch_size: The size of each batch. Returns: A ReplayableQueue.
3.310858
4.131645
0.801341
current_replay = self.replay(sess) try: self.set_replay(sess, True) yield finally: self.set_replay(sess, current_replay)
def replay_scope(self, sess)
Enters a replay scope that unsets it at the end.
4.01403
3.374046
1.189679
sess.run(self._set_replay, {self._set_replay_ph: replay})
def set_replay(self, sess, replay)
Changes the current replay setting on the graph.
5.072761
3.815926
1.329366
sess.run(self._clear_queue) # Run until full. while sess.run(self._fill_queue): pass
def refill(self, sess)
Clears the current queue and then refills it with new data.
7.885661
7.274832
1.083965
if not os.path.exists(WORK_DIRECTORY): os.mkdir(WORK_DIRECTORY) filepath = os.path.join(WORK_DIRECTORY, filename) if not os.path.exists(filepath): filepath, _ = request.urlretrieve(url + filename, filepath) statinfo = os.stat(filepath) print('Successfully downloaded', filename, statinfo.st_size...
def maybe_download(url, filename)
Download the data from Yann's website, unless it's already here.
1.774271
1.729584
1.025837
print('Extracting', filename) with gzip.open(filename) as bytestream: bytestream.read(8) buf = bytestream.read(1 * num_images) labels = np.frombuffer(buf, dtype=np.uint8) # Convert to dense 1-hot representation. return (np.arange(10) == labels[:, None]).astype(np.float32)
def mnist_extract_labels(filename, num_images)
Extract the labels into a 1-hot matrix [image index, label index].
2.085142
1.986128
1.049853
if any(len(a) != len(arrays[0]) for a in arrays): raise ValueError('All arrays must be the same length.') if not random_state: random_state = np.random order = random_state.permutation(len(arrays[0])) return [a[order] for a in arrays]
def permute_data(arrays, random_state=None)
Permute multiple numpy arrays with the same order.
2.2911
2.030169
1.128526
if training: data_filename = 'train-images-idx3-ubyte.gz' labels_filename = 'train-labels-idx1-ubyte.gz' count = 60000 else: data_filename = 't10k-images-idx3-ubyte.gz' labels_filename = 't10k-labels-idx1-ubyte.gz' count = 10000 data_filename = maybe_download(MNIST_URL, data_filename) ...
def mnist(training)
Downloads MNIST and loads it into numpy arrays.
1.708777
1.700689
1.004756
file_name = maybe_download('http://cs.stanford.edu/people/karpathy/char-rnn/', 'shakespear.txt') with open(file_name) as f: shakespeare_full = f.read() # Truncate the data. length = (len(shakespeare_full) // chunk_size) * chunk_size if length < len(shakespeare_full): s...
def shakespeare(chunk_size)
Downloads Shakespeare, converts it into ASCII codes and chunks it. Args: chunk_size: The dataset is broken down so that it is shaped into batches x chunk_size. Returns: A numpy array of ASCII codes shaped into batches x chunk_size.
2.587972
2.703152
0.95739
names = [] lengths = [] targets = [] with open(os.path.join(os.path.dirname(sys.modules[__name__].__file__), 'baby_names.csv'), 'rb') as f: first = True for l in csv.reader(f, delimiter=','): if first: first = False continue assert len(l) == 4, l ...
def baby_names(max_length=15)
Opens the baby_names csv file and produces numpy array. Args: max_length: The maximum length, 15 was the longest name when this was written. Short entries will be padded with the EOS marker. Returns: A numpy array of the names converted to ascii codes, the labels and an array of lengths. Raise...
2.491636
2.243523
1.110591
# We can put the data into a format that can be easily cleaved by # transposing it (so that it varies fastest in batch) and then making each # component have a single value. # This will make it compatible with the Pretty Tensor function # cleave_sequence. dims = [1, 0] for i in xrange(2, tensor.get_sha...
def reshape_data(tensor, per_example_length=1)
Reshapes input so that it is appropriate for sequence_lstm.. The expected format for sequence lstms is [timesteps * batch, per_example_length] and the data produced by the utilities is [batch, timestep, *optional* expected_length]. The result can be cleaved so that there is a Tensor per timestep. Args: ...
11.317982
8.690493
1.302341
x = prettytensor.wrap(x) # Backwards compatibility. if isinstance(arguments, bool): if arguments: return x.batch_normalize() else: return x # pylint: disable=protected-access kwargs = arguments._asdict() defaults = prettytensor._defaults # pylint: enable=protected-access for arg ...
def batch_normalize_with_arguments(x, arguments)
Applies batch normalization to x as specified in arguments. Args: x: A Pretty Tensor. arguments: Either a boolean to batch_normalize or a BatchNormalizationArguments Returns: x with batch normalization applied.
3.162648
3.108155
1.017532
# Pretty Tensor is a thin wrapper on Tensors. # Change this method to experiment with other architectures images = pt.wrap(images) with pt.defaults_scope(activation_fn=tf.nn.relu, l2loss=0.00001): return (images.flatten().fully_connected(100).fully_connected(100) .softmax_classifier(10, label...
def multilayer_fully_connected(images, labels)
Creates a multi layer network of fully_connected layers. Each layer is 100 neurons. Please change this to experiment with architectures. Args: images: The input images. labels: The labels as dense one-hot vectors. Returns: A softmax result.
6.193276
6.396183
0.968277
images = pt.wrap(images) with pt.defaults_scope(activation_fn=tf.nn.relu, l2loss=0.00001): return (images.conv2d(5, 20).max_pool(2, 2).conv2d(5, 50).max_pool(2, 2) .flatten().fully_connected(500).softmax_classifier(10, labels))
def lenet5(images, labels)
Creates a multi layer convolutional network. The architecture is similar to that defined in LeNet 5. Please change this to experiment with architectures. Args: images: The input images. labels: The labels as dense one-hot vectors. Returns: A softmax result.
3.290442
3.281546
1.002711
result = {} if self._parent: result.update(self._parent) result.update(self._map) return result
def _full_map(self)
Creates a full mapping of this and all parent key, value pairs.
4.751895
2.896214
1.640727
# pylint: disable=protected-access if not names: yield None, None else: name, var_scope = names with tf.name_scope(name) as scope: # TODO(eiderman): This is a workaround until the variable_scope updates land # in a TF release. old_vs = tf.get_variable_scope() if var_scope is...
def var_and_name_scope(names)
Creates a variable scope and a name scope. If a variable_scope is provided, this will reenter that variable scope. However, if none is provided then the variable scope will match the generated part of the name scope. Args: names: A tuple of name_scope, variable_scope or None. Yields: The result of n...
3.202627
3.177804
1.007812
# pylint: disable=protected-access g = tf.get_default_graph() # TODO(eiderman): Remove this hack once TF update is released. if isinstance(g._name_stack, tuple): return g._name_stack[0] + '/' else: return g._name_stack + '/'
def get_current_name_scope()
Gets the current name scope.
3.850513
3.993196
0.964268
if args or kwargs: func = functools.partial(func, *args, **kwargs) return Template(name, func)
def make_template(name, func, *args, **kwargs)
Given an arbitrary function, wrap it so that it does parameter sharing.
3.260762
2.493313
1.307803
for i, (trace, base) in enumerate(zip(stacktrace, base_case)): if trace != base: return stacktrace[i:] return stacktrace[-1:]
def skip_common_stack_elements(stacktrace, base_case)
Skips items that the target stacktrace shares with the base stacktrace.
3.718709
3.425541
1.085583
with pt.defaults_scope(activation_fn=tf.nn.relu, l2loss=0.00001): # The embedding lookup must be placed on a cpu. with tf.device('/cpu:0'): embedded = text_in.embedding_lookup(CHARS, [EMBEDDING_SIZE]) # Because the sequence LSTM expects each timestep to be its own Tensor, # we need to cleave ...
def create_model(text_in, timesteps, phase)
Creates a 2 layer LSTM model with dropout. Args: text_in: The input text as ASCII ordinals in a Tensor. timesteps: The number of timesteps in the sequence. phase: Phase controls whether or not dropout is active. In training mode we want to perform dropout, but in test we want to disable it. Retu...
8.618716
8.288252
1.039871
assert temperature > 0, 'Temperature must be greater than 0.' if not seed: # The model expects an input to do inference, so seed with a single letter. seed = chr(ord('A') + random.randint(0, 25)) result = '' # The recurrent runner takes care of tracking the model's state at each step # and provide...
def sample( input_placeholder, logits, seed=None, max_length=1024, temperature=1.0)
Samples from the LSTM model. Sampling is done by first running either the seed or an arbitrary character through the model and then drawing the next character from the probability distribution definted by `softmax`. Args: input_placeholder: A placeholder that expects a scalar feed. logits: The logits....
5.708477
5.404743
1.056198
# To compute the dimension of an unknown, we need to track which of the values # from old_shape are not copied for the numerator and any values specified as # integers for the denominator. # # After the loop, if any input dimension is unknown and not DIM_SAME, the # numerator will be 0. Otherwise it is ...
def _infer_unknown_dims(old_shape, shape_spec)
Attempts to replace DIM_REST (if present) with a value. Because of `pt.DIM_SAME`, this has more information to compute a shape value than the default reshape's shape function. Args: old_shape: The current shape of the Tensor as a list. shape_spec: A shape spec, see `pt.reshape`. Returns: A list de...
3.545864
3.34162
1.061121
old_shape = input_layer.get_shape().as_list() # Extract both a tensor that sets the new shape and as much of the new # shape is known. This lets us merge in any extra information we have about # the shape. try: new_shape = _infer_unknown_dims(old_shape, shape_spec) except TypeError: # shape_spec...
def reshape(input_layer, shape_spec)
Reshapes this tensor to the given spec. This provides additional functionality over the basic `tf.reshape`. In particular, it provides the ability to specify some dimensions as unchanged (`pt.DIM_SAME`) which can greatly aid in inferring the extra dimensions (`pt.DIM_REST`) and help maintain more shape informa...
4.007141
3.710842
1.079847