_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q266800
_tensor_product
test
def _tensor_product(t1, t2): """Computes the outer product of two possibly batched vectors. Args: t1: A `tf.Tensor` of shape `[..., n]`. t2: A `tf.Tensor` of shape `[..., m]`. Returns: A tensor of shape `[..., n, m]` with matching batch dimensions, let's call it `r`, whose components are: `...
python
{ "resource": "" }
q266801
_batch_transpose
test
def _batch_transpose(mat): """Transpose a possibly batched matrix. Args: mat: A `tf.Tensor` of shape `[..., n, m]`. Returns: A tensor of shape `[..., m, n]` with matching batch dimensions. """ n = distribution_util.prefer_static_rank(mat) perm = tf.range(n) perm = tf.concat([perm[:-2], [perm[-1]...
python
{ "resource": "" }
q266802
pad_shape_right_with_ones
test
def pad_shape_right_with_ones(x, ndims): """Maybe add `ndims` ones to `x.shape` on the right. If `ndims` is zero, this is a no-op; otherwise, we will create and return a new `Tensor` whose shape is that of `x` with `ndims` ones concatenated on the right side. If the shape of `x` is known statically, the shape ...
python
{ "resource": "" }
q266803
sum_rightmost_ndims_preserving_shape
test
def sum_rightmost_ndims_preserving_shape(x, ndims): """Return `Tensor` with right-most ndims summed. Args: x: the `Tensor` whose right-most `ndims` dimensions to sum ndims: number of right-most dimensions to sum. Returns: A `Tensor` resulting from calling `reduce_sum` on the `ndims` right-most d...
python
{ "resource": "" }
q266804
sqrt_with_finite_grads
test
def sqrt_with_finite_grads(x, name=None): """A sqrt function whose gradient at zero is very large but finite. Args: x: a `Tensor` whose sqrt is to be computed. name: a Python `str` prefixed to all ops created by this function. Default `None` (i.e., "sqrt_with_finite_grads"). Returns: sqrt: the...
python
{ "resource": "" }
q266805
maybe_get_common_dtype
test
def maybe_get_common_dtype(arg_list): """Return common dtype of arg_list, or None. Args: arg_list: an iterable of items which are either `None` or have a `dtype` property. Returns: dtype: The common dtype of items in `arg_list`, or `None` if the list is empty or all items are `None`. """ ...
python
{ "resource": "" }
q266806
minimize
test
def minimize(value_and_gradients_function, initial_position, num_correction_pairs=10, tolerance=1e-8, x_tolerance=0, f_relative_tolerance=0, initial_inverse_hessian_estimate=None, max_iterations=50, parallel_iteratio...
python
{ "resource": "" }
q266807
_get_initial_state
test
def _get_initial_state(value_and_gradients_function, initial_position, num_correction_pairs, tolerance): """Create LBfgsOptimizerResults with initial state of search procedure.""" init_args = bfgs_utils.get_initial_state_args( value_and_grad...
python
{ "resource": "" }
q266808
_get_search_direction
test
def _get_search_direction(state): """Computes the search direction to follow at the current state. On the `k`-th iteration of the main L-BFGS algorithm, the state has collected the most recent `m` correction pairs in position_deltas and gradient_deltas, where `k = state.num_iterations` and `m = min(k, num_corr...
python
{ "resource": "" }
q266809
_make_empty_queue_for
test
def _make_empty_queue_for(k, element): """Creates a `tf.Tensor` suitable to hold `k` element-shaped tensors. For example: ```python element = tf.constant([[0., 1., 2., 3., 4.], [5., 6., 7., 8., 9.]]) # A queue capable of holding 3 elements. _make_empty_queue_for(3, elemen...
python
{ "resource": "" }
q266810
_queue_push
test
def _queue_push(queue, should_update, new_vecs): """Conditionally push new vectors into a batch of first-in-first-out queues. The `queue` of shape `[k, ..., n]` can be thought of as a batch of queues, each holding `k` n-D vectors; while `new_vecs` of shape `[..., n]` is a fresh new batch of n-D vectors. The `s...
python
{ "resource": "" }
q266811
_psd_mask
test
def _psd_mask(x): """Computes whether each square matrix in the input is positive semi-definite. Args: x: A floating-point `Tensor` of shape `[B1, ..., Bn, M, M]`. Returns: mask: A floating-point `Tensor` of shape `[B1, ... Bn]`. Each scalar is 1 if the corresponding matrix was PSD, otherwise 0. ...
python
{ "resource": "" }
q266812
_det_large_enough_mask
test
def _det_large_enough_mask(x, det_bounds): """Returns whether the input matches the given determinant limit. Args: x: A floating-point `Tensor` of shape `[B1, ..., Bn, M, M]`. det_bounds: A floating-point `Tensor` that must broadcast to shape `[B1, ..., Bn]`, giving the desired lower bound on the ...
python
{ "resource": "" }
q266813
_uniform_correlation_like_matrix
test
def _uniform_correlation_like_matrix(num_rows, batch_shape, dtype, seed): """Returns a uniformly random `Tensor` of "correlation-like" matrices. A "correlation-like" matrix is a symmetric square matrix with all entries between -1 and 1 (inclusive) and 1s on the main diagonal. Of these, the ones that are posit...
python
{ "resource": "" }
q266814
correlation_matrix_volume_rejection_samples
test
def correlation_matrix_volume_rejection_samples( det_bounds, dim, sample_shape, dtype, seed): """Returns rejection samples from trying to get good correlation matrices. The proposal being rejected from is the uniform distribution on "correlation-like" matrices. We say a matrix is "correlation-like" if it ...
python
{ "resource": "" }
q266815
_clopper_pearson_confidence_interval
test
def _clopper_pearson_confidence_interval(samples, error_rate): """Computes a confidence interval for the mean of the given 1-D distribution. Assumes (and checks) that the given distribution is Bernoulli, i.e., takes only two values. This licenses using the CDF of the binomial distribution for the confidence, ...
python
{ "resource": "" }
q266816
compute_true_volumes
test
def compute_true_volumes( det_bounds, dim, num_samples, error_rate=1e-6, seed=42): """Returns confidence intervals for the desired correlation matrix volumes. The confidence intervals are computed by the [Clopper-Pearson method] (https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval). Args...
python
{ "resource": "" }
q266817
_von_mises_cdf_series
test
def _von_mises_cdf_series(x, concentration, num_terms, dtype): """Computes the von Mises CDF and its derivative via series expansion.""" # Keep the number of terms as a float. It should be a small integer, so # exactly representable as a float. num_terms = tf.cast(num_terms, dtype=dtype) def loop_body(n, rn,...
python
{ "resource": "" }
q266818
_von_mises_cdf_normal
test
def _von_mises_cdf_normal(x, concentration, dtype): """Computes the von Mises CDF and its derivative via Normal approximation.""" def cdf_func(concentration): """A helper function that is passed to value_and_gradient.""" # z is an "almost Normally distributed" random variable. z = ((np.sqrt(2. / np.pi)...
python
{ "resource": "" }
q266819
one_step
test
def one_step( objective_function, population, population_values=None, differential_weight=0.5, crossover_prob=0.9, seed=None, name=None): """Performs one step of the differential evolution algorithm. Args: objective_function: A Python callable that accepts a batch of possible ...
python
{ "resource": "" }
q266820
minimize
test
def minimize(objective_function, initial_population=None, initial_position=None, population_size=50, population_stddev=1., max_iterations=100, func_tolerance=0, position_tolerance=1e-8, differential_weight=0.5, ...
python
{ "resource": "" }
q266821
_get_initial_args
test
def _get_initial_args(objective_function, initial_population, initial_position, population_size, population_stddev, max_iterations, func_tolerance, position_tolerance...
python
{ "resource": "" }
q266822
_find_best_in_population
test
def _find_best_in_population(population, values): """Finds the population member with the lowest value.""" best_value = tf.math.reduce_min(input_tensor=values) best_index = tf.where(tf.math.equal(values, best_value))[0, 0] return ([population_part[best_index] for population_part in population], best_...
python
{ "resource": "" }
q266823
_check_convergence
test
def _check_convergence(population, population_values, func_tolerance, position_tolerance): """Checks whether the convergence criteria have been met.""" # Check func tolerance value_range = tf.math.abs( tf.math.reduce_max(input_tensor=popul...
python
{ "resource": "" }
q266824
_get_starting_population
test
def _get_starting_population(initial_population, initial_position, population_size, population_stddev, seed): """Constructs the initial population. If an initial population is not already provided, t...
python
{ "resource": "" }
q266825
_binary_crossover
test
def _binary_crossover(population, population_size, mutants, crossover_prob, seed): """Performs recombination by binary crossover for the current population. Let v_i denote the i'th component of the member v and m_i the correspo...
python
{ "resource": "" }
q266826
_get_mutants
test
def _get_mutants(population, population_size, mixing_indices, differential_weight): """Computes the mutatated vectors for each population member. Args: population: Python `list` of `Tensor`s representing the current population vectors. Each `Tensor` mus...
python
{ "resource": "" }
q266827
_get_mixing_indices
test
def _get_mixing_indices(size, seed=None, name=None): """Generates an array of indices suitable for mutation operation. The mutation operation in differential evolution requires that for every element of the population, three distinct other elements be chosen to produce a trial candidate. This function generate...
python
{ "resource": "" }
q266828
_ensure_list
test
def _ensure_list(tensor_or_list): """Converts the input arg to a list if it is not a list already. Args: tensor_or_list: A `Tensor` or a Python list of `Tensor`s. The argument to convert to a list of `Tensor`s. Returns: A tuple of two elements. The first is a Python list of `Tensor`s containing ...
python
{ "resource": "" }
q266829
_get_tol
test
def _get_tol(tol, dtype, validate_args): """Gets a Tensor of type `dtype`, 0 if `tol` is None, validation optional.""" if tol is None: return tf.convert_to_tensor(value=0, dtype=dtype) tol = tf.convert_to_tensor(value=tol, dtype=dtype) if validate_args: tol = distribution_util.with_dependencies([ ...
python
{ "resource": "" }
q266830
soft_threshold
test
def soft_threshold(x, threshold, name=None): """Soft Thresholding operator. This operator is defined by the equations ```none { x[i] - gamma, x[i] > gamma SoftThreshold(x, gamma)[i] = { 0, x[i] == gamma { x[i] + gamma, x[i] < -...
python
{ "resource": "" }
q266831
clip_by_value_preserve_gradient
test
def clip_by_value_preserve_gradient(t, clip_value_min, clip_value_max, name=None): """Clips values to a specified min and max while leaving gradient unaltered. Like `tf.clip_by_value`, this function returns a tensor of the same type and shape as input `t` but with values clamp...
python
{ "resource": "" }
q266832
build_input_pipeline
test
def build_input_pipeline(train_images, batch_size): """Build an iterator over training batches.""" training_dataset = tf.data.Dataset.from_tensor_slices(train_images) training_batches = training_dataset.shuffle( 50000, reshuffle_each_iteration=True).repeat().batch(batch_size) training_iterator = tf.compa...
python
{ "resource": "" }
q266833
plot_generated_images
test
def plot_generated_images(images, fname): """Save a synthetic image as a PNG file. Args: images: samples of synthetic images generated by the generative network. fname: Python `str`, filename to save the plot to. """ fig = plt.figure(figsize=(4, 4)) canvas = backend_agg.FigureCanvasAgg(fig) for i,...
python
{ "resource": "" }
q266834
SmilesGrammar.convert_to_string
test
def convert_to_string(self, productions): """Converts a sequence of productions into a string of terminal symbols. Args: productions: Tensor of shape [1, num_productions, num_production_rules]. Slices along the `num_productions` dimension represent one-hot vectors. Returns: str that co...
python
{ "resource": "" }
q266835
ProbabilisticGrammar.call
test
def call(self, inputs): """Runs the model forward to generate a sequence of productions. Args: inputs: Unused. Returns: productions: Tensor of shape [1, num_productions, num_production_rules]. Slices along the `num_productions` dimension represent one-hot vectors. """ del input...
python
{ "resource": "" }
q266836
ProbabilisticGrammarVariational.call
test
def call(self, inputs): """Runs the model forward to return a stochastic encoding. Args: inputs: Tensor of shape [1, num_productions, num_production_rules]. It is a sequence of productions of length `num_productions`. Each production is a one-hot vector of length `num_production_rules`: i...
python
{ "resource": "" }
q266837
Zipf._hat_integral
test
def _hat_integral(self, x): """Integral of the `hat` function, used for sampling. We choose a `hat` function, h(x) = x^(-power), which is a continuous (unnormalized) density touching each positive integer at the (unnormalized) pmf. This function implements `hat` integral: H(x) = int_x^inf h(t) dt; ...
python
{ "resource": "" }
q266838
Zipf._hat_integral_inverse
test
def _hat_integral_inverse(self, x): """Inverse function of _hat_integral.""" x = tf.cast(x, self.power.dtype) t = self.power - 1. return tf.math.expm1(-(tf.math.log(t) + tf.math.log(x)) / t)
python
{ "resource": "" }
q266839
matrix_rank
test
def matrix_rank(a, tol=None, validate_args=False, name=None): """Compute the matrix rank; the number of non-zero SVD singular values. Arguments: a: (Batch of) `float`-like matrix-shaped `Tensor`(s) which are to be pseudo-inverted. tol: Threshold below which the singular value is counted as "zero". ...
python
{ "resource": "" }
q266840
pinv
test
def pinv(a, rcond=None, validate_args=False, name=None): """Compute the Moore-Penrose pseudo-inverse of a matrix. Calculate the [generalized inverse of a matrix]( https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_inverse) using its singular-value decomposition (SVD) and including all large singular values. ...
python
{ "resource": "" }
q266841
lu_solve
test
def lu_solve(lower_upper, perm, rhs, validate_args=False, name=None): """Solves systems of linear eqns `A X = RHS`, given LU factorizations. Note: this function does not verify the implied matrix is actually invertible nor is this condition checked even when `validate_args=True`. Arg...
python
{ "resource": "" }
q266842
lu_matrix_inverse
test
def lu_matrix_inverse(lower_upper, perm, validate_args=False, name=None): """Computes a matrix inverse given the matrix's LU decomposition. This op is conceptually identical to, ````python inv_X = tf.lu_matrix_inverse(*tf.linalg.lu(X)) tf.assert_near(tf.matrix_inverse(X), inv_X) # ==> True ``` Note: ...
python
{ "resource": "" }
q266843
_lu_reconstruct_assertions
test
def _lu_reconstruct_assertions(lower_upper, perm, validate_args): """Returns list of assertions related to `lu_reconstruct` assumptions.""" assertions = [] message = 'Input `lower_upper` must have at least 2 dimensions.' if lower_upper.shape.ndims is not None: if lower_upper.shape.ndims < 2: raise Va...
python
{ "resource": "" }
q266844
_lu_solve_assertions
test
def _lu_solve_assertions(lower_upper, perm, rhs, validate_args): """Returns list of assertions related to `lu_solve` assumptions.""" assertions = _lu_reconstruct_assertions(lower_upper, perm, validate_args) message = 'Input `rhs` must have at least 2 dimensions.' if rhs.shape.ndims is not None: if rhs.shap...
python
{ "resource": "" }
q266845
_sparse_block_diag
test
def _sparse_block_diag(sp_a): """Returns a block diagonal rank 2 SparseTensor from a batch of SparseTensors. Args: sp_a: A rank 3 `SparseTensor` representing a batch of matrices. Returns: sp_block_diag_a: matrix-shaped, `float` `SparseTensor` with the same dtype as `sparse_or_matrix`, of shape [B * ...
python
{ "resource": "" }
q266846
_maybe_validate_matrix
test
def _maybe_validate_matrix(a, validate_args): """Checks that input is a `float` matrix.""" assertions = [] if not a.dtype.is_floating: raise TypeError('Input `a` must have `float`-like `dtype` ' '(saw {}).'.format(a.dtype.name)) if a.shape.ndims is not None: if a.shape.ndims < 2: ...
python
{ "resource": "" }
q266847
_grad_neg_log_likelihood_and_fim
test
def _grad_neg_log_likelihood_and_fim(model_matrix, linear_response, response, model): """Computes the neg-log-likelihood gradient and Fisher information for a GLM. Note that Fisher information is related to the Hessian of the log-likelihood by the equation ```none Fisher...
python
{ "resource": "" }
q266848
fit_sparse
test
def fit_sparse(model_matrix, response, model, model_coefficients_start, tolerance, l1_regularizer, l2_regularizer=None, maximum_iterations=None, maximum_full_sweeps_per_iteration=1, lea...
python
{ "resource": "" }
q266849
_gen_slices
test
def _gen_slices(num_blocks, n_in, n_out, mask_type=MASK_EXCLUSIVE): """Generate the slices for building an autoregressive mask.""" # TODO(b/67594795): Better support of dynamic shape. slices = [] col = 0 d_in = n_in // num_blocks d_out = n_out // num_blocks row = d_out if mask_type == MASK_EXCLUSIVE else ...
python
{ "resource": "" }
q266850
_gen_mask
test
def _gen_mask(num_blocks, n_in, n_out, mask_type=MASK_EXCLUSIVE, dtype=tf.float32): """Generate the mask for building an autoregressive dense layer.""" # TODO(b/67594795): Better support of dynamic shape. mask = np.zeros([n_out, n_in], dtype=dtype.as_numpy_d...
python
{ "resource": "" }
q266851
masked_dense
test
def masked_dense(inputs, units, num_blocks=None, exclusive=False, kernel_initializer=None, reuse=None, name=None, *args, # pylint: disable=keyword-arg-before-vararg **kwargs): """A ...
python
{ "resource": "" }
q266852
_create_input_order
test
def _create_input_order(input_size, input_order="left-to-right"): """Returns a degree vectors for the input.""" if isinstance(input_order, six.string_types): if input_order == "left-to-right": return np.arange(start=1, stop=input_size + 1) elif input_order == "right-to-left": return np.arange(st...
python
{ "resource": "" }
q266853
_create_degrees
test
def _create_degrees(input_size, hidden_units=None, input_order="left-to-right", hidden_degrees="equal"): """Returns a list of degree vectors, one for each input and hidden layer. A unit with degree d can only receive input from units with degree < d. Outp...
python
{ "resource": "" }
q266854
_create_masks
test
def _create_masks(degrees): """Returns a list of binary mask matrices enforcing autoregressivity.""" return [ # Create input->hidden and hidden->hidden masks. inp[:, np.newaxis] <= out for inp, out in zip(degrees[:-1], degrees[1:]) ] + [ # Create hidden->output mask. degrees[-1][:, n...
python
{ "resource": "" }
q266855
_make_masked_initializer
test
def _make_masked_initializer(mask, initializer): """Returns a masked version of the given initializer.""" initializer = tf.keras.initializers.get(initializer) def masked_initializer(shape, dtype=None, partition_info=None): # If no `partition_info` is given, then don't pass it to `initializer`, as # `initi...
python
{ "resource": "" }
q266856
AutoregressiveLayer.build
test
def build(self, input_shape): """See tfkl.Layer.build.""" if self._event_shape is None: # `event_shape` wasn't specied at __init__, so infer from `input_shape`. self._event_shape = [tf.compat.dimension_value(input_shape[-1])] self._event_size = self._event_shape[-1] self._event_ndims = l...
python
{ "resource": "" }
q266857
AutoregressiveLayer.call
test
def call(self, x): """See tfkl.Layer.call.""" with tf.compat.v2.name_scope(self.name or "AutoregressiveLayer_call"): x = tf.convert_to_tensor(value=x, dtype=self.dtype, name="x") input_shape = tf.shape(input=x) # TODO(b/67594795): Better support for dynamic shapes. if tensorshape_util.ra...
python
{ "resource": "" }
q266858
draw_sample
test
def draw_sample(num_samples, num_classes, logits, num_trials, dtype, seed): """Sample a multinomial. The batch shape is given by broadcasting num_trials with remove_last_dimension(logits). Args: num_samples: Python int or singleton integer Tensor: number of multinomial samples to draw. num_class...
python
{ "resource": "" }
q266859
_zero_dimensional_mvndiag
test
def _zero_dimensional_mvndiag(dtype): """Build a zero-dimensional MVNDiag object.""" dummy_mvndiag = tfd.MultivariateNormalDiag( scale_diag=tf.ones([0], dtype=dtype)) dummy_mvndiag.covariance = lambda: dummy_mvndiag.variance()[..., tf.newaxis] return dummy_mvndiag
python
{ "resource": "" }
q266860
_observe_timeseries_fn
test
def _observe_timeseries_fn(timeseries): """Build an observation_noise_fn that observes a Tensor timeseries.""" def observation_noise_fn(t): current_slice = timeseries[..., t, :] return tfd.MultivariateNormalDiag( loc=current_slice, scale_diag=tf.zeros_like(current_slice)) return observatio...
python
{ "resource": "" }
q266861
SparseLinearRegression.params_to_weights
test
def params_to_weights(self, global_scale_variance, global_scale_noncentered, local_scale_variances, local_scales_noncentered, weights_noncentered): """Build regression weights from model parameter...
python
{ "resource": "" }
q266862
_depth
test
def _depth(g): """Computes the number of edges on longest path from node to root.""" def _explore(v): if v.depth < 0: v.depth = ((1 + max([-1] + [_explore(annotated_graph[u]) for u in v.parents])) if v.parents else 0) return v.depth annotated_graph ...
python
{ "resource": "" }
q266863
_best_order
test
def _best_order(g): """Creates tuple of str tuple-str pairs representing resolved & sorted DAG.""" def _explore(u): """Recursive function to ascend up through unvisited dependencies.""" if u.depth < 0: return # Already visited. if not u.parents: result.append((u.name, u.parents)) u.de...
python
{ "resource": "" }
q266864
_prob_chain_rule_flatten
test
def _prob_chain_rule_flatten(named_makers): """Creates lists of callables suitable for JDSeq.""" def _make(dist_fn, args): if args is None: return lambda *_: dist_fn if not args: return lambda *_: dist_fn() def _fn(*xs): kwargs = dict(zip(args, reversed(xs[-len(args):]))) kwargs....
python
{ "resource": "" }
q266865
JointDistributionNamed._build
test
def _build(self, model): """Creates `dist_fn`, `dist_fn_wrapped`, `dist_fn_args`, `dist_fn_name`.""" if not _is_dict_like(model): raise TypeError('`model` must be convertible to `dict` (saw: {}).'.format( type(model).__name__)) [ self._dist_fn, self._dist_fn_wrapped, ...
python
{ "resource": "" }
q266866
VariationalGaussianProcess.variational_loss
test
def variational_loss(self, observations, observation_index_points=None, kl_weight=1., name='variational_loss'): """Variational loss for the VGP. Given `observations` and `observation_index_points`, compute the negat...
python
{ "resource": "" }
q266867
VariationalGaussianProcess.optimal_variational_posterior
test
def optimal_variational_posterior( kernel, inducing_index_points, observation_index_points, observations, observation_noise_variance, mean_fn=None, jitter=1e-6, name=None): """Model selection for optimal variational hyperparameters. Given the full training set (p...
python
{ "resource": "" }
q266868
build_is_last_day_of_season
test
def build_is_last_day_of_season(num_steps_per_season): """Build utility method to compute whether the season is changing.""" num_steps_per_cycle = np.sum(num_steps_per_season) changepoints = np.cumsum(np.ravel(num_steps_per_season)) - 1 def is_last_day_of_season(t): t_ = dist_util.maybe_get_static_value(t) ...
python
{ "resource": "" }
q266869
build_effects_to_residuals_matrix
test
def build_effects_to_residuals_matrix(num_seasons, dtype): """Build change-of-basis matrices for constrained seasonal effects. This method builds the matrix that transforms seasonal effects into effect residuals (differences from the mean effect), and additionally projects these residuals onto the subspace whe...
python
{ "resource": "" }
q266870
build_seasonal_transition_matrix
test
def build_seasonal_transition_matrix( num_seasons, is_last_day_of_season, dtype, basis_change_matrix=None, basis_change_matrix_inv=None): """Build a function computing transitions for a seasonal effect model.""" with tf.compat.v1.name_scope('build_seasonal_transition_matrix'): # If the season is changi...
python
{ "resource": "" }
q266871
build_seasonal_transition_noise
test
def build_seasonal_transition_noise( drift_scale, num_seasons, is_last_day_of_season): """Build the transition noise model for a SeasonalStateSpaceModel.""" # If the current season has just ended, increase the variance of its effect # following drift_scale. (the just-ended seasonal effect will always be the ...
python
{ "resource": "" }
q266872
build_constrained_seasonal_transition_noise
test
def build_constrained_seasonal_transition_noise( drift_scale, num_seasons, is_last_day_of_season): """Build transition noise distribution for a ConstrainedSeasonalSSM.""" # Conceptually, this method takes the noise covariance on effects L @ L' # computed by `build_seasonal_transition_noise`, with scale facto...
python
{ "resource": "" }
q266873
_is_empty_observation_data
test
def _is_empty_observation_data( feature_ndims, observation_index_points, observations): """Returns `True` if given observation data is empty. Emptiness means either 1. Both `observation_index_points` and `observations` are `None`, or 2. the "number of observations" shape is 0. The shape of `observa...
python
{ "resource": "" }
q266874
_validate_observation_data
test
def _validate_observation_data( kernel, observation_index_points, observations): """Ensure that observation data and locations have consistent shapes. This basically means that the batch shapes are broadcastable. We can only ensure this when those shapes are fully statically defined. Args: kernel: Th...
python
{ "resource": "" }
q266875
SequentialSchedule.add
test
def add(self, scheduler, max_iteration, bigdl_type="float"): """ Add a learning rate scheduler to the contained `schedules` :param scheduler: learning rate scheduler to be add :param max_iteration: iteration numbers this scheduler will run """ return callBigDlFunc(bigdl_...
python
{ "resource": "" }
q266876
BaseOptimizer.set_checkpoint
test
def set_checkpoint(self, checkpoint_trigger, checkpoint_path, isOverWrite=True): """ Configure checkpoint settings. :param checkpoint_trigger: the interval to write snapshots :param checkpoint_path: the path to write snapshots into :param isOverWrite: whe...
python
{ "resource": "" }
q266877
BaseOptimizer.set_gradclip_const
test
def set_gradclip_const(self, min_value, max_value): """ Configure constant clipping settings. :param min_value: the minimum value to clip by :param max_value: the maxmimum value to clip by """ callBigDlFunc(self.bigdl_type, "setConstantClip", self.value, min_value, max_...
python
{ "resource": "" }
q266878
BaseOptimizer.optimize
test
def optimize(self): """ Do an optimization. """ jmodel = callJavaFunc(self.value.optimize) from bigdl.nn.layer import Layer return Layer.of(jmodel)
python
{ "resource": "" }
q266879
BaseOptimizer.set_train_summary
test
def set_train_summary(self, summary): """ Set train summary. A TrainSummary object contains information necessary for the optimizer to know how often the logs are recorded, where to store the logs and how to retrieve them, etc. For details, refer to the docs of TrainSummary. ...
python
{ "resource": "" }
q266880
BaseOptimizer.set_val_summary
test
def set_val_summary(self, summary): """ Set validation summary. A ValidationSummary object contains information necessary for the optimizer to know how often the logs are recorded, where to store the logs and how to retrieve them, etc. For details, refer to the docs of Validation...
python
{ "resource": "" }
q266881
Optimizer.create
test
def create(model, training_set, criterion, end_trigger=None, batch_size=32, optim_method=None, cores=None, bigdl_type="float"): """ Create an optimizer. Depend on the input type, the returnin...
python
{ "resource": "" }
q266882
Optimizer.set_traindata
test
def set_traindata(self, training_rdd, batch_size): """ Set new training dataset, for optimizer reuse :param training_rdd: the training dataset :param batch_size: training batch size :return: """ callBigDlFunc(self.bigdl_type, "setTrainData", self.value, ...
python
{ "resource": "" }
q266883
TrainSummary.set_summary_trigger
test
def set_summary_trigger(self, name, trigger): """ Set the interval of recording for each indicator. :param tag: tag name. Supported tag names are "LearningRate", "Loss","Throughput", "Parameters". "Parameters" is an umbrella tag thatincludes weight, bias, gradWeight, gradBias, and some running...
python
{ "resource": "" }
q266884
read_data_sets
test
def read_data_sets(train_dir, data_type="train"): """ Parse or download mnist data if train_dir is empty. :param: train_dir: The directory storing the mnist data :param: data_type: Reading training set or testing set.It can be either "train" or "test" :return: ``` (ndarray, ndarray) repr...
python
{ "resource": "" }
q266885
get_news20
test
def get_news20(source_dir="./data/news20/"): """ Parse or download news20 if source_dir is empty. :param source_dir: The directory storing news data. :return: A list of (tokens, label) """ news_dir = download_news20(source_dir) texts = [] # list of text samples label_id = 0 for nam...
python
{ "resource": "" }
q266886
get_glove_w2v
test
def get_glove_w2v(source_dir="./data/news20/", dim=100): """ Parse or download the pre-trained glove word2vec if source_dir is empty. :param source_dir: The directory storing the pre-trained word2vec :param dim: The dimension of a vector :return: A dict mapping from word to vector """ w2v_d...
python
{ "resource": "" }
q266887
KerasModel.compile
test
def compile(self, optimizer, loss, metrics=None): """ Configures the learning process. Must be called before fit or evaluate. # Arguments optimizer: Optimization method to be used. One can alternatively pass in the corresponding string representation, such as 'sgd'. ...
python
{ "resource": "" }
q266888
KerasModel.fit
test
def fit(self, x, y=None, batch_size=32, nb_epoch=10, validation_data=None, distributed=True): """ Train a model for a fixed number of epochs on a dataset. # Arguments x: Input data. A Numpy array or RDD of Sample or Image DataSet. y: Labels. A Numpy array. Default is None if x i...
python
{ "resource": "" }
q266889
KerasModel.evaluate
test
def evaluate(self, x, y=None, batch_size=32): """ Evaluate a model on a given dataset in distributed mode. # Arguments x: Input data. A Numpy array or RDD of Sample. y: Labels. A Numpy array. Default is None if x is already RDD of Sample. batch_size: Number of samples pe...
python
{ "resource": "" }
q266890
KerasModel.predict
test
def predict(self, x, distributed=True): """ Use a model to do prediction. # Arguments x: Input data. A Numpy array or RDD of Sample. distributed: Boolean. Whether to do prediction in distributed mode or local mode. Default is True. In local mode, x must be a...
python
{ "resource": "" }
q266891
get_mnist
test
def get_mnist(sc, data_type="train", location="/tmp/mnist"): """ Get mnist dataset and parallelize into RDDs. Data would be downloaded automatically if it doesn't present at the specific location. :param sc: SparkContext. :param data_type: "train" for training data and "test" for testing data. ...
python
{ "resource": "" }
q266892
preprocess_mnist
test
def preprocess_mnist(sc, options): """ Preprocess mnist dataset. Normalize and transform into Sample of RDDs. """ train_data = get_mnist(sc, "train", options.dataPath)\ .map(lambda rec_tuple: (normalizer(rec_tuple[0], mnist.TRAIN_MEAN, mnist.TRAIN_STD), rec_tu...
python
{ "resource": "" }
q266893
get_end_trigger
test
def get_end_trigger(options): """ When to end the optimization based on input option. """ if options.endTriggerType.lower() == "epoch": return MaxEpoch(options.endTriggerNum) else: return MaxIteration(options.endTriggerNum)
python
{ "resource": "" }
q266894
validate_optimizer
test
def validate_optimizer(optimizer, test_data, options): """ Set validation and checkpoint for distributed optimizer. """ optimizer.set_validation( batch_size=options.batchSize, val_rdd=test_data, trigger=EveryEpoch(), val_method=[Top1Accuracy()] ) optimizer.set_che...
python
{ "resource": "" }
q266895
ModelBroadcast.value
test
def value(self): """ Return the broadcasted value """ if not hasattr(self, "_value") and self._path is not None: self._value = self._load(self._path) return self._value
python
{ "resource": "" }
q266896
callBigDlFunc
test
def callBigDlFunc(bigdl_type, name, *args): """ Call API in PythonBigDL """ gateway = _get_gateway() error = Exception("Cannot find function: %s" % name) for jinvoker in JavaCreator.instance(bigdl_type, gateway).value: # hasattr(jinvoker, name) always return true here, # so you need to i...
python
{ "resource": "" }
q266897
callJavaFunc
test
def callJavaFunc(func, *args): """ Call Java Function """ gateway = _get_gateway() args = [_py2java(gateway, a) for a in args] result = func(*args) return _java2py(gateway, result)
python
{ "resource": "" }
q266898
_to_java_object_rdd
test
def _to_java_object_rdd(rdd): """ Return a JavaRDD of Object by unpickling It will convert each Python object into Java object by Pyrolite, whenever the RDD is serialized in batch or not. """ rdd = rdd._reserialize(AutoBatchedSerializer(PickleSerializer())) return \ rdd.ctx._jvm.org.ap...
python
{ "resource": "" }
q266899
_py2java
test
def _py2java(gateway, obj): """ Convert Python object into Java """ if isinstance(obj, RDD): obj = _to_java_object_rdd(obj) elif isinstance(obj, DataFrame): obj = obj._jdf elif isinstance(obj, SparkContext): obj = obj._jsc elif isinstance(obj, (list, tuple)): obj = Li...
python
{ "resource": "" }