_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q266500
_numpy_text
test
def _numpy_text(tensor, is_repr=False): """Human-readable representation of a tensor's numpy value.""" if tensor.dtype.is_numpy_compatible: text = repr(tensor.numpy()) if is_repr else str(tensor.numpy()) else: text = "<unprintable>" if "\n" in text: text = "\n" + text return text
python
{ "resource": "" }
q266501
RandomVariable.sample_shape
test
def sample_shape(self): """Sample shape of random variable as a `TensorShape`.""" if isinstance(self._sample_shape, tf.Tensor): return tf.TensorShape(tf.get_static_value(self._sample_shape)) return tf.TensorShape(self._sample_shape)
python
{ "resource": "" }
q266502
RandomVariable.sample_shape_tensor
test
def sample_shape_tensor(self, name="sample_shape_tensor"): """Sample shape of random variable as a 1-D `Tensor`. Args: name: name to give to the op Returns: sample_shape: `Tensor`. """ with tf.compat.v1.name_scope(name): if isinstance(self._sample_shape, tf.Tensor): retur...
python
{ "resource": "" }
q266503
RandomVariable.value
test
def value(self): """Get tensor that the random variable corresponds to.""" if self._value is None: try: self._value = self.distribution.sample(self.sample_shape_tensor()) except NotImplementedError: raise NotImplementedError( "sample is not implemented for {0}. You must e...
python
{ "resource": "" }
q266504
RandomVariable.eval
test
def eval(self, session=None, feed_dict=None): """In a session, computes and returns the value of this random variable. This is not a graph construction method, it does not add ops to the graph. This convenience method requires a session where the graph containing this variable has been launched. If no...
python
{ "resource": "" }
q266505
RandomVariable.numpy
test
def numpy(self): """Value as NumPy array, only available for TF Eager.""" if not isinstance(self.value, ops.EagerTensor): raise NotImplementedError("value argument must be a EagerTensor.") return self.value.numpy()
python
{ "resource": "" }
q266506
normal_conjugates_known_scale_posterior
test
def normal_conjugates_known_scale_posterior(prior, scale, s, n): """Posterior Normal distribution with conjugate prior on the mean. This model assumes that `n` observations (with sum `s`) come from a Normal with unknown mean `loc` (described by the Normal `prior`) and known variance `scale**2`. The "known scal...
python
{ "resource": "" }
q266507
real_nvp_default_template
test
def real_nvp_default_template(hidden_layers, shift_only=False, activation=tf.nn.relu, name=None, *args, # pylint: disable=keyword-arg-before-vararg **kwargs): """Build...
python
{ "resource": "" }
q266508
_uniform_unit_norm
test
def _uniform_unit_norm(dimension, shape, dtype, seed): """Returns a batch of points chosen uniformly from the unit hypersphere.""" # This works because the Gaussian distribution is spherically symmetric. # raw shape: shape + [dimension] raw = normal.Normal( loc=dtype_util.as_numpy_dtype(dtype)(0), s...
python
{ "resource": "" }
q266509
LKJ._log_unnorm_prob
test
def _log_unnorm_prob(self, x, name=None): """Returns the unnormalized log density of an LKJ distribution. Args: x: `float` or `double` `Tensor` of correlation matrices. The shape of `x` must be `B + [D, D]`, where `B` broadcasts with the shape of `concentration`. name: Python `str`...
python
{ "resource": "" }
q266510
LKJ._log_normalization
test
def _log_normalization(self, name='log_normalization'): """Returns the log normalization of an LKJ distribution. Args: name: Python `str` name prefixed to Ops created by this function. Returns: log_z: A Tensor of the same shape and dtype as `concentration`, containing the corresponding...
python
{ "resource": "" }
q266511
common_dtype
test
def common_dtype(args_list, preferred_dtype=None): """Returns explict dtype from `args_list` if exists, else preferred_dtype.""" dtype = None preferred_dtype = (None if preferred_dtype is None else tf.as_dtype(preferred_dtype)) for a in tf.nest.flatten(args_list): if hasattr(a, 'dtype')...
python
{ "resource": "" }
q266512
_make_summary_statistic
test
def _make_summary_statistic(attr): """Factory for implementing summary statistics, eg, mean, stddev, mode.""" def _fn(self, **kwargs): """Implements summary statistic, eg, mean, stddev, mode.""" x = getattr(self.distribution, attr)(**kwargs) shape = prefer_static.concat([ self.distribution.batch...
python
{ "resource": "" }
q266513
_broadcast_to
test
def _broadcast_to(tensor_to_broadcast, target_tensors): """Helper to broadcast a tensor using a list of target tensors.""" output = tensor_to_broadcast for tensor in target_tensors: output += tf.zeros_like(tensor) return output
python
{ "resource": "" }
q266514
Triangular._pdf_at_peak
test
def _pdf_at_peak(self): """Pdf evaluated at the peak.""" return (self.peak - self.low) / (self.high - self.low)
python
{ "resource": "" }
q266515
effective_sample_size
test
def effective_sample_size(states, filter_threshold=0., filter_beyond_lag=None, name=None): """Estimate a lower bound on effective sample size for each independent chain. Roughly speaking, "effective sample size" (ESS) is the size of an i...
python
{ "resource": "" }
q266516
_effective_sample_size_single_state
test
def _effective_sample_size_single_state(states, filter_beyond_lag, filter_threshold): """ESS computation for one single Tensor argument.""" with tf.compat.v1.name_scope( 'effective_sample_size_single_state', values=[states, filter_beyond_lag, filter_threshold]): ...
python
{ "resource": "" }
q266517
_potential_scale_reduction_single_state
test
def _potential_scale_reduction_single_state(state, independent_chain_ndims): """potential_scale_reduction for one single state `Tensor`.""" with tf.compat.v1.name_scope( 'potential_scale_reduction_single_state', values=[state, independent_chain_ndims]): # We assume exactly one leading dimension inde...
python
{ "resource": "" }
q266518
_axis_size
test
def _axis_size(x, axis=None): """Get number of elements of `x` in `axis`, as type `x.dtype`.""" if axis is None: return tf.cast(tf.size(input=x), x.dtype) return tf.cast( tf.reduce_prod(input_tensor=tf.gather(tf.shape(input=x), axis)), x.dtype)
python
{ "resource": "" }
q266519
_broadcast_maybelist_arg
test
def _broadcast_maybelist_arg(states, secondary_arg, name): """Broadcast a listable secondary_arg to that of states.""" if _is_list_like(secondary_arg): if len(secondary_arg) != len(states): raise ValueError('Argument `%s` was a list of different length ({}) than ' '`states` ({})'.fo...
python
{ "resource": "" }
q266520
quadrature_scheme_lognormal_gauss_hermite
test
def quadrature_scheme_lognormal_gauss_hermite( loc, scale, quadrature_size, validate_args=False, name=None): # pylint: disable=unused-argument """Use Gauss-Hermite quadrature to form quadrature on positive-reals. Note: for a given `quadrature_size`, this method is generally less accurate than `quadratur...
python
{ "resource": "" }
q266521
quadrature_scheme_lognormal_quantiles
test
def quadrature_scheme_lognormal_quantiles( loc, scale, quadrature_size, validate_args=False, name=None): """Use LogNormal quantiles to form quadrature on positive-reals. Args: loc: `float`-like (batch of) scalar `Tensor`; the location parameter of the LogNormal prior. scale: `float`-like (bat...
python
{ "resource": "" }
q266522
_Mapping.merge
test
def merge(self, x=None, y=None, ildj=None, kwargs=None, mapping=None): """Returns new _Mapping with args merged with self. Args: x: `Tensor` or None. Input to forward; output of inverse. y: `Tensor` or None. Input to inverse; output of forward. ildj: `Tensor`. This is the (un-reduce_sum'ed) i...
python
{ "resource": "" }
q266523
_Mapping.remove
test
def remove(self, field): """To support weak referencing, removes cache key from the cache value.""" return _Mapping( x=None if field == "x" else self.x, y=None if field == "y" else self.y, ildj=self.ildj, kwargs=self.kwargs)
python
{ "resource": "" }
q266524
_Mapping._merge
test
def _merge(self, old, new, use_equals=False): """Helper to merge which handles merging one value.""" if old is None: return new if new is None: return old if (old == new) if use_equals else (old is new): return old raise ValueError("Incompatible values: %s != %s" % (old, new))
python
{ "resource": "" }
q266525
_Mapping._deep_tuple
test
def _deep_tuple(self, x): """Converts nested `tuple`, `list`, or `dict` to nested `tuple`.""" if isinstance(x, dict): return self._deep_tuple(tuple(sorted(x.items()))) elif isinstance(x, (list, tuple)): return tuple(map(self._deep_tuple, x)) return x
python
{ "resource": "" }
q266526
_left_doubling_increments
test
def _left_doubling_increments(batch_shape, max_doublings, step_size, seed=None, name=None): """Computes the doubling increments for the left end point. The doubling procedure expands an initial interval to find a superset of the true slice. At each doubling iteration, the interval w...
python
{ "resource": "" }
q266527
_find_best_interval_idx
test
def _find_best_interval_idx(x, name=None): """Finds the index of the optimal set of bounds for each chain. For each chain, finds the smallest set of bounds for which both edges lie outside the slice. This is equivalent to the point at which a for loop implementation (P715 of Neal (2003)) of the algorithm would...
python
{ "resource": "" }
q266528
slice_bounds_by_doubling
test
def slice_bounds_by_doubling(x_initial, target_log_prob, log_slice_heights, max_doublings, step_size, seed=None, name=None): """Returns the boun...
python
{ "resource": "" }
q266529
_sample_with_shrinkage
test
def _sample_with_shrinkage(x_initial, target_log_prob, log_slice_heights, step_size, lower_bounds, upper_bounds, seed=None, name=None): """Samples from the slice by applying shrinkage for rejected points. Implements the one dimensional slice sampling algorithm ...
python
{ "resource": "" }
q266530
slice_sampler_one_dim
test
def slice_sampler_one_dim(target_log_prob, x_initial, step_size=0.01, max_doublings=30, seed=None, name=None): """For a given x position in each Markov chain, returns the next x. Applies the one dimensional slice sampling algorithm as defined in Neal (2003) to an input tensor x of shape...
python
{ "resource": "" }
q266531
make_value_setter
test
def make_value_setter(**model_kwargs): """Creates a value-setting interceptor. This function creates an interceptor that sets values of Edward2 random variable objects. This is useful for a range of tasks, including conditioning on observed data, sampling from posterior predictive distributions, and as a bui...
python
{ "resource": "" }
q266532
make_log_joint_fn
test
def make_log_joint_fn(model): """Takes Edward probabilistic program and returns its log joint function. Args: model: Python callable which executes the generative process of a computable probability distribution using `ed.RandomVariable`s. Returns: A log-joint probability function. Its inputs are ...
python
{ "resource": "" }
q266533
_get_function_inputs
test
def _get_function_inputs(f, src_kwargs): """Filters inputs to be compatible with function `f`'s signature. Args: f: Function according to whose input signature we filter arguments. src_kwargs: Keyword arguments to filter according to `f`. Returns: kwargs: Dict of key-value pairs in `src_kwargs` whic...
python
{ "resource": "" }
q266534
_vggconv_block
test
def _vggconv_block(x, filters, kernel, stride, kernel_posterior_fn): """Network block for VGG.""" out = tfp.layers.Convolution2DFlipout( filters, kernel, padding='same', kernel_posterior_fn=kernel_posterior_fn)(x) out = tf.keras.layers.BatchNormalization()(out) out = tf.keras.layers.Acti...
python
{ "resource": "" }
q266535
_build_tree
test
def _build_tree(value_and_gradients_fn, current_state, current_target_log_prob, current_grads_target_log_prob, current_momentum, direction, depth, step_size, log_slice_sample, ...
python
{ "resource": "" }
q266536
_embed_no_none_gradient_check
test
def _embed_no_none_gradient_check(value_and_gradients_fn): """Wraps value and gradients function to assist with None gradients.""" @functools.wraps(value_and_gradients_fn) def func_wrapped(*args, **kwargs): """Wrapped function which checks for None gradients.""" value, grads = value_and_gradients_fn(*args...
python
{ "resource": "" }
q266537
_has_no_u_turn
test
def _has_no_u_turn(state_one, state_two, momentum): """If two given states and momentum do not exhibit a U-turn pattern.""" dot_product = sum([ tf.reduce_sum(input_tensor=(s1 - s2) * m) for s1, s2, m in zip(state_one, state_two, momentum) ]) return dot_product > 0
python
{ "resource": "" }
q266538
_leapfrog
test
def _leapfrog(value_and_gradients_fn, current_state, current_grads_target_log_prob, current_momentum, step_size): """Runs one step of leapfrog integration.""" mid_momentum = [ m + 0.5 * step * g for m, step, g in zip(current_momentum, step_size, cu...
python
{ "resource": "" }
q266539
_log_joint
test
def _log_joint(current_target_log_prob, current_momentum): """Log-joint probability given a state's log-probability and momentum.""" momentum_log_prob = -sum( [tf.reduce_sum(input_tensor=0.5 * (m**2.)) for m in current_momentum]) return current_target_log_prob + momentum_log_prob
python
{ "resource": "" }
q266540
_random_bernoulli
test
def _random_bernoulli(shape, probs, dtype=tf.int32, seed=None, name=None): """Returns samples from a Bernoulli distribution.""" with tf.compat.v1.name_scope(name, "random_bernoulli", [shape, probs]): probs = tf.convert_to_tensor(value=probs) random_uniform = tf.random.uniform(shape, dtype=probs.dtype, seed=...
python
{ "resource": "" }
q266541
default_loc_scale_fn
test
def default_loc_scale_fn( is_singular=False, loc_initializer=tf.compat.v1.initializers.random_normal(stddev=0.1), untransformed_scale_initializer=tf.compat.v1.initializers.random_normal( mean=-3., stddev=0.1), loc_regularizer=None, untransformed_scale_regularizer=None, loc_constraint=Non...
python
{ "resource": "" }
q266542
default_mean_field_normal_fn
test
def default_mean_field_normal_fn( is_singular=False, loc_initializer=tf.compat.v1.initializers.random_normal(stddev=0.1), untransformed_scale_initializer=tf.compat.v1.initializers.random_normal( mean=-3., stddev=0.1), loc_regularizer=None, untransformed_scale_regularizer=None, loc_constr...
python
{ "resource": "" }
q266543
default_multivariate_normal_fn
test
def default_multivariate_normal_fn(dtype, shape, name, trainable, add_variable_fn): """Creates multivariate standard `Normal` distribution. Args: dtype: Type of parameter's event. shape: Python `list`-like representing the parameter's event shape. name: Python `str` n...
python
{ "resource": "" }
q266544
deserialize_function
test
def deserialize_function(serial, function_type): """Deserializes the Keras-serialized function. (De)serializing Python functions from/to bytecode is unsafe. Therefore we also use the function's type as an anonymous function ('lambda') or named function in the Python environment ('function'). In the latter case...
python
{ "resource": "" }
q266545
serialize_function
test
def serialize_function(func): """Serializes function for Keras. (De)serializing Python functions from/to bytecode is unsafe. Therefore we return the function's type as an anonymous function ('lambda') or named function in the Python environment ('function'). In the latter case, this lets us use the Python sc...
python
{ "resource": "" }
q266546
broadcast_structure
test
def broadcast_structure(to_structure, from_structure): """Broadcasts `from_structure` to `to_structure`. This is useful for downstream usage of `zip` or `tf.nest.map_structure`. If `from_structure` is a singleton, it is tiled to match the structure of `to_structure`. Note that the elements in `from_structure`...
python
{ "resource": "" }
q266547
_nested_convert_to_tensor
test
def _nested_convert_to_tensor(struct, dtype=None, name=None): """Eagerly converts struct to Tensor, recursing upon failure.""" if dtype is not None or not tf.nest.is_nested(struct): return tf.convert_to_tensor(struct, dtype=dtype) if _maybe_convertible_to_tensor(struct): try: # Try converting the s...
python
{ "resource": "" }
q266548
convert_args_to_tensor
test
def convert_args_to_tensor(args, dtype=None, name=None): """Converts `args` to `Tensor`s. Use this when it is necessary to convert user-provided arguments that will then be passed to user-provided callables. When `dtype` is `None` this function behaves as follows: 1A. If the top-level structure is a `list`...
python
{ "resource": "" }
q266549
call_fn
test
def call_fn(fn, args): """Calls `fn` with `args`, possibly expanding `args`. Use this function when calling a user-provided callable using user-provided arguments. The expansion rules are as follows: `fn(*args)` if `args` is a `list` or a `tuple`, but not a `namedtuple`. `fn(**args)` if `args` is a `dict...
python
{ "resource": "" }
q266550
_get_tensor_like_attributes
test
def _get_tensor_like_attributes(): """Returns `Tensor` attributes related to shape and Python builtins.""" # Enable "Tensor semantics" for distributions. # See tensorflow/python/framework/ops.py `class Tensor` for details. attrs = dict() # Setup overloadable operators and white-listed members / properties. ...
python
{ "resource": "" }
q266551
make_mixture_prior
test
def make_mixture_prior(latent_size, mixture_components): """Creates the mixture of Gaussians prior distribution. Args: latent_size: The dimensionality of the latent representation. mixture_components: Number of elements of the mixture. Returns: random_prior: A `tfd.Distribution` instance representin...
python
{ "resource": "" }
q266552
pack_images
test
def pack_images(images, rows, cols): """Helper utility to make a field of images.""" shape = tf.shape(input=images) width = shape[-3] height = shape[-2] depth = shape[-1] images = tf.reshape(images, (-1, width, height, depth)) batch = tf.shape(input=images)[0] rows = tf.minimum(rows, batch) cols = tf....
python
{ "resource": "" }
q266553
download
test
def download(directory, filename): """Downloads a file.""" filepath = os.path.join(directory, filename) if tf.io.gfile.exists(filepath): return filepath if not tf.io.gfile.exists(directory): tf.io.gfile.makedirs(directory) url = os.path.join(ROOT_PATH, filename) print("Downloading %s to %s" % (url, ...
python
{ "resource": "" }
q266554
build_fake_input_fns
test
def build_fake_input_fns(batch_size): """Builds fake MNIST-style data for unit testing.""" random_sample = np.random.rand(batch_size, *IMAGE_SHAPE).astype("float32") def train_input_fn(): dataset = tf.data.Dataset.from_tensor_slices( random_sample).map(lambda row: (row, 0)).batch(batch_size).repeat()...
python
{ "resource": "" }
q266555
_validate_block_sizes
test
def _validate_block_sizes(block_sizes, bijectors, validate_args): """Helper to validate block sizes.""" block_sizes_shape = block_sizes.shape if tensorshape_util.is_fully_defined(block_sizes_shape): if (tensorshape_util.rank(block_sizes_shape) != 1 or (tensorshape_util.num_elements(block_sizes_shape) ...
python
{ "resource": "" }
q266556
maybe_check_wont_broadcast
test
def maybe_check_wont_broadcast(flat_xs, validate_args): """Verifies that `parts` don't broadcast.""" flat_xs = tuple(flat_xs) # So we can receive generators. if not validate_args: # Note: we don't try static validation because it is theoretically # possible that a user wants to take advantage of broadcas...
python
{ "resource": "" }
q266557
multivariate_normal_tril
test
def multivariate_normal_tril(x, dims, layer_fn=tf.compat.v1.layers.dense, loc_fn=lambda x: x, scale_fn=tril_with_diag_softplus_and_shift, name=None): """Constructs a trainab...
python
{ "resource": "" }
q266558
bernoulli
test
def bernoulli(x, layer_fn=tf.compat.v1.layers.dense, name=None): """Constructs a trainable `tfd.Bernoulli` distribution. This function creates a Bernoulli distribution parameterized by logits. Using default args, this function is mathematically equivalent to: ```none Y = Bernoulli(logits=matmul(W, x) + b) ...
python
{ "resource": "" }
q266559
normal
test
def normal(x, layer_fn=tf.compat.v1.layers.dense, loc_fn=lambda x: x, scale_fn=1., name=None): """Constructs a trainable `tfd.Normal` distribution. This function creates a Normal distribution parameterized by loc and scale. Using default args, this function is mathema...
python
{ "resource": "" }
q266560
poisson
test
def poisson(x, layer_fn=tf.compat.v1.layers.dense, log_rate_fn=lambda x: x, name=None): """Constructs a trainable `tfd.Poisson` distribution. This function creates a Poisson distribution parameterized by log rate. Using default args, this function is mathematically equivalent ...
python
{ "resource": "" }
q266561
_euler_method
test
def _euler_method(random_draw_parts, state_parts, drift_parts, step_size_parts, volatility_parts, name=None): """Applies one step of Euler-Maruyama method. Generates proposal of the form: ```python tfd.Normal(loc=state_p...
python
{ "resource": "" }
q266562
_get_drift
test
def _get_drift(step_size_parts, volatility_parts, grads_volatility, grads_target_log_prob, name=None): """Compute diffusion drift at the current location `current_state`. The drift of the diffusion at is computed as ```none 0.5 * `step_size` * volatility_parts * `target_log_prob_...
python
{ "resource": "" }
q266563
_compute_log_acceptance_correction
test
def _compute_log_acceptance_correction(current_state_parts, proposed_state_parts, current_volatility_parts, proposed_volatility_parts, current_drift_parts, ...
python
{ "resource": "" }
q266564
_maybe_call_volatility_fn_and_grads
test
def _maybe_call_volatility_fn_and_grads(volatility_fn, state, volatility_fn_results=None, grads_volatility_fn=None, sample_shape=None, ...
python
{ "resource": "" }
q266565
_maybe_broadcast_volatility
test
def _maybe_broadcast_volatility(volatility_parts, state_parts): """Helper to broadcast `volatility_parts` to the shape of `state_parts`.""" return [v + tf.zeros_like(sp, dtype=sp.dtype.base_dtype) for v, sp in zip(volatility_parts, state_parts)]
python
{ "resource": "" }
q266566
make_ar_transition_matrix
test
def make_ar_transition_matrix(coefficients): """Build transition matrix for an autoregressive StateSpaceModel. When applied to a vector of previous values, this matrix computes the expected new value (summing the previous states according to the autoregressive coefficients) in the top dimension of the state sp...
python
{ "resource": "" }
q266567
BatchReshape._sample_shape
test
def _sample_shape(self, x): """Computes graph and static `sample_shape`.""" x_ndims = ( tf.rank(x) if tensorshape_util.rank(x.shape) is None else tensorshape_util.rank(x.shape)) event_ndims = ( tf.size(input=self.event_shape_tensor()) if tensorshape_util.rank(self.event_shape...
python
{ "resource": "" }
q266568
BatchReshape._call_reshape_input_output
test
def _call_reshape_input_output(self, fn, x, extra_kwargs=None): """Calls `fn`, appropriately reshaping its input `x` and output.""" # Note: we take `extra_kwargs` as a dict rather than `**extra_kwargs` # because it is possible the user provided extra kwargs would itself # have `fn` and/or `x` as a key. ...
python
{ "resource": "" }
q266569
BatchReshape._call_and_reshape_output
test
def _call_and_reshape_output( self, fn, event_shape_list=None, static_event_shape_list=None, extra_kwargs=None): """Calls `fn` and appropriately reshapes its output.""" # Note: we take `extra_kwargs` as a dict rather than `**extra_kwargs` # because it is possible the user provi...
python
{ "resource": "" }
q266570
_bdtr
test
def _bdtr(k, n, p): """The binomial cumulative distribution function. Args: k: floating point `Tensor`. n: floating point `Tensor`. p: floating point `Tensor`. Returns: `sum_{j=0}^k p^j (1 - p)^(n - j)`. """ # Trick for getting safe backprop/gradients into n, k when # betainc(a = 0, ..) ...
python
{ "resource": "" }
q266571
JointDistributionCoroutine._flat_sample_distributions
test
def _flat_sample_distributions(self, sample_shape=(), seed=None, value=None): """Executes `model`, creating both samples and distributions.""" ds = [] values_out = [] seed = seed_stream.SeedStream('JointDistributionCoroutine', seed) gen = self._model() index = 0 d = next(gen) try: ...
python
{ "resource": "" }
q266572
latent_dirichlet_allocation
test
def latent_dirichlet_allocation(concentration, topics_words): """Latent Dirichlet Allocation in terms of its generative process. The model posits a distribution over bags of words and is parameterized by a concentration and the topic-word probabilities. It collapses per-word topic assignments. Args: con...
python
{ "resource": "" }
q266573
make_lda_variational
test
def make_lda_variational(activation, num_topics, layer_sizes): """Creates the variational distribution for LDA. Args: activation: Activation function to use. num_topics: The number of topics. layer_sizes: The number of hidden units per layer in the encoder. Returns: lda_variational: A function t...
python
{ "resource": "" }
q266574
get_topics_strings
test
def get_topics_strings(topics_words, alpha, vocabulary, topics_to_print=10, words_per_topic=10): """Returns the summary of the learned topics. Arguments: topics_words: KxV tensor with topics as rows and words as columns. alpha: 1xK tensor of prior Dirichlet concentrations for the ...
python
{ "resource": "" }
q266575
newsgroups_dataset
test
def newsgroups_dataset(directory, split_name, num_words, shuffle_and_repeat): """20 newsgroups as a tf.data.Dataset.""" data = np.load(download(directory, FILE_TEMPLATE.format(split=split_name))) # The last row is empty in both train and test. data = data[:-1] # Each row is a list of word ids in the document...
python
{ "resource": "" }
q266576
build_fake_input_fns
test
def build_fake_input_fns(batch_size): """Builds fake data for unit testing.""" num_words = 1000 vocabulary = [str(i) for i in range(num_words)] random_sample = np.random.randint( 10, size=(batch_size, num_words)).astype(np.float32) def train_input_fn(): dataset = tf.data.Dataset.from_tensor_slices...
python
{ "resource": "" }
q266577
build_input_fns
test
def build_input_fns(data_dir, batch_size): """Builds iterators for train and evaluation data. Each object is represented as a bag-of-words vector. Arguments: data_dir: Folder in which to store the data. batch_size: Batch size for both train and evaluation. Returns: train_input_fn: A function that...
python
{ "resource": "" }
q266578
minimize
test
def minimize(grad_and_hessian_loss_fn, x_start, tolerance, l1_regularizer, l2_regularizer=None, maximum_iterations=1, maximum_full_sweeps_per_iteration=1, learning_rate=None, name=None): """Minimize using Hessian-i...
python
{ "resource": "" }
q266579
add_ema_control_dependencies
test
def add_ema_control_dependencies(vector_quantizer, one_hot_assignments, codes, commitment_loss, decay): """Add control dependencies to the commmitment loss to update the codebook. Arg...
python
{ "resource": "" }
q266580
save_imgs
test
def save_imgs(x, fname): """Helper method to save a grid of images to a PNG file. Args: x: A numpy array of shape [n_images, height, width]. fname: The filename to write to (including extension). """ n = x.shape[0] fig = figure.Figure(figsize=(n, 1), frameon=False) canvas = backend_agg.FigureCanvas...
python
{ "resource": "" }
q266581
visualize_training
test
def visualize_training(images_val, reconstructed_images_val, random_images_val, log_dir, prefix, viz_n=10): """Helper method to save images visualizing model reconstructions. Args: images_val: Numpy array containing a batch of input images. ...
python
{ "resource": "" }
q266582
load_bernoulli_mnist_dataset
test
def load_bernoulli_mnist_dataset(directory, split_name): """Returns Hugo Larochelle's binary static MNIST tf.data.Dataset.""" amat_file = download(directory, FILE_TEMPLATE.format(split=split_name)) dataset = tf.data.TextLineDataset(amat_file) str_to_arr = lambda string: np.array([c == b"1" for c in string.split...
python
{ "resource": "" }
q266583
as_numpy_dtype
test
def as_numpy_dtype(dtype): """Returns a `np.dtype` based on this `dtype`.""" dtype = tf.as_dtype(dtype) if hasattr(dtype, 'as_numpy_dtype'): return dtype.as_numpy_dtype return dtype
python
{ "resource": "" }
q266584
base_dtype
test
def base_dtype(dtype): """Returns a non-reference `dtype` based on this `dtype`.""" dtype = tf.as_dtype(dtype) if hasattr(dtype, 'base_dtype'): return dtype.base_dtype return dtype
python
{ "resource": "" }
q266585
is_bool
test
def is_bool(dtype): """Returns whether this is a boolean data type.""" dtype = tf.as_dtype(dtype) if hasattr(dtype, 'is_bool'): return dtype.is_bool # We use `kind` because: # np.issubdtype(np.uint8, np.bool) == True. return np.dtype(dtype).kind == 'b'
python
{ "resource": "" }
q266586
is_complex
test
def is_complex(dtype): """Returns whether this is a complex floating point type.""" dtype = tf.as_dtype(dtype) if hasattr(dtype, 'is_complex'): return dtype.is_complex return np.issubdtype(np.dtype(dtype), np.complex)
python
{ "resource": "" }
q266587
max
test
def max(dtype): # pylint: disable=redefined-builtin """Returns the maximum representable value in this data type.""" dtype = tf.as_dtype(dtype) if hasattr(dtype, 'max'): return dtype.max use_finfo = is_floating(dtype) or is_complex(dtype) return np.finfo(dtype).max if use_finfo else np.iinfo(dtype).max
python
{ "resource": "" }
q266588
name
test
def name(dtype): """Returns the string name for this `dtype`.""" dtype = tf.as_dtype(dtype) if hasattr(dtype, 'name'): return dtype.name if hasattr(dtype, '__name__'): return dtype.__name__ return str(dtype)
python
{ "resource": "" }
q266589
size
test
def size(dtype): """Returns the number of bytes to represent this `dtype`.""" dtype = tf.as_dtype(dtype) if hasattr(dtype, 'size'): return dtype.size return np.dtype(dtype).itemsize
python
{ "resource": "" }
q266590
_assert_same_base_type
test
def _assert_same_base_type(items, expected_type=None): r"""Asserts all items are of the same base type. Args: items: List of graph items (e.g., `Variable`, `Tensor`, `SparseTensor`, `Operation`, or `IndexedSlices`). Can include `None` elements, which will be ignored. expected_type: Expected...
python
{ "resource": "" }
q266591
assert_same_float_dtype
test
def assert_same_float_dtype(tensors=None, dtype=None): """Validate and return float type based on `tensors` and `dtype`. For ops such as matrix multiplication, inputs and weights must be of the same float type. This function validates that all `tensors` are the same type, validates that type is `dtype` (if sup...
python
{ "resource": "" }
q266592
minimize
test
def minimize(objective_function, initial_simplex=None, initial_vertex=None, step_sizes=None, objective_at_initial_simplex=None, objective_at_initial_vertex=None, batch_evaluate_objective=False, func_tolerance=1e-8, p...
python
{ "resource": "" }
q266593
nelder_mead_one_step
test
def nelder_mead_one_step(current_simplex, current_objective_values, objective_function=None, dim=None, func_tolerance=None, position_tolerance=None, batch_evaluate_object...
python
{ "resource": "" }
q266594
_accept_reflected_fn
test
def _accept_reflected_fn(simplex, objective_values, worst_index, reflected, objective_at_reflected): """Creates the condition function pair for a reflection to be accepted.""" def _replace_worst_with_reflected(): ...
python
{ "resource": "" }
q266595
_expansion_fn
test
def _expansion_fn(objective_function, simplex, objective_values, worst_index, reflected, objective_at_reflected, face_centroid, expansion): """Creates the condition function pair for an expans...
python
{ "resource": "" }
q266596
_outside_contraction_fn
test
def _outside_contraction_fn(objective_function, simplex, objective_values, face_centroid, best_index, worst_index, reflected, ...
python
{ "resource": "" }
q266597
_shrink_towards_best
test
def _shrink_towards_best(objective_function, simplex, best_index, shrinkage, batch_evaluate_objective): """Shrinks the simplex around the best vertex.""" # If the contraction step fails to improve the average object...
python
{ "resource": "" }
q266598
_replace_at_index
test
def _replace_at_index(x, index, replacement): """Replaces an element at supplied index.""" x_new = tf.concat([x[:index], tf.expand_dims(replacement, axis=0), x[(index + 1):]], axis=0) return x_new
python
{ "resource": "" }
q266599
_check_convergence
test
def _check_convergence(simplex, best_vertex, best_objective, worst_objective, func_tolerance, position_tolerance): """Returns True if the simplex has converged. If the simplex size is smaller than the...
python
{ "resource": "" }