partition stringclasses 3
values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1
value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
test | _validate_block_sizes | Helper to validate block sizes. | tensorflow_probability/python/bijectors/blockwise.py | 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) ... | 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) ... | [
"Helper",
"to",
"validate",
"block",
"sizes",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/bijectors/blockwise.py#L151-L172 | [
"def",
"_validate_block_sizes",
"(",
"block_sizes",
",",
"bijectors",
",",
"validate_args",
")",
":",
"block_sizes_shape",
"=",
"block_sizes",
".",
"shape",
"if",
"tensorshape_util",
".",
"is_fully_defined",
"(",
"block_sizes_shape",
")",
":",
"if",
"(",
"tensorshap... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | maybe_check_wont_broadcast | Verifies that `parts` don't broadcast. | tensorflow_probability/python/distributions/joint_distribution.py | 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... | 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... | [
"Verifies",
"that",
"parts",
"don",
"t",
"broadcast",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/joint_distribution.py#L324-L341 | [
"def",
"maybe_check_wont_broadcast",
"(",
"flat_xs",
",",
"validate_args",
")",
":",
"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",
"# po... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | softplus_and_shift | Converts (batch of) scalars to (batch of) positive valued scalars.
Args:
x: (Batch of) `float`-like `Tensor` representing scalars which will be
transformed into positive elements.
shift: `Tensor` added to `softplus` transformation of elements.
Default value: `1e-5`.
name: A `name_scope` name ... | tensorflow_probability/python/trainable_distributions/trainable_distributions_lib.py | def softplus_and_shift(x, shift=1e-5, name=None):
"""Converts (batch of) scalars to (batch of) positive valued scalars.
Args:
x: (Batch of) `float`-like `Tensor` representing scalars which will be
transformed into positive elements.
shift: `Tensor` added to `softplus` transformation of elements.
... | def softplus_and_shift(x, shift=1e-5, name=None):
"""Converts (batch of) scalars to (batch of) positive valued scalars.
Args:
x: (Batch of) `float`-like `Tensor` representing scalars which will be
transformed into positive elements.
shift: `Tensor` added to `softplus` transformation of elements.
... | [
"Converts",
"(",
"batch",
"of",
")",
"scalars",
"to",
"(",
"batch",
"of",
")",
"positive",
"valued",
"scalars",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/trainable_distributions/trainable_distributions_lib.py#L42-L61 | [
"def",
"softplus_and_shift",
"(",
"x",
",",
"shift",
"=",
"1e-5",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"name",
",",
"'softplus_and_shift'",
",",
"[",
"x",
",",
"shift",
"]",
")",
":",
"... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | tril_with_diag_softplus_and_shift | Converts (batch of) vectors to (batch of) lower-triangular scale matrices.
Args:
x: (Batch of) `float`-like `Tensor` representing vectors which will be
transformed into lower-triangular scale matrices with positive diagonal
elements. Rightmost shape `n` must be such that
`n = dims * (dims + 1) ... | tensorflow_probability/python/trainable_distributions/trainable_distributions_lib.py | def tril_with_diag_softplus_and_shift(x, diag_shift=1e-5, name=None):
"""Converts (batch of) vectors to (batch of) lower-triangular scale matrices.
Args:
x: (Batch of) `float`-like `Tensor` representing vectors which will be
transformed into lower-triangular scale matrices with positive diagonal
el... | def tril_with_diag_softplus_and_shift(x, diag_shift=1e-5, name=None):
"""Converts (batch of) vectors to (batch of) lower-triangular scale matrices.
Args:
x: (Batch of) `float`-like `Tensor` representing vectors which will be
transformed into lower-triangular scale matrices with positive diagonal
el... | [
"Converts",
"(",
"batch",
"of",
")",
"vectors",
"to",
"(",
"batch",
"of",
")",
"lower",
"-",
"triangular",
"scale",
"matrices",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/trainable_distributions/trainable_distributions_lib.py#L64-L89 | [
"def",
"tril_with_diag_softplus_and_shift",
"(",
"x",
",",
"diag_shift",
"=",
"1e-5",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"name",
",",
"'tril_with_diag_softplus_and_shift'",
",",
"[",
"x",
",",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | multivariate_normal_tril | Constructs a trainable `tfd.MultivariateNormalTriL` distribution.
This function creates a MultivariateNormal (MVN) with lower-triangular scale
matrix. By default the MVN is parameterized via affine transformation of input
tensor `x`. Using default args, this function is mathematically equivalent to:
```none
... | tensorflow_probability/python/trainable_distributions/trainable_distributions_lib.py | 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... | 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... | [
"Constructs",
"a",
"trainable",
"tfd",
".",
"MultivariateNormalTriL",
"distribution",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/trainable_distributions/trainable_distributions_lib.py#L92-L197 | [
"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"... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | bernoulli | 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)
where,
W in R^[d, n]
b in R^d
```
#### Examples
This... | tensorflow_probability/python/trainable_distributions/trainable_distributions_lib.py | 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)
... | 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)
... | [
"Constructs",
"a",
"trainable",
"tfd",
".",
"Bernoulli",
"distribution",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/trainable_distributions/trainable_distributions_lib.py#L200-L281 | [
"def",
"bernoulli",
"(",
"x",
",",
"layer_fn",
"=",
"tf",
".",
"compat",
".",
"v1",
".",
"layers",
".",
"dense",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"name",
",",
"'bernoulli'",
",",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | normal | Constructs a trainable `tfd.Normal` distribution.
This function creates a Normal distribution parameterized by loc and scale.
Using default args, this function is mathematically equivalent to:
```none
Y = Normal(loc=matmul(W, x) + b, scale=1)
where,
W in R^[d, n]
b in R^d
```
#### Examples
... | tensorflow_probability/python/trainable_distributions/trainable_distributions_lib.py | 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... | 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... | [
"Constructs",
"a",
"trainable",
"tfd",
".",
"Normal",
"distribution",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/trainable_distributions/trainable_distributions_lib.py#L284-L387 | [
"def",
"normal",
"(",
"x",
",",
"layer_fn",
"=",
"tf",
".",
"compat",
".",
"v1",
".",
"layers",
".",
"dense",
",",
"loc_fn",
"=",
"lambda",
"x",
":",
"x",
",",
"scale_fn",
"=",
"1.",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compa... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | poisson | Constructs a trainable `tfd.Poisson` distribution.
This function creates a Poisson distribution parameterized by log rate.
Using default args, this function is mathematically equivalent to:
```none
Y = Poisson(log_rate=matmul(W, x) + b)
where,
W in R^[d, n]
b in R^d
```
#### Examples
This c... | tensorflow_probability/python/trainable_distributions/trainable_distributions_lib.py | 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 ... | 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 ... | [
"Constructs",
"a",
"trainable",
"tfd",
".",
"Poisson",
"distribution",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/trainable_distributions/trainable_distributions_lib.py#L390-L478 | [
"def",
"poisson",
"(",
"x",
",",
"layer_fn",
"=",
"tf",
".",
"compat",
".",
"v1",
".",
"layers",
".",
"dense",
",",
"log_rate_fn",
"=",
"lambda",
"x",
":",
"x",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"n... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | secant_root | r"""Finds root(s) of a function of single variable using the secant method.
The [secant method](https://en.wikipedia.org/wiki/Secant_method) is a
root-finding algorithm that uses a succession of roots of secant lines to
better approximate a root of a function. The secant method can be thought of
as a finite-di... | tensorflow_probability/python/math/root_search.py | def secant_root(objective_fn,
initial_position,
next_position=None,
value_at_position=None,
position_tolerance=1e-8,
value_tolerance=1e-8,
max_iterations=50,
stopping_policy_fn=tf.reduce_all,
... | def secant_root(objective_fn,
initial_position,
next_position=None,
value_at_position=None,
position_tolerance=1e-8,
value_tolerance=1e-8,
max_iterations=50,
stopping_policy_fn=tf.reduce_all,
... | [
"r",
"Finds",
"root",
"(",
"s",
")",
"of",
"a",
"function",
"of",
"single",
"variable",
"using",
"the",
"secant",
"method",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/math/root_search.py#L44-L321 | [
"def",
"secant_root",
"(",
"objective_fn",
",",
"initial_position",
",",
"next_position",
"=",
"None",
",",
"value_at_position",
"=",
"None",
",",
"position_tolerance",
"=",
"1e-8",
",",
"value_tolerance",
"=",
"1e-8",
",",
"max_iterations",
"=",
"50",
",",
"sto... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _euler_method | Applies one step of Euler-Maruyama method.
Generates proposal of the form:
```python
tfd.Normal(loc=state_parts + _get_drift(state_parts, ...),
scale=tf.sqrt(step_size * volatility_fn(current_state)))
```
`_get_drift(state_parts, ..)` is a diffusion drift value at `state_parts`.
Args:
... | tensorflow_probability/python/mcmc/langevin.py | 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... | 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... | [
"Applies",
"one",
"step",
"of",
"Euler",
"-",
"Maruyama",
"method",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/langevin.py#L630-L688 | [
"def",
"_euler_method",
"(",
"random_draw_parts",
",",
"state_parts",
",",
"drift_parts",
",",
"step_size_parts",
",",
"volatility_parts",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"name",
",",
"'mala... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _get_drift | 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_fn(current_state)`
+ `step_size` * `grads_volatility`
```
where `volatility_parts` = `volatility_fn(current_state)**2` and
`grads... | tensorflow_probability/python/mcmc/langevin.py | 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_... | 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_... | [
"Compute",
"diffusion",
"drift",
"at",
"the",
"current",
"location",
"current_state",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/langevin.py#L691-L745 | [
"def",
"_get_drift",
"(",
"step_size_parts",
",",
"volatility_parts",
",",
"grads_volatility",
",",
"grads_target_log_prob",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"name",
",",
"'mala_get_drift'",
",... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _compute_log_acceptance_correction | r"""Helper to `kernel` which computes the log acceptance-correction.
Computes `log_acceptance_correction` as described in `MetropolisHastings`
class. The proposal density is normal. More specifically,
```none
q(proposed_state | current_state) \sim N(current_state + current_drift,
step_size * current_volati... | tensorflow_probability/python/mcmc/langevin.py | def _compute_log_acceptance_correction(current_state_parts,
proposed_state_parts,
current_volatility_parts,
proposed_volatility_parts,
current_drift_parts,
... | def _compute_log_acceptance_correction(current_state_parts,
proposed_state_parts,
current_volatility_parts,
proposed_volatility_parts,
current_drift_parts,
... | [
"r",
"Helper",
"to",
"kernel",
"which",
"computes",
"the",
"log",
"acceptance",
"-",
"correction",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/langevin.py#L748-L869 | [
"def",
"_compute_log_acceptance_correction",
"(",
"current_state_parts",
",",
"proposed_state_parts",
",",
"current_volatility_parts",
",",
"proposed_volatility_parts",
",",
"current_drift_parts",
",",
"proposed_drift_parts",
",",
"step_size_parts",
",",
"independent_chain_ndims",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _maybe_call_volatility_fn_and_grads | Helper which computes `volatility_fn` results and grads, if needed. | tensorflow_probability/python/mcmc/langevin.py | def _maybe_call_volatility_fn_and_grads(volatility_fn,
state,
volatility_fn_results=None,
grads_volatility_fn=None,
sample_shape=None,
... | def _maybe_call_volatility_fn_and_grads(volatility_fn,
state,
volatility_fn_results=None,
grads_volatility_fn=None,
sample_shape=None,
... | [
"Helper",
"which",
"computes",
"volatility_fn",
"results",
"and",
"grads",
"if",
"needed",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/langevin.py#L872-L922 | [
"def",
"_maybe_call_volatility_fn_and_grads",
"(",
"volatility_fn",
",",
"state",
",",
"volatility_fn_results",
"=",
"None",
",",
"grads_volatility_fn",
"=",
"None",
",",
"sample_shape",
"=",
"None",
",",
"parallel_iterations",
"=",
"10",
")",
":",
"state_parts",
"=... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _maybe_broadcast_volatility | Helper to broadcast `volatility_parts` to the shape of `state_parts`. | tensorflow_probability/python/mcmc/langevin.py | 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)] | 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)] | [
"Helper",
"to",
"broadcast",
"volatility_parts",
"to",
"the",
"shape",
"of",
"state_parts",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/langevin.py#L925-L929 | [
"def",
"_maybe_broadcast_volatility",
"(",
"volatility_parts",
",",
"state_parts",
")",
":",
"return",
"[",
"v",
"+",
"tf",
".",
"zeros_like",
"(",
"sp",
",",
"dtype",
"=",
"sp",
".",
"dtype",
".",
"base_dtype",
")",
"for",
"v",
",",
"sp",
"in",
"zip",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _prepare_args | Helper which processes input args to meet list-like assumptions. | tensorflow_probability/python/mcmc/langevin.py | def _prepare_args(target_log_prob_fn,
volatility_fn,
state,
step_size,
target_log_prob=None,
grads_target_log_prob=None,
volatility=None,
grads_volatility_fn=None,
diffusion_dr... | def _prepare_args(target_log_prob_fn,
volatility_fn,
state,
step_size,
target_log_prob=None,
grads_target_log_prob=None,
volatility=None,
grads_volatility_fn=None,
diffusion_dr... | [
"Helper",
"which",
"processes",
"input",
"args",
"to",
"meet",
"list",
"-",
"like",
"assumptions",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/langevin.py#L932-L997 | [
"def",
"_prepare_args",
"(",
"target_log_prob_fn",
",",
"volatility_fn",
",",
"state",
",",
"step_size",
",",
"target_log_prob",
"=",
"None",
",",
"grads_target_log_prob",
"=",
"None",
",",
"volatility",
"=",
"None",
",",
"grads_volatility_fn",
"=",
"None",
",",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | make_ar_transition_matrix | 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 space,
and moves all previous values down by one d... | tensorflow_probability/python/sts/autoregressive.py | 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... | 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... | [
"Build",
"transition",
"matrix",
"for",
"an",
"autoregressive",
"StateSpaceModel",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/sts/autoregressive.py#L223-L257 | [
"def",
"make_ar_transition_matrix",
"(",
"coefficients",
")",
":",
"top_row",
"=",
"tf",
".",
"expand_dims",
"(",
"coefficients",
",",
"-",
"2",
")",
"coef_shape",
"=",
"dist_util",
".",
"prefer_static_shape",
"(",
"coefficients",
")",
"batch_shape",
",",
"order... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | diag_jacobian | Computes diagonal of the Jacobian matrix of `ys=fn(xs)` wrt `xs`.
If `ys` is a tensor or a list of tensors of the form `(ys_1, .., ys_n)` and
`xs` is of the form `(xs_1, .., xs_n)`, the function `jacobians_diag`
computes the diagonal of the Jacobian matrix, i.e., the partial derivatives
`(dys_1/dxs_1,.... | tensorflow_probability/python/math/diag_jacobian.py | def diag_jacobian(xs,
ys=None,
sample_shape=None,
fn=None,
parallel_iterations=10,
name=None):
"""Computes diagonal of the Jacobian matrix of `ys=fn(xs)` wrt `xs`.
If `ys` is a tensor or a list of tensors of the form `(ys_1... | def diag_jacobian(xs,
ys=None,
sample_shape=None,
fn=None,
parallel_iterations=10,
name=None):
"""Computes diagonal of the Jacobian matrix of `ys=fn(xs)` wrt `xs`.
If `ys` is a tensor or a list of tensors of the form `(ys_1... | [
"Computes",
"diagonal",
"of",
"the",
"Jacobian",
"matrix",
"of",
"ys",
"=",
"fn",
"(",
"xs",
")",
"wrt",
"xs",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/math/diag_jacobian.py#L32-L248 | [
"def",
"diag_jacobian",
"(",
"xs",
",",
"ys",
"=",
"None",
",",
"sample_shape",
"=",
"None",
",",
"fn",
"=",
"None",
",",
"parallel_iterations",
"=",
"10",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | calculate_reshape | Calculates the reshaped dimensions (replacing up to one -1 in reshape). | tensorflow_probability/python/distributions/batch_reshape.py | def calculate_reshape(original_shape, new_shape, validate=False, name=None):
"""Calculates the reshaped dimensions (replacing up to one -1 in reshape)."""
batch_shape_static = tensorshape_util.constant_value_as_shape(new_shape)
if tensorshape_util.is_fully_defined(batch_shape_static):
return np.int32(batch_sh... | def calculate_reshape(original_shape, new_shape, validate=False, name=None):
"""Calculates the reshaped dimensions (replacing up to one -1 in reshape)."""
batch_shape_static = tensorshape_util.constant_value_as_shape(new_shape)
if tensorshape_util.is_fully_defined(batch_shape_static):
return np.int32(batch_sh... | [
"Calculates",
"the",
"reshaped",
"dimensions",
"(",
"replacing",
"up",
"to",
"one",
"-",
"1",
"in",
"reshape",
")",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/batch_reshape.py#L380-L409 | [
"def",
"calculate_reshape",
"(",
"original_shape",
",",
"new_shape",
",",
"validate",
"=",
"False",
",",
"name",
"=",
"None",
")",
":",
"batch_shape_static",
"=",
"tensorshape_util",
".",
"constant_value_as_shape",
"(",
"new_shape",
")",
"if",
"tensorshape_util",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | validate_init_args_statically | Helper to __init__ which makes or raises assertions. | tensorflow_probability/python/distributions/batch_reshape.py | def validate_init_args_statically(distribution, batch_shape):
"""Helper to __init__ which makes or raises assertions."""
if tensorshape_util.rank(batch_shape.shape) is not None:
if tensorshape_util.rank(batch_shape.shape) != 1:
raise ValueError("`batch_shape` must be a vector "
"(sa... | def validate_init_args_statically(distribution, batch_shape):
"""Helper to __init__ which makes or raises assertions."""
if tensorshape_util.rank(batch_shape.shape) is not None:
if tensorshape_util.rank(batch_shape.shape) != 1:
raise ValueError("`batch_shape` must be a vector "
"(sa... | [
"Helper",
"to",
"__init__",
"which",
"makes",
"or",
"raises",
"assertions",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/batch_reshape.py#L412-L435 | [
"def",
"validate_init_args_statically",
"(",
"distribution",
",",
"batch_shape",
")",
":",
"if",
"tensorshape_util",
".",
"rank",
"(",
"batch_shape",
".",
"shape",
")",
"is",
"not",
"None",
":",
"if",
"tensorshape_util",
".",
"rank",
"(",
"batch_shape",
".",
"... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | BatchReshape._sample_shape | Computes graph and static `sample_shape`. | tensorflow_probability/python/distributions/batch_reshape.py | 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... | 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... | [
"Computes",
"graph",
"and",
"static",
"sample_shape",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/batch_reshape.py#L210-L232 | [
"def",
"_sample_shape",
"(",
"self",
",",
"x",
")",
":",
"x_ndims",
"=",
"(",
"tf",
".",
"rank",
"(",
"x",
")",
"if",
"tensorshape_util",
".",
"rank",
"(",
"x",
".",
"shape",
")",
"is",
"None",
"else",
"tensorshape_util",
".",
"rank",
"(",
"x",
"."... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | BatchReshape._call_reshape_input_output | Calls `fn`, appropriately reshaping its input `x` and output. | tensorflow_probability/python/distributions/batch_reshape.py | 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.
... | 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.
... | [
"Calls",
"fn",
"appropriately",
"reshaping",
"its",
"input",
"x",
"and",
"output",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/batch_reshape.py#L234-L262 | [
"def",
"_call_reshape_input_output",
"(",
"self",
",",
"fn",
",",
"x",
",",
"extra_kwargs",
"=",
"None",
")",
":",
"# 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` ... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | BatchReshape._call_and_reshape_output | Calls `fn` and appropriately reshapes its output. | tensorflow_probability/python/distributions/batch_reshape.py | 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... | 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... | [
"Calls",
"fn",
"and",
"appropriately",
"reshapes",
"its",
"output",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/batch_reshape.py#L264-L292 | [
"def",
"_call_and_reshape_output",
"(",
"self",
",",
"fn",
",",
"event_shape_list",
"=",
"None",
",",
"static_event_shape_list",
"=",
"None",
",",
"extra_kwargs",
"=",
"None",
")",
":",
"# Note: we take `extra_kwargs` as a dict rather than `**extra_kwargs`",
"# because it i... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | BatchReshape._validate_sample_arg | Helper which validates sample arg, e.g., input to `log_prob`. | tensorflow_probability/python/distributions/batch_reshape.py | def _validate_sample_arg(self, x):
"""Helper which validates sample arg, e.g., input to `log_prob`."""
with tf.name_scope("validate_sample_arg"):
x_ndims = (
tf.rank(x) if tensorshape_util.rank(x.shape) is None else
tensorshape_util.rank(x.shape))
event_ndims = (
tf.siz... | def _validate_sample_arg(self, x):
"""Helper which validates sample arg, e.g., input to `log_prob`."""
with tf.name_scope("validate_sample_arg"):
x_ndims = (
tf.rank(x) if tensorshape_util.rank(x.shape) is None else
tensorshape_util.rank(x.shape))
event_ndims = (
tf.siz... | [
"Helper",
"which",
"validates",
"sample",
"arg",
"e",
".",
"g",
".",
"input",
"to",
"log_prob",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/batch_reshape.py#L294-L377 | [
"def",
"_validate_sample_arg",
"(",
"self",
",",
"x",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"\"validate_sample_arg\"",
")",
":",
"x_ndims",
"=",
"(",
"tf",
".",
"rank",
"(",
"x",
")",
"if",
"tensorshape_util",
".",
"rank",
"(",
"x",
".",
"sha... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _bdtr | 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)`. | tensorflow_probability/python/distributions/binomial.py | 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, ..) ... | 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, ..) ... | [
"The",
"binomial",
"cumulative",
"distribution",
"function",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/binomial.py#L43-L62 | [
"def",
"_bdtr",
"(",
"k",
",",
"n",
",",
"p",
")",
":",
"# Trick for getting safe backprop/gradients into n, k when",
"# betainc(a = 0, ..) = nan",
"# Write:",
"# where(unsafe, safe_output, betainc(where(unsafe, safe_input, input)))",
"ones",
"=",
"tf",
".",
"ones_like",
"(... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | Binomial._maybe_assert_valid_sample | Check counts for proper shape, values, then return tensor version. | tensorflow_probability/python/distributions/binomial.py | def _maybe_assert_valid_sample(self, counts):
"""Check counts for proper shape, values, then return tensor version."""
if not self.validate_args:
return counts
counts = distribution_util.embed_check_nonnegative_integer_form(counts)
return distribution_util.with_dependencies([
assert_util.a... | def _maybe_assert_valid_sample(self, counts):
"""Check counts for proper shape, values, then return tensor version."""
if not self.validate_args:
return counts
counts = distribution_util.embed_check_nonnegative_integer_form(counts)
return distribution_util.with_dependencies([
assert_util.a... | [
"Check",
"counts",
"for",
"proper",
"shape",
"values",
"then",
"return",
"tensor",
"version",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/binomial.py#L299-L309 | [
"def",
"_maybe_assert_valid_sample",
"(",
"self",
",",
"counts",
")",
":",
"if",
"not",
"self",
".",
"validate_args",
":",
"return",
"counts",
"counts",
"=",
"distribution_util",
".",
"embed_check_nonnegative_integer_form",
"(",
"counts",
")",
"return",
"distributio... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | JointDistributionCoroutine._flat_sample_distributions | Executes `model`, creating both samples and distributions. | tensorflow_probability/python/distributions/joint_distribution_coroutine.py | 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:
... | 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:
... | [
"Executes",
"model",
"creating",
"both",
"samples",
"and",
"distributions",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/joint_distribution_coroutine.py#L170-L195 | [
"def",
"_flat_sample_distributions",
"(",
"self",
",",
"sample_shape",
"=",
"(",
")",
",",
"seed",
"=",
"None",
",",
"value",
"=",
"None",
")",
":",
"ds",
"=",
"[",
"]",
"values_out",
"=",
"[",
"]",
"seed",
"=",
"seed_stream",
".",
"SeedStream",
"(",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _kl_pareto_pareto | Calculate the batched KL divergence KL(a || b) with a and b Pareto.
Args:
a: instance of a Pareto distribution object.
b: instance of a Pareto distribution object.
name: (optional) Name to use for created operations.
default is "kl_pareto_pareto".
Returns:
Batchwise KL(a || b) | tensorflow_probability/python/distributions/pareto.py | def _kl_pareto_pareto(a, b, name=None):
"""Calculate the batched KL divergence KL(a || b) with a and b Pareto.
Args:
a: instance of a Pareto distribution object.
b: instance of a Pareto distribution object.
name: (optional) Name to use for created operations.
default is "kl_pareto_pareto".
Ret... | def _kl_pareto_pareto(a, b, name=None):
"""Calculate the batched KL divergence KL(a || b) with a and b Pareto.
Args:
a: instance of a Pareto distribution object.
b: instance of a Pareto distribution object.
name: (optional) Name to use for created operations.
default is "kl_pareto_pareto".
Ret... | [
"Calculate",
"the",
"batched",
"KL",
"divergence",
"KL",
"(",
"a",
"||",
"b",
")",
"with",
"a",
"and",
"b",
"Pareto",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/pareto.py#L249-L276 | [
"def",
"_kl_pareto_pareto",
"(",
"a",
",",
"b",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"name",
"or",
"\"kl_pareto_pareto\"",
")",
":",
"# Consistent with",
"# http://www.mast.queensu.ca/~communications/Papers/gil-msc11.pdf, page 55",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | Pareto._extend_support | Returns `f(x)` if x is in the support, and `alt` otherwise.
Given `f` which is defined on the support of this distribution
(e.g. x > scale), extend the function definition to the real line
by defining `f(x) = alt` for `x < scale`.
Args:
x: Floating-point Tensor to evaluate `f` at.
f: Lambd... | tensorflow_probability/python/distributions/pareto.py | def _extend_support(self, x, f, alt):
"""Returns `f(x)` if x is in the support, and `alt` otherwise.
Given `f` which is defined on the support of this distribution
(e.g. x > scale), extend the function definition to the real line
by defining `f(x) = alt` for `x < scale`.
Args:
x: Floating-po... | def _extend_support(self, x, f, alt):
"""Returns `f(x)` if x is in the support, and `alt` otherwise.
Given `f` which is defined on the support of this distribution
(e.g. x > scale), extend the function definition to the real line
by defining `f(x) = alt` for `x < scale`.
Args:
x: Floating-po... | [
"Returns",
"f",
"(",
"x",
")",
"if",
"x",
"is",
"in",
"the",
"support",
"and",
"alt",
"otherwise",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/pareto.py#L214-L245 | [
"def",
"_extend_support",
"(",
"self",
",",
"x",
",",
"f",
",",
"alt",
")",
":",
"# We need to do a series of broadcasts for the tf.where.",
"scale",
"=",
"self",
".",
"scale",
"+",
"tf",
".",
"zeros_like",
"(",
"self",
".",
"concentration",
")",
"is_invalid",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | latent_dirichlet_allocation | 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:
concentration: A Tensor of shape [1, num_topics], which parameterizes ... | tensorflow_probability/examples/latent_dirichlet_allocation_edward2.py | 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... | 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... | [
"Latent",
"Dirichlet",
"Allocation",
"in",
"terms",
"of",
"its",
"generative",
"process",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/latent_dirichlet_allocation_edward2.py#L168-L191 | [
"def",
"latent_dirichlet_allocation",
"(",
"concentration",
",",
"topics_words",
")",
":",
"topics",
"=",
"ed",
".",
"Dirichlet",
"(",
"concentration",
"=",
"concentration",
",",
"name",
"=",
"\"topics\"",
")",
"word_probs",
"=",
"tf",
".",
"matmul",
"(",
"top... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | make_lda_variational | 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 that takes a bag-of-words Tensor as
input and returns a distrib... | tensorflow_probability/examples/latent_dirichlet_allocation_edward2.py | 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... | 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... | [
"Creates",
"the",
"variational",
"distribution",
"for",
"LDA",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/latent_dirichlet_allocation_edward2.py#L194-L223 | [
"def",
"make_lda_variational",
"(",
"activation",
",",
"num_topics",
",",
"layer_sizes",
")",
":",
"encoder_net",
"=",
"tf",
".",
"keras",
".",
"Sequential",
"(",
")",
"for",
"num_hidden_units",
"in",
"layer_sizes",
":",
"encoder_net",
".",
"add",
"(",
"tf",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | model_fn | Builds the model function for use in an Estimator.
Arguments:
features: The input features for the Estimator.
labels: The labels, unused here.
mode: Signifies whether it is train or test or predict.
params: Some hyperparameters as a dictionary.
config: The RunConfig, unused here.
Returns:
... | tensorflow_probability/examples/latent_dirichlet_allocation_edward2.py | def model_fn(features, labels, mode, params, config):
"""Builds the model function for use in an Estimator.
Arguments:
features: The input features for the Estimator.
labels: The labels, unused here.
mode: Signifies whether it is train or test or predict.
params: Some hyperparameters as a dictionar... | def model_fn(features, labels, mode, params, config):
"""Builds the model function for use in an Estimator.
Arguments:
features: The input features for the Estimator.
labels: The labels, unused here.
mode: Signifies whether it is train or test or predict.
params: Some hyperparameters as a dictionar... | [
"Builds",
"the",
"model",
"function",
"for",
"use",
"in",
"an",
"Estimator",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/latent_dirichlet_allocation_edward2.py#L246-L368 | [
"def",
"model_fn",
"(",
"features",
",",
"labels",
",",
"mode",
",",
"params",
",",
"config",
")",
":",
"del",
"labels",
",",
"config",
"# Set up the model's learnable parameters.",
"logit_concentration",
"=",
"tf",
".",
"compat",
".",
"v1",
".",
"get_variable",... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | get_topics_strings | 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
topics.
vocabulary: A mapping of word's integer index to the corresponding string.
topics_to_print: The number o... | tensorflow_probability/examples/latent_dirichlet_allocation_edward2.py | 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
... | 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
... | [
"Returns",
"the",
"summary",
"of",
"the",
"learned",
"topics",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/latent_dirichlet_allocation_edward2.py#L371-L399 | [
"def",
"get_topics_strings",
"(",
"topics_words",
",",
"alpha",
",",
"vocabulary",
",",
"topics_to_print",
"=",
"10",
",",
"words_per_topic",
"=",
"10",
")",
":",
"alpha",
"=",
"np",
".",
"squeeze",
"(",
"alpha",
",",
"axis",
"=",
"0",
")",
"# Use a stable... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | newsgroups_dataset | 20 newsgroups as a tf.data.Dataset. | tensorflow_probability/examples/latent_dirichlet_allocation_edward2.py | 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... | 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... | [
"20",
"newsgroups",
"as",
"a",
"tf",
".",
"data",
".",
"Dataset",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/latent_dirichlet_allocation_edward2.py#L419-L457 | [
"def",
"newsgroups_dataset",
"(",
"directory",
",",
"split_name",
",",
"num_words",
",",
"shuffle_and_repeat",
")",
":",
"data",
"=",
"np",
".",
"load",
"(",
"download",
"(",
"directory",
",",
"FILE_TEMPLATE",
".",
"format",
"(",
"split",
"=",
"split_name",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | build_fake_input_fns | Builds fake data for unit testing. | tensorflow_probability/examples/latent_dirichlet_allocation_edward2.py | 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... | 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... | [
"Builds",
"fake",
"data",
"for",
"unit",
"testing",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/latent_dirichlet_allocation_edward2.py#L460-L478 | [
"def",
"build_fake_input_fns",
"(",
"batch_size",
")",
":",
"num_words",
"=",
"1000",
"vocabulary",
"=",
"[",
"str",
"(",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"num_words",
")",
"]",
"random_sample",
"=",
"np",
".",
"random",
".",
"randint",
"(",
"... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | build_input_fns | 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 returns an iterator over the training data.
... | tensorflow_probability/examples/latent_dirichlet_allocation_edward2.py | 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... | 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... | [
"Builds",
"iterators",
"for",
"train",
"and",
"evaluation",
"data",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/latent_dirichlet_allocation_edward2.py#L481-L519 | [
"def",
"build_input_fns",
"(",
"data_dir",
",",
"batch_size",
")",
":",
"with",
"open",
"(",
"download",
"(",
"data_dir",
",",
"\"vocab.pkl\"",
")",
",",
"\"r\"",
")",
"as",
"f",
":",
"words_to_idx",
"=",
"pickle",
".",
"load",
"(",
"f",
")",
"num_words"... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _kl_chi_chi | Calculate the batched KL divergence KL(a || b) with a and b Chi.
Args:
a: instance of a Chi distribution object.
b: instance of a Chi distribution object.
name: (optional) Name to use for created operations.
default is "kl_chi_chi".
Returns:
Batchwise KL(a || b) | tensorflow_probability/python/distributions/chi.py | def _kl_chi_chi(a, b, name=None):
"""Calculate the batched KL divergence KL(a || b) with a and b Chi.
Args:
a: instance of a Chi distribution object.
b: instance of a Chi distribution object.
name: (optional) Name to use for created operations.
default is "kl_chi_chi".
Returns:
Batchwise K... | def _kl_chi_chi(a, b, name=None):
"""Calculate the batched KL divergence KL(a || b) with a and b Chi.
Args:
a: instance of a Chi distribution object.
b: instance of a Chi distribution object.
name: (optional) Name to use for created operations.
default is "kl_chi_chi".
Returns:
Batchwise K... | [
"Calculate",
"the",
"batched",
"KL",
"divergence",
"KL",
"(",
"a",
"||",
"b",
")",
"with",
"a",
"and",
"b",
"Chi",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/chi.py#L124-L142 | [
"def",
"_kl_chi_chi",
"(",
"a",
",",
"b",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"name",
"or",
"\"kl_chi_chi\"",
")",
":",
"# Consistent with",
"# https://mast.queensu.ca/~communications/Papers/gil-msc11.pdf, page 118",
"# The paper ... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _sparse_or_dense_matmul_onehot | Returns a (dense) column of a Tensor or SparseTensor.
Args:
sparse_or_dense_matrix: matrix-shaped, `float` `Tensor` or `SparseTensor`.
col_index: scalar, `int` `Tensor` representing the index of the desired
column.
Returns:
column: vector-shaped, `float` `Tensor` with the same dtype as
`sp... | tensorflow_probability/python/optimizer/proximal_hessian_sparse.py | def _sparse_or_dense_matmul_onehot(sparse_or_dense_matrix, col_index):
"""Returns a (dense) column of a Tensor or SparseTensor.
Args:
sparse_or_dense_matrix: matrix-shaped, `float` `Tensor` or `SparseTensor`.
col_index: scalar, `int` `Tensor` representing the index of the desired
column.
Returns:
... | def _sparse_or_dense_matmul_onehot(sparse_or_dense_matrix, col_index):
"""Returns a (dense) column of a Tensor or SparseTensor.
Args:
sparse_or_dense_matrix: matrix-shaped, `float` `Tensor` or `SparseTensor`.
col_index: scalar, `int` `Tensor` representing the index of the desired
column.
Returns:
... | [
"Returns",
"a",
"(",
"dense",
")",
"column",
"of",
"a",
"Tensor",
"or",
"SparseTensor",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/proximal_hessian_sparse.py#L74-L105 | [
"def",
"_sparse_or_dense_matmul_onehot",
"(",
"sparse_or_dense_matrix",
",",
"col_index",
")",
":",
"if",
"isinstance",
"(",
"sparse_or_dense_matrix",
",",
"(",
"tf",
".",
"SparseTensor",
",",
"tf",
".",
"compat",
".",
"v1",
".",
"SparseTensorValue",
")",
")",
"... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | minimize_one_step | One step of (the outer loop of) the minimization algorithm.
This function returns a new value of `x`, equal to `x_start + x_update`. The
increment `x_update in R^n` is computed by a coordinate descent method, that
is, by a loop in which each iteration updates exactly one coordinate of
`x_update`. (Some updat... | tensorflow_probability/python/optimizer/proximal_hessian_sparse.py | def minimize_one_step(gradient_unregularized_loss,
hessian_unregularized_loss_outer,
hessian_unregularized_loss_middle,
x_start,
tolerance,
l1_regularizer,
l2_regularizer=None,
... | def minimize_one_step(gradient_unregularized_loss,
hessian_unregularized_loss_outer,
hessian_unregularized_loss_middle,
x_start,
tolerance,
l1_regularizer,
l2_regularizer=None,
... | [
"One",
"step",
"of",
"(",
"the",
"outer",
"loop",
"of",
")",
"the",
"minimization",
"algorithm",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/proximal_hessian_sparse.py#L119-L468 | [
"def",
"minimize_one_step",
"(",
"gradient_unregularized_loss",
",",
"hessian_unregularized_loss_outer",
",",
"hessian_unregularized_loss_middle",
",",
"x_start",
",",
"tolerance",
",",
"l1_regularizer",
",",
"l2_regularizer",
"=",
"None",
",",
"maximum_full_sweeps",
"=",
"... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | minimize | Minimize using Hessian-informed proximal gradient descent.
This function solves the regularized minimization problem
```none
argmin{ Loss(x)
+ l1_regularizer * ||x||_1
+ l2_regularizer * ||x||_2**2
: x in R^n }
```
where `Loss` is a convex C^2 function (typically, `Loss` i... | tensorflow_probability/python/optimizer/proximal_hessian_sparse.py | 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... | 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... | [
"Minimize",
"using",
"Hessian",
"-",
"informed",
"proximal",
"gradient",
"descent",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/proximal_hessian_sparse.py#L471-L590 | [
"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... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | make_encoder | Creates the encoder function.
Args:
base_depth: Layer base depth in encoder net.
activation: Activation function in hidden layers.
latent_size: The number of latent variables in the code.
code_size: The dimensionality of each latent variable.
Returns:
encoder: A `callable` mapping a `Tensor` o... | tensorflow_probability/examples/vq_vae.py | def make_encoder(base_depth, activation, latent_size, code_size):
"""Creates the encoder function.
Args:
base_depth: Layer base depth in encoder net.
activation: Activation function in hidden layers.
latent_size: The number of latent variables in the code.
code_size: The dimensionality of each late... | def make_encoder(base_depth, activation, latent_size, code_size):
"""Creates the encoder function.
Args:
base_depth: Layer base depth in encoder net.
activation: Activation function in hidden layers.
latent_size: The number of latent variables in the code.
code_size: The dimensionality of each late... | [
"Creates",
"the",
"encoder",
"function",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/vq_vae.py#L167-L209 | [
"def",
"make_encoder",
"(",
"base_depth",
",",
"activation",
",",
"latent_size",
",",
"code_size",
")",
":",
"conv",
"=",
"functools",
".",
"partial",
"(",
"tf",
".",
"keras",
".",
"layers",
".",
"Conv2D",
",",
"padding",
"=",
"\"SAME\"",
",",
"activation"... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | make_decoder | Creates the decoder function.
Args:
base_depth: Layer base depth in decoder net.
activation: Activation function in hidden layers.
input_size: The flattened latent input shape as an int.
output_shape: The output image shape as a list.
Returns:
decoder: A `callable` mapping a `Tensor` of encodi... | tensorflow_probability/examples/vq_vae.py | def make_decoder(base_depth, activation, input_size, output_shape):
"""Creates the decoder function.
Args:
base_depth: Layer base depth in decoder net.
activation: Activation function in hidden layers.
input_size: The flattened latent input shape as an int.
output_shape: The output image shape as a... | def make_decoder(base_depth, activation, input_size, output_shape):
"""Creates the decoder function.
Args:
base_depth: Layer base depth in decoder net.
activation: Activation function in hidden layers.
input_size: The flattened latent input shape as an int.
output_shape: The output image shape as a... | [
"Creates",
"the",
"decoder",
"function",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/vq_vae.py#L212-L256 | [
"def",
"make_decoder",
"(",
"base_depth",
",",
"activation",
",",
"input_size",
",",
"output_shape",
")",
":",
"deconv",
"=",
"functools",
".",
"partial",
"(",
"tf",
".",
"keras",
".",
"layers",
".",
"Conv2DTranspose",
",",
"padding",
"=",
"\"SAME\"",
",",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | add_ema_control_dependencies | Add control dependencies to the commmitment loss to update the codebook.
Args:
vector_quantizer: An instance of the VectorQuantizer class.
one_hot_assignments: The one-hot vectors corresponding to the matched
codebook entry for each code in the batch.
codes: A `float`-like `Tensor` containing the l... | tensorflow_probability/examples/vq_vae.py | 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... | 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... | [
"Add",
"control",
"dependencies",
"to",
"the",
"commmitment",
"loss",
"to",
"update",
"the",
"codebook",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/vq_vae.py#L259-L301 | [
"def",
"add_ema_control_dependencies",
"(",
"vector_quantizer",
",",
"one_hot_assignments",
",",
"codes",
",",
"commitment_loss",
",",
"decay",
")",
":",
"# Use an exponential moving average to update the codebook.",
"updated_ema_count",
"=",
"moving_averages",
".",
"assign_mov... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | save_imgs | 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). | tensorflow_probability/examples/vq_vae.py | 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... | 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... | [
"Helper",
"method",
"to",
"save",
"a",
"grid",
"of",
"images",
"to",
"a",
"PNG",
"file",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/vq_vae.py#L304-L321 | [
"def",
"save_imgs",
"(",
"x",
",",
"fname",
")",
":",
"n",
"=",
"x",
".",
"shape",
"[",
"0",
"]",
"fig",
"=",
"figure",
".",
"Figure",
"(",
"figsize",
"=",
"(",
"n",
",",
"1",
")",
",",
"frameon",
"=",
"False",
")",
"canvas",
"=",
"backend_agg"... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | visualize_training | Helper method to save images visualizing model reconstructions.
Args:
images_val: Numpy array containing a batch of input images.
reconstructed_images_val: Numpy array giving the expected output
(mean) of the decoder.
random_images_val: Optionally, a Numpy array giving the expected output
(me... | tensorflow_probability/examples/vq_vae.py | 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.
... | 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.
... | [
"Helper",
"method",
"to",
"save",
"images",
"visualizing",
"model",
"reconstructions",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/vq_vae.py#L324-L350 | [
"def",
"visualize_training",
"(",
"images_val",
",",
"reconstructed_images_val",
",",
"random_images_val",
",",
"log_dir",
",",
"prefix",
",",
"viz_n",
"=",
"10",
")",
":",
"save_imgs",
"(",
"images_val",
"[",
":",
"viz_n",
"]",
",",
"os",
".",
"path",
".",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | load_bernoulli_mnist_dataset | Returns Hugo Larochelle's binary static MNIST tf.data.Dataset. | tensorflow_probability/examples/vq_vae.py | 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... | 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... | [
"Returns",
"Hugo",
"Larochelle",
"s",
"binary",
"static",
"MNIST",
"tf",
".",
"data",
".",
"Dataset",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/vq_vae.py#L389-L400 | [
"def",
"load_bernoulli_mnist_dataset",
"(",
"directory",
",",
"split_name",
")",
":",
"amat_file",
"=",
"download",
"(",
"directory",
",",
"FILE_TEMPLATE",
".",
"format",
"(",
"split",
"=",
"split_name",
")",
")",
"dataset",
"=",
"tf",
".",
"data",
".",
"Tex... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | build_input_pipeline | Builds an Iterator switching between train and heldout data. | tensorflow_probability/examples/vq_vae.py | def build_input_pipeline(data_dir, batch_size, heldout_size, mnist_type):
"""Builds an Iterator switching between train and heldout data."""
# Build an iterator over training batches.
if mnist_type in [MnistType.FAKE_DATA, MnistType.THRESHOLD]:
if mnist_type == MnistType.FAKE_DATA:
mnist_data = build_fa... | def build_input_pipeline(data_dir, batch_size, heldout_size, mnist_type):
"""Builds an Iterator switching between train and heldout data."""
# Build an iterator over training batches.
if mnist_type in [MnistType.FAKE_DATA, MnistType.THRESHOLD]:
if mnist_type == MnistType.FAKE_DATA:
mnist_data = build_fa... | [
"Builds",
"an",
"Iterator",
"switching",
"between",
"train",
"and",
"heldout",
"data",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/vq_vae.py#L403-L442 | [
"def",
"build_input_pipeline",
"(",
"data_dir",
",",
"batch_size",
",",
"heldout_size",
",",
"mnist_type",
")",
":",
"# Build an iterator over training batches.",
"if",
"mnist_type",
"in",
"[",
"MnistType",
".",
"FAKE_DATA",
",",
"MnistType",
".",
"THRESHOLD",
"]",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | as_numpy_dtype | Returns a `np.dtype` based on this `dtype`. | tensorflow_probability/python/internal/dtype_util.py | 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 | 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 | [
"Returns",
"a",
"np",
".",
"dtype",
"based",
"on",
"this",
"dtype",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/dtype_util.py#L44-L49 | [
"def",
"as_numpy_dtype",
"(",
"dtype",
")",
":",
"dtype",
"=",
"tf",
".",
"as_dtype",
"(",
"dtype",
")",
"if",
"hasattr",
"(",
"dtype",
",",
"'as_numpy_dtype'",
")",
":",
"return",
"dtype",
".",
"as_numpy_dtype",
"return",
"dtype"
] | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | base_dtype | Returns a non-reference `dtype` based on this `dtype`. | tensorflow_probability/python/internal/dtype_util.py | 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 | 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 | [
"Returns",
"a",
"non",
"-",
"reference",
"dtype",
"based",
"on",
"this",
"dtype",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/dtype_util.py#L52-L57 | [
"def",
"base_dtype",
"(",
"dtype",
")",
":",
"dtype",
"=",
"tf",
".",
"as_dtype",
"(",
"dtype",
")",
"if",
"hasattr",
"(",
"dtype",
",",
"'base_dtype'",
")",
":",
"return",
"dtype",
".",
"base_dtype",
"return",
"dtype"
] | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | is_bool | Returns whether this is a boolean data type. | tensorflow_probability/python/internal/dtype_util.py | 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' | 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' | [
"Returns",
"whether",
"this",
"is",
"a",
"boolean",
"data",
"type",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/dtype_util.py#L80-L87 | [
"def",
"is_bool",
"(",
"dtype",
")",
":",
"dtype",
"=",
"tf",
".",
"as_dtype",
"(",
"dtype",
")",
"if",
"hasattr",
"(",
"dtype",
",",
"'is_bool'",
")",
":",
"return",
"dtype",
".",
"is_bool",
"# We use `kind` because:",
"# np.issubdtype(np.uint8, np.bool) == Tru... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | is_complex | Returns whether this is a complex floating point type. | tensorflow_probability/python/internal/dtype_util.py | 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) | 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) | [
"Returns",
"whether",
"this",
"is",
"a",
"complex",
"floating",
"point",
"type",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/dtype_util.py#L90-L95 | [
"def",
"is_complex",
"(",
"dtype",
")",
":",
"dtype",
"=",
"tf",
".",
"as_dtype",
"(",
"dtype",
")",
"if",
"hasattr",
"(",
"dtype",
",",
"'is_complex'",
")",
":",
"return",
"dtype",
".",
"is_complex",
"return",
"np",
".",
"issubdtype",
"(",
"np",
".",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | is_floating | Returns whether this is a (non-quantized, real) floating point type. | tensorflow_probability/python/internal/dtype_util.py | def is_floating(dtype):
"""Returns whether this is a (non-quantized, real) floating point type."""
dtype = tf.as_dtype(dtype)
if hasattr(dtype, 'is_floating'):
return dtype.is_floating
return np.issubdtype(np.dtype(dtype), np.float) | def is_floating(dtype):
"""Returns whether this is a (non-quantized, real) floating point type."""
dtype = tf.as_dtype(dtype)
if hasattr(dtype, 'is_floating'):
return dtype.is_floating
return np.issubdtype(np.dtype(dtype), np.float) | [
"Returns",
"whether",
"this",
"is",
"a",
"(",
"non",
"-",
"quantized",
"real",
")",
"floating",
"point",
"type",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/dtype_util.py#L98-L103 | [
"def",
"is_floating",
"(",
"dtype",
")",
":",
"dtype",
"=",
"tf",
".",
"as_dtype",
"(",
"dtype",
")",
"if",
"hasattr",
"(",
"dtype",
",",
"'is_floating'",
")",
":",
"return",
"dtype",
".",
"is_floating",
"return",
"np",
".",
"issubdtype",
"(",
"np",
".... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | is_integer | Returns whether this is a (non-quantized) integer type. | tensorflow_probability/python/internal/dtype_util.py | def is_integer(dtype):
"""Returns whether this is a (non-quantized) integer type."""
dtype = tf.as_dtype(dtype)
if hasattr(dtype, 'is_integer'):
return dtype.is_integer
return np.issubdtype(np.dtype(dtype), np.integer) | def is_integer(dtype):
"""Returns whether this is a (non-quantized) integer type."""
dtype = tf.as_dtype(dtype)
if hasattr(dtype, 'is_integer'):
return dtype.is_integer
return np.issubdtype(np.dtype(dtype), np.integer) | [
"Returns",
"whether",
"this",
"is",
"a",
"(",
"non",
"-",
"quantized",
")",
"integer",
"type",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/dtype_util.py#L106-L111 | [
"def",
"is_integer",
"(",
"dtype",
")",
":",
"dtype",
"=",
"tf",
".",
"as_dtype",
"(",
"dtype",
")",
"if",
"hasattr",
"(",
"dtype",
",",
"'is_integer'",
")",
":",
"return",
"dtype",
".",
"is_integer",
"return",
"np",
".",
"issubdtype",
"(",
"np",
".",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | max | Returns the maximum representable value in this data type. | tensorflow_probability/python/internal/dtype_util.py | 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 | 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 | [
"Returns",
"the",
"maximum",
"representable",
"value",
"in",
"this",
"data",
"type",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/dtype_util.py#L114-L120 | [
"def",
"max",
"(",
"dtype",
")",
":",
"# pylint: disable=redefined-builtin",
"dtype",
"=",
"tf",
".",
"as_dtype",
"(",
"dtype",
")",
"if",
"hasattr",
"(",
"dtype",
",",
"'max'",
")",
":",
"return",
"dtype",
".",
"max",
"use_finfo",
"=",
"is_floating",
"(",... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | name | Returns the string name for this `dtype`. | tensorflow_probability/python/internal/dtype_util.py | 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) | 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) | [
"Returns",
"the",
"string",
"name",
"for",
"this",
"dtype",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/dtype_util.py#L132-L139 | [
"def",
"name",
"(",
"dtype",
")",
":",
"dtype",
"=",
"tf",
".",
"as_dtype",
"(",
"dtype",
")",
"if",
"hasattr",
"(",
"dtype",
",",
"'name'",
")",
":",
"return",
"dtype",
".",
"name",
"if",
"hasattr",
"(",
"dtype",
",",
"'__name__'",
")",
":",
"retu... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | size | Returns the number of bytes to represent this `dtype`. | tensorflow_probability/python/internal/dtype_util.py | 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 | 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 | [
"Returns",
"the",
"number",
"of",
"bytes",
"to",
"represent",
"this",
"dtype",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/dtype_util.py#L142-L147 | [
"def",
"size",
"(",
"dtype",
")",
":",
"dtype",
"=",
"tf",
".",
"as_dtype",
"(",
"dtype",
")",
"if",
"hasattr",
"(",
"dtype",
",",
"'size'",
")",
":",
"return",
"dtype",
".",
"size",
"return",
"np",
".",
"dtype",
"(",
"dtype",
")",
".",
"itemsize"
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _assert_same_base_type | 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 type. If not specified, assert all items are
of ... | tensorflow_probability/python/internal/dtype_util.py | 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... | 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... | [
"r",
"Asserts",
"all",
"items",
"are",
"of",
"the",
"same",
"base",
"type",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/dtype_util.py#L150-L198 | [
"def",
"_assert_same_base_type",
"(",
"items",
",",
"expected_type",
"=",
"None",
")",
":",
"original_expected_type",
"=",
"expected_type",
"mismatch",
"=",
"False",
"for",
"item",
"in",
"items",
":",
"if",
"item",
"is",
"not",
"None",
":",
"item_type",
"=",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | assert_same_float_dtype | 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 supplied), and returns the type. Type must
be a floating poin... | tensorflow_probability/python/internal/dtype_util.py | 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... | 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... | [
"Validate",
"and",
"return",
"float",
"type",
"based",
"on",
"tensors",
"and",
"dtype",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/dtype_util.py#L201-L228 | [
"def",
"assert_same_float_dtype",
"(",
"tensors",
"=",
"None",
",",
"dtype",
"=",
"None",
")",
":",
"if",
"tensors",
":",
"dtype",
"=",
"_assert_same_base_type",
"(",
"tensors",
",",
"dtype",
")",
"if",
"not",
"dtype",
":",
"dtype",
"=",
"tf",
".",
"floa... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _kl_categorical_categorical | Calculate the batched KL divergence KL(a || b) with a, b OneHotCategorical.
Args:
a: instance of a OneHotCategorical distribution object.
b: instance of a OneHotCategorical distribution object.
name: (optional) Name to use for created operations.
default is "kl_categorical_categorical".
Returns:... | tensorflow_probability/python/distributions/onehot_categorical.py | def _kl_categorical_categorical(a, b, name=None):
"""Calculate the batched KL divergence KL(a || b) with a, b OneHotCategorical.
Args:
a: instance of a OneHotCategorical distribution object.
b: instance of a OneHotCategorical distribution object.
name: (optional) Name to use for created operations.
... | def _kl_categorical_categorical(a, b, name=None):
"""Calculate the batched KL divergence KL(a || b) with a, b OneHotCategorical.
Args:
a: instance of a OneHotCategorical distribution object.
b: instance of a OneHotCategorical distribution object.
name: (optional) Name to use for created operations.
... | [
"Calculate",
"the",
"batched",
"KL",
"divergence",
"KL",
"(",
"a",
"||",
"b",
")",
"with",
"a",
"b",
"OneHotCategorical",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/onehot_categorical.py#L241-L258 | [
"def",
"_kl_categorical_categorical",
"(",
"a",
",",
"b",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"name",
"or",
"\"kl_categorical_categorical\"",
")",
":",
"# sum(p ln(p / q))",
"return",
"tf",
".",
"reduce_sum",
"(",
"input_t... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | minimize | Minimum of the objective function using the Nelder Mead simplex algorithm.
Performs an unconstrained minimization of a (possibly non-smooth) function
using the Nelder Mead simplex method. Nelder Mead method does not support
univariate functions. Hence the dimensions of the domain must be 2 or greater.
For deta... | tensorflow_probability/python/optimizer/nelder_mead.py | 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... | 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... | [
"Minimum",
"of",
"the",
"objective",
"function",
"using",
"the",
"Nelder",
"Mead",
"simplex",
"algorithm",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/nelder_mead.py#L62-L340 | [
"def",
"minimize",
"(",
"objective_function",
",",
"initial_simplex",
"=",
"None",
",",
"initial_vertex",
"=",
"None",
",",
"step_sizes",
"=",
"None",
",",
"objective_at_initial_simplex",
"=",
"None",
",",
"objective_at_initial_vertex",
"=",
"None",
",",
"batch_eval... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | nelder_mead_one_step | A single iteration of the Nelder Mead algorithm. | tensorflow_probability/python/optimizer/nelder_mead.py | def nelder_mead_one_step(current_simplex,
current_objective_values,
objective_function=None,
dim=None,
func_tolerance=None,
position_tolerance=None,
batch_evaluate_object... | def nelder_mead_one_step(current_simplex,
current_objective_values,
objective_function=None,
dim=None,
func_tolerance=None,
position_tolerance=None,
batch_evaluate_object... | [
"A",
"single",
"iteration",
"of",
"the",
"Nelder",
"Mead",
"algorithm",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/nelder_mead.py#L343-L456 | [
"def",
"nelder_mead_one_step",
"(",
"current_simplex",
",",
"current_objective_values",
",",
"objective_function",
"=",
"None",
",",
"dim",
"=",
"None",
",",
"func_tolerance",
"=",
"None",
",",
"position_tolerance",
"=",
"None",
",",
"batch_evaluate_objective",
"=",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _accept_reflected_fn | Creates the condition function pair for a reflection to be accepted. | tensorflow_probability/python/optimizer/nelder_mead.py | 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():
... | 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():
... | [
"Creates",
"the",
"condition",
"function",
"pair",
"for",
"a",
"reflection",
"to",
"be",
"accepted",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/nelder_mead.py#L459-L470 | [
"def",
"_accept_reflected_fn",
"(",
"simplex",
",",
"objective_values",
",",
"worst_index",
",",
"reflected",
",",
"objective_at_reflected",
")",
":",
"def",
"_replace_worst_with_reflected",
"(",
")",
":",
"next_simplex",
"=",
"_replace_at_index",
"(",
"simplex",
",",... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _expansion_fn | Creates the condition function pair for an expansion. | tensorflow_probability/python/optimizer/nelder_mead.py | 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... | 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... | [
"Creates",
"the",
"condition",
"function",
"pair",
"for",
"an",
"expansion",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/nelder_mead.py#L473-L497 | [
"def",
"_expansion_fn",
"(",
"objective_function",
",",
"simplex",
",",
"objective_values",
",",
"worst_index",
",",
"reflected",
",",
"objective_at_reflected",
",",
"face_centroid",
",",
"expansion",
")",
":",
"def",
"_expand_and_maybe_replace",
"(",
")",
":",
"\"\... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _outside_contraction_fn | Creates the condition function pair for an outside contraction. | tensorflow_probability/python/optimizer/nelder_mead.py | def _outside_contraction_fn(objective_function,
simplex,
objective_values,
face_centroid,
best_index,
worst_index,
reflected,
... | def _outside_contraction_fn(objective_function,
simplex,
objective_values,
face_centroid,
best_index,
worst_index,
reflected,
... | [
"Creates",
"the",
"condition",
"function",
"pair",
"for",
"an",
"outside",
"contraction",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/nelder_mead.py#L500-L538 | [
"def",
"_outside_contraction_fn",
"(",
"objective_function",
",",
"simplex",
",",
"objective_values",
",",
"face_centroid",
",",
"best_index",
",",
"worst_index",
",",
"reflected",
",",
"objective_at_reflected",
",",
"contraction",
",",
"shrinkage",
",",
"batch_evaluate... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _shrink_towards_best | Shrinks the simplex around the best vertex. | tensorflow_probability/python/optimizer/nelder_mead.py | 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... | 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... | [
"Shrinks",
"the",
"simplex",
"around",
"the",
"best",
"vertex",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/nelder_mead.py#L581-L599 | [
"def",
"_shrink_towards_best",
"(",
"objective_function",
",",
"simplex",
",",
"best_index",
",",
"shrinkage",
",",
"batch_evaluate_objective",
")",
":",
"# If the contraction step fails to improve the average objective enough,",
"# the simplex is shrunk towards the best vertex.",
"b... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _replace_at_index | Replaces an element at supplied index. | tensorflow_probability/python/optimizer/nelder_mead.py | 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 | 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 | [
"Replaces",
"an",
"element",
"at",
"supplied",
"index",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/nelder_mead.py#L602-L606 | [
"def",
"_replace_at_index",
"(",
"x",
",",
"index",
",",
"replacement",
")",
":",
"x_new",
"=",
"tf",
".",
"concat",
"(",
"[",
"x",
"[",
":",
"index",
"]",
",",
"tf",
".",
"expand_dims",
"(",
"replacement",
",",
"axis",
"=",
"0",
")",
",",
"x",
"... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _check_convergence | Returns True if the simplex has converged.
If the simplex size is smaller than the `position_tolerance` or the variation
of the function value over the vertices of the simplex is smaller than the
`func_tolerance` return True else False.
Args:
simplex: `Tensor` of real dtype. The simplex to test for conver... | tensorflow_probability/python/optimizer/nelder_mead.py | 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... | 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... | [
"Returns",
"True",
"if",
"the",
"simplex",
"has",
"converged",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/nelder_mead.py#L609-L646 | [
"def",
"_check_convergence",
"(",
"simplex",
",",
"best_vertex",
",",
"best_objective",
",",
"worst_objective",
",",
"func_tolerance",
",",
"position_tolerance",
")",
":",
"objective_convergence",
"=",
"tf",
".",
"abs",
"(",
"worst_objective",
"-",
"best_objective",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _prepare_args | Computes the initial simplex and the objective values at the simplex.
Args:
objective_function: A Python callable that accepts a point as a
real `Tensor` and returns a `Tensor` of real dtype containing
the value of the function at that point. The function
to be evaluated at the simplex. If `ba... | tensorflow_probability/python/optimizer/nelder_mead.py | def _prepare_args(objective_function,
initial_simplex,
initial_vertex,
step_sizes,
objective_at_initial_simplex,
objective_at_initial_vertex,
batch_evaluate_objective):
"""Computes the initial simplex and the o... | def _prepare_args(objective_function,
initial_simplex,
initial_vertex,
step_sizes,
objective_at_initial_simplex,
objective_at_initial_vertex,
batch_evaluate_objective):
"""Computes the initial simplex and the o... | [
"Computes",
"the",
"initial",
"simplex",
"and",
"the",
"objective",
"values",
"at",
"the",
"simplex",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/nelder_mead.py#L649-L751 | [
"def",
"_prepare_args",
"(",
"objective_function",
",",
"initial_simplex",
",",
"initial_vertex",
",",
"step_sizes",
",",
"objective_at_initial_simplex",
",",
"objective_at_initial_vertex",
",",
"batch_evaluate_objective",
")",
":",
"if",
"objective_at_initial_simplex",
"is",... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _default_step_sizes | Chooses default step sizes according to [Gao and Han(2010)][3]. | tensorflow_probability/python/optimizer/nelder_mead.py | def _default_step_sizes(reference_vertex):
"""Chooses default step sizes according to [Gao and Han(2010)][3]."""
# Step size to choose when the coordinate is zero.
small_sizes = tf.ones_like(reference_vertex) * 0.00025
# Step size to choose when the coordinate is non-zero.
large_sizes = reference_vertex * 0.0... | def _default_step_sizes(reference_vertex):
"""Chooses default step sizes according to [Gao and Han(2010)][3]."""
# Step size to choose when the coordinate is zero.
small_sizes = tf.ones_like(reference_vertex) * 0.00025
# Step size to choose when the coordinate is non-zero.
large_sizes = reference_vertex * 0.0... | [
"Chooses",
"default",
"step",
"sizes",
"according",
"to",
"[",
"Gao",
"and",
"Han",
"(",
"2010",
")",
"]",
"[",
"3",
"]",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/nelder_mead.py#L754-L762 | [
"def",
"_default_step_sizes",
"(",
"reference_vertex",
")",
":",
"# Step size to choose when the coordinate is zero.",
"small_sizes",
"=",
"tf",
".",
"ones_like",
"(",
"reference_vertex",
")",
"*",
"0.00025",
"# Step size to choose when the coordinate is non-zero.",
"large_sizes"... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _prepare_args_with_initial_simplex | Evaluates the objective function at the specified initial simplex. | tensorflow_probability/python/optimizer/nelder_mead.py | def _prepare_args_with_initial_simplex(objective_function,
initial_simplex,
objective_at_initial_simplex,
batch_evaluate_objective):
"""Evaluates the objective function at the specified initial simplex... | def _prepare_args_with_initial_simplex(objective_function,
initial_simplex,
objective_at_initial_simplex,
batch_evaluate_objective):
"""Evaluates the objective function at the specified initial simplex... | [
"Evaluates",
"the",
"objective",
"function",
"at",
"the",
"specified",
"initial",
"simplex",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/nelder_mead.py#L765-L789 | [
"def",
"_prepare_args_with_initial_simplex",
"(",
"objective_function",
",",
"initial_simplex",
",",
"objective_at_initial_simplex",
",",
"batch_evaluate_objective",
")",
":",
"initial_simplex",
"=",
"tf",
".",
"convert_to_tensor",
"(",
"value",
"=",
"initial_simplex",
")",... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _prepare_args_with_initial_vertex | Constructs a standard axes aligned simplex. | tensorflow_probability/python/optimizer/nelder_mead.py | def _prepare_args_with_initial_vertex(objective_function,
initial_vertex,
step_sizes,
objective_at_initial_vertex,
batch_evaluate_objective):
"""Constructs a standard... | def _prepare_args_with_initial_vertex(objective_function,
initial_vertex,
step_sizes,
objective_at_initial_vertex,
batch_evaluate_objective):
"""Constructs a standard... | [
"Constructs",
"a",
"standard",
"axes",
"aligned",
"simplex",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/nelder_mead.py#L792-L829 | [
"def",
"_prepare_args_with_initial_vertex",
"(",
"objective_function",
",",
"initial_vertex",
",",
"step_sizes",
",",
"objective_at_initial_vertex",
",",
"batch_evaluate_objective",
")",
":",
"dim",
"=",
"tf",
".",
"size",
"(",
"input",
"=",
"initial_vertex",
")",
"nu... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _resolve_parameters | Applies the [Gao and Han][3] presciption to the unspecified parameters. | tensorflow_probability/python/optimizer/nelder_mead.py | def _resolve_parameters(dim,
reflection,
expansion,
contraction,
shrinkage,
dtype):
"""Applies the [Gao and Han][3] presciption to the unspecified parameters."""
dim = tf.cast(dim, dtype=dtype)
... | def _resolve_parameters(dim,
reflection,
expansion,
contraction,
shrinkage,
dtype):
"""Applies the [Gao and Han][3] presciption to the unspecified parameters."""
dim = tf.cast(dim, dtype=dtype)
... | [
"Applies",
"the",
"[",
"Gao",
"and",
"Han",
"]",
"[",
"3",
"]",
"presciption",
"to",
"the",
"unspecified",
"parameters",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/nelder_mead.py#L832-L844 | [
"def",
"_resolve_parameters",
"(",
"dim",
",",
"reflection",
",",
"expansion",
",",
"contraction",
",",
"shrinkage",
",",
"dtype",
")",
":",
"dim",
"=",
"tf",
".",
"cast",
"(",
"dim",
",",
"dtype",
"=",
"dtype",
")",
"reflection",
"=",
"1.",
"if",
"ref... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _evaluate_objective_multiple | Evaluates the objective function on a batch of points.
If `batch_evaluate_objective` is True, returns
`objective function(arg_batch)` else it maps the `objective_function`
across the `arg_batch`.
Args:
objective_function: A Python callable that accepts a single `Tensor` of
rank 'R > 1' and any shape... | tensorflow_probability/python/optimizer/nelder_mead.py | def _evaluate_objective_multiple(objective_function, arg_batch,
batch_evaluate_objective):
"""Evaluates the objective function on a batch of points.
If `batch_evaluate_objective` is True, returns
`objective function(arg_batch)` else it maps the `objective_function`
across the `... | def _evaluate_objective_multiple(objective_function, arg_batch,
batch_evaluate_objective):
"""Evaluates the objective function on a batch of points.
If `batch_evaluate_objective` is True, returns
`objective function(arg_batch)` else it maps the `objective_function`
across the `... | [
"Evaluates",
"the",
"objective",
"function",
"on",
"a",
"batch",
"of",
"points",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/nelder_mead.py#L847-L880 | [
"def",
"_evaluate_objective_multiple",
"(",
"objective_function",
",",
"arg_batch",
",",
"batch_evaluate_objective",
")",
":",
"n_points",
"=",
"tf",
".",
"shape",
"(",
"input",
"=",
"arg_batch",
")",
"[",
"0",
"]",
"if",
"batch_evaluate_objective",
":",
"return",... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | plot_weight_posteriors | Save a PNG plot with histograms of weight means and stddevs.
Args:
names: A Python `iterable` of `str` variable names.
qm_vals: A Python `iterable`, the same length as `names`,
whose elements are Numpy `array`s, of any shape, containing
posterior means of weight varibles.
qs_vals: A Python `i... | tensorflow_probability/examples/bayesian_neural_network.py | def plot_weight_posteriors(names, qm_vals, qs_vals, fname):
"""Save a PNG plot with histograms of weight means and stddevs.
Args:
names: A Python `iterable` of `str` variable names.
qm_vals: A Python `iterable`, the same length as `names`,
whose elements are Numpy `array`s, of any shape, containing
... | def plot_weight_posteriors(names, qm_vals, qs_vals, fname):
"""Save a PNG plot with histograms of weight means and stddevs.
Args:
names: A Python `iterable` of `str` variable names.
qm_vals: A Python `iterable`, the same length as `names`,
whose elements are Numpy `array`s, of any shape, containing
... | [
"Save",
"a",
"PNG",
"plot",
"with",
"histograms",
"of",
"weight",
"means",
"and",
"stddevs",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/bayesian_neural_network.py#L90-L121 | [
"def",
"plot_weight_posteriors",
"(",
"names",
",",
"qm_vals",
",",
"qs_vals",
",",
"fname",
")",
":",
"fig",
"=",
"figure",
".",
"Figure",
"(",
"figsize",
"=",
"(",
"6",
",",
"3",
")",
")",
"canvas",
"=",
"backend_agg",
".",
"FigureCanvasAgg",
"(",
"f... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | plot_heldout_prediction | Save a PNG plot visualizing posterior uncertainty on heldout data.
Args:
input_vals: A `float`-like Numpy `array` of shape
`[num_heldout] + IMAGE_SHAPE`, containing heldout input images.
probs: A `float`-like Numpy array of shape `[num_monte_carlo,
num_heldout, num_classes]` containing Monte Carl... | tensorflow_probability/examples/bayesian_neural_network.py | def plot_heldout_prediction(input_vals, probs,
fname, n=10, title=""):
"""Save a PNG plot visualizing posterior uncertainty on heldout data.
Args:
input_vals: A `float`-like Numpy `array` of shape
`[num_heldout] + IMAGE_SHAPE`, containing heldout input images.
probs: A `fl... | def plot_heldout_prediction(input_vals, probs,
fname, n=10, title=""):
"""Save a PNG plot visualizing posterior uncertainty on heldout data.
Args:
input_vals: A `float`-like Numpy `array` of shape
`[num_heldout] + IMAGE_SHAPE`, containing heldout input images.
probs: A `fl... | [
"Save",
"a",
"PNG",
"plot",
"visualizing",
"posterior",
"uncertainty",
"on",
"heldout",
"data",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/bayesian_neural_network.py#L124-L158 | [
"def",
"plot_heldout_prediction",
"(",
"input_vals",
",",
"probs",
",",
"fname",
",",
"n",
"=",
"10",
",",
"title",
"=",
"\"\"",
")",
":",
"fig",
"=",
"figure",
".",
"Figure",
"(",
"figsize",
"=",
"(",
"9",
",",
"3",
"*",
"n",
")",
")",
"canvas",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | build_input_pipeline | Build an Iterator switching between train and heldout data. | tensorflow_probability/examples/bayesian_neural_network.py | def build_input_pipeline(mnist_data, batch_size, heldout_size):
"""Build an Iterator switching between train and heldout data."""
# Build an iterator over training batches.
training_dataset = tf.data.Dataset.from_tensor_slices(
(mnist_data.train.images, np.int32(mnist_data.train.labels)))
training_batche... | def build_input_pipeline(mnist_data, batch_size, heldout_size):
"""Build an Iterator switching between train and heldout data."""
# Build an iterator over training batches.
training_dataset = tf.data.Dataset.from_tensor_slices(
(mnist_data.train.images, np.int32(mnist_data.train.labels)))
training_batche... | [
"Build",
"an",
"Iterator",
"switching",
"between",
"train",
"and",
"heldout",
"data",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/bayesian_neural_network.py#L161-L187 | [
"def",
"build_input_pipeline",
"(",
"mnist_data",
",",
"batch_size",
",",
"heldout_size",
")",
":",
"# Build an iterator over training batches.",
"training_dataset",
"=",
"tf",
".",
"data",
".",
"Dataset",
".",
"from_tensor_slices",
"(",
"(",
"mnist_data",
".",
"train... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | build_fake_data | Build fake MNIST-style data for unit testing. | tensorflow_probability/examples/bayesian_neural_network.py | def build_fake_data(num_examples=10):
"""Build fake MNIST-style data for unit testing."""
class Dummy(object):
pass
num_examples = 10
mnist_data = Dummy()
mnist_data.train = Dummy()
mnist_data.train.images = np.float32(np.random.randn(
num_examples, *IMAGE_SHAPE))
mnist_data.train.labels = np.... | def build_fake_data(num_examples=10):
"""Build fake MNIST-style data for unit testing."""
class Dummy(object):
pass
num_examples = 10
mnist_data = Dummy()
mnist_data.train = Dummy()
mnist_data.train.images = np.float32(np.random.randn(
num_examples, *IMAGE_SHAPE))
mnist_data.train.labels = np.... | [
"Build",
"fake",
"MNIST",
"-",
"style",
"data",
"for",
"unit",
"testing",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/bayesian_neural_network.py#L190-L210 | [
"def",
"build_fake_data",
"(",
"num_examples",
"=",
"10",
")",
":",
"class",
"Dummy",
"(",
"object",
")",
":",
"pass",
"num_examples",
"=",
"10",
"mnist_data",
"=",
"Dummy",
"(",
")",
"mnist_data",
".",
"train",
"=",
"Dummy",
"(",
")",
"mnist_data",
".",... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _kl_bernoulli_bernoulli | Calculate the batched KL divergence KL(a || b) with a and b Bernoulli.
Args:
a: instance of a Bernoulli distribution object.
b: instance of a Bernoulli distribution object.
name: (optional) Name to use for created operations.
default is "kl_bernoulli_bernoulli".
Returns:
Batchwise KL(a || b) | tensorflow_probability/python/distributions/bernoulli.py | def _kl_bernoulli_bernoulli(a, b, name=None):
"""Calculate the batched KL divergence KL(a || b) with a and b Bernoulli.
Args:
a: instance of a Bernoulli distribution object.
b: instance of a Bernoulli distribution object.
name: (optional) Name to use for created operations.
default is "kl_bernoul... | def _kl_bernoulli_bernoulli(a, b, name=None):
"""Calculate the batched KL divergence KL(a || b) with a and b Bernoulli.
Args:
a: instance of a Bernoulli distribution object.
b: instance of a Bernoulli distribution object.
name: (optional) Name to use for created operations.
default is "kl_bernoul... | [
"Calculate",
"the",
"batched",
"KL",
"divergence",
"KL",
"(",
"a",
"||",
"b",
")",
"with",
"a",
"and",
"b",
"Bernoulli",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/bernoulli.py#L159-L175 | [
"def",
"_kl_bernoulli_bernoulli",
"(",
"a",
",",
"b",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"name",
"or",
"\"kl_bernoulli_bernoulli\"",
")",
":",
"delta_probs0",
"=",
"tf",
".",
"nn",
".",
"softplus",
"(",
"-",
"b",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | BlockwiseInitializer.get_config | Returns initializer configuration as a JSON-serializable dict. | tensorflow_probability/python/layers/initializers.py | def get_config(self):
"""Returns initializer configuration as a JSON-serializable dict."""
return {
'initializers': [
tf.compat.v2.initializers.serialize(
tf.keras.initializers.get(init))
for init in self.initializers
],
'sizes': self.sizes,
... | def get_config(self):
"""Returns initializer configuration as a JSON-serializable dict."""
return {
'initializers': [
tf.compat.v2.initializers.serialize(
tf.keras.initializers.get(init))
for init in self.initializers
],
'sizes': self.sizes,
... | [
"Returns",
"initializer",
"configuration",
"as",
"a",
"JSON",
"-",
"serializable",
"dict",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/layers/initializers.py#L106-L116 | [
"def",
"get_config",
"(",
"self",
")",
":",
"return",
"{",
"'initializers'",
":",
"[",
"tf",
".",
"compat",
".",
"v2",
".",
"initializers",
".",
"serialize",
"(",
"tf",
".",
"keras",
".",
"initializers",
".",
"get",
"(",
"init",
")",
")",
"for",
"ini... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | BlockwiseInitializer.from_config | Instantiates an initializer from a configuration dictionary. | tensorflow_probability/python/layers/initializers.py | def from_config(cls, config):
"""Instantiates an initializer from a configuration dictionary."""
return cls(**{
'initializers': [tf.compat.v2.initializers.deserialize(init)
for init in config.get('initializers', [])],
'sizes': config.get('sizes', []),
'validate_a... | def from_config(cls, config):
"""Instantiates an initializer from a configuration dictionary."""
return cls(**{
'initializers': [tf.compat.v2.initializers.deserialize(init)
for init in config.get('initializers', [])],
'sizes': config.get('sizes', []),
'validate_a... | [
"Instantiates",
"an",
"initializer",
"from",
"a",
"configuration",
"dictionary",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/layers/initializers.py#L119-L126 | [
"def",
"from_config",
"(",
"cls",
",",
"config",
")",
":",
"return",
"cls",
"(",
"*",
"*",
"{",
"'initializers'",
":",
"[",
"tf",
".",
"compat",
".",
"v2",
".",
"initializers",
".",
"deserialize",
"(",
"init",
")",
"for",
"init",
"in",
"config",
".",... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _matmul | Numpy matmul wrapper. | tensorflow_probability/python/internal/backend/numpy/linalg.py | def _matmul(a, b,
transpose_a=False, transpose_b=False,
adjoint_a=False, adjoint_b=False,
a_is_sparse=False, b_is_sparse=False,
name=None): # pylint: disable=unused-argument
"""Numpy matmul wrapper."""
if a_is_sparse or b_is_sparse:
raise NotImplementedError('Num... | def _matmul(a, b,
transpose_a=False, transpose_b=False,
adjoint_a=False, adjoint_b=False,
a_is_sparse=False, b_is_sparse=False,
name=None): # pylint: disable=unused-argument
"""Numpy matmul wrapper."""
if a_is_sparse or b_is_sparse:
raise NotImplementedError('Num... | [
"Numpy",
"matmul",
"wrapper",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/backend/numpy/linalg.py#L97-L109 | [
"def",
"_matmul",
"(",
"a",
",",
"b",
",",
"transpose_a",
"=",
"False",
",",
"transpose_b",
"=",
"False",
",",
"adjoint_a",
"=",
"False",
",",
"adjoint_b",
"=",
"False",
",",
"a_is_sparse",
"=",
"False",
",",
"b_is_sparse",
"=",
"False",
",",
"name",
"... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | MultivariateStudentTLinearOperator._std_var_helper | Helper to compute stddev, covariance and variance. | tensorflow_probability/python/distributions/multivariate_student_t.py | def _std_var_helper(self, statistic, statistic_name, statistic_ndims,
df_factor_fn):
"""Helper to compute stddev, covariance and variance."""
df = tf.reshape(
self.df,
tf.concat([
tf.shape(input=self.df),
tf.ones([statistic_ndims], dtype=tf.int32)
... | def _std_var_helper(self, statistic, statistic_name, statistic_ndims,
df_factor_fn):
"""Helper to compute stddev, covariance and variance."""
df = tf.reshape(
self.df,
tf.concat([
tf.shape(input=self.df),
tf.ones([statistic_ndims], dtype=tf.int32)
... | [
"Helper",
"to",
"compute",
"stddev",
"covariance",
"and",
"variance",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/multivariate_student_t.py#L306-L337 | [
"def",
"_std_var_helper",
"(",
"self",
",",
"statistic",
",",
"statistic_name",
",",
"statistic_ndims",
",",
"df_factor_fn",
")",
":",
"df",
"=",
"tf",
".",
"reshape",
"(",
"self",
".",
"df",
",",
"tf",
".",
"concat",
"(",
"[",
"tf",
".",
"shape",
"(",... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | assign_moving_mean_variance | Compute exponentially weighted moving {mean,variance} of a streaming value.
The `value` updated exponentially weighted moving `mean_var` and
`variance_var` are given by the following recurrence relations:
```python
variance_var = decay * (variance_var + (1 - decay) * (value - mean_var)**2)
mean_var = de... | tensorflow_probability/python/distributions/internal/moving_stats.py | def assign_moving_mean_variance(
mean_var, variance_var, value, decay, name=None):
"""Compute exponentially weighted moving {mean,variance} of a streaming value.
The `value` updated exponentially weighted moving `mean_var` and
`variance_var` are given by the following recurrence relations:
```python
var... | def assign_moving_mean_variance(
mean_var, variance_var, value, decay, name=None):
"""Compute exponentially weighted moving {mean,variance} of a streaming value.
The `value` updated exponentially weighted moving `mean_var` and
`variance_var` are given by the following recurrence relations:
```python
var... | [
"Compute",
"exponentially",
"weighted",
"moving",
"{",
"mean",
"variance",
"}",
"of",
"a",
"streaming",
"value",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/internal/moving_stats.py#L31-L110 | [
"def",
"assign_moving_mean_variance",
"(",
"mean_var",
",",
"variance_var",
",",
"value",
",",
"decay",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"name",
",",
"\"assign_moving_mean_variance\"",
",",
"... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | assign_log_moving_mean_exp | Compute the log of the exponentially weighted moving mean of the exp.
If `log_value` is a draw from a stationary random variable, this function
approximates `log(E[exp(log_value)])`, i.e., a weighted log-sum-exp. More
precisely, a `tf.Variable`, `log_mean_exp_var`, is updated by `log_value`
using the following... | tensorflow_probability/python/distributions/internal/moving_stats.py | def assign_log_moving_mean_exp(
log_mean_exp_var, log_value, decay, name=None):
"""Compute the log of the exponentially weighted moving mean of the exp.
If `log_value` is a draw from a stationary random variable, this function
approximates `log(E[exp(log_value)])`, i.e., a weighted log-sum-exp. More
precis... | def assign_log_moving_mean_exp(
log_mean_exp_var, log_value, decay, name=None):
"""Compute the log of the exponentially weighted moving mean of the exp.
If `log_value` is a draw from a stationary random variable, this function
approximates `log(E[exp(log_value)])`, i.e., a weighted log-sum-exp. More
precis... | [
"Compute",
"the",
"log",
"of",
"the",
"exponentially",
"weighted",
"moving",
"mean",
"of",
"the",
"exp",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/internal/moving_stats.py#L113-L180 | [
"def",
"assign_log_moving_mean_exp",
"(",
"log_mean_exp_var",
",",
"log_value",
",",
"decay",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"name",
",",
"\"assign_log_moving_mean_exp\"",
",",
"[",
"log_mean... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | moving_mean_variance | Compute exponentially weighted moving {mean,variance} of a streaming value.
The exponentially-weighting moving `mean_var` and `variance_var` are updated
by `value` according to the following recurrence:
```python
variance_var = decay * (variance_var + (1-decay) * (value - mean_var)**2)
mean_var = decay ... | tensorflow_probability/python/distributions/internal/moving_stats.py | def moving_mean_variance(value, decay, name=None):
"""Compute exponentially weighted moving {mean,variance} of a streaming value.
The exponentially-weighting moving `mean_var` and `variance_var` are updated
by `value` according to the following recurrence:
```python
variance_var = decay * (variance_var + (1... | def moving_mean_variance(value, decay, name=None):
"""Compute exponentially weighted moving {mean,variance} of a streaming value.
The exponentially-weighting moving `mean_var` and `variance_var` are updated
by `value` according to the following recurrence:
```python
variance_var = decay * (variance_var + (1... | [
"Compute",
"exponentially",
"weighted",
"moving",
"{",
"mean",
"variance",
"}",
"of",
"a",
"streaming",
"value",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/internal/moving_stats.py#L186-L245 | [
"def",
"moving_mean_variance",
"(",
"value",
",",
"decay",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"variable_scope",
"(",
"name",
",",
"\"moving_mean_variance\"",
",",
"[",
"value",
",",
"decay",
"]",
")",
":",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | CholeskyOuterProduct._make_columnar | Ensures non-scalar input has at least one column.
Example:
If `x = [1, 2, 3]` then the output is `[[1], [2], [3]]`.
If `x = [[1, 2, 3], [4, 5, 6]]` then the output is unchanged.
If `x = 1` then the output is unchanged.
Args:
x: `Tensor`.
Returns:
columnar_x: `Tensor` with ... | tensorflow_probability/python/bijectors/cholesky_outer_product.py | def _make_columnar(self, x):
"""Ensures non-scalar input has at least one column.
Example:
If `x = [1, 2, 3]` then the output is `[[1], [2], [3]]`.
If `x = [[1, 2, 3], [4, 5, 6]]` then the output is unchanged.
If `x = 1` then the output is unchanged.
Args:
x: `Tensor`.
Retur... | def _make_columnar(self, x):
"""Ensures non-scalar input has at least one column.
Example:
If `x = [1, 2, 3]` then the output is `[[1], [2], [3]]`.
If `x = [[1, 2, 3], [4, 5, 6]]` then the output is unchanged.
If `x = 1` then the output is unchanged.
Args:
x: `Tensor`.
Retur... | [
"Ensures",
"non",
"-",
"scalar",
"input",
"has",
"at",
"least",
"one",
"column",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/bijectors/cholesky_outer_product.py#L190-L217 | [
"def",
"_make_columnar",
"(",
"self",
",",
"x",
")",
":",
"if",
"tensorshape_util",
".",
"rank",
"(",
"x",
".",
"shape",
")",
"is",
"not",
"None",
":",
"if",
"tensorshape_util",
".",
"rank",
"(",
"x",
".",
"shape",
")",
"==",
"1",
":",
"x",
"=",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _kl_laplace_laplace | Calculate the batched KL divergence KL(a || b) with a and b Laplace.
Args:
a: instance of a Laplace distribution object.
b: instance of a Laplace distribution object.
name: (optional) Name to use for created operations.
default is "kl_laplace_laplace".
Returns:
Batchwise KL(a || b) | tensorflow_probability/python/distributions/laplace.py | def _kl_laplace_laplace(a, b, name=None):
"""Calculate the batched KL divergence KL(a || b) with a and b Laplace.
Args:
a: instance of a Laplace distribution object.
b: instance of a Laplace distribution object.
name: (optional) Name to use for created operations.
default is "kl_laplace_laplace".... | def _kl_laplace_laplace(a, b, name=None):
"""Calculate the batched KL divergence KL(a || b) with a and b Laplace.
Args:
a: instance of a Laplace distribution object.
b: instance of a Laplace distribution object.
name: (optional) Name to use for created operations.
default is "kl_laplace_laplace".... | [
"Calculate",
"the",
"batched",
"KL",
"divergence",
"KL",
"(",
"a",
"||",
"b",
")",
"with",
"a",
"and",
"b",
"Laplace",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/laplace.py#L212-L231 | [
"def",
"_kl_laplace_laplace",
"(",
"a",
",",
"b",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"name",
"or",
"\"kl_laplace_laplace\"",
")",
":",
"# Consistent with",
"# http://www.mast.queensu.ca/~communications/Papers/gil-msc11.pdf, page 38... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | random_rademacher | Generates `Tensor` consisting of `-1` or `+1`, chosen uniformly at random.
For more details, see [Rademacher distribution](
https://en.wikipedia.org/wiki/Rademacher_distribution).
Args:
shape: Vector-shaped, `int` `Tensor` representing shape of output.
dtype: (Optional) TF `dtype` representing `dtype` o... | tensorflow_probability/python/math/random_ops.py | def random_rademacher(shape, dtype=tf.float32, seed=None, name=None):
"""Generates `Tensor` consisting of `-1` or `+1`, chosen uniformly at random.
For more details, see [Rademacher distribution](
https://en.wikipedia.org/wiki/Rademacher_distribution).
Args:
shape: Vector-shaped, `int` `Tensor` representi... | def random_rademacher(shape, dtype=tf.float32, seed=None, name=None):
"""Generates `Tensor` consisting of `-1` or `+1`, chosen uniformly at random.
For more details, see [Rademacher distribution](
https://en.wikipedia.org/wiki/Rademacher_distribution).
Args:
shape: Vector-shaped, `int` `Tensor` representi... | [
"Generates",
"Tensor",
"consisting",
"of",
"-",
"1",
"or",
"+",
"1",
"chosen",
"uniformly",
"at",
"random",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/math/random_ops.py#L33-L58 | [
"def",
"random_rademacher",
"(",
"shape",
",",
"dtype",
"=",
"tf",
".",
"float32",
",",
"seed",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"name",
",",
"'random_rademacher'",
",",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | random_rayleigh | Generates `Tensor` of positive reals drawn from a Rayleigh distributions.
The probability density function of a Rayleigh distribution with `scale`
parameter is given by:
```none
f(x) = x scale**-2 exp(-x**2 0.5 scale**-2)
```
For more details, see [Rayleigh distribution](
https://en.wikipedia.org/wiki/... | tensorflow_probability/python/math/random_ops.py | def random_rayleigh(shape, scale=None, dtype=tf.float32, seed=None, name=None):
"""Generates `Tensor` of positive reals drawn from a Rayleigh distributions.
The probability density function of a Rayleigh distribution with `scale`
parameter is given by:
```none
f(x) = x scale**-2 exp(-x**2 0.5 scale**-2)
`... | def random_rayleigh(shape, scale=None, dtype=tf.float32, seed=None, name=None):
"""Generates `Tensor` of positive reals drawn from a Rayleigh distributions.
The probability density function of a Rayleigh distribution with `scale`
parameter is given by:
```none
f(x) = x scale**-2 exp(-x**2 0.5 scale**-2)
`... | [
"Generates",
"Tensor",
"of",
"positive",
"reals",
"drawn",
"from",
"a",
"Rayleigh",
"distributions",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/math/random_ops.py#L61-L99 | [
"def",
"random_rayleigh",
"(",
"shape",
",",
"scale",
"=",
"None",
",",
"dtype",
"=",
"tf",
".",
"float32",
",",
"seed",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"name",
",",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _pick_scalar_condition | Convenience function which chooses the condition based on the predicate. | tensorflow_probability/python/distributions/transformed_distribution.py | def _pick_scalar_condition(pred, cond_true, cond_false):
"""Convenience function which chooses the condition based on the predicate."""
# Note: This function is only valid if all of pred, cond_true, and cond_false
# are scalars. This means its semantics are arguably more like tf.cond than
# tf.where even though... | def _pick_scalar_condition(pred, cond_true, cond_false):
"""Convenience function which chooses the condition based on the predicate."""
# Note: This function is only valid if all of pred, cond_true, and cond_false
# are scalars. This means its semantics are arguably more like tf.cond than
# tf.where even though... | [
"Convenience",
"function",
"which",
"chooses",
"the",
"condition",
"based",
"on",
"the",
"predicate",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/transformed_distribution.py#L41-L49 | [
"def",
"_pick_scalar_condition",
"(",
"pred",
",",
"cond_true",
",",
"cond_false",
")",
":",
"# Note: This function is only valid if all of pred, cond_true, and cond_false",
"# are scalars. This means its semantics are arguably more like tf.cond than",
"# tf.where even though we use tf.where... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | TransformedDistribution._finish_log_prob_for_one_fiber | Finish computation of log_prob on one element of the inverse image. | tensorflow_probability/python/distributions/transformed_distribution.py | def _finish_log_prob_for_one_fiber(self, y, x, ildj, event_ndims,
**distribution_kwargs):
"""Finish computation of log_prob on one element of the inverse image."""
x = self._maybe_rotate_dims(x, rotate_right=True)
log_prob = self.distribution.log_prob(x, **distribution_k... | def _finish_log_prob_for_one_fiber(self, y, x, ildj, event_ndims,
**distribution_kwargs):
"""Finish computation of log_prob on one element of the inverse image."""
x = self._maybe_rotate_dims(x, rotate_right=True)
log_prob = self.distribution.log_prob(x, **distribution_k... | [
"Finish",
"computation",
"of",
"log_prob",
"on",
"one",
"element",
"of",
"the",
"inverse",
"image",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/transformed_distribution.py#L415-L430 | [
"def",
"_finish_log_prob_for_one_fiber",
"(",
"self",
",",
"y",
",",
"x",
",",
"ildj",
",",
"event_ndims",
",",
"*",
"*",
"distribution_kwargs",
")",
":",
"x",
"=",
"self",
".",
"_maybe_rotate_dims",
"(",
"x",
",",
"rotate_right",
"=",
"True",
")",
"log_pr... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | TransformedDistribution._finish_prob_for_one_fiber | Finish computation of prob on one element of the inverse image. | tensorflow_probability/python/distributions/transformed_distribution.py | def _finish_prob_for_one_fiber(self, y, x, ildj, event_ndims,
**distribution_kwargs):
"""Finish computation of prob on one element of the inverse image."""
x = self._maybe_rotate_dims(x, rotate_right=True)
prob = self.distribution.prob(x, **distribution_kwargs)
if self._... | def _finish_prob_for_one_fiber(self, y, x, ildj, event_ndims,
**distribution_kwargs):
"""Finish computation of prob on one element of the inverse image."""
x = self._maybe_rotate_dims(x, rotate_right=True)
prob = self.distribution.prob(x, **distribution_kwargs)
if self._... | [
"Finish",
"computation",
"of",
"prob",
"on",
"one",
"element",
"of",
"the",
"inverse",
"image",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/transformed_distribution.py#L451-L465 | [
"def",
"_finish_prob_for_one_fiber",
"(",
"self",
",",
"y",
",",
"x",
",",
"ildj",
",",
"event_ndims",
",",
"*",
"*",
"distribution_kwargs",
")",
":",
"x",
"=",
"self",
".",
"_maybe_rotate_dims",
"(",
"x",
",",
"rotate_right",
"=",
"True",
")",
"prob",
"... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | TransformedDistribution._maybe_validate_shape_override | Helper to __init__ which ensures override batch/event_shape are valid. | tensorflow_probability/python/distributions/transformed_distribution.py | def _maybe_validate_shape_override(self, override_shape, base_is_scalar,
validate_args, name):
"""Helper to __init__ which ensures override batch/event_shape are valid."""
if override_shape is None:
override_shape = []
override_shape = tf.convert_to_tensor(
... | def _maybe_validate_shape_override(self, override_shape, base_is_scalar,
validate_args, name):
"""Helper to __init__ which ensures override batch/event_shape are valid."""
if override_shape is None:
override_shape = []
override_shape = tf.convert_to_tensor(
... | [
"Helper",
"to",
"__init__",
"which",
"ensures",
"override",
"batch",
"/",
"event_shape",
"are",
"valid",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/transformed_distribution.py#L603-L655 | [
"def",
"_maybe_validate_shape_override",
"(",
"self",
",",
"override_shape",
",",
"base_is_scalar",
",",
"validate_args",
",",
"name",
")",
":",
"if",
"override_shape",
"is",
"None",
":",
"override_shape",
"=",
"[",
"]",
"override_shape",
"=",
"tf",
".",
"conver... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | TransformedDistribution._maybe_rotate_dims | Helper which rolls left event_dims left or right event_dims right. | tensorflow_probability/python/distributions/transformed_distribution.py | def _maybe_rotate_dims(self, x, rotate_right=False):
"""Helper which rolls left event_dims left or right event_dims right."""
needs_rotation_const = tf.get_static_value(self._needs_rotation)
if needs_rotation_const is not None and not needs_rotation_const:
return x
ndims = prefer_static.rank(x)
... | def _maybe_rotate_dims(self, x, rotate_right=False):
"""Helper which rolls left event_dims left or right event_dims right."""
needs_rotation_const = tf.get_static_value(self._needs_rotation)
if needs_rotation_const is not None and not needs_rotation_const:
return x
ndims = prefer_static.rank(x)
... | [
"Helper",
"which",
"rolls",
"left",
"event_dims",
"left",
"or",
"right",
"event_dims",
"right",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/transformed_distribution.py#L657-L666 | [
"def",
"_maybe_rotate_dims",
"(",
"self",
",",
"x",
",",
"rotate_right",
"=",
"False",
")",
":",
"needs_rotation_const",
"=",
"tf",
".",
"get_static_value",
"(",
"self",
".",
"_needs_rotation",
")",
"if",
"needs_rotation_const",
"is",
"not",
"None",
"and",
"no... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _undo_batch_normalization | r"""Inverse of tf.nn.batch_normalization.
Args:
x: Input `Tensor` of arbitrary dimensionality.
mean: A mean `Tensor`.
variance: A variance `Tensor`.
offset: An offset `Tensor`, often denoted `beta` in equations, or
None. If present, will be added to the normalized tensor.
scale: A scale `Te... | tensorflow_probability/python/bijectors/batch_normalization.py | def _undo_batch_normalization(x,
mean,
variance,
offset,
scale,
variance_epsilon,
name=None):
r"""Inverse of tf.nn.batch_normalization.
... | def _undo_batch_normalization(x,
mean,
variance,
offset,
scale,
variance_epsilon,
name=None):
r"""Inverse of tf.nn.batch_normalization.
... | [
"r",
"Inverse",
"of",
"tf",
".",
"nn",
".",
"batch_normalization",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/bijectors/batch_normalization.py#L33-L68 | [
"def",
"_undo_batch_normalization",
"(",
"x",
",",
"mean",
",",
"variance",
",",
"offset",
",",
"scale",
",",
"variance_epsilon",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v2",
".",
"name_scope",
"(",
"name",
"or",
"\"undo_ba... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | BatchNormalization._validate_bn_layer | Check for valid BatchNormalization layer.
Args:
layer: Instance of `tf.layers.BatchNormalization`.
Raises:
ValueError: If batchnorm_layer argument is not an instance of
`tf.layers.BatchNormalization`, or if `batchnorm_layer.renorm=True` or
if `batchnorm_layer.virtual_batch_size` is spec... | tensorflow_probability/python/bijectors/batch_normalization.py | def _validate_bn_layer(self, layer):
"""Check for valid BatchNormalization layer.
Args:
layer: Instance of `tf.layers.BatchNormalization`.
Raises:
ValueError: If batchnorm_layer argument is not an instance of
`tf.layers.BatchNormalization`, or if `batchnorm_layer.renorm=True` or
if ... | def _validate_bn_layer(self, layer):
"""Check for valid BatchNormalization layer.
Args:
layer: Instance of `tf.layers.BatchNormalization`.
Raises:
ValueError: If batchnorm_layer argument is not an instance of
`tf.layers.BatchNormalization`, or if `batchnorm_layer.renorm=True` or
if ... | [
"Check",
"for",
"valid",
"BatchNormalization",
"layer",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/bijectors/batch_normalization.py#L164-L182 | [
"def",
"_validate_bn_layer",
"(",
"self",
",",
"layer",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"layer",
",",
"tf",
".",
"keras",
".",
"layers",
".",
"BatchNormalization",
")",
"and",
"not",
"isinstance",
"(",
"layer",
",",
"tf",
".",
"compat",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _slice_single_param | Slices a single parameter of a distribution.
Args:
param: A `Tensor`, the original parameter to slice.
param_event_ndims: `int` event parameterization rank for this parameter.
slices: A `tuple` of normalized slices.
dist_batch_shape: The distribution's batch shape `Tensor`.
Returns:
new_param:... | tensorflow_probability/python/distributions/internal/slicing.py | def _slice_single_param(param, param_event_ndims, slices, dist_batch_shape):
"""Slices a single parameter of a distribution.
Args:
param: A `Tensor`, the original parameter to slice.
param_event_ndims: `int` event parameterization rank for this parameter.
slices: A `tuple` of normalized slices.
dis... | def _slice_single_param(param, param_event_ndims, slices, dist_batch_shape):
"""Slices a single parameter of a distribution.
Args:
param: A `Tensor`, the original parameter to slice.
param_event_ndims: `int` event parameterization rank for this parameter.
slices: A `tuple` of normalized slices.
dis... | [
"Slices",
"a",
"single",
"parameter",
"of",
"a",
"distribution",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/internal/slicing.py#L46-L104 | [
"def",
"_slice_single_param",
"(",
"param",
",",
"param_event_ndims",
",",
"slices",
",",
"dist_batch_shape",
")",
":",
"# Extend param shape with ones on the left to match dist_batch_shape.",
"param_shape",
"=",
"tf",
".",
"shape",
"(",
"input",
"=",
"param",
")",
"ins... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _slice_params_to_dict | Computes the override dictionary of sliced parameters.
Args:
dist: The tfd.Distribution being batch-sliced.
params_event_ndims: Per-event parameter ranks, a `str->int` `dict`.
slices: Slices as received by __getitem__.
Returns:
overrides: `str->Tensor` `dict` of batch-sliced parameter overrides. | tensorflow_probability/python/distributions/internal/slicing.py | def _slice_params_to_dict(dist, params_event_ndims, slices):
"""Computes the override dictionary of sliced parameters.
Args:
dist: The tfd.Distribution being batch-sliced.
params_event_ndims: Per-event parameter ranks, a `str->int` `dict`.
slices: Slices as received by __getitem__.
Returns:
over... | def _slice_params_to_dict(dist, params_event_ndims, slices):
"""Computes the override dictionary of sliced parameters.
Args:
dist: The tfd.Distribution being batch-sliced.
params_event_ndims: Per-event parameter ranks, a `str->int` `dict`.
slices: Slices as received by __getitem__.
Returns:
over... | [
"Computes",
"the",
"override",
"dictionary",
"of",
"sliced",
"parameters",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/internal/slicing.py#L107-L142 | [
"def",
"_slice_params_to_dict",
"(",
"dist",
",",
"params_event_ndims",
",",
"slices",
")",
":",
"override_dict",
"=",
"{",
"}",
"for",
"param_name",
",",
"param_event_ndims",
"in",
"six",
".",
"iteritems",
"(",
"params_event_ndims",
")",
":",
"# Verify that eithe... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _apply_single_step | Applies a single slicing step to `dist`, returning a new instance. | tensorflow_probability/python/distributions/internal/slicing.py | def _apply_single_step(dist, params_event_ndims, slices, params_overrides):
"""Applies a single slicing step to `dist`, returning a new instance."""
if len(slices) == 1 and slices[0] == Ellipsis:
# The path used by Distribution.copy: batch_slice(...args..., Ellipsis)
override_dict = {}
else:
override_... | def _apply_single_step(dist, params_event_ndims, slices, params_overrides):
"""Applies a single slicing step to `dist`, returning a new instance."""
if len(slices) == 1 and slices[0] == Ellipsis:
# The path used by Distribution.copy: batch_slice(...args..., Ellipsis)
override_dict = {}
else:
override_... | [
"Applies",
"a",
"single",
"slicing",
"step",
"to",
"dist",
"returning",
"a",
"new",
"instance",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/internal/slicing.py#L145-L155 | [
"def",
"_apply_single_step",
"(",
"dist",
",",
"params_event_ndims",
",",
"slices",
",",
"params_overrides",
")",
":",
"if",
"len",
"(",
"slices",
")",
"==",
"1",
"and",
"slices",
"[",
"0",
"]",
"==",
"Ellipsis",
":",
"# The path used by Distribution.copy: batch... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _apply_slice_sequence | Applies a sequence of slice or copy-with-overrides operations to `dist`. | tensorflow_probability/python/distributions/internal/slicing.py | def _apply_slice_sequence(dist, params_event_ndims, slice_overrides_seq):
"""Applies a sequence of slice or copy-with-overrides operations to `dist`."""
for slices, overrides in slice_overrides_seq:
dist = _apply_single_step(dist, params_event_ndims, slices, overrides)
return dist | def _apply_slice_sequence(dist, params_event_ndims, slice_overrides_seq):
"""Applies a sequence of slice or copy-with-overrides operations to `dist`."""
for slices, overrides in slice_overrides_seq:
dist = _apply_single_step(dist, params_event_ndims, slices, overrides)
return dist | [
"Applies",
"a",
"sequence",
"of",
"slice",
"or",
"copy",
"-",
"with",
"-",
"overrides",
"operations",
"to",
"dist",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/internal/slicing.py#L158-L162 | [
"def",
"_apply_slice_sequence",
"(",
"dist",
",",
"params_event_ndims",
",",
"slice_overrides_seq",
")",
":",
"for",
"slices",
",",
"overrides",
"in",
"slice_overrides_seq",
":",
"dist",
"=",
"_apply_single_step",
"(",
"dist",
",",
"params_event_ndims",
",",
"slices... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | batch_slice | Slices `dist` along its batch dimensions. Helper for tfd.Distribution.
Args:
dist: A `tfd.Distribution` instance.
params_event_ndims: A `dict` of `str->int` indicating the number of
dimensions of a given parameter required to parameterize a single event.
params_overrides: A `dict` of parameter over... | tensorflow_probability/python/distributions/internal/slicing.py | def batch_slice(dist, params_event_ndims, params_overrides, slices):
"""Slices `dist` along its batch dimensions. Helper for tfd.Distribution.
Args:
dist: A `tfd.Distribution` instance.
params_event_ndims: A `dict` of `str->int` indicating the number of
dimensions of a given parameter required to par... | def batch_slice(dist, params_event_ndims, params_overrides, slices):
"""Slices `dist` along its batch dimensions. Helper for tfd.Distribution.
Args:
dist: A `tfd.Distribution` instance.
params_event_ndims: A `dict` of `str->int` indicating the number of
dimensions of a given parameter required to par... | [
"Slices",
"dist",
"along",
"its",
"batch",
"dimensions",
".",
"Helper",
"for",
"tfd",
".",
"Distribution",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/internal/slicing.py#L165-L191 | [
"def",
"batch_slice",
"(",
"dist",
",",
"params_event_ndims",
",",
"params_overrides",
",",
"slices",
")",
":",
"if",
"not",
"isinstance",
"(",
"slices",
",",
"collections",
".",
"Sequence",
")",
":",
"slices",
"=",
"(",
"slices",
",",
")",
"# We track the h... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.