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 | _value_and_gradients | Helper to `maybe_call_fn_and_grads`. | tensorflow_probability/python/mcmc/internal/util.py | def _value_and_gradients(fn, fn_arg_list, result=None, grads=None, name=None):
"""Helper to `maybe_call_fn_and_grads`."""
with tf.compat.v1.name_scope(name, 'value_and_gradients',
[fn_arg_list, result, grads]):
def _convert_to_tensor(x, name):
ctt = lambda x_: x_ if x_ is N... | def _value_and_gradients(fn, fn_arg_list, result=None, grads=None, name=None):
"""Helper to `maybe_call_fn_and_grads`."""
with tf.compat.v1.name_scope(name, 'value_and_gradients',
[fn_arg_list, result, grads]):
def _convert_to_tensor(x, name):
ctt = lambda x_: x_ if x_ is N... | [
"Helper",
"to",
"maybe_call_fn_and_grads",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/internal/util.py#L176-L218 | [
"def",
"_value_and_gradients",
"(",
"fn",
",",
"fn_arg_list",
",",
"result",
"=",
"None",
",",
"grads",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"name",
",",
"'value_and_gradients'",... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | maybe_call_fn_and_grads | Calls `fn` and computes the gradient of the result wrt `args_list`. | tensorflow_probability/python/mcmc/internal/util.py | def maybe_call_fn_and_grads(fn,
fn_arg_list,
result=None,
grads=None,
check_non_none_grads=True,
name=None):
"""Calls `fn` and computes the gradient of the result wrt `args_list`... | def maybe_call_fn_and_grads(fn,
fn_arg_list,
result=None,
grads=None,
check_non_none_grads=True,
name=None):
"""Calls `fn` and computes the gradient of the result wrt `args_list`... | [
"Calls",
"fn",
"and",
"computes",
"the",
"gradient",
"of",
"the",
"result",
"wrt",
"args_list",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/internal/util.py#L221-L244 | [
"def",
"maybe_call_fn_and_grads",
"(",
"fn",
",",
"fn_arg_list",
",",
"result",
"=",
"None",
",",
"grads",
"=",
"None",
",",
"check_non_none_grads",
"=",
"True",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | smart_for_loop | Construct a for loop, preferring a python loop if `n` is staticaly known.
Given `loop_num_iter` and `body_fn`, return an op corresponding to executing
`body_fn` `loop_num_iter` times, feeding previous outputs of `body_fn` into
the next iteration.
If `loop_num_iter` is statically known, the op is constructed v... | tensorflow_probability/python/mcmc/internal/util.py | def smart_for_loop(loop_num_iter, body_fn, initial_loop_vars,
parallel_iterations=10, name=None):
"""Construct a for loop, preferring a python loop if `n` is staticaly known.
Given `loop_num_iter` and `body_fn`, return an op corresponding to executing
`body_fn` `loop_num_iter` times, feeding p... | def smart_for_loop(loop_num_iter, body_fn, initial_loop_vars,
parallel_iterations=10, name=None):
"""Construct a for loop, preferring a python loop if `n` is staticaly known.
Given `loop_num_iter` and `body_fn`, return an op corresponding to executing
`body_fn` `loop_num_iter` times, feeding p... | [
"Construct",
"a",
"for",
"loop",
"preferring",
"a",
"python",
"loop",
"if",
"n",
"is",
"staticaly",
"known",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/internal/util.py#L247-L290 | [
"def",
"smart_for_loop",
"(",
"loop_num_iter",
",",
"body_fn",
",",
"initial_loop_vars",
",",
"parallel_iterations",
"=",
"10",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"name",
",",
"'smart_for_loop'... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | trace_scan | A simplified version of `tf.scan` that has configurable tracing.
This function repeatedly calls `loop_fn(state, elem)`, where `state` is the
`initial_state` during the first iteration, and the return value of `loop_fn`
for every iteration thereafter. `elem` is a slice of `elements` along the
first dimension, a... | tensorflow_probability/python/mcmc/internal/util.py | def trace_scan(loop_fn,
initial_state,
elems,
trace_fn,
parallel_iterations=10,
name=None):
"""A simplified version of `tf.scan` that has configurable tracing.
This function repeatedly calls `loop_fn(state, elem)`, where `state` is the
`i... | def trace_scan(loop_fn,
initial_state,
elems,
trace_fn,
parallel_iterations=10,
name=None):
"""A simplified version of `tf.scan` that has configurable tracing.
This function repeatedly calls `loop_fn(state, elem)`, where `state` is the
`i... | [
"A",
"simplified",
"version",
"of",
"tf",
".",
"scan",
"that",
"has",
"configurable",
"tracing",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/internal/util.py#L293-L379 | [
"def",
"trace_scan",
"(",
"loop_fn",
",",
"initial_state",
",",
"elems",
",",
"trace_fn",
",",
"parallel_iterations",
"=",
"10",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"name",
",",
"'trace_scan... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | make_innermost_setter | Wraps a setter so it applies to the inner-most results in `kernel_results`.
The wrapped setter unwraps `kernel_results` and applies `setter` to the first
results without an `inner_results` attribute.
Args:
setter: A callable that takes the kernel results as well as some `*args` and
`**kwargs` and retu... | tensorflow_probability/python/mcmc/internal/util.py | def make_innermost_setter(setter):
"""Wraps a setter so it applies to the inner-most results in `kernel_results`.
The wrapped setter unwraps `kernel_results` and applies `setter` to the first
results without an `inner_results` attribute.
Args:
setter: A callable that takes the kernel results as well as so... | def make_innermost_setter(setter):
"""Wraps a setter so it applies to the inner-most results in `kernel_results`.
The wrapped setter unwraps `kernel_results` and applies `setter` to the first
results without an `inner_results` attribute.
Args:
setter: A callable that takes the kernel results as well as so... | [
"Wraps",
"a",
"setter",
"so",
"it",
"applies",
"to",
"the",
"inner",
"-",
"most",
"results",
"in",
"kernel_results",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/internal/util.py#L382-L411 | [
"def",
"make_innermost_setter",
"(",
"setter",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"setter",
")",
"def",
"_new_setter",
"(",
"kernel_results",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Wrapped setter.\"\"\"",
"results_stack",
"=",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | make_innermost_getter | Wraps a getter so it applies to the inner-most results in `kernel_results`.
The wrapped getter unwraps `kernel_results` and returns the return value of
`getter` called with the first results without an `inner_results` attribute.
Args:
getter: A callable that takes Kernel results and returns some value.
R... | tensorflow_probability/python/mcmc/internal/util.py | def make_innermost_getter(getter):
"""Wraps a getter so it applies to the inner-most results in `kernel_results`.
The wrapped getter unwraps `kernel_results` and returns the return value of
`getter` called with the first results without an `inner_results` attribute.
Args:
getter: A callable that takes Ker... | def make_innermost_getter(getter):
"""Wraps a getter so it applies to the inner-most results in `kernel_results`.
The wrapped getter unwraps `kernel_results` and returns the return value of
`getter` called with the first results without an `inner_results` attribute.
Args:
getter: A callable that takes Ker... | [
"Wraps",
"a",
"getter",
"so",
"it",
"applies",
"to",
"the",
"inner",
"-",
"most",
"results",
"in",
"kernel_results",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/internal/util.py#L414-L437 | [
"def",
"make_innermost_getter",
"(",
"getter",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"getter",
")",
"def",
"_new_getter",
"(",
"kernel_results",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Wrapped getter.\"\"\"",
"results_stack",
"=",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | enable_store_parameters_in_results | Enables the `store_parameters_in_results` parameter in a chain of kernels.
This is a temporary utility for use during the transition period of the
parameter storage methods.
Args:
kernel: A TransitionKernel.
Returns:
kernel: The same kernel, but recreated with `store_parameters_in_results`
re... | tensorflow_probability/python/mcmc/internal/util.py | def enable_store_parameters_in_results(kernel):
"""Enables the `store_parameters_in_results` parameter in a chain of kernels.
This is a temporary utility for use during the transition period of the
parameter storage methods.
Args:
kernel: A TransitionKernel.
Returns:
kernel: The same kernel, but re... | def enable_store_parameters_in_results(kernel):
"""Enables the `store_parameters_in_results` parameter in a chain of kernels.
This is a temporary utility for use during the transition period of the
parameter storage methods.
Args:
kernel: A TransitionKernel.
Returns:
kernel: The same kernel, but re... | [
"Enables",
"the",
"store_parameters_in_results",
"parameter",
"in",
"a",
"chain",
"of",
"kernels",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/internal/util.py#L440-L474 | [
"def",
"enable_store_parameters_in_results",
"(",
"kernel",
")",
":",
"kernel_stack",
"=",
"[",
"]",
"while",
"hasattr",
"(",
"kernel",
",",
"'parameters'",
")",
"and",
"'inner_kernel'",
"in",
"kernel",
".",
"parameters",
":",
"kernel_stack",
".",
"append",
"(",... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _replace_event_shape_in_shape_tensor | Replaces the rightmost dims in a `Tensor` representing a shape.
Args:
input_shape: a rank-1 `Tensor` of integers
event_shape_in: the event shape expected to be present in rightmost dims
of `shape_in`.
event_shape_out: the event shape with which to replace `event_shape_in` in
the rightmost dim... | tensorflow_probability/python/bijectors/reshape.py | def _replace_event_shape_in_shape_tensor(
input_shape, event_shape_in, event_shape_out, validate_args):
"""Replaces the rightmost dims in a `Tensor` representing a shape.
Args:
input_shape: a rank-1 `Tensor` of integers
event_shape_in: the event shape expected to be present in rightmost dims
of `... | def _replace_event_shape_in_shape_tensor(
input_shape, event_shape_in, event_shape_out, validate_args):
"""Replaces the rightmost dims in a `Tensor` representing a shape.
Args:
input_shape: a rank-1 `Tensor` of integers
event_shape_in: the event shape expected to be present in rightmost dims
of `... | [
"Replaces",
"the",
"rightmost",
"dims",
"in",
"a",
"Tensor",
"representing",
"a",
"shape",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/bijectors/reshape.py#L243-L313 | [
"def",
"_replace_event_shape_in_shape_tensor",
"(",
"input_shape",
",",
"event_shape_in",
",",
"event_shape_out",
",",
"validate_args",
")",
":",
"output_tensorshape",
",",
"is_validated",
"=",
"_replace_event_shape_in_tensorshape",
"(",
"tensorshape_util",
".",
"constant_val... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _replace_event_shape_in_tensorshape | Replaces the event shape dims of a `TensorShape`.
Args:
input_tensorshape: a `TensorShape` instance in which to attempt replacing
event shape.
event_shape_in: `Tensor` shape representing the event shape expected to
be present in (rightmost dims of) `tensorshape_in`. Must be compatible
with ... | tensorflow_probability/python/bijectors/reshape.py | def _replace_event_shape_in_tensorshape(
input_tensorshape, event_shape_in, event_shape_out):
"""Replaces the event shape dims of a `TensorShape`.
Args:
input_tensorshape: a `TensorShape` instance in which to attempt replacing
event shape.
event_shape_in: `Tensor` shape representing the event sha... | def _replace_event_shape_in_tensorshape(
input_tensorshape, event_shape_in, event_shape_out):
"""Replaces the event shape dims of a `TensorShape`.
Args:
input_tensorshape: a `TensorShape` instance in which to attempt replacing
event shape.
event_shape_in: `Tensor` shape representing the event sha... | [
"Replaces",
"the",
"event",
"shape",
"dims",
"of",
"a",
"TensorShape",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/bijectors/reshape.py#L316-L382 | [
"def",
"_replace_event_shape_in_tensorshape",
"(",
"input_tensorshape",
",",
"event_shape_in",
",",
"event_shape_out",
")",
":",
"event_shape_in_ndims",
"=",
"tensorshape_util",
".",
"num_elements",
"(",
"event_shape_in",
".",
"shape",
")",
"if",
"tensorshape_util",
".",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _maybe_check_valid_shape | Check that a shape Tensor is int-type and otherwise sane. | tensorflow_probability/python/bijectors/reshape.py | def _maybe_check_valid_shape(shape, validate_args):
"""Check that a shape Tensor is int-type and otherwise sane."""
if not dtype_util.is_integer(shape.dtype):
raise TypeError('{} dtype ({}) should be `int`-like.'.format(
shape, dtype_util.name(shape.dtype)))
assertions = []
message = '`{}` rank sh... | def _maybe_check_valid_shape(shape, validate_args):
"""Check that a shape Tensor is int-type and otherwise sane."""
if not dtype_util.is_integer(shape.dtype):
raise TypeError('{} dtype ({}) should be `int`-like.'.format(
shape, dtype_util.name(shape.dtype)))
assertions = []
message = '`{}` rank sh... | [
"Check",
"that",
"a",
"shape",
"Tensor",
"is",
"int",
"-",
"type",
"and",
"otherwise",
"sane",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/bijectors/reshape.py#L385-L421 | [
"def",
"_maybe_check_valid_shape",
"(",
"shape",
",",
"validate_args",
")",
":",
"if",
"not",
"dtype_util",
".",
"is_integer",
"(",
"shape",
".",
"dtype",
")",
":",
"raise",
"TypeError",
"(",
"'{} dtype ({}) should be `int`-like.'",
".",
"format",
"(",
"shape",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _kl_beta_beta | Calculate the batchwise KL divergence KL(d1 || d2) with d1 and d2 Beta.
Args:
d1: instance of a Beta distribution object.
d2: instance of a Beta distribution object.
name: (optional) Name to use for created operations.
default is "kl_beta_beta".
Returns:
Batchwise KL(d1 || d2) | tensorflow_probability/python/distributions/beta.py | def _kl_beta_beta(d1, d2, name=None):
"""Calculate the batchwise KL divergence KL(d1 || d2) with d1 and d2 Beta.
Args:
d1: instance of a Beta distribution object.
d2: instance of a Beta distribution object.
name: (optional) Name to use for created operations.
default is "kl_beta_beta".
Returns... | def _kl_beta_beta(d1, d2, name=None):
"""Calculate the batchwise KL divergence KL(d1 || d2) with d1 and d2 Beta.
Args:
d1: instance of a Beta distribution object.
d2: instance of a Beta distribution object.
name: (optional) Name to use for created operations.
default is "kl_beta_beta".
Returns... | [
"Calculate",
"the",
"batchwise",
"KL",
"divergence",
"KL",
"(",
"d1",
"||",
"d2",
")",
"with",
"d1",
"and",
"d2",
"Beta",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/beta.py#L331-L353 | [
"def",
"_kl_beta_beta",
"(",
"d1",
",",
"d2",
",",
"name",
"=",
"None",
")",
":",
"def",
"delta",
"(",
"fn",
",",
"is_property",
"=",
"True",
")",
":",
"fn1",
"=",
"getattr",
"(",
"d1",
",",
"fn",
")",
"fn2",
"=",
"getattr",
"(",
"d2",
",",
"fn... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | Beta._maybe_assert_valid_sample | Checks the validity of a sample. | tensorflow_probability/python/distributions/beta.py | def _maybe_assert_valid_sample(self, x):
"""Checks the validity of a sample."""
if not self.validate_args:
return x
return distribution_util.with_dependencies([
assert_util.assert_positive(x, message="sample must be positive"),
assert_util.assert_less(x, 1., message="sample must be les... | def _maybe_assert_valid_sample(self, x):
"""Checks the validity of a sample."""
if not self.validate_args:
return x
return distribution_util.with_dependencies([
assert_util.assert_positive(x, message="sample must be positive"),
assert_util.assert_less(x, 1., message="sample must be les... | [
"Checks",
"the",
"validity",
"of",
"a",
"sample",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/beta.py#L320-L327 | [
"def",
"_maybe_assert_valid_sample",
"(",
"self",
",",
"x",
")",
":",
"if",
"not",
"self",
".",
"validate_args",
":",
"return",
"x",
"return",
"distribution_util",
".",
"with_dependencies",
"(",
"[",
"assert_util",
".",
"assert_positive",
"(",
"x",
",",
"messa... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | converged_any | Condition to stop when any batch member converges, or all have failed. | tensorflow_probability/python/optimizer/bfgs_utils.py | def converged_any(converged, failed):
"""Condition to stop when any batch member converges, or all have failed."""
return (tf.reduce_any(input_tensor=converged) |
tf.reduce_all(input_tensor=failed)) | def converged_any(converged, failed):
"""Condition to stop when any batch member converges, or all have failed."""
return (tf.reduce_any(input_tensor=converged) |
tf.reduce_all(input_tensor=failed)) | [
"Condition",
"to",
"stop",
"when",
"any",
"batch",
"member",
"converges",
"or",
"all",
"have",
"failed",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/bfgs_utils.py#L36-L39 | [
"def",
"converged_any",
"(",
"converged",
",",
"failed",
")",
":",
"return",
"(",
"tf",
".",
"reduce_any",
"(",
"input_tensor",
"=",
"converged",
")",
"|",
"tf",
".",
"reduce_all",
"(",
"input_tensor",
"=",
"failed",
")",
")"
] | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | get_initial_state_args | Returns a dictionary to populate the initial state of the search procedure.
Performs an initial convergence check and the first evaluation of the
objective function.
Args:
value_and_gradients_function: A Python callable that accepts a tensor and
returns a tuple of two tensors: the objective function v... | tensorflow_probability/python/optimizer/bfgs_utils.py | def get_initial_state_args(value_and_gradients_function,
initial_position,
grad_tolerance,
control_inputs=None):
"""Returns a dictionary to populate the initial state of the search procedure.
Performs an initial convergence check and ... | def get_initial_state_args(value_and_gradients_function,
initial_position,
grad_tolerance,
control_inputs=None):
"""Returns a dictionary to populate the initial state of the search procedure.
Performs an initial convergence check and ... | [
"Returns",
"a",
"dictionary",
"to",
"populate",
"the",
"initial",
"state",
"of",
"the",
"search",
"procedure",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/bfgs_utils.py#L47-L91 | [
"def",
"get_initial_state_args",
"(",
"value_and_gradients_function",
",",
"initial_position",
",",
"grad_tolerance",
",",
"control_inputs",
"=",
"None",
")",
":",
"if",
"control_inputs",
":",
"with",
"tf",
".",
"control_dependencies",
"(",
"control_inputs",
")",
":",... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | line_search_step | Performs the line search step of the BFGS search procedure.
Uses hager_zhang line search procedure to compute a suitable step size
to advance the current `state.position` along the given `search_direction`.
Also, if the line search is successful, updates the `state.position` by
taking the corresponding step.
... | tensorflow_probability/python/optimizer/bfgs_utils.py | def line_search_step(state, value_and_gradients_function, search_direction,
grad_tolerance, f_relative_tolerance, x_tolerance,
stopping_condition):
"""Performs the line search step of the BFGS search procedure.
Uses hager_zhang line search procedure to compute a suitable s... | def line_search_step(state, value_and_gradients_function, search_direction,
grad_tolerance, f_relative_tolerance, x_tolerance,
stopping_condition):
"""Performs the line search step of the BFGS search procedure.
Uses hager_zhang line search procedure to compute a suitable s... | [
"Performs",
"the",
"line",
"search",
"step",
"of",
"the",
"BFGS",
"search",
"procedure",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/bfgs_utils.py#L94-L180 | [
"def",
"line_search_step",
"(",
"state",
",",
"value_and_gradients_function",
",",
"search_direction",
",",
"grad_tolerance",
",",
"f_relative_tolerance",
",",
"x_tolerance",
",",
"stopping_condition",
")",
":",
"line_search_value_grad_func",
"=",
"_restrict_along_direction",... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _restrict_along_direction | Restricts a function in n-dimensions to a given direction.
Suppose f: R^n -> R. Then given a point x0 and a vector p0 in R^n, the
restriction of the function along that direction is defined by:
```None
g(t) = f(x0 + t * p0)
```
This function performs this restriction on the given function. In addition, i... | tensorflow_probability/python/optimizer/bfgs_utils.py | def _restrict_along_direction(value_and_gradients_function,
position,
direction):
"""Restricts a function in n-dimensions to a given direction.
Suppose f: R^n -> R. Then given a point x0 and a vector p0 in R^n, the
restriction of the function along that... | def _restrict_along_direction(value_and_gradients_function,
position,
direction):
"""Restricts a function in n-dimensions to a given direction.
Suppose f: R^n -> R. Then given a point x0 and a vector p0 in R^n, the
restriction of the function along that... | [
"Restricts",
"a",
"function",
"in",
"n",
"-",
"dimensions",
"to",
"a",
"given",
"direction",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/bfgs_utils.py#L202-L255 | [
"def",
"_restrict_along_direction",
"(",
"value_and_gradients_function",
",",
"position",
",",
"direction",
")",
":",
"def",
"_restricted_func",
"(",
"t",
")",
":",
"t",
"=",
"_broadcast",
"(",
"t",
",",
"position",
")",
"pt",
"=",
"position",
"+",
"tf",
"."... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _update_position | Updates the state advancing its position by a given position_delta. | tensorflow_probability/python/optimizer/bfgs_utils.py | def _update_position(state,
position_delta,
next_objective,
next_gradient,
grad_tolerance,
f_relative_tolerance,
x_tolerance):
"""Updates the state advancing its position by a given position_d... | def _update_position(state,
position_delta,
next_objective,
next_gradient,
grad_tolerance,
f_relative_tolerance,
x_tolerance):
"""Updates the state advancing its position by a given position_d... | [
"Updates",
"the",
"state",
"advancing",
"its",
"position",
"by",
"a",
"given",
"position_delta",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/bfgs_utils.py#L258-L284 | [
"def",
"_update_position",
"(",
"state",
",",
"position_delta",
",",
"next_objective",
",",
"next_gradient",
",",
"grad_tolerance",
",",
"f_relative_tolerance",
",",
"x_tolerance",
")",
":",
"failed",
"=",
"state",
".",
"failed",
"|",
"~",
"tf",
".",
"math",
"... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | norm | Compute the norm of the given (possibly batched) value.
Args:
value: A `Tensor` of real dtype.
dims: An Python integer with the number of non-batching dimensions in the
value, i.e. `dims=0` (scalars), `dims=1` (vectors), `dims=2` (matrices).
order: Order of the norm, defaults to `np.inf`. | tensorflow_probability/python/optimizer/bfgs_utils.py | def norm(value, dims, order=None):
"""Compute the norm of the given (possibly batched) value.
Args:
value: A `Tensor` of real dtype.
dims: An Python integer with the number of non-batching dimensions in the
value, i.e. `dims=0` (scalars), `dims=1` (vectors), `dims=2` (matrices).
order: Order of t... | def norm(value, dims, order=None):
"""Compute the norm of the given (possibly batched) value.
Args:
value: A `Tensor` of real dtype.
dims: An Python integer with the number of non-batching dimensions in the
value, i.e. `dims=0` (scalars), `dims=1` (vectors), `dims=2` (matrices).
order: Order of t... | [
"Compute",
"the",
"norm",
"of",
"the",
"given",
"(",
"possibly",
"batched",
")",
"value",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/bfgs_utils.py#L287-L306 | [
"def",
"norm",
"(",
"value",
",",
"dims",
",",
"order",
"=",
"None",
")",
":",
"if",
"dims",
"==",
"0",
":",
"return",
"tf",
".",
"math",
".",
"abs",
"(",
"value",
")",
"elif",
"dims",
"==",
"1",
":",
"axis",
"=",
"-",
"1",
"elif",
"dims",
"=... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _check_convergence | Checks if the algorithm satisfies the convergence criteria. | tensorflow_probability/python/optimizer/bfgs_utils.py | def _check_convergence(current_position,
next_position,
current_objective,
next_objective,
next_gradient,
grad_tolerance,
f_relative_tolerance,
x_tolerance):
... | def _check_convergence(current_position,
next_position,
current_objective,
next_objective,
next_gradient,
grad_tolerance,
f_relative_tolerance,
x_tolerance):
... | [
"Checks",
"if",
"the",
"algorithm",
"satisfies",
"the",
"convergence",
"criteria",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/bfgs_utils.py#L309-L322 | [
"def",
"_check_convergence",
"(",
"current_position",
",",
"next_position",
",",
"current_objective",
",",
"next_objective",
",",
"next_gradient",
",",
"grad_tolerance",
",",
"f_relative_tolerance",
",",
"x_tolerance",
")",
":",
"grad_converged",
"=",
"norm",
"(",
"ne... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _broadcast | Broadcast a value to match the batching dimensions of a target.
If necessary the value is converted into a tensor. Both value and target
should be of the same dtype.
Args:
value: A value to broadcast.
target: A `Tensor` of shape [b1, ..., bn, d].
Returns:
A `Tensor` of shape [b1, ..., bn] and sam... | tensorflow_probability/python/optimizer/bfgs_utils.py | def _broadcast(value, target):
"""Broadcast a value to match the batching dimensions of a target.
If necessary the value is converted into a tensor. Both value and target
should be of the same dtype.
Args:
value: A value to broadcast.
target: A `Tensor` of shape [b1, ..., bn, d].
Returns:
A `Te... | def _broadcast(value, target):
"""Broadcast a value to match the batching dimensions of a target.
If necessary the value is converted into a tensor. Both value and target
should be of the same dtype.
Args:
value: A value to broadcast.
target: A `Tensor` of shape [b1, ..., bn, d].
Returns:
A `Te... | [
"Broadcast",
"a",
"value",
"to",
"match",
"the",
"batching",
"dimensions",
"of",
"a",
"target",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/bfgs_utils.py#L325-L340 | [
"def",
"_broadcast",
"(",
"value",
",",
"target",
")",
":",
"return",
"tf",
".",
"broadcast_to",
"(",
"tf",
".",
"convert_to_tensor",
"(",
"value",
"=",
"value",
",",
"dtype",
"=",
"target",
".",
"dtype",
")",
",",
"distribution_util",
".",
"prefer_static_... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _harmonic_number | Compute the harmonic number from its analytic continuation.
Derivation from [here](
https://en.wikipedia.org/wiki/Digamma_function#Relation_to_harmonic_numbers)
and [Euler's constant](
https://en.wikipedia.org/wiki/Euler%E2%80%93Mascheroni_constant).
Args:
x: input float.
Returns:
z: The analytic... | tensorflow_probability/python/distributions/kumaraswamy.py | def _harmonic_number(x):
"""Compute the harmonic number from its analytic continuation.
Derivation from [here](
https://en.wikipedia.org/wiki/Digamma_function#Relation_to_harmonic_numbers)
and [Euler's constant](
https://en.wikipedia.org/wiki/Euler%E2%80%93Mascheroni_constant).
Args:
x: input float.
... | def _harmonic_number(x):
"""Compute the harmonic number from its analytic continuation.
Derivation from [here](
https://en.wikipedia.org/wiki/Digamma_function#Relation_to_harmonic_numbers)
and [Euler's constant](
https://en.wikipedia.org/wiki/Euler%E2%80%93Mascheroni_constant).
Args:
x: input float.
... | [
"Compute",
"the",
"harmonic",
"number",
"from",
"its",
"analytic",
"continuation",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/kumaraswamy.py#L40-L55 | [
"def",
"_harmonic_number",
"(",
"x",
")",
":",
"one",
"=",
"tf",
".",
"ones",
"(",
"[",
"]",
",",
"dtype",
"=",
"x",
".",
"dtype",
")",
"return",
"tf",
".",
"math",
".",
"digamma",
"(",
"x",
"+",
"one",
")",
"-",
"tf",
".",
"math",
".",
"diga... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | Kumaraswamy._moment | Compute the n'th (uncentered) moment. | tensorflow_probability/python/distributions/kumaraswamy.py | def _moment(self, n):
"""Compute the n'th (uncentered) moment."""
total_concentration = self.concentration1 + self.concentration0
expanded_concentration1 = tf.ones_like(
total_concentration, dtype=self.dtype) * self.concentration1
expanded_concentration0 = tf.ones_like(
total_concentrati... | def _moment(self, n):
"""Compute the n'th (uncentered) moment."""
total_concentration = self.concentration1 + self.concentration0
expanded_concentration1 = tf.ones_like(
total_concentration, dtype=self.dtype) * self.concentration1
expanded_concentration0 = tf.ones_like(
total_concentrati... | [
"Compute",
"the",
"n",
"th",
"(",
"uncentered",
")",
"moment",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/kumaraswamy.py#L191-L201 | [
"def",
"_moment",
"(",
"self",
",",
"n",
")",
":",
"total_concentration",
"=",
"self",
".",
"concentration1",
"+",
"self",
".",
"concentration0",
"expanded_concentration1",
"=",
"tf",
".",
"ones_like",
"(",
"total_concentration",
",",
"dtype",
"=",
"self",
"."... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _maybe_validate_target_accept_prob | Validates that target_accept_prob is in (0, 1). | tensorflow_probability/python/mcmc/simple_step_size_adaptation.py | def _maybe_validate_target_accept_prob(target_accept_prob, validate_args):
"""Validates that target_accept_prob is in (0, 1)."""
if not validate_args:
return target_accept_prob
with tf.control_dependencies([
tf.compat.v1.assert_positive(
target_accept_prob, message='`target_accept_prob` must b... | def _maybe_validate_target_accept_prob(target_accept_prob, validate_args):
"""Validates that target_accept_prob is in (0, 1)."""
if not validate_args:
return target_accept_prob
with tf.control_dependencies([
tf.compat.v1.assert_positive(
target_accept_prob, message='`target_accept_prob` must b... | [
"Validates",
"that",
"target_accept_prob",
"is",
"in",
"(",
"0",
"1",
")",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/simple_step_size_adaptation.py#L422-L434 | [
"def",
"_maybe_validate_target_accept_prob",
"(",
"target_accept_prob",
",",
"validate_args",
")",
":",
"if",
"not",
"validate_args",
":",
"return",
"target_accept_prob",
"with",
"tf",
".",
"control_dependencies",
"(",
"[",
"tf",
".",
"compat",
".",
"v1",
".",
"as... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | default_exchange_proposed_fn | Default exchange proposal function, for replica exchange MC.
With probability `prob_exchange` propose combinations of replica for exchange.
When exchanging, create combinations of adjacent replicas in
[Replica Exchange Monte Carlo](
https://en.wikipedia.org/wiki/Parallel_tempering)
```
exchange_fn = defau... | tensorflow_probability/python/mcmc/replica_exchange_mc.py | def default_exchange_proposed_fn(prob_exchange):
"""Default exchange proposal function, for replica exchange MC.
With probability `prob_exchange` propose combinations of replica for exchange.
When exchanging, create combinations of adjacent replicas in
[Replica Exchange Monte Carlo](
https://en.wikipedia.org... | def default_exchange_proposed_fn(prob_exchange):
"""Default exchange proposal function, for replica exchange MC.
With probability `prob_exchange` propose combinations of replica for exchange.
When exchanging, create combinations of adjacent replicas in
[Replica Exchange Monte Carlo](
https://en.wikipedia.org... | [
"Default",
"exchange",
"proposal",
"function",
"for",
"replica",
"exchange",
"MC",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/replica_exchange_mc.py#L49-L109 | [
"def",
"default_exchange_proposed_fn",
"(",
"prob_exchange",
")",
":",
"def",
"default_exchange_proposed_fn_",
"(",
"num_replica",
",",
"seed",
"=",
"None",
")",
":",
"\"\"\"Default function for `exchange_proposed_fn` of `kernel`.\"\"\"",
"seed_stream",
"=",
"distributions",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _get_field | field_name from kernel_results or kernel_results.accepted_results. | tensorflow_probability/python/mcmc/replica_exchange_mc.py | def _get_field(kernel_results, field_name):
"""field_name from kernel_results or kernel_results.accepted_results."""
if hasattr(kernel_results, field_name):
return getattr(kernel_results, field_name)
if hasattr(kernel_results, 'accepted_results'):
return getattr(kernel_results.accepted_results, field_name... | def _get_field(kernel_results, field_name):
"""field_name from kernel_results or kernel_results.accepted_results."""
if hasattr(kernel_results, field_name):
return getattr(kernel_results, field_name)
if hasattr(kernel_results, 'accepted_results'):
return getattr(kernel_results.accepted_results, field_name... | [
"field_name",
"from",
"kernel_results",
"or",
"kernel_results",
".",
"accepted_results",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/replica_exchange_mc.py#L569-L575 | [
"def",
"_get_field",
"(",
"kernel_results",
",",
"field_name",
")",
":",
"if",
"hasattr",
"(",
"kernel_results",
",",
"field_name",
")",
":",
"return",
"getattr",
"(",
"kernel_results",
",",
"field_name",
")",
"if",
"hasattr",
"(",
"kernel_results",
",",
"'acc... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | ReplicaExchangeMC.one_step | Takes one step of the TransitionKernel.
Args:
current_state: `Tensor` or Python `list` of `Tensor`s representing the
current state(s) of the Markov chain(s).
previous_kernel_results: A (possibly nested) `tuple`, `namedtuple` or
`list` of `Tensor`s representing internal calculations made... | tensorflow_probability/python/mcmc/replica_exchange_mc.py | def one_step(self, current_state, previous_kernel_results):
"""Takes one step of the TransitionKernel.
Args:
current_state: `Tensor` or Python `list` of `Tensor`s representing the
current state(s) of the Markov chain(s).
previous_kernel_results: A (possibly nested) `tuple`, `namedtuple` or
... | def one_step(self, current_state, previous_kernel_results):
"""Takes one step of the TransitionKernel.
Args:
current_state: `Tensor` or Python `list` of `Tensor`s representing the
current state(s) of the Markov chain(s).
previous_kernel_results: A (possibly nested) `tuple`, `namedtuple` or
... | [
"Takes",
"one",
"step",
"of",
"the",
"TransitionKernel",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/replica_exchange_mc.py#L316-L417 | [
"def",
"one_step",
"(",
"self",
",",
"current_state",
",",
"previous_kernel_results",
")",
":",
"# Key difficulty: The type of exchanges differs from one call to the",
"# next...even the number of exchanges can differ.",
"# As a result, exchanges must happen dynamically, in while loops.",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | ReplicaExchangeMC._get_exchanged_states | Get list of TensorArrays holding exchanged states, and zeros. | tensorflow_probability/python/mcmc/replica_exchange_mc.py | def _get_exchanged_states(self, old_states, exchange_proposed,
exchange_proposed_n, sampled_replica_states,
sampled_replica_results):
"""Get list of TensorArrays holding exchanged states, and zeros."""
with tf.compat.v1.name_scope('get_exchanged_states'):
... | def _get_exchanged_states(self, old_states, exchange_proposed,
exchange_proposed_n, sampled_replica_states,
sampled_replica_results):
"""Get list of TensorArrays holding exchanged states, and zeros."""
with tf.compat.v1.name_scope('get_exchanged_states'):
... | [
"Get",
"list",
"of",
"TensorArrays",
"holding",
"exchanged",
"states",
"and",
"zeros",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/replica_exchange_mc.py#L419-L498 | [
"def",
"_get_exchanged_states",
"(",
"self",
",",
"old_states",
",",
"exchange_proposed",
",",
"exchange_proposed_n",
",",
"sampled_replica_states",
",",
"sampled_replica_results",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"'get_excha... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | ReplicaExchangeMC.bootstrap_results | Returns an object with the same type as returned by `one_step`.
Args:
init_state: `Tensor` or Python `list` of `Tensor`s representing the
initial state(s) of the Markov chain(s).
Returns:
kernel_results: A (possibly nested) `tuple`, `namedtuple` or `list` of
`Tensor`s representing ... | tensorflow_probability/python/mcmc/replica_exchange_mc.py | def bootstrap_results(self, init_state):
"""Returns an object with the same type as returned by `one_step`.
Args:
init_state: `Tensor` or Python `list` of `Tensor`s representing the
initial state(s) of the Markov chain(s).
Returns:
kernel_results: A (possibly nested) `tuple`, `namedtup... | def bootstrap_results(self, init_state):
"""Returns an object with the same type as returned by `one_step`.
Args:
init_state: `Tensor` or Python `list` of `Tensor`s representing the
initial state(s) of the Markov chain(s).
Returns:
kernel_results: A (possibly nested) `tuple`, `namedtup... | [
"Returns",
"an",
"object",
"with",
"the",
"same",
"type",
"as",
"returned",
"by",
"one_step",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/replica_exchange_mc.py#L519-L556 | [
"def",
"bootstrap_results",
"(",
"self",
",",
"init_state",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"name",
"=",
"mcmc_util",
".",
"make_name",
"(",
"self",
".",
"name",
",",
"'remc'",
",",
"'bootstrap_results'",
")",
",... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | DirichletMultinomial._variance_scale_term | Helper to `_covariance` and `_variance` which computes a shared scale. | tensorflow_probability/python/distributions/dirichlet_multinomial.py | def _variance_scale_term(self):
"""Helper to `_covariance` and `_variance` which computes a shared scale."""
# Expand back the last dim so the shape of _variance_scale_term matches the
# shape of self.concentration.
c0 = self.total_concentration[..., tf.newaxis]
return tf.sqrt((1. + c0 / self.total_... | def _variance_scale_term(self):
"""Helper to `_covariance` and `_variance` which computes a shared scale."""
# Expand back the last dim so the shape of _variance_scale_term matches the
# shape of self.concentration.
c0 = self.total_concentration[..., tf.newaxis]
return tf.sqrt((1. + c0 / self.total_... | [
"Helper",
"to",
"_covariance",
"and",
"_variance",
"which",
"computes",
"a",
"shared",
"scale",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/dirichlet_multinomial.py#L322-L327 | [
"def",
"_variance_scale_term",
"(",
"self",
")",
":",
"# Expand back the last dim so the shape of _variance_scale_term matches the",
"# shape of self.concentration.",
"c0",
"=",
"self",
".",
"total_concentration",
"[",
"...",
",",
"tf",
".",
"newaxis",
"]",
"return",
"tf",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | DirichletMultinomial._maybe_assert_valid_concentration | Checks the validity of the concentration parameter. | tensorflow_probability/python/distributions/dirichlet_multinomial.py | def _maybe_assert_valid_concentration(self, concentration, validate_args):
"""Checks the validity of the concentration parameter."""
if not validate_args:
return concentration
concentration = distribution_util.embed_check_categorical_event_shape(
concentration)
return distribution_util.wit... | def _maybe_assert_valid_concentration(self, concentration, validate_args):
"""Checks the validity of the concentration parameter."""
if not validate_args:
return concentration
concentration = distribution_util.embed_check_categorical_event_shape(
concentration)
return distribution_util.wit... | [
"Checks",
"the",
"validity",
"of",
"the",
"concentration",
"parameter",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/dirichlet_multinomial.py#L329-L338 | [
"def",
"_maybe_assert_valid_concentration",
"(",
"self",
",",
"concentration",
",",
"validate_args",
")",
":",
"if",
"not",
"validate_args",
":",
"return",
"concentration",
"concentration",
"=",
"distribution_util",
".",
"embed_check_categorical_event_shape",
"(",
"concen... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | DirichletMultinomial._maybe_assert_valid_sample | Check counts for proper shape, values, then return tensor version. | tensorflow_probability/python/distributions/dirichlet_multinomial.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/dirichlet_multinomial.py#L340-L350 | [
"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 | forward_log_det_jacobian_fn | Makes a function which applies a list of Bijectors' `log_det_jacobian`s. | tensorflow_probability/python/mcmc/transformed_kernel.py | def forward_log_det_jacobian_fn(bijector):
"""Makes a function which applies a list of Bijectors' `log_det_jacobian`s."""
if not mcmc_util.is_list_like(bijector):
bijector = [bijector]
def fn(transformed_state_parts, event_ndims):
return sum([
b.forward_log_det_jacobian(sp, event_ndims=e)
... | def forward_log_det_jacobian_fn(bijector):
"""Makes a function which applies a list of Bijectors' `log_det_jacobian`s."""
if not mcmc_util.is_list_like(bijector):
bijector = [bijector]
def fn(transformed_state_parts, event_ndims):
return sum([
b.forward_log_det_jacobian(sp, event_ndims=e)
... | [
"Makes",
"a",
"function",
"which",
"applies",
"a",
"list",
"of",
"Bijectors",
"log_det_jacobian",
"s",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/transformed_kernel.py#L42-L53 | [
"def",
"forward_log_det_jacobian_fn",
"(",
"bijector",
")",
":",
"if",
"not",
"mcmc_util",
".",
"is_list_like",
"(",
"bijector",
")",
":",
"bijector",
"=",
"[",
"bijector",
"]",
"def",
"fn",
"(",
"transformed_state_parts",
",",
"event_ndims",
")",
":",
"return... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | forward_transform_fn | Makes a function which applies a list of Bijectors' `forward`s. | tensorflow_probability/python/mcmc/transformed_kernel.py | def forward_transform_fn(bijector):
"""Makes a function which applies a list of Bijectors' `forward`s."""
if not mcmc_util.is_list_like(bijector):
bijector = [bijector]
def fn(transformed_state_parts):
return [b.forward(sp) for b, sp in zip(bijector, transformed_state_parts)]
return fn | def forward_transform_fn(bijector):
"""Makes a function which applies a list of Bijectors' `forward`s."""
if not mcmc_util.is_list_like(bijector):
bijector = [bijector]
def fn(transformed_state_parts):
return [b.forward(sp) for b, sp in zip(bijector, transformed_state_parts)]
return fn | [
"Makes",
"a",
"function",
"which",
"applies",
"a",
"list",
"of",
"Bijectors",
"forward",
"s",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/transformed_kernel.py#L56-L64 | [
"def",
"forward_transform_fn",
"(",
"bijector",
")",
":",
"if",
"not",
"mcmc_util",
".",
"is_list_like",
"(",
"bijector",
")",
":",
"bijector",
"=",
"[",
"bijector",
"]",
"def",
"fn",
"(",
"transformed_state_parts",
")",
":",
"return",
"[",
"b",
".",
"forw... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | inverse_transform_fn | Makes a function which applies a list of Bijectors' `inverse`s. | tensorflow_probability/python/mcmc/transformed_kernel.py | def inverse_transform_fn(bijector):
"""Makes a function which applies a list of Bijectors' `inverse`s."""
if not mcmc_util.is_list_like(bijector):
bijector = [bijector]
def fn(state_parts):
return [b.inverse(sp)
for b, sp in zip(bijector, state_parts)]
return fn | def inverse_transform_fn(bijector):
"""Makes a function which applies a list of Bijectors' `inverse`s."""
if not mcmc_util.is_list_like(bijector):
bijector = [bijector]
def fn(state_parts):
return [b.inverse(sp)
for b, sp in zip(bijector, state_parts)]
return fn | [
"Makes",
"a",
"function",
"which",
"applies",
"a",
"list",
"of",
"Bijectors",
"inverse",
"s",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/transformed_kernel.py#L67-L74 | [
"def",
"inverse_transform_fn",
"(",
"bijector",
")",
":",
"if",
"not",
"mcmc_util",
".",
"is_list_like",
"(",
"bijector",
")",
":",
"bijector",
"=",
"[",
"bijector",
"]",
"def",
"fn",
"(",
"state_parts",
")",
":",
"return",
"[",
"b",
".",
"inverse",
"(",... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | TransformedTransitionKernel.one_step | Runs one iteration of the Transformed Kernel.
Args:
current_state: `Tensor` or Python `list` of `Tensor`s
representing the current state(s) of the Markov chain(s),
_after_ application of `bijector.forward`. The first `r`
dimensions index independent chains,
`r = tf.rank(target... | tensorflow_probability/python/mcmc/transformed_kernel.py | def one_step(self, current_state, previous_kernel_results):
"""Runs one iteration of the Transformed Kernel.
Args:
current_state: `Tensor` or Python `list` of `Tensor`s
representing the current state(s) of the Markov chain(s),
_after_ application of `bijector.forward`. The first `r`
... | def one_step(self, current_state, previous_kernel_results):
"""Runs one iteration of the Transformed Kernel.
Args:
current_state: `Tensor` or Python `list` of `Tensor`s
representing the current state(s) of the Markov chain(s),
_after_ application of `bijector.forward`. The first `r`
... | [
"Runs",
"one",
"iteration",
"of",
"the",
"Transformed",
"Kernel",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/transformed_kernel.py#L230-L273 | [
"def",
"one_step",
"(",
"self",
",",
"current_state",
",",
"previous_kernel_results",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"name",
"=",
"mcmc_util",
".",
"make_name",
"(",
"self",
".",
"name",
",",
"'transformed_kernel'",... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | TransformedTransitionKernel.bootstrap_results | Returns an object with the same type as returned by `one_step`.
Unlike other `TransitionKernel`s,
`TransformedTransitionKernel.bootstrap_results` has the option of
initializing the `TransformedTransitionKernelResults` from either an initial
state, eg, requiring computing `bijector.inverse(init_state)`,... | tensorflow_probability/python/mcmc/transformed_kernel.py | def bootstrap_results(self, init_state=None, transformed_init_state=None):
"""Returns an object with the same type as returned by `one_step`.
Unlike other `TransitionKernel`s,
`TransformedTransitionKernel.bootstrap_results` has the option of
initializing the `TransformedTransitionKernelResults` from ei... | def bootstrap_results(self, init_state=None, transformed_init_state=None):
"""Returns an object with the same type as returned by `one_step`.
Unlike other `TransitionKernel`s,
`TransformedTransitionKernel.bootstrap_results` has the option of
initializing the `TransformedTransitionKernelResults` from ei... | [
"Returns",
"an",
"object",
"with",
"the",
"same",
"type",
"as",
"returned",
"by",
"one_step",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/transformed_kernel.py#L275-L347 | [
"def",
"bootstrap_results",
"(",
"self",
",",
"init_state",
"=",
"None",
",",
"transformed_init_state",
"=",
"None",
")",
":",
"if",
"(",
"init_state",
"is",
"None",
")",
"==",
"(",
"transformed_init_state",
"is",
"None",
")",
":",
"raise",
"ValueError",
"("... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | val_where | Like tf.where but works on namedtuples. | tensorflow_probability/python/optimizer/linesearch/internal/hager_zhang_lib.py | def val_where(cond, tval, fval):
"""Like tf.where but works on namedtuples."""
if isinstance(tval, tf.Tensor):
return tf.where(cond, tval, fval)
elif isinstance(tval, tuple):
cls = type(tval)
return cls(*(val_where(cond, t, f) for t, f in zip(tval, fval)))
else:
raise Exception(TypeError) | def val_where(cond, tval, fval):
"""Like tf.where but works on namedtuples."""
if isinstance(tval, tf.Tensor):
return tf.where(cond, tval, fval)
elif isinstance(tval, tuple):
cls = type(tval)
return cls(*(val_where(cond, t, f) for t, f in zip(tval, fval)))
else:
raise Exception(TypeError) | [
"Like",
"tf",
".",
"where",
"but",
"works",
"on",
"namedtuples",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/linesearch/internal/hager_zhang_lib.py#L39-L47 | [
"def",
"val_where",
"(",
"cond",
",",
"tval",
",",
"fval",
")",
":",
"if",
"isinstance",
"(",
"tval",
",",
"tf",
".",
"Tensor",
")",
":",
"return",
"tf",
".",
"where",
"(",
"cond",
",",
"tval",
",",
"fval",
")",
"elif",
"isinstance",
"(",
"tval",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | secant2 | Performs the secant square procedure of Hager Zhang.
Given an interval that brackets a root, this procedure performs an update of
both end points using two intermediate points generated using the secant
interpolation. For details see the steps S1-S4 in [Hager and Zhang (2006)][2].
The interval [a, b] must sat... | tensorflow_probability/python/optimizer/linesearch/internal/hager_zhang_lib.py | def secant2(value_and_gradients_function,
val_0,
search_interval,
f_lim,
sufficient_decrease_param=0.1,
curvature_param=0.9,
name=None):
"""Performs the secant square procedure of Hager Zhang.
Given an interval that brackets a root, this proce... | def secant2(value_and_gradients_function,
val_0,
search_interval,
f_lim,
sufficient_decrease_param=0.1,
curvature_param=0.9,
name=None):
"""Performs the secant square procedure of Hager Zhang.
Given an interval that brackets a root, this proce... | [
"Performs",
"the",
"secant",
"square",
"procedure",
"of",
"Hager",
"Zhang",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/linesearch/internal/hager_zhang_lib.py#L60-L174 | [
"def",
"secant2",
"(",
"value_and_gradients_function",
",",
"val_0",
",",
"search_interval",
",",
"f_lim",
",",
"sufficient_decrease_param",
"=",
"0.1",
",",
"curvature_param",
"=",
"0.9",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _secant2_inner | Helper function for secant square. | tensorflow_probability/python/optimizer/linesearch/internal/hager_zhang_lib.py | def _secant2_inner(value_and_gradients_function,
initial_args,
val_0,
val_c,
f_lim,
sufficient_decrease_param,
curvature_param):
"""Helper function for secant square."""
# Apply the `update` function on... | def _secant2_inner(value_and_gradients_function,
initial_args,
val_0,
val_c,
f_lim,
sufficient_decrease_param,
curvature_param):
"""Helper function for secant square."""
# Apply the `update` function on... | [
"Helper",
"function",
"for",
"secant",
"square",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/linesearch/internal/hager_zhang_lib.py#L177-L238 | [
"def",
"_secant2_inner",
"(",
"value_and_gradients_function",
",",
"initial_args",
",",
"val_0",
",",
"val_c",
",",
"f_lim",
",",
"sufficient_decrease_param",
",",
"curvature_param",
")",
":",
"# Apply the `update` function on active branch members to squeeze their",
"# bracket... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _secant2_inner_update | Helper function for secant-square step. | tensorflow_probability/python/optimizer/linesearch/internal/hager_zhang_lib.py | def _secant2_inner_update(value_and_gradients_function,
initial_args,
val_0,
val_c,
f_lim,
sufficient_decrease_param,
curvature_param):
"""Helper function for sec... | def _secant2_inner_update(value_and_gradients_function,
initial_args,
val_0,
val_c,
f_lim,
sufficient_decrease_param,
curvature_param):
"""Helper function for sec... | [
"Helper",
"function",
"for",
"secant",
"-",
"square",
"step",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/linesearch/internal/hager_zhang_lib.py#L241-L288 | [
"def",
"_secant2_inner_update",
"(",
"value_and_gradients_function",
",",
"initial_args",
",",
"val_0",
",",
"val_c",
",",
"f_lim",
",",
"sufficient_decrease_param",
",",
"curvature_param",
")",
":",
"# Fail if `val_c` is no longer finite.",
"new_failed",
"=",
"initial_args... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | update | Squeezes a bracketing interval containing the minimum.
Given an interval which brackets a minimum and a point in that interval,
finds a smaller nested interval which also brackets the minimum. If the
supplied point does not lie in the bracketing interval, the current interval
is returned.
The following desc... | tensorflow_probability/python/optimizer/linesearch/internal/hager_zhang_lib.py | def update(value_and_gradients_function, val_left, val_right, val_trial, f_lim,
active=None):
"""Squeezes a bracketing interval containing the minimum.
Given an interval which brackets a minimum and a point in that interval,
finds a smaller nested interval which also brackets the minimum. If the
sup... | def update(value_and_gradients_function, val_left, val_right, val_trial, f_lim,
active=None):
"""Squeezes a bracketing interval containing the minimum.
Given an interval which brackets a minimum and a point in that interval,
finds a smaller nested interval which also brackets the minimum. If the
sup... | [
"Squeezes",
"a",
"bracketing",
"interval",
"containing",
"the",
"minimum",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/linesearch/internal/hager_zhang_lib.py#L301-L423 | [
"def",
"update",
"(",
"value_and_gradients_function",
",",
"val_left",
",",
"val_right",
",",
"val_trial",
",",
"f_lim",
",",
"active",
"=",
"None",
")",
":",
"# We should only update if the trial point is within the interval.",
"within_range",
"=",
"(",
"val_left",
"."... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | bracket | Brackets the minimum given an initial starting point.
Applies the Hager Zhang bracketing algorithm to find an interval containing
a region with points satisfying Wolfe conditions. Uses the supplied initial
step size 'c', the right end point of the provided search interval, to find
such an interval. The only co... | tensorflow_probability/python/optimizer/linesearch/internal/hager_zhang_lib.py | def bracket(value_and_gradients_function,
search_interval,
f_lim,
max_iterations,
expansion_param=5.0):
"""Brackets the minimum given an initial starting point.
Applies the Hager Zhang bracketing algorithm to find an interval containing
a region with points satisfy... | def bracket(value_and_gradients_function,
search_interval,
f_lim,
max_iterations,
expansion_param=5.0):
"""Brackets the minimum given an initial starting point.
Applies the Hager Zhang bracketing algorithm to find an interval containing
a region with points satisfy... | [
"Brackets",
"the",
"minimum",
"given",
"an",
"initial",
"starting",
"point",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/linesearch/internal/hager_zhang_lib.py#L426-L545 | [
"def",
"bracket",
"(",
"value_and_gradients_function",
",",
"search_interval",
",",
"f_lim",
",",
"max_iterations",
",",
"expansion_param",
"=",
"5.0",
")",
":",
"already_stopped",
"=",
"search_interval",
".",
"failed",
"|",
"search_interval",
".",
"converged",
"# I... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | bisect | Bisects an interval and updates to satisfy opposite slope conditions.
Corresponds to the step U3 in [Hager and Zhang (2006)][2].
Args:
value_and_gradients_function: A Python callable that accepts a real scalar
tensor and returns a namedtuple containing the value filed `f` of the
function and its d... | tensorflow_probability/python/optimizer/linesearch/internal/hager_zhang_lib.py | def bisect(value_and_gradients_function,
initial_left,
initial_right,
f_lim):
"""Bisects an interval and updates to satisfy opposite slope conditions.
Corresponds to the step U3 in [Hager and Zhang (2006)][2].
Args:
value_and_gradients_function: A Python callable that accept... | def bisect(value_and_gradients_function,
initial_left,
initial_right,
f_lim):
"""Bisects an interval and updates to satisfy opposite slope conditions.
Corresponds to the step U3 in [Hager and Zhang (2006)][2].
Args:
value_and_gradients_function: A Python callable that accept... | [
"Bisects",
"an",
"interval",
"and",
"updates",
"to",
"satisfy",
"opposite",
"slope",
"conditions",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/linesearch/internal/hager_zhang_lib.py#L548-L596 | [
"def",
"bisect",
"(",
"value_and_gradients_function",
",",
"initial_left",
",",
"initial_right",
",",
"f_lim",
")",
":",
"failed",
"=",
"~",
"is_finite",
"(",
"initial_left",
",",
"initial_right",
")",
"needs_bisect",
"=",
"(",
"initial_right",
".",
"df",
"<",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _bisect | Actual implementation of bisect given initial_args in a _BracketResult. | tensorflow_probability/python/optimizer/linesearch/internal/hager_zhang_lib.py | def _bisect(value_and_gradients_function, initial_args, f_lim):
"""Actual implementation of bisect given initial_args in a _BracketResult."""
def _loop_cond(curr):
# TODO(b/112524024): Also take into account max_iterations.
return ~tf.reduce_all(input_tensor=curr.stopped)
def _loop_body(curr):
"""Nar... | def _bisect(value_and_gradients_function, initial_args, f_lim):
"""Actual implementation of bisect given initial_args in a _BracketResult."""
def _loop_cond(curr):
# TODO(b/112524024): Also take into account max_iterations.
return ~tf.reduce_all(input_tensor=curr.stopped)
def _loop_body(curr):
"""Nar... | [
"Actual",
"implementation",
"of",
"bisect",
"given",
"initial_args",
"in",
"a",
"_BracketResult",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/linesearch/internal/hager_zhang_lib.py#L599-L643 | [
"def",
"_bisect",
"(",
"value_and_gradients_function",
",",
"initial_args",
",",
"f_lim",
")",
":",
"def",
"_loop_cond",
"(",
"curr",
")",
":",
"# TODO(b/112524024): Also take into account max_iterations.",
"return",
"~",
"tf",
".",
"reduce_all",
"(",
"input_tensor",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | is_finite | Checks if the supplied values are finite.
Args:
val_1: A namedtuple instance with the function value and derivative,
as returned e.g. by value_and_gradients_function evaluations.
val_2: (Optional) A namedtuple instance with the function value and
derivative, as returned e.g. by value_and_gradient... | tensorflow_probability/python/optimizer/linesearch/internal/hager_zhang_lib.py | def is_finite(val_1, val_2=None):
"""Checks if the supplied values are finite.
Args:
val_1: A namedtuple instance with the function value and derivative,
as returned e.g. by value_and_gradients_function evaluations.
val_2: (Optional) A namedtuple instance with the function value and
derivative,... | def is_finite(val_1, val_2=None):
"""Checks if the supplied values are finite.
Args:
val_1: A namedtuple instance with the function value and derivative,
as returned e.g. by value_and_gradients_function evaluations.
val_2: (Optional) A namedtuple instance with the function value and
derivative,... | [
"Checks",
"if",
"the",
"supplied",
"values",
"are",
"finite",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/linesearch/internal/hager_zhang_lib.py#L646-L663 | [
"def",
"is_finite",
"(",
"val_1",
",",
"val_2",
"=",
"None",
")",
":",
"val_1_finite",
"=",
"tf",
".",
"math",
".",
"is_finite",
"(",
"val_1",
".",
"f",
")",
"&",
"tf",
".",
"math",
".",
"is_finite",
"(",
"val_1",
".",
"df",
")",
"if",
"val_2",
"... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _satisfies_wolfe | Checks whether the Wolfe or approx Wolfe conditions are satisfied.
The Wolfe conditions are a set of stopping criteria for an inexact line search
algorithm. Let f(a) be the function value along the search direction and
df(a) the derivative along the search direction evaluated a distance 'a'.
Here 'a' is the di... | tensorflow_probability/python/optimizer/linesearch/internal/hager_zhang_lib.py | def _satisfies_wolfe(val_0,
val_c,
f_lim,
sufficient_decrease_param,
curvature_param):
"""Checks whether the Wolfe or approx Wolfe conditions are satisfied.
The Wolfe conditions are a set of stopping criteria for an inexact line se... | def _satisfies_wolfe(val_0,
val_c,
f_lim,
sufficient_decrease_param,
curvature_param):
"""Checks whether the Wolfe or approx Wolfe conditions are satisfied.
The Wolfe conditions are a set of stopping criteria for an inexact line se... | [
"Checks",
"whether",
"the",
"Wolfe",
"or",
"approx",
"Wolfe",
"conditions",
"are",
"satisfied",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/linesearch/internal/hager_zhang_lib.py#L666-L730 | [
"def",
"_satisfies_wolfe",
"(",
"val_0",
",",
"val_c",
",",
"f_lim",
",",
"sufficient_decrease_param",
",",
"curvature_param",
")",
":",
"exact_wolfe_suff_dec",
"=",
"(",
"sufficient_decrease_param",
"*",
"val_0",
".",
"df",
">=",
"(",
"val_c",
".",
"f",
"-",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _secant | Returns the secant interpolation for the minimum.
The secant method is a technique for finding roots of nonlinear functions.
When finding the minimum, one applies the secant method to the derivative
of the function.
For an arbitrary function and a bounding interval, the secant approximation
can produce the n... | tensorflow_probability/python/optimizer/linesearch/internal/hager_zhang_lib.py | def _secant(val_a, val_b):
"""Returns the secant interpolation for the minimum.
The secant method is a technique for finding roots of nonlinear functions.
When finding the minimum, one applies the secant method to the derivative
of the function.
For an arbitrary function and a bounding interval, the secant a... | def _secant(val_a, val_b):
"""Returns the secant interpolation for the minimum.
The secant method is a technique for finding roots of nonlinear functions.
When finding the minimum, one applies the secant method to the derivative
of the function.
For an arbitrary function and a bounding interval, the secant a... | [
"Returns",
"the",
"secant",
"interpolation",
"for",
"the",
"minimum",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/linesearch/internal/hager_zhang_lib.py#L733-L756 | [
"def",
"_secant",
"(",
"val_a",
",",
"val_b",
")",
":",
"return",
"(",
"val_a",
".",
"x",
"*",
"val_b",
".",
"df",
"-",
"val_b",
".",
"x",
"*",
"val_a",
".",
"df",
")",
"/",
"(",
"val_b",
".",
"df",
"-",
"val_a",
".",
"df",
")"
] | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | make_simple_step_size_update_policy | Create a function implementing a step-size update policy.
The simple policy increases or decreases the `step_size_var` based on the
average of `exp(minimum(0., log_accept_ratio))`. It is based on
[Section 4.2 of Andrieu and Thoms (2008)](
https://people.eecs.berkeley.edu/~jordan/sail/readings/andrieu-thoms.pdf... | tensorflow_probability/python/mcmc/hmc.py | def make_simple_step_size_update_policy(num_adaptation_steps,
target_rate=0.75,
decrement_multiplier=0.01,
increment_multiplier=0.01,
step_counter=None):
"""C... | def make_simple_step_size_update_policy(num_adaptation_steps,
target_rate=0.75,
decrement_multiplier=0.01,
increment_multiplier=0.01,
step_counter=None):
"""C... | [
"Create",
"a",
"function",
"implementing",
"a",
"step",
"-",
"size",
"update",
"policy",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/hmc.py#L60-L162 | [
"def",
"make_simple_step_size_update_policy",
"(",
"num_adaptation_steps",
",",
"target_rate",
"=",
"0.75",
",",
"decrement_multiplier",
"=",
"0.01",
",",
"increment_multiplier",
"=",
"0.01",
",",
"step_counter",
"=",
"None",
")",
":",
"if",
"step_counter",
"is",
"N... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _leapfrog_integrator_one_step | Applies `num_leapfrog_steps` of the leapfrog integrator.
Assumes a simple quadratic kinetic energy function: `0.5 ||momentum||**2`.
#### Examples:
##### Simple quadratic potential.
```python
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import tensorflow as tf
from tensorfl... | tensorflow_probability/python/mcmc/hmc.py | def _leapfrog_integrator_one_step(
target_log_prob_fn,
independent_chain_ndims,
step_sizes,
current_momentum_parts,
current_state_parts,
current_target_log_prob,
current_target_log_prob_grad_parts,
state_gradients_are_stopped=False,
name=None):
"""Applies `num_leapfrog_steps` of th... | def _leapfrog_integrator_one_step(
target_log_prob_fn,
independent_chain_ndims,
step_sizes,
current_momentum_parts,
current_state_parts,
current_target_log_prob,
current_target_log_prob_grad_parts,
state_gradients_are_stopped=False,
name=None):
"""Applies `num_leapfrog_steps` of th... | [
"Applies",
"num_leapfrog_steps",
"of",
"the",
"leapfrog",
"integrator",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/hmc.py#L820-L1049 | [
"def",
"_leapfrog_integrator_one_step",
"(",
"target_log_prob_fn",
",",
"independent_chain_ndims",
",",
"step_sizes",
",",
"current_momentum_parts",
",",
"current_state_parts",
",",
"current_target_log_prob",
",",
"current_target_log_prob_grad_parts",
",",
"state_gradients_are_stop... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _compute_log_acceptance_correction | Helper to `kernel` which computes the log acceptance-correction.
A sufficient but not necessary condition for the existence of a stationary
distribution, `p(x)`, is "detailed balance", i.e.:
```none
p(x'|x) p(x) = p(x|x') p(x')
```
In the Metropolis-Hastings algorithm, a state is proposed according to
... | tensorflow_probability/python/mcmc/hmc.py | def _compute_log_acceptance_correction(current_momentums,
proposed_momentums,
independent_chain_ndims,
name=None):
"""Helper to `kernel` which computes the log acceptance-correction.
A sufficient bu... | def _compute_log_acceptance_correction(current_momentums,
proposed_momentums,
independent_chain_ndims,
name=None):
"""Helper to `kernel` which computes the log acceptance-correction.
A sufficient bu... | [
"Helper",
"to",
"kernel",
"which",
"computes",
"the",
"log",
"acceptance",
"-",
"correction",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/hmc.py#L1052-L1145 | [
"def",
"_compute_log_acceptance_correction",
"(",
"current_momentums",
",",
"proposed_momentums",
",",
"independent_chain_ndims",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"name",
",",
"'compute_log_acceptanc... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _prepare_args | Helper which processes input args to meet list-like assumptions. | tensorflow_probability/python/mcmc/hmc.py | def _prepare_args(target_log_prob_fn,
state,
step_size,
target_log_prob=None,
grads_target_log_prob=None,
maybe_expand=False,
state_gradients_are_stopped=False):
"""Helper which processes input args to meet lis... | def _prepare_args(target_log_prob_fn,
state,
step_size,
target_log_prob=None,
grads_target_log_prob=None,
maybe_expand=False,
state_gradients_are_stopped=False):
"""Helper which processes input args to meet lis... | [
"Helper",
"which",
"processes",
"input",
"args",
"to",
"meet",
"list",
"-",
"like",
"assumptions",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/hmc.py#L1148-L1186 | [
"def",
"_prepare_args",
"(",
"target_log_prob_fn",
",",
"state",
",",
"step_size",
",",
"target_log_prob",
"=",
"None",
",",
"grads_target_log_prob",
"=",
"None",
",",
"maybe_expand",
"=",
"False",
",",
"state_gradients_are_stopped",
"=",
"False",
")",
":",
"state... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _log_sum_sq | Computes log(sum(x**2)). | tensorflow_probability/python/mcmc/hmc.py | def _log_sum_sq(x, axis=None):
"""Computes log(sum(x**2))."""
return tf.reduce_logsumexp(
input_tensor=2. * tf.math.log(tf.abs(x)), axis=axis) | def _log_sum_sq(x, axis=None):
"""Computes log(sum(x**2))."""
return tf.reduce_logsumexp(
input_tensor=2. * tf.math.log(tf.abs(x)), axis=axis) | [
"Computes",
"log",
"(",
"sum",
"(",
"x",
"**",
"2",
"))",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/hmc.py#L1189-L1192 | [
"def",
"_log_sum_sq",
"(",
"x",
",",
"axis",
"=",
"None",
")",
":",
"return",
"tf",
".",
"reduce_logsumexp",
"(",
"input_tensor",
"=",
"2.",
"*",
"tf",
".",
"math",
".",
"log",
"(",
"tf",
".",
"abs",
"(",
"x",
")",
")",
",",
"axis",
"=",
"axis",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | HamiltonianMonteCarlo.one_step | Runs one iteration of Hamiltonian Monte Carlo.
Args:
current_state: `Tensor` or Python `list` of `Tensor`s representing the
current state(s) of the Markov chain(s). The first `r` dimensions index
independent chains, `r = tf.rank(target_log_prob_fn(*current_state))`.
previous_kernel_resu... | tensorflow_probability/python/mcmc/hmc.py | def one_step(self, current_state, previous_kernel_results):
"""Runs one iteration of Hamiltonian Monte Carlo.
Args:
current_state: `Tensor` or Python `list` of `Tensor`s representing the
current state(s) of the Markov chain(s). The first `r` dimensions index
independent chains, `r = tf.ra... | def one_step(self, current_state, previous_kernel_results):
"""Runs one iteration of Hamiltonian Monte Carlo.
Args:
current_state: `Tensor` or Python `list` of `Tensor`s representing the
current state(s) of the Markov chain(s). The first `r` dimensions index
independent chains, `r = tf.ra... | [
"Runs",
"one",
"iteration",
"of",
"Hamiltonian",
"Monte",
"Carlo",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/hmc.py#L516-L554 | [
"def",
"one_step",
"(",
"self",
",",
"current_state",
",",
"previous_kernel_results",
")",
":",
"previous_step_size_assign",
"=",
"(",
"[",
"]",
"if",
"self",
".",
"step_size_update_fn",
"is",
"None",
"else",
"(",
"previous_kernel_results",
".",
"extra",
".",
"s... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | HamiltonianMonteCarlo.bootstrap_results | Creates initial `previous_kernel_results` using a supplied `state`. | tensorflow_probability/python/mcmc/hmc.py | def bootstrap_results(self, init_state):
"""Creates initial `previous_kernel_results` using a supplied `state`."""
kernel_results = self._impl.bootstrap_results(init_state)
if self.step_size_update_fn is not None:
step_size_assign = self.step_size_update_fn(self.step_size, None) # pylint: disable=not... | def bootstrap_results(self, init_state):
"""Creates initial `previous_kernel_results` using a supplied `state`."""
kernel_results = self._impl.bootstrap_results(init_state)
if self.step_size_update_fn is not None:
step_size_assign = self.step_size_update_fn(self.step_size, None) # pylint: disable=not... | [
"Creates",
"initial",
"previous_kernel_results",
"using",
"a",
"supplied",
"state",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/hmc.py#L556-L564 | [
"def",
"bootstrap_results",
"(",
"self",
",",
"init_state",
")",
":",
"kernel_results",
"=",
"self",
".",
"_impl",
".",
"bootstrap_results",
"(",
"init_state",
")",
"if",
"self",
".",
"step_size_update_fn",
"is",
"not",
"None",
":",
"step_size_assign",
"=",
"s... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | bayesian_resnet | Constructs a ResNet18 model.
Args:
input_shape: A `tuple` indicating the Tensor shape.
num_classes: `int` representing the number of class labels.
kernel_posterior_scale_mean: Python `int` number for the kernel
posterior's scale (log variance) mean. The smaller the mean the closer
is the init... | tensorflow_probability/examples/models/bayesian_resnet.py | def bayesian_resnet(input_shape,
num_classes=10,
kernel_posterior_scale_mean=-9.0,
kernel_posterior_scale_stddev=0.1,
kernel_posterior_scale_constraint=0.2):
"""Constructs a ResNet18 model.
Args:
input_shape: A `tuple` indicating t... | def bayesian_resnet(input_shape,
num_classes=10,
kernel_posterior_scale_mean=-9.0,
kernel_posterior_scale_stddev=0.1,
kernel_posterior_scale_constraint=0.2):
"""Constructs a ResNet18 model.
Args:
input_shape: A `tuple` indicating t... | [
"Constructs",
"a",
"ResNet18",
"model",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/models/bayesian_resnet.py#L25-L92 | [
"def",
"bayesian_resnet",
"(",
"input_shape",
",",
"num_classes",
"=",
"10",
",",
"kernel_posterior_scale_mean",
"=",
"-",
"9.0",
",",
"kernel_posterior_scale_stddev",
"=",
"0.1",
",",
"kernel_posterior_scale_constraint",
"=",
"0.2",
")",
":",
"filters",
"=",
"[",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _resnet_block | Network block for ResNet. | tensorflow_probability/examples/models/bayesian_resnet.py | def _resnet_block(x, filters, kernel, stride, kernel_posterior_fn):
"""Network block for ResNet."""
x = tf.keras.layers.BatchNormalization()(x)
x = tf.keras.layers.Activation('relu')(x)
if stride != 1 or filters != x.shape[1]:
shortcut = _projection_shortcut(x, filters, stride, kernel_posterior_fn)
else:... | def _resnet_block(x, filters, kernel, stride, kernel_posterior_fn):
"""Network block for ResNet."""
x = tf.keras.layers.BatchNormalization()(x)
x = tf.keras.layers.Activation('relu')(x)
if stride != 1 or filters != x.shape[1]:
shortcut = _projection_shortcut(x, filters, stride, kernel_posterior_fn)
else:... | [
"Network",
"block",
"for",
"ResNet",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/models/bayesian_resnet.py#L95-L121 | [
"def",
"_resnet_block",
"(",
"x",
",",
"filters",
",",
"kernel",
",",
"stride",
",",
"kernel_posterior_fn",
")",
":",
"x",
"=",
"tf",
".",
"keras",
".",
"layers",
".",
"BatchNormalization",
"(",
")",
"(",
"x",
")",
"x",
"=",
"tf",
".",
"keras",
".",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | make_encoder | Create the encoder function.
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:
encoder: A `callable` mapping a bag-of-words `Tensor` to a
`tfd.Distribution` instance over topics. | tensorflow_probability/examples/latent_dirichlet_allocation_distributions.py | def make_encoder(activation, num_topics, layer_sizes):
"""Create the encoder function.
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:
encoder: A `callable` mapping a bag-of-words `Tensor` ... | def make_encoder(activation, num_topics, layer_sizes):
"""Create the encoder function.
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:
encoder: A `callable` mapping a bag-of-words `Tensor` ... | [
"Create",
"the",
"encoder",
"function",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/latent_dirichlet_allocation_distributions.py#L164-L194 | [
"def",
"make_encoder",
"(",
"activation",
",",
"num_topics",
",",
"layer_sizes",
")",
":",
"encoder_net",
"=",
"tf",
".",
"keras",
".",
"Sequential",
"(",
")",
"for",
"num_hidden_units",
"in",
"layer_sizes",
":",
"encoder_net",
".",
"add",
"(",
"tf",
".",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | make_decoder | Create the decoder function.
Args:
num_topics: The number of topics.
num_words: The number of words.
Returns:
decoder: A `callable` mapping a `Tensor` of encodings to a
`tfd.Distribution` instance over words. | tensorflow_probability/examples/latent_dirichlet_allocation_distributions.py | def make_decoder(num_topics, num_words):
"""Create the decoder function.
Args:
num_topics: The number of topics.
num_words: The number of words.
Returns:
decoder: A `callable` mapping a `Tensor` of encodings to a
`tfd.Distribution` instance over words.
"""
topics_words_logits = tf.compat.v... | def make_decoder(num_topics, num_words):
"""Create the decoder function.
Args:
num_topics: The number of topics.
num_words: The number of words.
Returns:
decoder: A `callable` mapping a `Tensor` of encodings to a
`tfd.Distribution` instance over words.
"""
topics_words_logits = tf.compat.v... | [
"Create",
"the",
"decoder",
"function",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/latent_dirichlet_allocation_distributions.py#L197-L222 | [
"def",
"make_decoder",
"(",
"num_topics",
",",
"num_words",
")",
":",
"topics_words_logits",
"=",
"tf",
".",
"compat",
".",
"v1",
".",
"get_variable",
"(",
"\"topics_words_logits\"",
",",
"shape",
"=",
"[",
"num_topics",
",",
"num_words",
"]",
",",
"initialize... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | make_prior | Create the prior distribution.
Args:
num_topics: Number of topics.
initial_value: The starting value for the prior parameters.
Returns:
prior: A `callable` that returns a `tf.distribution.Distribution`
instance, the prior distribution.
prior_variables: A `list` of `Variable` objects, the t... | tensorflow_probability/examples/latent_dirichlet_allocation_distributions.py | def make_prior(num_topics, initial_value):
"""Create the prior distribution.
Args:
num_topics: Number of topics.
initial_value: The starting value for the prior parameters.
Returns:
prior: A `callable` that returns a `tf.distribution.Distribution`
instance, the prior distribution.
prior_... | def make_prior(num_topics, initial_value):
"""Create the prior distribution.
Args:
num_topics: Number of topics.
initial_value: The starting value for the prior parameters.
Returns:
prior: A `callable` that returns a `tf.distribution.Distribution`
instance, the prior distribution.
prior_... | [
"Create",
"the",
"prior",
"distribution",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/latent_dirichlet_allocation_distributions.py#L225-L255 | [
"def",
"make_prior",
"(",
"num_topics",
",",
"initial_value",
")",
":",
"def",
"_softplus_inverse",
"(",
"x",
")",
":",
"return",
"np",
".",
"log",
"(",
"np",
".",
"expm1",
"(",
"x",
")",
")",
"logit_concentration",
"=",
"tf",
".",
"compat",
".",
"v1",... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | model_fn | Build 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:
Es... | tensorflow_probability/examples/latent_dirichlet_allocation_distributions.py | def model_fn(features, labels, mode, params, config):
"""Build 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... | def model_fn(features, labels, mode, params, config):
"""Build 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... | [
"Build",
"the",
"model",
"function",
"for",
"use",
"in",
"an",
"estimator",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/latent_dirichlet_allocation_distributions.py#L258-L362 | [
"def",
"model_fn",
"(",
"features",
",",
"labels",
",",
"mode",
",",
"params",
",",
"config",
")",
":",
"del",
"labels",
",",
"config",
"encoder",
"=",
"make_encoder",
"(",
"params",
"[",
"\"activation\"",
"]",
",",
"params",
"[",
"\"num_topics\"",
"]",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | sample_chain | Implements Markov chain Monte Carlo via repeated `TransitionKernel` steps.
This function samples from an Markov chain at `current_state` and whose
stationary distribution is governed by the supplied `TransitionKernel`
instance (`kernel`).
This function can sample from multiple chains, in parallel. (Whether or... | tensorflow_probability/python/mcmc/sample.py | def sample_chain(
num_results,
current_state,
previous_kernel_results=None,
kernel=None,
num_burnin_steps=0,
num_steps_between_results=0,
trace_fn=lambda current_state, kernel_results: kernel_results,
return_final_kernel_results=False,
parallel_iterations=10,
name=None,
):
"""I... | def sample_chain(
num_results,
current_state,
previous_kernel_results=None,
kernel=None,
num_burnin_steps=0,
num_steps_between_results=0,
trace_fn=lambda current_state, kernel_results: kernel_results,
return_final_kernel_results=False,
parallel_iterations=10,
name=None,
):
"""I... | [
"Implements",
"Markov",
"chain",
"Monte",
"Carlo",
"via",
"repeated",
"TransitionKernel",
"steps",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/sample.py#L81-L372 | [
"def",
"sample_chain",
"(",
"num_results",
",",
"current_state",
",",
"previous_kernel_results",
"=",
"None",
",",
"kernel",
"=",
"None",
",",
"num_burnin_steps",
"=",
"0",
",",
"num_steps_between_results",
"=",
"0",
",",
"trace_fn",
"=",
"lambda",
"current_state"... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | deep_exponential_family | A multi-layered topic model over a documents-by-terms matrix. | tensorflow_probability/examples/deep_exponential_family.py | def deep_exponential_family(data_size, feature_size, units, shape):
"""A multi-layered topic model over a documents-by-terms matrix."""
w2 = ed.Gamma(0.1, 0.3, sample_shape=[units[2], units[1]], name="w2")
w1 = ed.Gamma(0.1, 0.3, sample_shape=[units[1], units[0]], name="w1")
w0 = ed.Gamma(0.1, 0.3, sample_shape... | def deep_exponential_family(data_size, feature_size, units, shape):
"""A multi-layered topic model over a documents-by-terms matrix."""
w2 = ed.Gamma(0.1, 0.3, sample_shape=[units[2], units[1]], name="w2")
w1 = ed.Gamma(0.1, 0.3, sample_shape=[units[1], units[0]], name="w1")
w0 = ed.Gamma(0.1, 0.3, sample_shape... | [
"A",
"multi",
"-",
"layered",
"topic",
"model",
"over",
"a",
"documents",
"-",
"by",
"-",
"terms",
"matrix",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/deep_exponential_family.py#L105-L115 | [
"def",
"deep_exponential_family",
"(",
"data_size",
",",
"feature_size",
",",
"units",
",",
"shape",
")",
":",
"w2",
"=",
"ed",
".",
"Gamma",
"(",
"0.1",
",",
"0.3",
",",
"sample_shape",
"=",
"[",
"units",
"[",
"2",
"]",
",",
"units",
"[",
"1",
"]",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | trainable_positive_deterministic | Learnable Deterministic distribution over positive reals. | tensorflow_probability/examples/deep_exponential_family.py | def trainable_positive_deterministic(shape, min_loc=1e-3, name=None):
"""Learnable Deterministic distribution over positive reals."""
with tf.compat.v1.variable_scope(
None, default_name="trainable_positive_deterministic"):
unconstrained_loc = tf.compat.v1.get_variable("unconstrained_loc", shape)
loc ... | def trainable_positive_deterministic(shape, min_loc=1e-3, name=None):
"""Learnable Deterministic distribution over positive reals."""
with tf.compat.v1.variable_scope(
None, default_name="trainable_positive_deterministic"):
unconstrained_loc = tf.compat.v1.get_variable("unconstrained_loc", shape)
loc ... | [
"Learnable",
"Deterministic",
"distribution",
"over",
"positive",
"reals",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/deep_exponential_family.py#L118-L125 | [
"def",
"trainable_positive_deterministic",
"(",
"shape",
",",
"min_loc",
"=",
"1e-3",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"variable_scope",
"(",
"None",
",",
"default_name",
"=",
"\"trainable_positive_deterministic\""... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | trainable_gamma | Learnable Gamma via concentration and scale parameterization. | tensorflow_probability/examples/deep_exponential_family.py | def trainable_gamma(shape, min_concentration=1e-3, min_scale=1e-5, name=None):
"""Learnable Gamma via concentration and scale parameterization."""
with tf.compat.v1.variable_scope(None, default_name="trainable_gamma"):
unconstrained_concentration = tf.compat.v1.get_variable(
"unconstrained_concentration... | def trainable_gamma(shape, min_concentration=1e-3, min_scale=1e-5, name=None):
"""Learnable Gamma via concentration and scale parameterization."""
with tf.compat.v1.variable_scope(None, default_name="trainable_gamma"):
unconstrained_concentration = tf.compat.v1.get_variable(
"unconstrained_concentration... | [
"Learnable",
"Gamma",
"via",
"concentration",
"and",
"scale",
"parameterization",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/deep_exponential_family.py#L128-L144 | [
"def",
"trainable_gamma",
"(",
"shape",
",",
"min_concentration",
"=",
"1e-3",
",",
"min_scale",
"=",
"1e-5",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"variable_scope",
"(",
"None",
",",
"default_name",
"=",
"\"tra... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | deep_exponential_family_variational | Posterior approx. for deep exponential family p(w{0,1,2}, z{1,2,3} | x). | tensorflow_probability/examples/deep_exponential_family.py | def deep_exponential_family_variational(data_size, feature_size, units):
"""Posterior approx. for deep exponential family p(w{0,1,2}, z{1,2,3} | x)."""
qw2 = trainable_positive_deterministic([units[2], units[1]], name="qw2")
qw1 = trainable_positive_deterministic([units[1], units[0]], name="qw1")
qw0 = trainabl... | def deep_exponential_family_variational(data_size, feature_size, units):
"""Posterior approx. for deep exponential family p(w{0,1,2}, z{1,2,3} | x)."""
qw2 = trainable_positive_deterministic([units[2], units[1]], name="qw2")
qw1 = trainable_positive_deterministic([units[1], units[0]], name="qw1")
qw0 = trainabl... | [
"Posterior",
"approx",
".",
"for",
"deep",
"exponential",
"family",
"p",
"(",
"w",
"{",
"0",
"1",
"2",
"}",
"z",
"{",
"1",
"2",
"3",
"}",
"|",
"x",
")",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/deep_exponential_family.py#L147-L155 | [
"def",
"deep_exponential_family_variational",
"(",
"data_size",
",",
"feature_size",
",",
"units",
")",
":",
"qw2",
"=",
"trainable_positive_deterministic",
"(",
"[",
"units",
"[",
"2",
"]",
",",
"units",
"[",
"1",
"]",
"]",
",",
"name",
"=",
"\"qw2\"",
")",... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | load_nips2011_papers | Loads NIPS 2011 conference papers.
The NIPS 1987-2015 data set is in the form of a 11,463 x 5,812 matrix of
per-paper word counts, containing 11,463 words and 5,811 NIPS conference
papers (Perrone et al., 2016). We subset to papers in 2011 and words appearing
in at least two documents and having a total word c... | tensorflow_probability/examples/deep_exponential_family.py | def load_nips2011_papers(path):
"""Loads NIPS 2011 conference papers.
The NIPS 1987-2015 data set is in the form of a 11,463 x 5,812 matrix of
per-paper word counts, containing 11,463 words and 5,811 NIPS conference
papers (Perrone et al., 2016). We subset to papers in 2011 and words appearing
in at least tw... | def load_nips2011_papers(path):
"""Loads NIPS 2011 conference papers.
The NIPS 1987-2015 data set is in the form of a 11,463 x 5,812 matrix of
per-paper word counts, containing 11,463 words and 5,811 NIPS conference
papers (Perrone et al., 2016). We subset to papers in 2011 and words appearing
in at least tw... | [
"Loads",
"NIPS",
"2011",
"conference",
"papers",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/deep_exponential_family.py#L178-L231 | [
"def",
"load_nips2011_papers",
"(",
"path",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
"filename",
"=",
"\"NIPS_1987-2015.csv\"",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"filename",
")",
"if"... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _AmplitudeLengthScaleMixin._init_params | Shared init logic for `amplitude` and `length_scale` params.
Args:
amplitude: `Tensor` (or convertible) or `None` to convert, validate.
length_scale: `Tensor` (or convertible) or `None` to convert, validate.
validate_args: If `True`, parameters are checked for validity despite
possibly de... | tensorflow_probability/python/positive_semidefinite_kernels/matern.py | def _init_params(self, amplitude, length_scale, validate_args):
"""Shared init logic for `amplitude` and `length_scale` params.
Args:
amplitude: `Tensor` (or convertible) or `None` to convert, validate.
length_scale: `Tensor` (or convertible) or `None` to convert, validate.
validate_args: If ... | def _init_params(self, amplitude, length_scale, validate_args):
"""Shared init logic for `amplitude` and `length_scale` params.
Args:
amplitude: `Tensor` (or convertible) or `None` to convert, validate.
length_scale: `Tensor` (or convertible) or `None` to convert, validate.
validate_args: If ... | [
"Shared",
"init",
"logic",
"for",
"amplitude",
"and",
"length_scale",
"params",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/positive_semidefinite_kernels/matern.py#L44-L68 | [
"def",
"_init_params",
"(",
"self",
",",
"amplitude",
",",
"length_scale",
",",
"validate_args",
")",
":",
"dtype",
"=",
"util",
".",
"maybe_get_common_dtype",
"(",
"[",
"amplitude",
",",
"length_scale",
"]",
")",
"if",
"amplitude",
"is",
"not",
"None",
":",... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _registered_kl | Get the KL function registered for classes a and b. | tensorflow_probability/python/distributions/kullback_leibler.py | def _registered_kl(type_a, type_b):
"""Get the KL function registered for classes a and b."""
hierarchy_a = tf_inspect.getmro(type_a)
hierarchy_b = tf_inspect.getmro(type_b)
dist_to_children = None
kl_fn = None
for mro_to_a, parent_a in enumerate(hierarchy_a):
for mro_to_b, parent_b in enumerate(hierarc... | def _registered_kl(type_a, type_b):
"""Get the KL function registered for classes a and b."""
hierarchy_a = tf_inspect.getmro(type_a)
hierarchy_b = tf_inspect.getmro(type_b)
dist_to_children = None
kl_fn = None
for mro_to_a, parent_a in enumerate(hierarchy_a):
for mro_to_b, parent_b in enumerate(hierarc... | [
"Get",
"the",
"KL",
"function",
"registered",
"for",
"classes",
"a",
"and",
"b",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/kullback_leibler.py#L34-L47 | [
"def",
"_registered_kl",
"(",
"type_a",
",",
"type_b",
")",
":",
"hierarchy_a",
"=",
"tf_inspect",
".",
"getmro",
"(",
"type_a",
")",
"hierarchy_b",
"=",
"tf_inspect",
".",
"getmro",
"(",
"type_b",
")",
"dist_to_children",
"=",
"None",
"kl_fn",
"=",
"None",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | kl_divergence | Get the KL-divergence KL(distribution_a || distribution_b).
If there is no KL method registered specifically for `type(distribution_a)`
and `type(distribution_b)`, then the class hierarchies of these types are
searched.
If one KL method is registered between any pairs of classes in these two
parent hierarch... | tensorflow_probability/python/distributions/kullback_leibler.py | def kl_divergence(distribution_a, distribution_b,
allow_nan_stats=True, name=None):
"""Get the KL-divergence KL(distribution_a || distribution_b).
If there is no KL method registered specifically for `type(distribution_a)`
and `type(distribution_b)`, then the class hierarchies of these types ar... | def kl_divergence(distribution_a, distribution_b,
allow_nan_stats=True, name=None):
"""Get the KL-divergence KL(distribution_a || distribution_b).
If there is no KL method registered specifically for `type(distribution_a)`
and `type(distribution_b)`, then the class hierarchies of these types ar... | [
"Get",
"the",
"KL",
"-",
"divergence",
"KL",
"(",
"distribution_a",
"||",
"distribution_b",
")",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/kullback_leibler.py#L50-L110 | [
"def",
"kl_divergence",
"(",
"distribution_a",
",",
"distribution_b",
",",
"allow_nan_stats",
"=",
"True",
",",
"name",
"=",
"None",
")",
":",
"kl_fn",
"=",
"_registered_kl",
"(",
"type",
"(",
"distribution_a",
")",
",",
"type",
"(",
"distribution_b",
")",
"... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | cross_entropy | Computes the (Shannon) cross entropy.
Denote two distributions by `P` (`ref`) and `Q` (`other`). Assuming `P, Q`
are absolutely continuous with respect to one another and permit densities
`p(x) dr(x)` and `q(x) dr(x)`, (Shanon) cross entropy is defined as:
```none
H[P, Q] = E_p[-log q(X)] = -int_F p(x) log ... | tensorflow_probability/python/distributions/kullback_leibler.py | def cross_entropy(ref, other,
allow_nan_stats=True, name=None):
"""Computes the (Shannon) cross entropy.
Denote two distributions by `P` (`ref`) and `Q` (`other`). Assuming `P, Q`
are absolutely continuous with respect to one another and permit densities
`p(x) dr(x)` and `q(x) dr(x)`, (Shanon... | def cross_entropy(ref, other,
allow_nan_stats=True, name=None):
"""Computes the (Shannon) cross entropy.
Denote two distributions by `P` (`ref`) and `Q` (`other`). Assuming `P, Q`
are absolutely continuous with respect to one another and permit densities
`p(x) dr(x)` and `q(x) dr(x)`, (Shanon... | [
"Computes",
"the",
"(",
"Shannon",
")",
"cross",
"entropy",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/kullback_leibler.py#L113-L142 | [
"def",
"cross_entropy",
"(",
"ref",
",",
"other",
",",
"allow_nan_stats",
"=",
"True",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"name",
"or",
"\"cross_entropy\"",
")",
":",
"return",
"ref",
".",
"entropy",
"(",
")",
"+"... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | read_image | Returns an image tensor. | tensorflow_probability/examples/sprites_dataset.py | def read_image(filepath):
"""Returns an image tensor."""
im_bytes = tf.io.read_file(filepath)
im = tf.image.decode_image(im_bytes, channels=CHANNELS)
im = tf.image.convert_image_dtype(im, tf.float32)
return im | def read_image(filepath):
"""Returns an image tensor."""
im_bytes = tf.io.read_file(filepath)
im = tf.image.decode_image(im_bytes, channels=CHANNELS)
im = tf.image.convert_image_dtype(im, tf.float32)
return im | [
"Returns",
"an",
"image",
"tensor",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/sprites_dataset.py#L113-L118 | [
"def",
"read_image",
"(",
"filepath",
")",
":",
"im_bytes",
"=",
"tf",
".",
"io",
".",
"read_file",
"(",
"filepath",
")",
"im",
"=",
"tf",
".",
"image",
".",
"decode_image",
"(",
"im_bytes",
",",
"channels",
"=",
"CHANNELS",
")",
"im",
"=",
"tf",
"."... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | download_sprites | Downloads the sprites data and returns the saved filepath. | tensorflow_probability/examples/sprites_dataset.py | def download_sprites():
"""Downloads the sprites data and returns the saved filepath."""
filepath = os.path.join(FLAGS.data_dir, DATA_SPRITES_DIR)
if not tf.io.gfile.exists(filepath):
if not tf.io.gfile.exists(FLAGS.data_dir):
tf.io.gfile.makedirs(FLAGS.data_dir)
zip_name = "{}.zip".format(filepath)... | def download_sprites():
"""Downloads the sprites data and returns the saved filepath."""
filepath = os.path.join(FLAGS.data_dir, DATA_SPRITES_DIR)
if not tf.io.gfile.exists(filepath):
if not tf.io.gfile.exists(FLAGS.data_dir):
tf.io.gfile.makedirs(FLAGS.data_dir)
zip_name = "{}.zip".format(filepath)... | [
"Downloads",
"the",
"sprites",
"data",
"and",
"returns",
"the",
"saved",
"filepath",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/sprites_dataset.py#L126-L137 | [
"def",
"download_sprites",
"(",
")",
":",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"FLAGS",
".",
"data_dir",
",",
"DATA_SPRITES_DIR",
")",
"if",
"not",
"tf",
".",
"io",
".",
"gfile",
".",
"exists",
"(",
"filepath",
")",
":",
"if",
"not",... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | create_character | Creates a character sprite from a set of attribute sprites. | tensorflow_probability/examples/sprites_dataset.py | def create_character(skin, hair, top, pants):
"""Creates a character sprite from a set of attribute sprites."""
dtype = skin.dtype
hair_mask = tf.cast(hair[..., -1:] <= 0, dtype)
top_mask = tf.cast(top[..., -1:] <= 0, dtype)
pants_mask = tf.cast(pants[..., -1:] <= 0, dtype)
char = (skin * hair_mask) + hair
... | def create_character(skin, hair, top, pants):
"""Creates a character sprite from a set of attribute sprites."""
dtype = skin.dtype
hair_mask = tf.cast(hair[..., -1:] <= 0, dtype)
top_mask = tf.cast(top[..., -1:] <= 0, dtype)
pants_mask = tf.cast(pants[..., -1:] <= 0, dtype)
char = (skin * hair_mask) + hair
... | [
"Creates",
"a",
"character",
"sprite",
"from",
"a",
"set",
"of",
"attribute",
"sprites",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/sprites_dataset.py#L140-L149 | [
"def",
"create_character",
"(",
"skin",
",",
"hair",
",",
"top",
",",
"pants",
")",
":",
"dtype",
"=",
"skin",
".",
"dtype",
"hair_mask",
"=",
"tf",
".",
"cast",
"(",
"hair",
"[",
"...",
",",
"-",
"1",
":",
"]",
"<=",
"0",
",",
"dtype",
")",
"t... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | create_seq | Creates a sequence.
Args:
character: A character sprite tensor.
action_metadata: An action metadata tuple.
direction: An integer representing the direction, i.e., the row
offset within each action group corresponding to a particular
direction.
length: Desired length of the sequence. If th... | tensorflow_probability/examples/sprites_dataset.py | def create_seq(character, action_metadata, direction, length=8, start=0):
"""Creates a sequence.
Args:
character: A character sprite tensor.
action_metadata: An action metadata tuple.
direction: An integer representing the direction, i.e., the row
offset within each action group corresponding to ... | def create_seq(character, action_metadata, direction, length=8, start=0):
"""Creates a sequence.
Args:
character: A character sprite tensor.
action_metadata: An action metadata tuple.
direction: An integer representing the direction, i.e., the row
offset within each action group corresponding to ... | [
"Creates",
"a",
"sequence",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/sprites_dataset.py#L152-L185 | [
"def",
"create_seq",
"(",
"character",
",",
"action_metadata",
",",
"direction",
",",
"length",
"=",
"8",
",",
"start",
"=",
"0",
")",
":",
"sprite_start",
"=",
"(",
"action_metadata",
"[",
"0",
"]",
"+",
"direction",
")",
"*",
"FRAME_SIZE",
"sprite_end",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | create_random_seq | Creates a random sequence. | tensorflow_probability/examples/sprites_dataset.py | def create_random_seq(character, action_metadata, direction, length=8):
"""Creates a random sequence."""
start = tf.random.uniform([], maxval=action_metadata[1], dtype=tf.int32)
return create_seq(character, action_metadata, direction, length, start) | def create_random_seq(character, action_metadata, direction, length=8):
"""Creates a random sequence."""
start = tf.random.uniform([], maxval=action_metadata[1], dtype=tf.int32)
return create_seq(character, action_metadata, direction, length, start) | [
"Creates",
"a",
"random",
"sequence",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/sprites_dataset.py#L188-L191 | [
"def",
"create_random_seq",
"(",
"character",
",",
"action_metadata",
",",
"direction",
",",
"length",
"=",
"8",
")",
":",
"start",
"=",
"tf",
".",
"random",
".",
"uniform",
"(",
"[",
"]",
",",
"maxval",
"=",
"action_metadata",
"[",
"1",
"]",
",",
"dty... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | create_sprites_dataset | Creates a tf.data pipeline for the sprites dataset.
Args:
characters: A list of (skin, hair, top, pants) tuples containing
relative paths to the sprite png image for each attribute.
actions: A list of Actions.
directions: A list of Directions.
channels: Number of image channels to yield.
le... | tensorflow_probability/examples/sprites_dataset.py | def create_sprites_dataset(characters, actions, directions, channels=3,
length=8, shuffle=False, fake_data=False):
"""Creates a tf.data pipeline for the sprites dataset.
Args:
characters: A list of (skin, hair, top, pants) tuples containing
relative paths to the sprite png imag... | def create_sprites_dataset(characters, actions, directions, channels=3,
length=8, shuffle=False, fake_data=False):
"""Creates a tf.data pipeline for the sprites dataset.
Args:
characters: A list of (skin, hair, top, pants) tuples containing
relative paths to the sprite png imag... | [
"Creates",
"a",
"tf",
".",
"data",
"pipeline",
"for",
"the",
"sprites",
"dataset",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/sprites_dataset.py#L194-L273 | [
"def",
"create_sprites_dataset",
"(",
"characters",
",",
"actions",
",",
"directions",
",",
"channels",
"=",
"3",
",",
"length",
"=",
"8",
",",
"shuffle",
"=",
"False",
",",
"fake_data",
"=",
"False",
")",
":",
"if",
"fake_data",
":",
"dummy_image",
"=",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _maybe_validate_distributions | Checks that `distributions` satisfies all assumptions. | tensorflow_probability/python/distributions/blockwise.py | def _maybe_validate_distributions(distributions, dtype_override, validate_args):
"""Checks that `distributions` satisfies all assumptions."""
assertions = []
if not _is_iterable(distributions) or not distributions:
raise ValueError('`distributions` must be a list of one or more '
'distri... | def _maybe_validate_distributions(distributions, dtype_override, validate_args):
"""Checks that `distributions` satisfies all assumptions."""
assertions = []
if not _is_iterable(distributions) or not distributions:
raise ValueError('`distributions` must be a list of one or more '
'distri... | [
"Checks",
"that",
"distributions",
"satisfies",
"all",
"assumptions",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/blockwise.py#L177-L225 | [
"def",
"_maybe_validate_distributions",
"(",
"distributions",
",",
"dtype_override",
",",
"validate_args",
")",
":",
"assertions",
"=",
"[",
"]",
"if",
"not",
"_is_iterable",
"(",
"distributions",
")",
"or",
"not",
"distributions",
":",
"raise",
"ValueError",
"(",... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _kl_blockwise_blockwise | Calculate the batched KL divergence KL(b0 || b1) with b0 and b1 Blockwise distributions.
Args:
b0: instance of a Blockwise distribution object.
b1: instance of a Blockwise distribution object.
name: (optional) Name to use for created operations. Default is
"kl_blockwise_blockwise".
Returns:
... | tensorflow_probability/python/distributions/blockwise.py | def _kl_blockwise_blockwise(b0, b1, name=None):
"""Calculate the batched KL divergence KL(b0 || b1) with b0 and b1 Blockwise distributions.
Args:
b0: instance of a Blockwise distribution object.
b1: instance of a Blockwise distribution object.
name: (optional) Name to use for created operations. Defaul... | def _kl_blockwise_blockwise(b0, b1, name=None):
"""Calculate the batched KL divergence KL(b0 || b1) with b0 and b1 Blockwise distributions.
Args:
b0: instance of a Blockwise distribution object.
b1: instance of a Blockwise distribution object.
name: (optional) Name to use for created operations. Defaul... | [
"Calculate",
"the",
"batched",
"KL",
"divergence",
"KL",
"(",
"b0",
"||",
"b1",
")",
"with",
"b0",
"and",
"b1",
"Blockwise",
"distributions",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/blockwise.py#L229-L269 | [
"def",
"_kl_blockwise_blockwise",
"(",
"b0",
",",
"b1",
",",
"name",
"=",
"None",
")",
":",
"if",
"len",
"(",
"b0",
".",
"distributions",
")",
"!=",
"len",
"(",
"b1",
".",
"distributions",
")",
":",
"raise",
"ValueError",
"(",
"'Can only compute KL diverge... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _kl_half_normal_half_normal | Calculate the batched KL divergence KL(a || b) with a and b `HalfNormal`.
Args:
a: Instance of a `HalfNormal` distribution object.
b: Instance of a `HalfNormal` distribution object.
name: (optional) Name to use for created operations.
default is "kl_half_normal_half_normal".
Returns:
Batchwi... | tensorflow_probability/python/distributions/half_normal.py | def _kl_half_normal_half_normal(a, b, name=None):
"""Calculate the batched KL divergence KL(a || b) with a and b `HalfNormal`.
Args:
a: Instance of a `HalfNormal` distribution object.
b: Instance of a `HalfNormal` distribution object.
name: (optional) Name to use for created operations.
default i... | def _kl_half_normal_half_normal(a, b, name=None):
"""Calculate the batched KL divergence KL(a || b) with a and b `HalfNormal`.
Args:
a: Instance of a `HalfNormal` distribution object.
b: Instance of a `HalfNormal` distribution object.
name: (optional) Name to use for created operations.
default i... | [
"Calculate",
"the",
"batched",
"KL",
"divergence",
"KL",
"(",
"a",
"||",
"b",
")",
"with",
"a",
"and",
"b",
"HalfNormal",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/half_normal.py#L180-L196 | [
"def",
"_kl_half_normal_half_normal",
"(",
"a",
",",
"b",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"name",
"or",
"\"kl_half_normal_half_normal\"",
")",
":",
"# Consistent with",
"# http://www.mast.queensu.ca/~communications/Papers/gil-ms... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _flatten_summand_list | Flatten a list of kernels which may contain _SumKernel instances.
Args:
kernels: Python list of `PositiveSemidefiniteKernel` instances
Returns:
Python list containing the elements of kernels, with any _SumKernel
instances replaced by their `kernels` property contents. | tensorflow_probability/python/positive_semidefinite_kernels/positive_semidefinite_kernel.py | def _flatten_summand_list(kernels):
"""Flatten a list of kernels which may contain _SumKernel instances.
Args:
kernels: Python list of `PositiveSemidefiniteKernel` instances
Returns:
Python list containing the elements of kernels, with any _SumKernel
instances replaced by their `kernels` property co... | def _flatten_summand_list(kernels):
"""Flatten a list of kernels which may contain _SumKernel instances.
Args:
kernels: Python list of `PositiveSemidefiniteKernel` instances
Returns:
Python list containing the elements of kernels, with any _SumKernel
instances replaced by their `kernels` property co... | [
"Flatten",
"a",
"list",
"of",
"kernels",
"which",
"may",
"contain",
"_SumKernel",
"instances",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/positive_semidefinite_kernels/positive_semidefinite_kernel.py#L608-L624 | [
"def",
"_flatten_summand_list",
"(",
"kernels",
")",
":",
"flattened",
"=",
"[",
"]",
"for",
"k",
"in",
"kernels",
":",
"if",
"isinstance",
"(",
"k",
",",
"_SumKernel",
")",
":",
"flattened",
"+=",
"k",
".",
"kernels",
"else",
":",
"flattened",
".",
"a... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _flatten_multiplicand_list | Flatten a list of kernels which may contain _ProductKernel instances.
Args:
kernels: Python list of `PositiveSemidefiniteKernel` instances
Returns:
Python list containing the elements of kernels, with any _ProductKernel
instances replaced by their `kernels` property contents. | tensorflow_probability/python/positive_semidefinite_kernels/positive_semidefinite_kernel.py | def _flatten_multiplicand_list(kernels):
"""Flatten a list of kernels which may contain _ProductKernel instances.
Args:
kernels: Python list of `PositiveSemidefiniteKernel` instances
Returns:
Python list containing the elements of kernels, with any _ProductKernel
instances replaced by their `kernels... | def _flatten_multiplicand_list(kernels):
"""Flatten a list of kernels which may contain _ProductKernel instances.
Args:
kernels: Python list of `PositiveSemidefiniteKernel` instances
Returns:
Python list containing the elements of kernels, with any _ProductKernel
instances replaced by their `kernels... | [
"Flatten",
"a",
"list",
"of",
"kernels",
"which",
"may",
"contain",
"_ProductKernel",
"instances",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/positive_semidefinite_kernels/positive_semidefinite_kernel.py#L627-L643 | [
"def",
"_flatten_multiplicand_list",
"(",
"kernels",
")",
":",
"flattened",
"=",
"[",
"]",
"for",
"k",
"in",
"kernels",
":",
"if",
"isinstance",
"(",
"k",
",",
"_ProductKernel",
")",
":",
"flattened",
"+=",
"k",
".",
"kernels",
"else",
":",
"flattened",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | build_input_pipeline | Build an Iterator switching between train and heldout data. | tensorflow_probability/examples/cifar10_bnn.py | def build_input_pipeline(x_train, x_test, y_train, y_test,
batch_size, valid_size):
"""Build an Iterator switching between train and heldout data."""
x_train = x_train.astype("float32")
x_test = x_test.astype("float32")
x_train /= 255
x_test /= 255
y_train = y_train.flatten()
y... | def build_input_pipeline(x_train, x_test, y_train, y_test,
batch_size, valid_size):
"""Build an Iterator switching between train and heldout data."""
x_train = x_train.astype("float32")
x_test = x_test.astype("float32")
x_train /= 255
x_test /= 255
y_train = y_train.flatten()
y... | [
"Build",
"an",
"Iterator",
"switching",
"between",
"train",
"and",
"heldout",
"data",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/cifar10_bnn.py#L109-L152 | [
"def",
"build_input_pipeline",
"(",
"x_train",
",",
"x_test",
",",
"y_train",
",",
"y_test",
",",
"batch_size",
",",
"valid_size",
")",
":",
"x_train",
"=",
"x_train",
".",
"astype",
"(",
"\"float32\"",
")",
"x_test",
"=",
"x_test",
".",
"astype",
"(",
"\"... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | build_fake_data | Build fake CIFAR10-style data for unit testing. | tensorflow_probability/examples/cifar10_bnn.py | def build_fake_data():
"""Build fake CIFAR10-style data for unit testing."""
num_examples = 10
x_train = np.random.rand(num_examples, *IMAGE_SHAPE).astype(np.float32)
y_train = np.random.permutation(np.arange(num_examples)).astype(np.int32)
x_test = np.random.rand(num_examples, *IMAGE_SHAPE).astype(np.float32... | def build_fake_data():
"""Build fake CIFAR10-style data for unit testing."""
num_examples = 10
x_train = np.random.rand(num_examples, *IMAGE_SHAPE).astype(np.float32)
y_train = np.random.permutation(np.arange(num_examples)).astype(np.int32)
x_test = np.random.rand(num_examples, *IMAGE_SHAPE).astype(np.float32... | [
"Build",
"fake",
"CIFAR10",
"-",
"style",
"data",
"for",
"unit",
"testing",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/cifar10_bnn.py#L155-L162 | [
"def",
"build_fake_data",
"(",
")",
":",
"num_examples",
"=",
"10",
"x_train",
"=",
"np",
".",
"random",
".",
"rand",
"(",
"num_examples",
",",
"*",
"IMAGE_SHAPE",
")",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"y_train",
"=",
"np",
".",
"random",... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | count_integers | Counts the number of occurrences of each value in an integer array `arr`.
Works like `tf.math.bincount`, but provides an `axis` kwarg that specifies
dimensions to reduce over. With
`~axis = [i for i in range(arr.ndim) if i not in axis]`,
this function returns a `Tensor` of shape `[K] + arr.shape[~axis]`.
... | tensorflow_probability/python/stats/quantiles.py | def count_integers(arr,
weights=None,
minlength=None,
maxlength=None,
axis=None,
dtype=tf.int32,
name=None):
"""Counts the number of occurrences of each value in an integer array `arr`.
Works like `tf.... | def count_integers(arr,
weights=None,
minlength=None,
maxlength=None,
axis=None,
dtype=tf.int32,
name=None):
"""Counts the number of occurrences of each value in an integer array `arr`.
Works like `tf.... | [
"Counts",
"the",
"number",
"of",
"occurrences",
"of",
"each",
"value",
"in",
"an",
"integer",
"array",
"arr",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/stats/quantiles.py#L39-L155 | [
"def",
"count_integers",
"(",
"arr",
",",
"weights",
"=",
"None",
",",
"minlength",
"=",
"None",
",",
"maxlength",
"=",
"None",
",",
"axis",
"=",
"None",
",",
"dtype",
"=",
"tf",
".",
"int32",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | find_bins | Bin values into discrete intervals.
Given `edges = [c0, ..., cK]`, defining intervals
`I0 = [c0, c1)`, `I1 = [c1, c2)`, ..., `I_{K-1} = [c_{K-1}, cK]`,
This function returns `bins`, such that:
`edges[bins[i]] <= x[i] < edges[bins[i] + 1]`.
Args:
x: Numeric `N-D` `Tensor` with `N > 0`.
edges: `Tens... | tensorflow_probability/python/stats/quantiles.py | def find_bins(x,
edges,
extend_lower_interval=False,
extend_upper_interval=False,
dtype=None,
name=None):
"""Bin values into discrete intervals.
Given `edges = [c0, ..., cK]`, defining intervals
`I0 = [c0, c1)`, `I1 = [c1, c2)`, ..., `I_{K-1} ... | def find_bins(x,
edges,
extend_lower_interval=False,
extend_upper_interval=False,
dtype=None,
name=None):
"""Bin values into discrete intervals.
Given `edges = [c0, ..., cK]`, defining intervals
`I0 = [c0, c1)`, `I1 = [c1, c2)`, ..., `I_{K-1} ... | [
"Bin",
"values",
"into",
"discrete",
"intervals",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/stats/quantiles.py#L158-L289 | [
"def",
"find_bins",
"(",
"x",
",",
"edges",
",",
"extend_lower_interval",
"=",
"False",
",",
"extend_upper_interval",
"=",
"False",
",",
"dtype",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"# TFP users may be surprised to see the \"action\" in the leftmost dim o... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | histogram | Count how often `x` falls in intervals defined by `edges`.
Given `edges = [c0, ..., cK]`, defining intervals
`I0 = [c0, c1)`, `I1 = [c1, c2)`, ..., `I_{K-1} = [c_{K-1}, cK]`,
This function counts how often `x` falls into each interval.
Values of `x` outside of the intervals cause errors. Consider using
`ex... | tensorflow_probability/python/stats/quantiles.py | def histogram(x,
edges,
axis=None,
extend_lower_interval=False,
extend_upper_interval=False,
dtype=None,
name=None):
"""Count how often `x` falls in intervals defined by `edges`.
Given `edges = [c0, ..., cK]`, defining intervals
... | def histogram(x,
edges,
axis=None,
extend_lower_interval=False,
extend_upper_interval=False,
dtype=None,
name=None):
"""Count how often `x` falls in intervals defined by `edges`.
Given `edges = [c0, ..., cK]`, defining intervals
... | [
"Count",
"how",
"often",
"x",
"falls",
"in",
"intervals",
"defined",
"by",
"edges",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/stats/quantiles.py#L292-L400 | [
"def",
"histogram",
"(",
"x",
",",
"edges",
",",
"axis",
"=",
"None",
",",
"extend_lower_interval",
"=",
"False",
",",
"extend_upper_interval",
"=",
"False",
",",
"dtype",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | percentile | Compute the `q`-th percentile(s) of `x`.
Given a vector `x`, the `q`-th percentile of `x` is the value `q / 100` of the
way from the minimum to the maximum in a sorted copy of `x`.
The values and distances of the two nearest neighbors as well as the
`interpolation` parameter will determine the percentile if t... | tensorflow_probability/python/stats/quantiles.py | def percentile(x,
q,
axis=None,
interpolation=None,
keep_dims=False,
validate_args=False,
preserve_gradients=True,
name=None):
"""Compute the `q`-th percentile(s) of `x`.
Given a vector `x`, the `q`-th percenti... | def percentile(x,
q,
axis=None,
interpolation=None,
keep_dims=False,
validate_args=False,
preserve_gradients=True,
name=None):
"""Compute the `q`-th percentile(s) of `x`.
Given a vector `x`, the `q`-th percenti... | [
"Compute",
"the",
"q",
"-",
"th",
"percentile",
"(",
"s",
")",
"of",
"x",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/stats/quantiles.py#L403-L623 | [
"def",
"percentile",
"(",
"x",
",",
"q",
",",
"axis",
"=",
"None",
",",
"interpolation",
"=",
"None",
",",
"keep_dims",
"=",
"False",
",",
"validate_args",
"=",
"False",
",",
"preserve_gradients",
"=",
"True",
",",
"name",
"=",
"None",
")",
":",
"name"... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | quantiles | Compute quantiles of `x` along `axis`.
The quantiles of a distribution are cut points dividing the range into
intervals with equal probabilities.
Given a vector `x` of samples, this function estimates the cut points by
returning `num_quantiles + 1` cut points, `(c0, ..., cn)`, such that, roughly
speaking, e... | tensorflow_probability/python/stats/quantiles.py | def quantiles(x,
num_quantiles,
axis=None,
interpolation=None,
keep_dims=False,
validate_args=False,
name=None):
"""Compute quantiles of `x` along `axis`.
The quantiles of a distribution are cut points dividing the range into
int... | def quantiles(x,
num_quantiles,
axis=None,
interpolation=None,
keep_dims=False,
validate_args=False,
name=None):
"""Compute quantiles of `x` along `axis`.
The quantiles of a distribution are cut points dividing the range into
int... | [
"Compute",
"quantiles",
"of",
"x",
"along",
"axis",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/stats/quantiles.py#L626-L723 | [
"def",
"quantiles",
"(",
"x",
",",
"num_quantiles",
",",
"axis",
"=",
"None",
",",
"interpolation",
"=",
"None",
",",
"keep_dims",
"=",
"False",
",",
"validate_args",
"=",
"False",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _get_static_ndims | Get static number of dimensions and assert that some expectations are met.
This function returns the number of dimensions 'ndims' of x, as a Python int.
The optional expect arguments are used to check the ndims of x, but this is
only done if the static ndims of x is not None.
Args:
x: A Tensor.
expe... | tensorflow_probability/python/stats/quantiles.py | def _get_static_ndims(x,
expect_static=False,
expect_ndims=None,
expect_ndims_no_more_than=None,
expect_ndims_at_least=None):
"""Get static number of dimensions and assert that some expectations are met.
This function returns t... | def _get_static_ndims(x,
expect_static=False,
expect_ndims=None,
expect_ndims_no_more_than=None,
expect_ndims_at_least=None):
"""Get static number of dimensions and assert that some expectations are met.
This function returns t... | [
"Get",
"static",
"number",
"of",
"dimensions",
"and",
"assert",
"that",
"some",
"expectations",
"are",
"met",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/stats/quantiles.py#L726-L787 | [
"def",
"_get_static_ndims",
"(",
"x",
",",
"expect_static",
"=",
"False",
",",
"expect_ndims",
"=",
"None",
",",
"expect_ndims_no_more_than",
"=",
"None",
",",
"expect_ndims_at_least",
"=",
"None",
")",
":",
"ndims",
"=",
"x",
".",
"shape",
".",
"ndims",
"if... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _get_best_effort_ndims | Get static ndims if possible. Fallback on `tf.rank(x)`. | tensorflow_probability/python/stats/quantiles.py | def _get_best_effort_ndims(x,
expect_ndims=None,
expect_ndims_at_least=None,
expect_ndims_no_more_than=None):
"""Get static ndims if possible. Fallback on `tf.rank(x)`."""
ndims_static = _get_static_ndims(
x,
expect_ndims=... | def _get_best_effort_ndims(x,
expect_ndims=None,
expect_ndims_at_least=None,
expect_ndims_no_more_than=None):
"""Get static ndims if possible. Fallback on `tf.rank(x)`."""
ndims_static = _get_static_ndims(
x,
expect_ndims=... | [
"Get",
"static",
"ndims",
"if",
"possible",
".",
"Fallback",
"on",
"tf",
".",
"rank",
"(",
"x",
")",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/stats/quantiles.py#L790-L802 | [
"def",
"_get_best_effort_ndims",
"(",
"x",
",",
"expect_ndims",
"=",
"None",
",",
"expect_ndims_at_least",
"=",
"None",
",",
"expect_ndims_no_more_than",
"=",
"None",
")",
":",
"ndims_static",
"=",
"_get_static_ndims",
"(",
"x",
",",
"expect_ndims",
"=",
"expect_n... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _insert_back_keep_dims | Insert the dims in `axis` back as singletons after being removed.
Args:
x: `Tensor`.
axis: Python list of integers.
Returns:
`Tensor` with same values as `x`, but additional singleton dimensions. | tensorflow_probability/python/stats/quantiles.py | def _insert_back_keep_dims(x, axis):
"""Insert the dims in `axis` back as singletons after being removed.
Args:
x: `Tensor`.
axis: Python list of integers.
Returns:
`Tensor` with same values as `x`, but additional singleton dimensions.
"""
for i in sorted(axis):
x = tf.expand_dims(x, axis=... | def _insert_back_keep_dims(x, axis):
"""Insert the dims in `axis` back as singletons after being removed.
Args:
x: `Tensor`.
axis: Python list of integers.
Returns:
`Tensor` with same values as `x`, but additional singleton dimensions.
"""
for i in sorted(axis):
x = tf.expand_dims(x, axis=... | [
"Insert",
"the",
"dims",
"in",
"axis",
"back",
"as",
"singletons",
"after",
"being",
"removed",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/stats/quantiles.py#L805-L817 | [
"def",
"_insert_back_keep_dims",
"(",
"x",
",",
"axis",
")",
":",
"for",
"i",
"in",
"sorted",
"(",
"axis",
")",
":",
"x",
"=",
"tf",
".",
"expand_dims",
"(",
"x",
",",
"axis",
"=",
"i",
")",
"return",
"x"
] | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _make_static_axis_non_negative_list | Convert possibly negatively indexed axis to non-negative list of ints.
Args:
axis: Integer Tensor.
ndims: Number of dimensions into which axis indexes.
Returns:
A list of non-negative Python integers.
Raises:
ValueError: If `axis` is not statically defined. | tensorflow_probability/python/stats/quantiles.py | def _make_static_axis_non_negative_list(axis, ndims):
"""Convert possibly negatively indexed axis to non-negative list of ints.
Args:
axis: Integer Tensor.
ndims: Number of dimensions into which axis indexes.
Returns:
A list of non-negative Python integers.
Raises:
ValueError: If `axis` is ... | def _make_static_axis_non_negative_list(axis, ndims):
"""Convert possibly negatively indexed axis to non-negative list of ints.
Args:
axis: Integer Tensor.
ndims: Number of dimensions into which axis indexes.
Returns:
A list of non-negative Python integers.
Raises:
ValueError: If `axis` is ... | [
"Convert",
"possibly",
"negatively",
"indexed",
"axis",
"to",
"non",
"-",
"negative",
"list",
"of",
"ints",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/stats/quantiles.py#L820-L844 | [
"def",
"_make_static_axis_non_negative_list",
"(",
"axis",
",",
"ndims",
")",
":",
"axis",
"=",
"distribution_util",
".",
"make_non_negative_axis",
"(",
"axis",
",",
"ndims",
")",
"axis_const",
"=",
"tf",
".",
"get_static_value",
"(",
"axis",
")",
"if",
"axis_co... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _move_dims_to_flat_end | Move dims corresponding to `axis` in `x` to the end, then flatten.
Args:
x: `Tensor` with shape `[B0,B1,...,Bb]`.
axis: Python list of indices into dimensions of `x`.
x_ndims: Python integer holding number of dimensions in `x`.
right_end: Python bool. Whether to move dims to the right end (else l... | tensorflow_probability/python/stats/quantiles.py | def _move_dims_to_flat_end(x, axis, x_ndims, right_end=True):
"""Move dims corresponding to `axis` in `x` to the end, then flatten.
Args:
x: `Tensor` with shape `[B0,B1,...,Bb]`.
axis: Python list of indices into dimensions of `x`.
x_ndims: Python integer holding number of dimensions in `x`.
righ... | def _move_dims_to_flat_end(x, axis, x_ndims, right_end=True):
"""Move dims corresponding to `axis` in `x` to the end, then flatten.
Args:
x: `Tensor` with shape `[B0,B1,...,Bb]`.
axis: Python list of indices into dimensions of `x`.
x_ndims: Python integer holding number of dimensions in `x`.
righ... | [
"Move",
"dims",
"corresponding",
"to",
"axis",
"in",
"x",
"to",
"the",
"end",
"then",
"flatten",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/stats/quantiles.py#L847-L884 | [
"def",
"_move_dims_to_flat_end",
"(",
"x",
",",
"axis",
",",
"x_ndims",
",",
"right_end",
"=",
"True",
")",
":",
"if",
"not",
"axis",
":",
"return",
"x",
"# Suppose x.shape = [a, b, c, d]",
"# Suppose axis = [1, 3]",
"# other_dims = [0, 2] in example above.",
"other_dim... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | _sort_tensor | Use `top_k` to sort a `Tensor` along the last dimension. | tensorflow_probability/python/stats/quantiles.py | def _sort_tensor(tensor):
"""Use `top_k` to sort a `Tensor` along the last dimension."""
sorted_, _ = tf.nn.top_k(tensor, k=tf.shape(input=tensor)[-1])
sorted_.set_shape(tensor.shape)
return sorted_ | def _sort_tensor(tensor):
"""Use `top_k` to sort a `Tensor` along the last dimension."""
sorted_, _ = tf.nn.top_k(tensor, k=tf.shape(input=tensor)[-1])
sorted_.set_shape(tensor.shape)
return sorted_ | [
"Use",
"top_k",
"to",
"sort",
"a",
"Tensor",
"along",
"the",
"last",
"dimension",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/stats/quantiles.py#L887-L891 | [
"def",
"_sort_tensor",
"(",
"tensor",
")",
":",
"sorted_",
",",
"_",
"=",
"tf",
".",
"nn",
".",
"top_k",
"(",
"tensor",
",",
"k",
"=",
"tf",
".",
"shape",
"(",
"input",
"=",
"tensor",
")",
"[",
"-",
"1",
"]",
")",
"sorted_",
".",
"set_shape",
"... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | Sum.make_component_state_space_models | Build an ordered list of Distribution instances for component models.
Args:
num_timesteps: Python `int` number of timesteps to model.
param_vals: a list of `Tensor` parameter values in order corresponding to
`self.parameters`, or a dict mapping from parameter names to values.
initial_step... | tensorflow_probability/python/sts/sum.py | def make_component_state_space_models(self,
num_timesteps,
param_vals,
initial_step=0):
"""Build an ordered list of Distribution instances for component models.
Args:
num_timesteps: Pyt... | def make_component_state_space_models(self,
num_timesteps,
param_vals,
initial_step=0):
"""Build an ordered list of Distribution instances for component models.
Args:
num_timesteps: Pyt... | [
"Build",
"an",
"ordered",
"list",
"of",
"Distribution",
"instances",
"for",
"component",
"models",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/sts/sum.py#L475-L516 | [
"def",
"make_component_state_space_models",
"(",
"self",
",",
"num_timesteps",
",",
"param_vals",
",",
"initial_step",
"=",
"0",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"'make_component_state_space_models'",
")",
":",
"# List the ... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | amari_alpha | The Amari-alpha Csiszar-function in log-space.
A Csiszar-function is a member of,
```none
F = { f:R_+ to R : f convex }.
```
When `self_normalized = True`, the Amari-alpha Csiszar-function is:
```none
f(u) = { -log(u) + (u - 1), alpha = 0
{ u log(u) - (u - 1), alpha = 1
{ [(u*... | tensorflow_probability/python/vi/csiszar_divergence.py | def amari_alpha(logu, alpha=1., self_normalized=False, name=None):
"""The Amari-alpha Csiszar-function in log-space.
A Csiszar-function is a member of,
```none
F = { f:R_+ to R : f convex }.
```
When `self_normalized = True`, the Amari-alpha Csiszar-function is:
```none
f(u) = { -log(u) + (u - 1), ... | def amari_alpha(logu, alpha=1., self_normalized=False, name=None):
"""The Amari-alpha Csiszar-function in log-space.
A Csiszar-function is a member of,
```none
F = { f:R_+ to R : f convex }.
```
When `self_normalized = True`, the Amari-alpha Csiszar-function is:
```none
f(u) = { -log(u) + (u - 1), ... | [
"The",
"Amari",
"-",
"alpha",
"Csiszar",
"-",
"function",
"in",
"log",
"-",
"space",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/vi/csiszar_divergence.py#L51-L118 | [
"def",
"amari_alpha",
"(",
"logu",
",",
"alpha",
"=",
"1.",
",",
"self_normalized",
"=",
"False",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"name",
",",
"\"amari_alpha\"",
",",
"[",
"logu",
"]... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | kl_reverse | The reverse Kullback-Leibler Csiszar-function in log-space.
A Csiszar-function is a member of,
```none
F = { f:R_+ to R : f convex }.
```
When `self_normalized = True`, the KL-reverse Csiszar-function is:
```none
f(u) = -log(u) + (u - 1)
```
When `self_normalized = False` the `(u - 1)` term is om... | tensorflow_probability/python/vi/csiszar_divergence.py | def kl_reverse(logu, self_normalized=False, name=None):
"""The reverse Kullback-Leibler Csiszar-function in log-space.
A Csiszar-function is a member of,
```none
F = { f:R_+ to R : f convex }.
```
When `self_normalized = True`, the KL-reverse Csiszar-function is:
```none
f(u) = -log(u) + (u - 1)
`... | def kl_reverse(logu, self_normalized=False, name=None):
"""The reverse Kullback-Leibler Csiszar-function in log-space.
A Csiszar-function is a member of,
```none
F = { f:R_+ to R : f convex }.
```
When `self_normalized = True`, the KL-reverse Csiszar-function is:
```none
f(u) = -log(u) + (u - 1)
`... | [
"The",
"reverse",
"Kullback",
"-",
"Leibler",
"Csiszar",
"-",
"function",
"in",
"log",
"-",
"space",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/vi/csiszar_divergence.py#L121-L166 | [
"def",
"kl_reverse",
"(",
"logu",
",",
"self_normalized",
"=",
"False",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"name",
",",
"\"kl_reverse\"",
",",
"[",
"logu",
"]",
")",
":",
"return",
"ama... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | jensen_shannon | The Jensen-Shannon Csiszar-function in log-space.
A Csiszar-function is a member of,
```none
F = { f:R_+ to R : f convex }.
```
When `self_normalized = True`, the Jensen-Shannon Csiszar-function is:
```none
f(u) = u log(u) - (1 + u) log(1 + u) + (u + 1) log(2)
```
When `self_normalized = False` t... | tensorflow_probability/python/vi/csiszar_divergence.py | def jensen_shannon(logu, self_normalized=False, name=None):
"""The Jensen-Shannon Csiszar-function in log-space.
A Csiszar-function is a member of,
```none
F = { f:R_+ to R : f convex }.
```
When `self_normalized = True`, the Jensen-Shannon Csiszar-function is:
```none
f(u) = u log(u) - (1 + u) log(... | def jensen_shannon(logu, self_normalized=False, name=None):
"""The Jensen-Shannon Csiszar-function in log-space.
A Csiszar-function is a member of,
```none
F = { f:R_+ to R : f convex }.
```
When `self_normalized = True`, the Jensen-Shannon Csiszar-function is:
```none
f(u) = u log(u) - (1 + u) log(... | [
"The",
"Jensen",
"-",
"Shannon",
"Csiszar",
"-",
"function",
"in",
"log",
"-",
"space",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/vi/csiszar_divergence.py#L217-L272 | [
"def",
"jensen_shannon",
"(",
"logu",
",",
"self_normalized",
"=",
"False",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"name",
",",
"\"jensen_shannon\"",
",",
"[",
"logu",
"]",
")",
":",
"logu",
... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | pearson | The Pearson Csiszar-function in log-space.
A Csiszar-function is a member of,
```none
F = { f:R_+ to R : f convex }.
```
The Pearson Csiszar-function is:
```none
f(u) = (u - 1)**2
```
Warning: this function makes non-log-space calculations and may therefore be
numerically unstable for `|logu| >... | tensorflow_probability/python/vi/csiszar_divergence.py | def pearson(logu, name=None):
"""The Pearson Csiszar-function in log-space.
A Csiszar-function is a member of,
```none
F = { f:R_+ to R : f convex }.
```
The Pearson Csiszar-function is:
```none
f(u) = (u - 1)**2
```
Warning: this function makes non-log-space calculations and may therefore be
... | def pearson(logu, name=None):
"""The Pearson Csiszar-function in log-space.
A Csiszar-function is a member of,
```none
F = { f:R_+ to R : f convex }.
```
The Pearson Csiszar-function is:
```none
f(u) = (u - 1)**2
```
Warning: this function makes non-log-space calculations and may therefore be
... | [
"The",
"Pearson",
"Csiszar",
"-",
"function",
"in",
"log",
"-",
"space",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/vi/csiszar_divergence.py#L360-L389 | [
"def",
"pearson",
"(",
"logu",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"name",
",",
"\"pearson\"",
",",
"[",
"logu",
"]",
")",
":",
"logu",
"=",
"tf",
".",
"convert_to_tensor",
"(",
"value... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
test | squared_hellinger | The Squared-Hellinger Csiszar-function in log-space.
A Csiszar-function is a member of,
```none
F = { f:R_+ to R : f convex }.
```
The Squared-Hellinger Csiszar-function is:
```none
f(u) = (sqrt(u) - 1)**2
```
This Csiszar-function induces a symmetric f-Divergence, i.e.,
`D_f[p, q] = D_f[q, p]`... | tensorflow_probability/python/vi/csiszar_divergence.py | def squared_hellinger(logu, name=None):
"""The Squared-Hellinger Csiszar-function in log-space.
A Csiszar-function is a member of,
```none
F = { f:R_+ to R : f convex }.
```
The Squared-Hellinger Csiszar-function is:
```none
f(u) = (sqrt(u) - 1)**2
```
This Csiszar-function induces a symmetric ... | def squared_hellinger(logu, name=None):
"""The Squared-Hellinger Csiszar-function in log-space.
A Csiszar-function is a member of,
```none
F = { f:R_+ to R : f convex }.
```
The Squared-Hellinger Csiszar-function is:
```none
f(u) = (sqrt(u) - 1)**2
```
This Csiszar-function induces a symmetric ... | [
"The",
"Squared",
"-",
"Hellinger",
"Csiszar",
"-",
"function",
"in",
"log",
"-",
"space",
"."
] | tensorflow/probability | python | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/vi/csiszar_divergence.py#L392-L424 | [
"def",
"squared_hellinger",
"(",
"logu",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"name",
",",
"\"squared_hellinger\"",
",",
"[",
"logu",
"]",
")",
":",
"logu",
"=",
"tf",
".",
"convert_to_tens... | e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.