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
_log_ndtr_lower
Asymptotic expansion version of `Log[cdf(x)]`, appropriate for `x<<-1`.
tensorflow_probability/python/internal/special_math.py
def _log_ndtr_lower(x, series_order): """Asymptotic expansion version of `Log[cdf(x)]`, appropriate for `x<<-1`.""" x_2 = tf.square(x) # Log of the term multiplying (1 + sum) log_scale = -0.5 * x_2 - tf.math.log(-x) - 0.5 * np.log(2. * np.pi) return log_scale + tf.math.log(_log_ndtr_asymptotic_series(x, serie...
def _log_ndtr_lower(x, series_order): """Asymptotic expansion version of `Log[cdf(x)]`, appropriate for `x<<-1`.""" x_2 = tf.square(x) # Log of the term multiplying (1 + sum) log_scale = -0.5 * x_2 - tf.math.log(-x) - 0.5 * np.log(2. * np.pi) return log_scale + tf.math.log(_log_ndtr_asymptotic_series(x, serie...
[ "Asymptotic", "expansion", "version", "of", "Log", "[", "cdf", "(", "x", ")", "]", "appropriate", "for", "x<<", "-", "1", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/special_math.py#L383-L388
[ "def", "_log_ndtr_lower", "(", "x", ",", "series_order", ")", ":", "x_2", "=", "tf", ".", "square", "(", "x", ")", "# Log of the term multiplying (1 + sum)", "log_scale", "=", "-", "0.5", "*", "x_2", "-", "tf", ".", "math", ".", "log", "(", "-", "x", "...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_log_ndtr_asymptotic_series
Calculates the asymptotic series used in log_ndtr.
tensorflow_probability/python/internal/special_math.py
def _log_ndtr_asymptotic_series(x, series_order): """Calculates the asymptotic series used in log_ndtr.""" npdt = dtype_util.as_numpy_dtype(x.dtype) if series_order <= 0: return npdt(1) x_2 = tf.square(x) even_sum = tf.zeros_like(x) odd_sum = tf.zeros_like(x) x_2n = x_2 # Start with x^{2*1} = x^{2*n}...
def _log_ndtr_asymptotic_series(x, series_order): """Calculates the asymptotic series used in log_ndtr.""" npdt = dtype_util.as_numpy_dtype(x.dtype) if series_order <= 0: return npdt(1) x_2 = tf.square(x) even_sum = tf.zeros_like(x) odd_sum = tf.zeros_like(x) x_2n = x_2 # Start with x^{2*1} = x^{2*n}...
[ "Calculates", "the", "asymptotic", "series", "used", "in", "log_ndtr", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/special_math.py#L391-L407
[ "def", "_log_ndtr_asymptotic_series", "(", "x", ",", "series_order", ")", ":", "npdt", "=", "dtype_util", ".", "as_numpy_dtype", "(", "x", ".", "dtype", ")", "if", "series_order", "<=", "0", ":", "return", "npdt", "(", "1", ")", "x_2", "=", "tf", ".", ...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
erfinv
The inverse function for erf, the error function. Args: x: `Tensor` of type `float32`, `float64`. name: Python string. A name for the operation (default="erfinv"). Returns: x: `Tensor` with `dtype=x.dtype`. Raises: TypeError: if `x` is not floating-type.
tensorflow_probability/python/internal/special_math.py
def erfinv(x, name="erfinv"): """The inverse function for erf, the error function. Args: x: `Tensor` of type `float32`, `float64`. name: Python string. A name for the operation (default="erfinv"). Returns: x: `Tensor` with `dtype=x.dtype`. Raises: TypeError: if `x` is not floating-type. """...
def erfinv(x, name="erfinv"): """The inverse function for erf, the error function. Args: x: `Tensor` of type `float32`, `float64`. name: Python string. A name for the operation (default="erfinv"). Returns: x: `Tensor` with `dtype=x.dtype`. Raises: TypeError: if `x` is not floating-type. """...
[ "The", "inverse", "function", "for", "erf", "the", "error", "function", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/special_math.py#L410-L429
[ "def", "erfinv", "(", "x", ",", "name", "=", "\"erfinv\"", ")", ":", "with", "tf", ".", "name_scope", "(", "name", ")", ":", "x", "=", "tf", ".", "convert_to_tensor", "(", "value", "=", "x", ",", "name", "=", "\"x\"", ")", "if", "dtype_util", ".", ...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
log_cdf_laplace
Log Laplace distribution function. This function calculates `Log[L(x)]`, where `L(x)` is the cumulative distribution function of the Laplace distribution, i.e. ```L(x) := 0.5 * int_{-infty}^x e^{-|t|} dt``` For numerical accuracy, `L(x)` is computed in different ways depending on `x`, ``` x <= 0: Lo...
tensorflow_probability/python/internal/special_math.py
def log_cdf_laplace(x, name="log_cdf_laplace"): """Log Laplace distribution function. This function calculates `Log[L(x)]`, where `L(x)` is the cumulative distribution function of the Laplace distribution, i.e. ```L(x) := 0.5 * int_{-infty}^x e^{-|t|} dt``` For numerical accuracy, `L(x)` is computed in dif...
def log_cdf_laplace(x, name="log_cdf_laplace"): """Log Laplace distribution function. This function calculates `Log[L(x)]`, where `L(x)` is the cumulative distribution function of the Laplace distribution, i.e. ```L(x) := 0.5 * int_{-infty}^x e^{-|t|} dt``` For numerical accuracy, `L(x)` is computed in dif...
[ "Log", "Laplace", "distribution", "function", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/special_math.py#L437-L482
[ "def", "log_cdf_laplace", "(", "x", ",", "name", "=", "\"log_cdf_laplace\"", ")", ":", "with", "tf", ".", "name_scope", "(", "name", ")", ":", "x", "=", "tf", ".", "convert_to_tensor", "(", "value", "=", "x", ",", "name", "=", "\"x\"", ")", "# For x < ...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
text_messages_joint_log_prob
Joint log probability function.
tensorflow_probability/python/mcmc/text_messages_hmc.py
def text_messages_joint_log_prob(count_data, lambda_1, lambda_2, tau): """Joint log probability function.""" alpha = (1. / tf.reduce_mean(input_tensor=count_data)) rv_lambda = tfd.Exponential(rate=alpha) rv_tau = tfd.Uniform() lambda_ = tf.gather( [lambda_1, lambda_2], indices=tf.cast( ...
def text_messages_joint_log_prob(count_data, lambda_1, lambda_2, tau): """Joint log probability function.""" alpha = (1. / tf.reduce_mean(input_tensor=count_data)) rv_lambda = tfd.Exponential(rate=alpha) rv_tau = tfd.Uniform() lambda_ = tf.gather( [lambda_1, lambda_2], indices=tf.cast( ...
[ "Joint", "log", "probability", "function", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/text_messages_hmc.py#L44-L61
[ "def", "text_messages_joint_log_prob", "(", "count_data", ",", "lambda_1", ",", "lambda_2", ",", "tau", ")", ":", "alpha", "=", "(", "1.", "/", "tf", ".", "reduce_mean", "(", "input_tensor", "=", "count_data", ")", ")", "rv_lambda", "=", "tfd", ".", "Expon...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
benchmark_text_messages_hmc
Runs HMC on the text-messages unnormalized posterior.
tensorflow_probability/python/mcmc/text_messages_hmc.py
def benchmark_text_messages_hmc( num_results=int(3e3), num_burnin_steps=int(3e3), num_leapfrog_steps=3): """Runs HMC on the text-messages unnormalized posterior.""" if not tf.executing_eagerly(): tf.compat.v1.reset_default_graph() # Build a static, pretend dataset. count_data = tf.cast( ...
def benchmark_text_messages_hmc( num_results=int(3e3), num_burnin_steps=int(3e3), num_leapfrog_steps=3): """Runs HMC on the text-messages unnormalized posterior.""" if not tf.executing_eagerly(): tf.compat.v1.reset_default_graph() # Build a static, pretend dataset. count_data = tf.cast( ...
[ "Runs", "HMC", "on", "the", "text", "-", "messages", "unnormalized", "posterior", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/text_messages_hmc.py#L64-L153
[ "def", "benchmark_text_messages_hmc", "(", "num_results", "=", "int", "(", "3e3", ")", ",", "num_burnin_steps", "=", "int", "(", "3e3", ")", ",", "num_leapfrog_steps", "=", "3", ")", ":", "if", "not", "tf", ".", "executing_eagerly", "(", ")", ":", "tf", ...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
GaussianProcess._is_univariate_marginal
True if the given index_points would yield a univariate marginal. Args: index_points: the set of index set locations at which to compute the marginal Gaussian distribution. If this set is of size 1, the marginal is univariate. Returns: is_univariate: Boolean indicating whether the marg...
tensorflow_probability/python/distributions/gaussian_process.py
def _is_univariate_marginal(self, index_points): """True if the given index_points would yield a univariate marginal. Args: index_points: the set of index set locations at which to compute the marginal Gaussian distribution. If this set is of size 1, the marginal is univariate. Returns: ...
def _is_univariate_marginal(self, index_points): """True if the given index_points would yield a univariate marginal. Args: index_points: the set of index set locations at which to compute the marginal Gaussian distribution. If this set is of size 1, the marginal is univariate. Returns: ...
[ "True", "if", "the", "given", "index_points", "would", "yield", "a", "univariate", "marginal", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/gaussian_process.py#L286-L307
[ "def", "_is_univariate_marginal", "(", "self", ",", "index_points", ")", ":", "num_index_points", "=", "tf", ".", "compat", ".", "dimension_value", "(", "index_points", ".", "shape", "[", "-", "(", "self", ".", "kernel", ".", "feature_ndims", "+", "1", ")", ...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
GaussianProcess.get_marginal_distribution
Compute the marginal of this GP over function values at `index_points`. Args: index_points: `float` `Tensor` representing finite (batch of) vector(s) of points in the index set over which the GP is defined. Shape has the form `[b1, ..., bB, e, f1, ..., fF]` where `F` is the number of feature ...
tensorflow_probability/python/distributions/gaussian_process.py
def get_marginal_distribution(self, index_points=None): """Compute the marginal of this GP over function values at `index_points`. Args: index_points: `float` `Tensor` representing finite (batch of) vector(s) of points in the index set over which the GP is defined. Shape has the form `[b1...
def get_marginal_distribution(self, index_points=None): """Compute the marginal of this GP over function values at `index_points`. Args: index_points: `float` `Tensor` representing finite (batch of) vector(s) of points in the index set over which the GP is defined. Shape has the form `[b1...
[ "Compute", "the", "marginal", "of", "this", "GP", "over", "function", "values", "at", "index_points", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/gaussian_process.py#L320-L366
[ "def", "get_marginal_distribution", "(", "self", ",", "index_points", "=", "None", ")", ":", "with", "self", ".", "_name_scope", "(", "'get_marginal_distribution'", ")", ":", "# TODO(cgs): consider caching the result here, keyed on `index_points`.", "index_points", "=", "se...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
GaussianProcess._get_index_points
Return `index_points` if not None, else `self._index_points`. Args: index_points: if given, this is what is returned; else, `self._index_points` Returns: index_points: the given arg, if not None, else the class member `self._index_points`. Rases: ValueError: if `index_points...
tensorflow_probability/python/distributions/gaussian_process.py
def _get_index_points(self, index_points=None): """Return `index_points` if not None, else `self._index_points`. Args: index_points: if given, this is what is returned; else, `self._index_points` Returns: index_points: the given arg, if not None, else the class member `self._index_...
def _get_index_points(self, index_points=None): """Return `index_points` if not None, else `self._index_points`. Args: index_points: if given, this is what is returned; else, `self._index_points` Returns: index_points: the given arg, if not None, else the class member `self._index_...
[ "Return", "index_points", "if", "not", "None", "else", "self", ".", "_index_points", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/gaussian_process.py#L388-L413
[ "def", "_get_index_points", "(", "self", ",", "index_points", "=", "None", ")", ":", "if", "self", ".", "_index_points", "is", "None", "and", "index_points", "is", "None", ":", "raise", "ValueError", "(", "'This GaussianProcess instance was not instantiated with a val...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_logsum_expbig_minus_expsmall
Stable evaluation of `Log[exp{big} - exp{small}]`. To work correctly, we should have the pointwise relation: `small <= big`. Args: big: Floating-point `Tensor` small: Floating-point `Tensor` with same `dtype` as `big` and broadcastable shape. Returns: `Tensor` of same `dtype` of `big` and br...
tensorflow_probability/python/distributions/quantized_distribution.py
def _logsum_expbig_minus_expsmall(big, small): """Stable evaluation of `Log[exp{big} - exp{small}]`. To work correctly, we should have the pointwise relation: `small <= big`. Args: big: Floating-point `Tensor` small: Floating-point `Tensor` with same `dtype` as `big` and broadcastable shape. R...
def _logsum_expbig_minus_expsmall(big, small): """Stable evaluation of `Log[exp{big} - exp{small}]`. To work correctly, we should have the pointwise relation: `small <= big`. Args: big: Floating-point `Tensor` small: Floating-point `Tensor` with same `dtype` as `big` and broadcastable shape. R...
[ "Stable", "evaluation", "of", "Log", "[", "exp", "{", "big", "}", "-", "exp", "{", "small", "}", "]", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/quantized_distribution.py#L35-L49
[ "def", "_logsum_expbig_minus_expsmall", "(", "big", ",", "small", ")", ":", "with", "tf", ".", "name_scope", "(", "\"logsum_expbig_minus_expsmall\"", ")", ":", "return", "tf", ".", "math", ".", "log1p", "(", "-", "tf", ".", "exp", "(", "small", "-", "big",...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
QuantizedDistribution._log_prob_with_logsf_and_logcdf
Compute log_prob(y) using log survival_function and cdf together.
tensorflow_probability/python/distributions/quantized_distribution.py
def _log_prob_with_logsf_and_logcdf(self, y): """Compute log_prob(y) using log survival_function and cdf together.""" # There are two options that would be equal if we had infinite precision: # Log[ sf(y - 1) - sf(y) ] # = Log[ exp{logsf(y - 1)} - exp{logsf(y)} ] # Log[ cdf(y) - cdf(y - 1) ] #...
def _log_prob_with_logsf_and_logcdf(self, y): """Compute log_prob(y) using log survival_function and cdf together.""" # There are two options that would be equal if we had infinite precision: # Log[ sf(y - 1) - sf(y) ] # = Log[ exp{logsf(y - 1)} - exp{logsf(y)} ] # Log[ cdf(y) - cdf(y - 1) ] #...
[ "Compute", "log_prob", "(", "y", ")", "using", "log", "survival_function", "and", "cdf", "together", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/quantized_distribution.py#L372-L394
[ "def", "_log_prob_with_logsf_and_logcdf", "(", "self", ",", "y", ")", ":", "# There are two options that would be equal if we had infinite precision:", "# Log[ sf(y - 1) - sf(y) ]", "# = Log[ exp{logsf(y - 1)} - exp{logsf(y)} ]", "# Log[ cdf(y) - cdf(y - 1) ]", "# = Log[ exp{logcdf(y)} -...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
make_iaf_stack
Creates an stacked IAF bijector. This bijector operates on vector-valued events. Args: total_event_size: Number of dimensions to operate over. num_hidden_layers: How many hidden layers to use in each IAF. seed: Random seed for the initializers. dtype: DType for the variables. Returns: bijec...
experimental/neutra/neutra_kernel.py
def make_iaf_stack(total_event_size, num_hidden_layers=2, seed=None, dtype=tf.float32): """Creates an stacked IAF bijector. This bijector operates on vector-valued events. Args: total_event_size: Number of dimensions to operate over. num_hidden_la...
def make_iaf_stack(total_event_size, num_hidden_layers=2, seed=None, dtype=tf.float32): """Creates an stacked IAF bijector. This bijector operates on vector-valued events. Args: total_event_size: Number of dimensions to operate over. num_hidden_la...
[ "Creates", "an", "stacked", "IAF", "bijector", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/experimental/neutra/neutra_kernel.py#L33-L86
[ "def", "make_iaf_stack", "(", "total_event_size", ",", "num_hidden_layers", "=", "2", ",", "seed", "=", "None", ",", "dtype", "=", "tf", ".", "float32", ")", ":", "seed", "=", "tfd", ".", "SeedStream", "(", "seed", ",", "'make_iaf_stack'", ")", "def", "m...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
NeuTra.one_step
Runs one iteration of NeuTra. 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_results: `collections...
experimental/neutra/neutra_kernel.py
def one_step(self, current_state, previous_kernel_results): """Runs one iteration of NeuTra. 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_pro...
def one_step(self, current_state, previous_kernel_results): """Runs one iteration of NeuTra. 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_pro...
[ "Runs", "one", "iteration", "of", "NeuTra", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/experimental/neutra/neutra_kernel.py#L350-L381
[ "def", "one_step", "(", "self", ",", "current_state", ",", "previous_kernel_results", ")", ":", "@", "tfp", ".", "mcmc", ".", "internal", ".", "util", ".", "make_innermost_setter", "def", "set_num_leapfrog_steps", "(", "kernel_results", ",", "num_leapfrog_steps", ...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
NeuTra.bootstrap_results
Trains the bijector and creates initial `previous_kernel_results`. The supplied `state` is only used to determine the number of chains to run in parallel_iterations Args: state: `Tensor` or Python `list` of `Tensor`s representing the initial state(s) of the Markov chain(s). The first `r` dim...
experimental/neutra/neutra_kernel.py
def bootstrap_results(self, state): """Trains the bijector and creates initial `previous_kernel_results`. The supplied `state` is only used to determine the number of chains to run in parallel_iterations Args: state: `Tensor` or Python `list` of `Tensor`s representing the initial state(s...
def bootstrap_results(self, state): """Trains the bijector and creates initial `previous_kernel_results`. The supplied `state` is only used to determine the number of chains to run in parallel_iterations Args: state: `Tensor` or Python `list` of `Tensor`s representing the initial state(s...
[ "Trains", "the", "bijector", "and", "creates", "initial", "previous_kernel_results", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/experimental/neutra/neutra_kernel.py#L383-L444
[ "def", "bootstrap_results", "(", "self", ",", "state", ")", ":", "def", "loss", "(", ")", ":", "q", "=", "self", ".", "_flattened_variational_distribution", "(", ")", "# TODO(siege): How to seed this?", "samples", "=", "q", ".", "sample", "(", "self", ".", "...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_WishartLinearOperator.mean_log_det
Computes E[log(det(X))] under this Wishart distribution.
tensorflow_probability/python/distributions/wishart.py
def mean_log_det(self, name="mean_log_det"): """Computes E[log(det(X))] under this Wishart distribution.""" with self._name_scope(name): return (self._multi_digamma(0.5 * self.df, self.dimension) + self.dimension * math.log(2.) + 2 * self.scale_operator.log_abs_determinant())
def mean_log_det(self, name="mean_log_det"): """Computes E[log(det(X))] under this Wishart distribution.""" with self._name_scope(name): return (self._multi_digamma(0.5 * self.df, self.dimension) + self.dimension * math.log(2.) + 2 * self.scale_operator.log_abs_determinant())
[ "Computes", "E", "[", "log", "(", "det", "(", "X", "))", "]", "under", "this", "Wishart", "distribution", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/wishart.py#L402-L407
[ "def", "mean_log_det", "(", "self", ",", "name", "=", "\"mean_log_det\"", ")", ":", "with", "self", ".", "_name_scope", "(", "name", ")", ":", "return", "(", "self", ".", "_multi_digamma", "(", "0.5", "*", "self", ".", "df", ",", "self", ".", "dimensio...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_WishartLinearOperator.log_normalization
Computes the log normalizing constant, log(Z).
tensorflow_probability/python/distributions/wishart.py
def log_normalization(self, name="log_normalization"): """Computes the log normalizing constant, log(Z).""" with self._name_scope(name): return (self.df * self.scale_operator.log_abs_determinant() + 0.5 * self.df * self.dimension * math.log(2.) + self._multi_lgamma(0.5 * self.d...
def log_normalization(self, name="log_normalization"): """Computes the log normalizing constant, log(Z).""" with self._name_scope(name): return (self.df * self.scale_operator.log_abs_determinant() + 0.5 * self.df * self.dimension * math.log(2.) + self._multi_lgamma(0.5 * self.d...
[ "Computes", "the", "log", "normalizing", "constant", "log", "(", "Z", ")", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/wishart.py#L409-L414
[ "def", "log_normalization", "(", "self", ",", "name", "=", "\"log_normalization\"", ")", ":", "with", "self", ".", "_name_scope", "(", "name", ")", ":", "return", "(", "self", ".", "df", "*", "self", ".", "scale_operator", ".", "log_abs_determinant", "(", ...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_WishartLinearOperator._multi_gamma_sequence
Creates sequence used in multivariate (di)gamma; shape = shape(a)+[p].
tensorflow_probability/python/distributions/wishart.py
def _multi_gamma_sequence(self, a, p, name="multi_gamma_sequence"): """Creates sequence used in multivariate (di)gamma; shape = shape(a)+[p].""" with self._name_scope(name): # Linspace only takes scalars, so we'll add in the offset afterwards. seq = tf.linspace( tf.constant(0., dtype=self....
def _multi_gamma_sequence(self, a, p, name="multi_gamma_sequence"): """Creates sequence used in multivariate (di)gamma; shape = shape(a)+[p].""" with self._name_scope(name): # Linspace only takes scalars, so we'll add in the offset afterwards. seq = tf.linspace( tf.constant(0., dtype=self....
[ "Creates", "sequence", "used", "in", "multivariate", "(", "di", ")", "gamma", ";", "shape", "=", "shape", "(", "a", ")", "+", "[", "p", "]", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/wishart.py#L416-L423
[ "def", "_multi_gamma_sequence", "(", "self", ",", "a", ",", "p", ",", "name", "=", "\"multi_gamma_sequence\"", ")", ":", "with", "self", ".", "_name_scope", "(", "name", ")", ":", "# Linspace only takes scalars, so we'll add in the offset afterwards.", "seq", "=", "...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_WishartLinearOperator._multi_lgamma
Computes the log multivariate gamma function; log(Gamma_p(a)).
tensorflow_probability/python/distributions/wishart.py
def _multi_lgamma(self, a, p, name="multi_lgamma"): """Computes the log multivariate gamma function; log(Gamma_p(a)).""" with self._name_scope(name): seq = self._multi_gamma_sequence(a, p) return (0.25 * p * (p - 1.) * math.log(math.pi) + tf.reduce_sum(input_tensor=tf.math.lgamma(seq),...
def _multi_lgamma(self, a, p, name="multi_lgamma"): """Computes the log multivariate gamma function; log(Gamma_p(a)).""" with self._name_scope(name): seq = self._multi_gamma_sequence(a, p) return (0.25 * p * (p - 1.) * math.log(math.pi) + tf.reduce_sum(input_tensor=tf.math.lgamma(seq),...
[ "Computes", "the", "log", "multivariate", "gamma", "function", ";", "log", "(", "Gamma_p", "(", "a", "))", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/wishart.py#L425-L430
[ "def", "_multi_lgamma", "(", "self", ",", "a", ",", "p", ",", "name", "=", "\"multi_lgamma\"", ")", ":", "with", "self", ".", "_name_scope", "(", "name", ")", ":", "seq", "=", "self", ".", "_multi_gamma_sequence", "(", "a", ",", "p", ")", "return", "...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_WishartLinearOperator._multi_digamma
Computes the multivariate digamma function; Psi_p(a).
tensorflow_probability/python/distributions/wishart.py
def _multi_digamma(self, a, p, name="multi_digamma"): """Computes the multivariate digamma function; Psi_p(a).""" with self._name_scope(name): seq = self._multi_gamma_sequence(a, p) return tf.reduce_sum(input_tensor=tf.math.digamma(seq), axis=[-1])
def _multi_digamma(self, a, p, name="multi_digamma"): """Computes the multivariate digamma function; Psi_p(a).""" with self._name_scope(name): seq = self._multi_gamma_sequence(a, p) return tf.reduce_sum(input_tensor=tf.math.digamma(seq), axis=[-1])
[ "Computes", "the", "multivariate", "digamma", "function", ";", "Psi_p", "(", "a", ")", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/wishart.py#L432-L436
[ "def", "_multi_digamma", "(", "self", ",", "a", ",", "p", ",", "name", "=", "\"multi_digamma\"", ")", ":", "with", "self", ".", "_name_scope", "(", "name", ")", ":", "seq", "=", "self", ".", "_multi_gamma_sequence", "(", "a", ",", "p", ")", "return", ...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_outer_squared_difference
Convenience function analogous to tf.squared_difference.
tensorflow_probability/python/distributions/mixture_same_family.py
def _outer_squared_difference(x, y): """Convenience function analogous to tf.squared_difference.""" z = x - y return z[..., tf.newaxis, :] * z[..., tf.newaxis]
def _outer_squared_difference(x, y): """Convenience function analogous to tf.squared_difference.""" z = x - y return z[..., tf.newaxis, :] * z[..., tf.newaxis]
[ "Convenience", "function", "analogous", "to", "tf", ".", "squared_difference", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/mixture_same_family.py#L536-L539
[ "def", "_outer_squared_difference", "(", "x", ",", "y", ")", ":", "z", "=", "x", "-", "y", "return", "z", "[", "...", ",", "tf", ".", "newaxis", ",", ":", "]", "*", "z", "[", "...", ",", "tf", ".", "newaxis", "]" ]
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_value_and_batch_jacobian
Enables uniform interface to value and batch jacobian calculation. Works in both eager and graph modes. Arguments: f: The scalar function to evaluate. x: The value at which to compute the value and the batch jacobian. Returns: A tuple (f(x), J(x)), where J(x) is the batch jacobian.
tensorflow_probability/python/distributions/mixture_same_family.py
def _value_and_batch_jacobian(f, x): """Enables uniform interface to value and batch jacobian calculation. Works in both eager and graph modes. Arguments: f: The scalar function to evaluate. x: The value at which to compute the value and the batch jacobian. Returns: A tuple (f(x), J(x)), where J(...
def _value_and_batch_jacobian(f, x): """Enables uniform interface to value and batch jacobian calculation. Works in both eager and graph modes. Arguments: f: The scalar function to evaluate. x: The value at which to compute the value and the batch jacobian. Returns: A tuple (f(x), J(x)), where J(...
[ "Enables", "uniform", "interface", "to", "value", "and", "batch", "jacobian", "calculation", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/mixture_same_family.py#L542-L562
[ "def", "_value_and_batch_jacobian", "(", "f", ",", "x", ")", ":", "if", "tf", ".", "executing_eagerly", "(", ")", ":", "with", "tf", ".", "GradientTape", "(", ")", "as", "tape", ":", "tape", ".", "watch", "(", "x", ")", "value", "=", "f", "(", "x",...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_prevent_2nd_derivative
Disables computation of the second derivatives for a tensor. NB: you need to apply a non-identity function to the output tensor for the exception to be raised. Arguments: x: A tensor. Returns: A tensor with the same value and the same derivative as x, but that raises LookupError when trying to co...
tensorflow_probability/python/distributions/mixture_same_family.py
def _prevent_2nd_derivative(x): """Disables computation of the second derivatives for a tensor. NB: you need to apply a non-identity function to the output tensor for the exception to be raised. Arguments: x: A tensor. Returns: A tensor with the same value and the same derivative as x, but that rai...
def _prevent_2nd_derivative(x): """Disables computation of the second derivatives for a tensor. NB: you need to apply a non-identity function to the output tensor for the exception to be raised. Arguments: x: A tensor. Returns: A tensor with the same value and the same derivative as x, but that rai...
[ "Disables", "computation", "of", "the", "second", "derivatives", "for", "a", "tensor", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/mixture_same_family.py#L566-L583
[ "def", "_prevent_2nd_derivative", "(", "x", ")", ":", "def", "grad", "(", "dy", ")", ":", "return", "array_ops", ".", "prevent_gradient", "(", "dy", ",", "message", "=", "\"Second derivative is not implemented.\"", ")", "return", "tf", ".", "identity", "(", "x...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
MixtureSameFamily._reparameterize_sample
Adds reparameterization (pathwise) gradients to samples of the mixture. Implicit reparameterization gradients are dx/dphi = -(d transform(x, phi) / dx)^-1 * d transform(x, phi) / dphi, where transform(x, phi) is distributional transform that removes all parameters from samples x. We implement t...
tensorflow_probability/python/distributions/mixture_same_family.py
def _reparameterize_sample(self, x): """Adds reparameterization (pathwise) gradients to samples of the mixture. Implicit reparameterization gradients are dx/dphi = -(d transform(x, phi) / dx)^-1 * d transform(x, phi) / dphi, where transform(x, phi) is distributional transform that removes all pa...
def _reparameterize_sample(self, x): """Adds reparameterization (pathwise) gradients to samples of the mixture. Implicit reparameterization gradients are dx/dphi = -(d transform(x, phi) / dx)^-1 * d transform(x, phi) / dphi, where transform(x, phi) is distributional transform that removes all pa...
[ "Adds", "reparameterization", "(", "pathwise", ")", "gradients", "to", "samples", "of", "the", "mixture", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/mixture_same_family.py#L407-L467
[ "def", "_reparameterize_sample", "(", "self", ",", "x", ")", ":", "# Remove the existing gradients of x wrt parameters of the components.", "x", "=", "tf", ".", "stop_gradient", "(", "x", ")", "x_2d_shape", "=", "[", "-", "1", ",", "self", ".", "_event_size", "]",...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
MixtureSameFamily._distributional_transform
Performs distributional transform of the mixture samples. Distributional transform removes the parameters from samples of a multivariate distribution by applying conditional CDFs: (F(x_1), F(x_2 | x1_), ..., F(x_d | x_1, ..., x_d-1)) (the indexing is over the "flattened" event dimensions). The re...
tensorflow_probability/python/distributions/mixture_same_family.py
def _distributional_transform(self, x): """Performs distributional transform of the mixture samples. Distributional transform removes the parameters from samples of a multivariate distribution by applying conditional CDFs: (F(x_1), F(x_2 | x1_), ..., F(x_d | x_1, ..., x_d-1)) (the indexing is ove...
def _distributional_transform(self, x): """Performs distributional transform of the mixture samples. Distributional transform removes the parameters from samples of a multivariate distribution by applying conditional CDFs: (F(x_1), F(x_2 | x1_), ..., F(x_d | x_1, ..., x_d-1)) (the indexing is ove...
[ "Performs", "distributional", "transform", "of", "the", "mixture", "samples", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/mixture_same_family.py#L469-L533
[ "def", "_distributional_transform", "(", "self", ",", "x", ")", ":", "if", "tensorshape_util", ".", "rank", "(", "x", ".", "shape", ")", "is", "None", ":", "# tf.nn.softmax raises an error when applied to inputs of undefined rank.", "raise", "ValueError", "(", "\"Dist...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_split_covariance_into_marginals
Split a covariance matrix into block-diagonal marginals of given sizes.
tensorflow_probability/python/sts/decomposition.py
def _split_covariance_into_marginals(covariance, block_sizes): """Split a covariance matrix into block-diagonal marginals of given sizes.""" start_dim = 0 marginals = [] for size in block_sizes: end_dim = start_dim + size marginals.append(covariance[..., start_dim:end_dim, start_dim:end_dim]) start_...
def _split_covariance_into_marginals(covariance, block_sizes): """Split a covariance matrix into block-diagonal marginals of given sizes.""" start_dim = 0 marginals = [] for size in block_sizes: end_dim = start_dim + size marginals.append(covariance[..., start_dim:end_dim, start_dim:end_dim]) start_...
[ "Split", "a", "covariance", "matrix", "into", "block", "-", "diagonal", "marginals", "of", "given", "sizes", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/sts/decomposition.py#L29-L37
[ "def", "_split_covariance_into_marginals", "(", "covariance", ",", "block_sizes", ")", ":", "start_dim", "=", "0", "marginals", "=", "[", "]", "for", "size", "in", "block_sizes", ":", "end_dim", "=", "start_dim", "+", "size", "marginals", ".", "append", "(", ...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_decompose_from_posterior_marginals
Utility method to decompose a joint posterior into components. Args: model: `tfp.sts.Sum` instance defining an additive STS model. posterior_means: float `Tensor` of shape `concat( [[num_posterior_draws], batch_shape, num_timesteps, latent_size])` representing the posterior mean over latents in a...
tensorflow_probability/python/sts/decomposition.py
def _decompose_from_posterior_marginals( model, posterior_means, posterior_covs, parameter_samples): """Utility method to decompose a joint posterior into components. Args: model: `tfp.sts.Sum` instance defining an additive STS model. posterior_means: float `Tensor` of shape `concat( [[num_poster...
def _decompose_from_posterior_marginals( model, posterior_means, posterior_covs, parameter_samples): """Utility method to decompose a joint posterior into components. Args: model: `tfp.sts.Sum` instance defining an additive STS model. posterior_means: float `Tensor` of shape `concat( [[num_poster...
[ "Utility", "method", "to", "decompose", "a", "joint", "posterior", "into", "components", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/sts/decomposition.py#L40-L106
[ "def", "_decompose_from_posterior_marginals", "(", "model", ",", "posterior_means", ",", "posterior_covs", ",", "parameter_samples", ")", ":", "try", ":", "model", ".", "components", "except", "AttributeError", ":", "raise", "ValueError", "(", "'Model decomposed into co...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
decompose_by_component
Decompose an observed time series into contributions from each component. This method decomposes a time series according to the posterior represention of a structural time series model. In particular, it: - Computes the posterior marginal mean and covariances over the additive model's latent space. -...
tensorflow_probability/python/sts/decomposition.py
def decompose_by_component(model, observed_time_series, parameter_samples): """Decompose an observed time series into contributions from each component. This method decomposes a time series according to the posterior represention of a structural time series model. In particular, it: - Computes the posterior ...
def decompose_by_component(model, observed_time_series, parameter_samples): """Decompose an observed time series into contributions from each component. This method decomposes a time series according to the posterior represention of a structural time series model. In particular, it: - Computes the posterior ...
[ "Decompose", "an", "observed", "time", "series", "into", "contributions", "from", "each", "component", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/sts/decomposition.py#L109-L219
[ "def", "decompose_by_component", "(", "model", ",", "observed_time_series", ",", "parameter_samples", ")", ":", "with", "tf", ".", "compat", ".", "v1", ".", "name_scope", "(", "'decompose_by_component'", ",", "values", "=", "[", "observed_time_series", "]", ")", ...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
decompose_forecast_by_component
Decompose a forecast distribution into contributions from each component. Args: model: An instance of `tfp.sts.Sum` representing a structural time series model. forecast_dist: A `Distribution` instance returned by `tfp.sts.forecast()`. (specifically, must be a `tfd.MixtureSameFamily` over a ...
tensorflow_probability/python/sts/decomposition.py
def decompose_forecast_by_component(model, forecast_dist, parameter_samples): """Decompose a forecast distribution into contributions from each component. Args: model: An instance of `tfp.sts.Sum` representing a structural time series model. forecast_dist: A `Distribution` instance returned by `tfp.s...
def decompose_forecast_by_component(model, forecast_dist, parameter_samples): """Decompose a forecast distribution into contributions from each component. Args: model: An instance of `tfp.sts.Sum` representing a structural time series model. forecast_dist: A `Distribution` instance returned by `tfp.s...
[ "Decompose", "a", "forecast", "distribution", "into", "contributions", "from", "each", "component", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/sts/decomposition.py#L222-L325
[ "def", "decompose_forecast_by_component", "(", "model", ",", "forecast_dist", ",", "parameter_samples", ")", ":", "with", "tf", ".", "compat", ".", "v1", ".", "name_scope", "(", "'decompose_forecast_by_component'", ")", ":", "try", ":", "forecast_lgssm", "=", "for...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
dense_to_sparse
Converts dense `Tensor` to `SparseTensor`, dropping `ignore_value` cells. Args: x: A `Tensor`. ignore_value: Entries in `x` equal to this value will be absent from the return `SparseTensor`. If `None`, default value of `x` dtype will be used (e.g. '' for `str`, 0 for `int`). name: Python `str...
tensorflow_probability/python/math/sparse.py
def dense_to_sparse(x, ignore_value=None, name=None): """Converts dense `Tensor` to `SparseTensor`, dropping `ignore_value` cells. Args: x: A `Tensor`. ignore_value: Entries in `x` equal to this value will be absent from the return `SparseTensor`. If `None`, default value of `x` dtype will be u...
def dense_to_sparse(x, ignore_value=None, name=None): """Converts dense `Tensor` to `SparseTensor`, dropping `ignore_value` cells. Args: x: A `Tensor`. ignore_value: Entries in `x` equal to this value will be absent from the return `SparseTensor`. If `None`, default value of `x` dtype will be u...
[ "Converts", "dense", "Tensor", "to", "SparseTensor", "dropping", "ignore_value", "cells", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/math/sparse.py#L30-L61
[ "def", "dense_to_sparse", "(", "x", ",", "ignore_value", "=", "None", ",", "name", "=", "None", ")", ":", "# Copied (with modifications) from:", "# tensorflow/contrib/layers/python/ops/sparse_ops.py.", "with", "tf", ".", "compat", ".", "v1", ".", "name_scope", "(", ...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_operator
Defers an operator overload to `attr`. Args: attr: Operator attribute to use. Returns: Function calling operator attribute.
tensorflow_probability/python/edward2/random_variable.py
def _operator(attr): """Defers an operator overload to `attr`. Args: attr: Operator attribute to use. Returns: Function calling operator attribute. """ @functools.wraps(attr) def func(a, *args): return attr(a.value, *args) return func
def _operator(attr): """Defers an operator overload to `attr`. Args: attr: Operator attribute to use. Returns: Function calling operator attribute. """ @functools.wraps(attr) def func(a, *args): return attr(a.value, *args) return func
[ "Defers", "an", "operator", "overload", "to", "attr", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/edward2/random_variable.py#L32-L44
[ "def", "_operator", "(", "attr", ")", ":", "@", "functools", ".", "wraps", "(", "attr", ")", "def", "func", "(", "a", ",", "*", "args", ")", ":", "return", "attr", "(", "a", ".", "value", ",", "*", "args", ")", "return", "func" ]
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_numpy_text
Human-readable representation of a tensor's numpy value.
tensorflow_probability/python/edward2/random_variable.py
def _numpy_text(tensor, is_repr=False): """Human-readable representation of a tensor's numpy value.""" if tensor.dtype.is_numpy_compatible: text = repr(tensor.numpy()) if is_repr else str(tensor.numpy()) else: text = "<unprintable>" if "\n" in text: text = "\n" + text return text
def _numpy_text(tensor, is_repr=False): """Human-readable representation of a tensor's numpy value.""" if tensor.dtype.is_numpy_compatible: text = repr(tensor.numpy()) if is_repr else str(tensor.numpy()) else: text = "<unprintable>" if "\n" in text: text = "\n" + text return text
[ "Human", "-", "readable", "representation", "of", "a", "tensor", "s", "numpy", "value", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/edward2/random_variable.py#L287-L295
[ "def", "_numpy_text", "(", "tensor", ",", "is_repr", "=", "False", ")", ":", "if", "tensor", ".", "dtype", ".", "is_numpy_compatible", ":", "text", "=", "repr", "(", "tensor", ".", "numpy", "(", ")", ")", "if", "is_repr", "else", "str", "(", "tensor", ...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
RandomVariable.sample_shape
Sample shape of random variable as a `TensorShape`.
tensorflow_probability/python/edward2/random_variable.py
def sample_shape(self): """Sample shape of random variable as a `TensorShape`.""" if isinstance(self._sample_shape, tf.Tensor): return tf.TensorShape(tf.get_static_value(self._sample_shape)) return tf.TensorShape(self._sample_shape)
def sample_shape(self): """Sample shape of random variable as a `TensorShape`.""" if isinstance(self._sample_shape, tf.Tensor): return tf.TensorShape(tf.get_static_value(self._sample_shape)) return tf.TensorShape(self._sample_shape)
[ "Sample", "shape", "of", "random", "variable", "as", "a", "TensorShape", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/edward2/random_variable.py#L133-L137
[ "def", "sample_shape", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "_sample_shape", ",", "tf", ".", "Tensor", ")", ":", "return", "tf", ".", "TensorShape", "(", "tf", ".", "get_static_value", "(", "self", ".", "_sample_shape", ")", ")", ...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
RandomVariable.sample_shape_tensor
Sample shape of random variable as a 1-D `Tensor`. Args: name: name to give to the op Returns: sample_shape: `Tensor`.
tensorflow_probability/python/edward2/random_variable.py
def sample_shape_tensor(self, name="sample_shape_tensor"): """Sample shape of random variable as a 1-D `Tensor`. Args: name: name to give to the op Returns: sample_shape: `Tensor`. """ with tf.compat.v1.name_scope(name): if isinstance(self._sample_shape, tf.Tensor): retur...
def sample_shape_tensor(self, name="sample_shape_tensor"): """Sample shape of random variable as a 1-D `Tensor`. Args: name: name to give to the op Returns: sample_shape: `Tensor`. """ with tf.compat.v1.name_scope(name): if isinstance(self._sample_shape, tf.Tensor): retur...
[ "Sample", "shape", "of", "random", "variable", "as", "a", "1", "-", "D", "Tensor", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/edward2/random_variable.py#L139-L152
[ "def", "sample_shape_tensor", "(", "self", ",", "name", "=", "\"sample_shape_tensor\"", ")", ":", "with", "tf", ".", "compat", ".", "v1", ".", "name_scope", "(", "name", ")", ":", "if", "isinstance", "(", "self", ".", "_sample_shape", ",", "tf", ".", "Te...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
RandomVariable.value
Get tensor that the random variable corresponds to.
tensorflow_probability/python/edward2/random_variable.py
def value(self): """Get tensor that the random variable corresponds to.""" if self._value is None: try: self._value = self.distribution.sample(self.sample_shape_tensor()) except NotImplementedError: raise NotImplementedError( "sample is not implemented for {0}. You must e...
def value(self): """Get tensor that the random variable corresponds to.""" if self._value is None: try: self._value = self.distribution.sample(self.sample_shape_tensor()) except NotImplementedError: raise NotImplementedError( "sample is not implemented for {0}. You must e...
[ "Get", "tensor", "that", "the", "random", "variable", "corresponds", "to", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/edward2/random_variable.py#L160-L170
[ "def", "value", "(", "self", ")", ":", "if", "self", ".", "_value", "is", "None", ":", "try", ":", "self", ".", "_value", "=", "self", ".", "distribution", ".", "sample", "(", "self", ".", "sample_shape_tensor", "(", ")", ")", "except", "NotImplemented...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
RandomVariable.eval
In a session, computes and returns the value of this random variable. This is not a graph construction method, it does not add ops to the graph. This convenience method requires a session where the graph containing this variable has been launched. If no session is passed, the default session is used. ...
tensorflow_probability/python/edward2/random_variable.py
def eval(self, session=None, feed_dict=None): """In a session, computes and returns the value of this random variable. This is not a graph construction method, it does not add ops to the graph. This convenience method requires a session where the graph containing this variable has been launched. If no...
def eval(self, session=None, feed_dict=None): """In a session, computes and returns the value of this random variable. This is not a graph construction method, it does not add ops to the graph. This convenience method requires a session where the graph containing this variable has been launched. If no...
[ "In", "a", "session", "computes", "and", "returns", "the", "value", "of", "this", "random", "variable", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/edward2/random_variable.py#L236-L268
[ "def", "eval", "(", "self", ",", "session", "=", "None", ",", "feed_dict", "=", "None", ")", ":", "return", "self", ".", "value", ".", "eval", "(", "session", "=", "session", ",", "feed_dict", "=", "feed_dict", ")" ]
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
RandomVariable.numpy
Value as NumPy array, only available for TF Eager.
tensorflow_probability/python/edward2/random_variable.py
def numpy(self): """Value as NumPy array, only available for TF Eager.""" if not isinstance(self.value, ops.EagerTensor): raise NotImplementedError("value argument must be a EagerTensor.") return self.value.numpy()
def numpy(self): """Value as NumPy array, only available for TF Eager.""" if not isinstance(self.value, ops.EagerTensor): raise NotImplementedError("value argument must be a EagerTensor.") return self.value.numpy()
[ "Value", "as", "NumPy", "array", "only", "available", "for", "TF", "Eager", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/edward2/random_variable.py#L270-L275
[ "def", "numpy", "(", "self", ")", ":", "if", "not", "isinstance", "(", "self", ".", "value", ",", "ops", ".", "EagerTensor", ")", ":", "raise", "NotImplementedError", "(", "\"value argument must be a EagerTensor.\"", ")", "return", "self", ".", "value", ".", ...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
normal_conjugates_known_scale_posterior
Posterior Normal distribution with conjugate prior on the mean. This model assumes that `n` observations (with sum `s`) come from a Normal with unknown mean `loc` (described by the Normal `prior`) and known variance `scale**2`. The "known scale posterior" is the distribution of the unknown `loc`. Accepts a ...
tensorflow_probability/python/distributions/normal_conjugate_posteriors.py
def normal_conjugates_known_scale_posterior(prior, scale, s, n): """Posterior Normal distribution with conjugate prior on the mean. This model assumes that `n` observations (with sum `s`) come from a Normal with unknown mean `loc` (described by the Normal `prior`) and known variance `scale**2`. The "known scal...
def normal_conjugates_known_scale_posterior(prior, scale, s, n): """Posterior Normal distribution with conjugate prior on the mean. This model assumes that `n` observations (with sum `s`) come from a Normal with unknown mean `loc` (described by the Normal `prior`) and known variance `scale**2`. The "known scal...
[ "Posterior", "Normal", "distribution", "with", "conjugate", "prior", "on", "the", "mean", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/normal_conjugate_posteriors.py#L25-L81
[ "def", "normal_conjugates_known_scale_posterior", "(", "prior", ",", "scale", ",", "s", ",", "n", ")", ":", "if", "not", "isinstance", "(", "prior", ",", "normal", ".", "Normal", ")", ":", "raise", "TypeError", "(", "\"Expected prior to be an instance of type Norm...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
real_nvp_default_template
Build a scale-and-shift function using a multi-layer neural network. This will be wrapped in a make_template to ensure the variables are only created once. It takes the `d`-dimensional input x[0:d] and returns the `D-d` dimensional outputs `loc` ("mu") and `log_scale` ("alpha"). The default template does not ...
tensorflow_probability/python/bijectors/real_nvp.py
def real_nvp_default_template(hidden_layers, shift_only=False, activation=tf.nn.relu, name=None, *args, # pylint: disable=keyword-arg-before-vararg **kwargs): """Build...
def real_nvp_default_template(hidden_layers, shift_only=False, activation=tf.nn.relu, name=None, *args, # pylint: disable=keyword-arg-before-vararg **kwargs): """Build...
[ "Build", "a", "scale", "-", "and", "-", "shift", "function", "using", "a", "multi", "-", "layer", "neural", "network", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/bijectors/real_nvp.py#L228-L305
[ "def", "real_nvp_default_template", "(", "hidden_layers", ",", "shift_only", "=", "False", ",", "activation", "=", "tf", ".", "nn", ".", "relu", ",", "name", "=", "None", ",", "*", "args", ",", "# pylint: disable=keyword-arg-before-vararg", "*", "*", "kwargs", ...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_uniform_unit_norm
Returns a batch of points chosen uniformly from the unit hypersphere.
tensorflow_probability/python/distributions/lkj.py
def _uniform_unit_norm(dimension, shape, dtype, seed): """Returns a batch of points chosen uniformly from the unit hypersphere.""" # This works because the Gaussian distribution is spherically symmetric. # raw shape: shape + [dimension] raw = normal.Normal( loc=dtype_util.as_numpy_dtype(dtype)(0), s...
def _uniform_unit_norm(dimension, shape, dtype, seed): """Returns a batch of points chosen uniformly from the unit hypersphere.""" # This works because the Gaussian distribution is spherically symmetric. # raw shape: shape + [dimension] raw = normal.Normal( loc=dtype_util.as_numpy_dtype(dtype)(0), s...
[ "Returns", "a", "batch", "of", "points", "chosen", "uniformly", "from", "the", "unit", "hypersphere", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/lkj.py#L47-L56
[ "def", "_uniform_unit_norm", "(", "dimension", ",", "shape", ",", "dtype", ",", "seed", ")", ":", "# This works because the Gaussian distribution is spherically symmetric.", "# raw shape: shape + [dimension]", "raw", "=", "normal", ".", "Normal", "(", "loc", "=", "dtype_u...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_replicate
Replicate the input tensor n times along a new (major) dimension.
tensorflow_probability/python/distributions/lkj.py
def _replicate(n, tensor): """Replicate the input tensor n times along a new (major) dimension.""" # TODO(axch) Does this already exist somewhere? Should it get contributed? multiples = tf.concat([[n], tf.ones_like(tensor.shape)], axis=0) return tf.tile(tf.expand_dims(tensor, axis=0), multiples)
def _replicate(n, tensor): """Replicate the input tensor n times along a new (major) dimension.""" # TODO(axch) Does this already exist somewhere? Should it get contributed? multiples = tf.concat([[n], tf.ones_like(tensor.shape)], axis=0) return tf.tile(tf.expand_dims(tensor, axis=0), multiples)
[ "Replicate", "the", "input", "tensor", "n", "times", "along", "a", "new", "(", "major", ")", "dimension", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/lkj.py#L59-L63
[ "def", "_replicate", "(", "n", ",", "tensor", ")", ":", "# TODO(axch) Does this already exist somewhere? Should it get contributed?", "multiples", "=", "tf", ".", "concat", "(", "[", "[", "n", "]", ",", "tf", ".", "ones_like", "(", "tensor", ".", "shape", ")", ...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
LKJ._sample_n
Returns a Tensor of samples from an LKJ distribution. Args: num_samples: Python `int`. The number of samples to draw. seed: Python integer seed for RNG name: Python `str` name prefixed to Ops created by this function. Returns: samples: A Tensor of correlation matrices with shape `[n, B...
tensorflow_probability/python/distributions/lkj.py
def _sample_n(self, num_samples, seed=None, name=None): """Returns a Tensor of samples from an LKJ distribution. Args: num_samples: Python `int`. The number of samples to draw. seed: Python integer seed for RNG name: Python `str` name prefixed to Ops created by this function. Returns: ...
def _sample_n(self, num_samples, seed=None, name=None): """Returns a Tensor of samples from an LKJ distribution. Args: num_samples: Python `int`. The number of samples to draw. seed: Python integer seed for RNG name: Python `str` name prefixed to Ops created by this function. Returns: ...
[ "Returns", "a", "Tensor", "of", "samples", "from", "an", "LKJ", "distribution", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/lkj.py#L190-L313
[ "def", "_sample_n", "(", "self", ",", "num_samples", ",", "seed", "=", "None", ",", "name", "=", "None", ")", ":", "if", "self", ".", "dimension", "<", "0", ":", "raise", "ValueError", "(", "'Cannot sample negative-dimension correlation matrices.'", ")", "# No...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
LKJ._log_unnorm_prob
Returns the unnormalized log density of an LKJ distribution. Args: x: `float` or `double` `Tensor` of correlation matrices. The shape of `x` must be `B + [D, D]`, where `B` broadcasts with the shape of `concentration`. name: Python `str` name prefixed to Ops created by this function. ...
tensorflow_probability/python/distributions/lkj.py
def _log_unnorm_prob(self, x, name=None): """Returns the unnormalized log density of an LKJ distribution. Args: x: `float` or `double` `Tensor` of correlation matrices. The shape of `x` must be `B + [D, D]`, where `B` broadcasts with the shape of `concentration`. name: Python `str`...
def _log_unnorm_prob(self, x, name=None): """Returns the unnormalized log density of an LKJ distribution. Args: x: `float` or `double` `Tensor` of correlation matrices. The shape of `x` must be `B + [D, D]`, where `B` broadcasts with the shape of `concentration`. name: Python `str`...
[ "Returns", "the", "unnormalized", "log", "density", "of", "an", "LKJ", "distribution", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/lkj.py#L371-L410
[ "def", "_log_unnorm_prob", "(", "self", ",", "x", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "name", "or", "'log_unnorm_prob_lkj'", ")", ":", "x", "=", "tf", ".", "convert_to_tensor", "(", "value", "=", "x", ",", "name", ...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
LKJ._log_normalization
Returns the log normalization of an LKJ distribution. Args: name: Python `str` name prefixed to Ops created by this function. Returns: log_z: A Tensor of the same shape and dtype as `concentration`, containing the corresponding log normalizers.
tensorflow_probability/python/distributions/lkj.py
def _log_normalization(self, name='log_normalization'): """Returns the log normalization of an LKJ distribution. Args: name: Python `str` name prefixed to Ops created by this function. Returns: log_z: A Tensor of the same shape and dtype as `concentration`, containing the corresponding...
def _log_normalization(self, name='log_normalization'): """Returns the log normalization of an LKJ distribution. Args: name: Python `str` name prefixed to Ops created by this function. Returns: log_z: A Tensor of the same shape and dtype as `concentration`, containing the corresponding...
[ "Returns", "the", "log", "normalization", "of", "an", "LKJ", "distribution", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/lkj.py#L412-L432
[ "def", "_log_normalization", "(", "self", ",", "name", "=", "'log_normalization'", ")", ":", "# The formula is from D. Lewandowski et al [1], p. 1999, from the", "# proof that eqs 16 and 17 are equivalent.", "with", "tf", ".", "name_scope", "(", "name", "or", "'log_normalizatio...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
common_dtype
Returns explict dtype from `args_list` if exists, else preferred_dtype.
tensorflow_probability/python/internal/backend/numpy/internal/utils.py
def common_dtype(args_list, preferred_dtype=None): """Returns explict dtype from `args_list` if exists, else preferred_dtype.""" dtype = None preferred_dtype = (None if preferred_dtype is None else tf.as_dtype(preferred_dtype)) for a in tf.nest.flatten(args_list): if hasattr(a, 'dtype')...
def common_dtype(args_list, preferred_dtype=None): """Returns explict dtype from `args_list` if exists, else preferred_dtype.""" dtype = None preferred_dtype = (None if preferred_dtype is None else tf.as_dtype(preferred_dtype)) for a in tf.nest.flatten(args_list): if hasattr(a, 'dtype')...
[ "Returns", "explict", "dtype", "from", "args_list", "if", "exists", "else", "preferred_dtype", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/backend/numpy/internal/utils.py#L58-L74
[ "def", "common_dtype", "(", "args_list", ",", "preferred_dtype", "=", "None", ")", ":", "dtype", "=", "None", "preferred_dtype", "=", "(", "None", "if", "preferred_dtype", "is", "None", "else", "tf", ".", "as_dtype", "(", "preferred_dtype", ")", ")", "for", ...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_make_summary_statistic
Factory for implementing summary statistics, eg, mean, stddev, mode.
tensorflow_probability/python/distributions/sample.py
def _make_summary_statistic(attr): """Factory for implementing summary statistics, eg, mean, stddev, mode.""" def _fn(self, **kwargs): """Implements summary statistic, eg, mean, stddev, mode.""" x = getattr(self.distribution, attr)(**kwargs) shape = prefer_static.concat([ self.distribution.batch...
def _make_summary_statistic(attr): """Factory for implementing summary statistics, eg, mean, stddev, mode.""" def _fn(self, **kwargs): """Implements summary statistic, eg, mean, stddev, mode.""" x = getattr(self.distribution, attr)(**kwargs) shape = prefer_static.concat([ self.distribution.batch...
[ "Factory", "for", "implementing", "summary", "statistics", "eg", "mean", "stddev", "mode", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/sample.py#L34-L52
[ "def", "_make_summary_statistic", "(", "attr", ")", ":", "def", "_fn", "(", "self", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Implements summary statistic, eg, mean, stddev, mode.\"\"\"", "x", "=", "getattr", "(", "self", ".", "distribution", ",", "attr", ")", "...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_kl_sample
Batched KL divergence `KL(a || b)` for Sample distributions. We can leverage the fact that: ``` KL(Sample(a) || Sample(b)) = sum(KL(a || b)) ``` where the sum is over the `sample_shape` dims. Args: a: Instance of `Sample` distribution. b: Instance of `Sample` distribution. name: (optional) n...
tensorflow_probability/python/distributions/sample.py
def _kl_sample(a, b, name='kl_sample'): """Batched KL divergence `KL(a || b)` for Sample distributions. We can leverage the fact that: ``` KL(Sample(a) || Sample(b)) = sum(KL(a || b)) ``` where the sum is over the `sample_shape` dims. Args: a: Instance of `Sample` distribution. b: Instance of ...
def _kl_sample(a, b, name='kl_sample'): """Batched KL divergence `KL(a || b)` for Sample distributions. We can leverage the fact that: ``` KL(Sample(a) || Sample(b)) = sum(KL(a || b)) ``` where the sum is over the `sample_shape` dims. Args: a: Instance of `Sample` distribution. b: Instance of ...
[ "Batched", "KL", "divergence", "KL", "(", "a", "||", "b", ")", "for", "Sample", "distributions", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/sample.py#L241-L278
[ "def", "_kl_sample", "(", "a", ",", "b", ",", "name", "=", "'kl_sample'", ")", ":", "assertions", "=", "[", "]", "a_ss", "=", "tf", ".", "get_static_value", "(", "a", ".", "sample_shape", ")", "b_ss", "=", "tf", ".", "get_static_value", "(", "b", "."...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_broadcast_to
Helper to broadcast a tensor using a list of target tensors.
tensorflow_probability/python/distributions/triangular.py
def _broadcast_to(tensor_to_broadcast, target_tensors): """Helper to broadcast a tensor using a list of target tensors.""" output = tensor_to_broadcast for tensor in target_tensors: output += tf.zeros_like(tensor) return output
def _broadcast_to(tensor_to_broadcast, target_tensors): """Helper to broadcast a tensor using a list of target tensors.""" output = tensor_to_broadcast for tensor in target_tensors: output += tf.zeros_like(tensor) return output
[ "Helper", "to", "broadcast", "a", "tensor", "using", "a", "list", "of", "target", "tensors", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/triangular.py#L33-L38
[ "def", "_broadcast_to", "(", "tensor_to_broadcast", ",", "target_tensors", ")", ":", "output", "=", "tensor_to_broadcast", "for", "tensor", "in", "target_tensors", ":", "output", "+=", "tf", ".", "zeros_like", "(", "tensor", ")", "return", "output" ]
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
Triangular._pdf_at_peak
Pdf evaluated at the peak.
tensorflow_probability/python/distributions/triangular.py
def _pdf_at_peak(self): """Pdf evaluated at the peak.""" return (self.peak - self.low) / (self.high - self.low)
def _pdf_at_peak(self): """Pdf evaluated at the peak.""" return (self.peak - self.low) / (self.high - self.low)
[ "Pdf", "evaluated", "at", "the", "peak", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/triangular.py#L186-L188
[ "def", "_pdf_at_peak", "(", "self", ")", ":", "return", "(", "self", ".", "peak", "-", "self", ".", "low", ")", "/", "(", "self", ".", "high", "-", "self", ".", "low", ")" ]
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
effective_sample_size
Estimate a lower bound on effective sample size for each independent chain. Roughly speaking, "effective sample size" (ESS) is the size of an iid sample with the same variance as `state`. More precisely, given a stationary sequence of possibly correlated random variables `X_1, X_2,...,X_N`, each identically d...
tensorflow_probability/python/mcmc/diagnostic.py
def effective_sample_size(states, filter_threshold=0., filter_beyond_lag=None, name=None): """Estimate a lower bound on effective sample size for each independent chain. Roughly speaking, "effective sample size" (ESS) is the size of an i...
def effective_sample_size(states, filter_threshold=0., filter_beyond_lag=None, name=None): """Estimate a lower bound on effective sample size for each independent chain. Roughly speaking, "effective sample size" (ESS) is the size of an i...
[ "Estimate", "a", "lower", "bound", "on", "effective", "sample", "size", "for", "each", "independent", "chain", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/diagnostic.py#L35-L143
[ "def", "effective_sample_size", "(", "states", ",", "filter_threshold", "=", "0.", ",", "filter_beyond_lag", "=", "None", ",", "name", "=", "None", ")", ":", "states_was_list", "=", "_is_list_like", "(", "states", ")", "# Convert all args to lists.", "if", "not", ...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_effective_sample_size_single_state
ESS computation for one single Tensor argument.
tensorflow_probability/python/mcmc/diagnostic.py
def _effective_sample_size_single_state(states, filter_beyond_lag, filter_threshold): """ESS computation for one single Tensor argument.""" with tf.compat.v1.name_scope( 'effective_sample_size_single_state', values=[states, filter_beyond_lag, filter_threshold]): ...
def _effective_sample_size_single_state(states, filter_beyond_lag, filter_threshold): """ESS computation for one single Tensor argument.""" with tf.compat.v1.name_scope( 'effective_sample_size_single_state', values=[states, filter_beyond_lag, filter_threshold]): ...
[ "ESS", "computation", "for", "one", "single", "Tensor", "argument", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/diagnostic.py#L146-L200
[ "def", "_effective_sample_size_single_state", "(", "states", ",", "filter_beyond_lag", ",", "filter_threshold", ")", ":", "with", "tf", ".", "compat", ".", "v1", ".", "name_scope", "(", "'effective_sample_size_single_state'", ",", "values", "=", "[", "states", ",", ...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
potential_scale_reduction
Gelman and Rubin (1992)'s potential scale reduction for chain convergence. Given `N > 1` states from each of `C > 1` independent chains, the potential scale reduction factor, commonly referred to as R-hat, measures convergence of the chains (to the same target) by testing for equality of means. Specifically, R...
tensorflow_probability/python/mcmc/diagnostic.py
def potential_scale_reduction(chains_states, independent_chain_ndims=1, name=None): """Gelman and Rubin (1992)'s potential scale reduction for chain convergence. Given `N > 1` states from each of `C > 1` independent chains, the potential scale reduction...
def potential_scale_reduction(chains_states, independent_chain_ndims=1, name=None): """Gelman and Rubin (1992)'s potential scale reduction for chain convergence. Given `N > 1` states from each of `C > 1` independent chains, the potential scale reduction...
[ "Gelman", "and", "Rubin", "(", "1992", ")", "s", "potential", "scale", "reduction", "for", "chain", "convergence", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/diagnostic.py#L203-L332
[ "def", "potential_scale_reduction", "(", "chains_states", ",", "independent_chain_ndims", "=", "1", ",", "name", "=", "None", ")", ":", "chains_states_was_list", "=", "_is_list_like", "(", "chains_states", ")", "if", "not", "chains_states_was_list", ":", "chains_state...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_potential_scale_reduction_single_state
potential_scale_reduction for one single state `Tensor`.
tensorflow_probability/python/mcmc/diagnostic.py
def _potential_scale_reduction_single_state(state, independent_chain_ndims): """potential_scale_reduction for one single state `Tensor`.""" with tf.compat.v1.name_scope( 'potential_scale_reduction_single_state', values=[state, independent_chain_ndims]): # We assume exactly one leading dimension inde...
def _potential_scale_reduction_single_state(state, independent_chain_ndims): """potential_scale_reduction for one single state `Tensor`.""" with tf.compat.v1.name_scope( 'potential_scale_reduction_single_state', values=[state, independent_chain_ndims]): # We assume exactly one leading dimension inde...
[ "potential_scale_reduction", "for", "one", "single", "state", "Tensor", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/diagnostic.py#L335-L370
[ "def", "_potential_scale_reduction_single_state", "(", "state", ",", "independent_chain_ndims", ")", ":", "with", "tf", ".", "compat", ".", "v1", ".", "name_scope", "(", "'potential_scale_reduction_single_state'", ",", "values", "=", "[", "state", ",", "independent_ch...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_axis_size
Get number of elements of `x` in `axis`, as type `x.dtype`.
tensorflow_probability/python/mcmc/diagnostic.py
def _axis_size(x, axis=None): """Get number of elements of `x` in `axis`, as type `x.dtype`.""" if axis is None: return tf.cast(tf.size(input=x), x.dtype) return tf.cast( tf.reduce_prod(input_tensor=tf.gather(tf.shape(input=x), axis)), x.dtype)
def _axis_size(x, axis=None): """Get number of elements of `x` in `axis`, as type `x.dtype`.""" if axis is None: return tf.cast(tf.size(input=x), x.dtype) return tf.cast( tf.reduce_prod(input_tensor=tf.gather(tf.shape(input=x), axis)), x.dtype)
[ "Get", "number", "of", "elements", "of", "x", "in", "axis", "as", "type", "x", ".", "dtype", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/diagnostic.py#L388-L393
[ "def", "_axis_size", "(", "x", ",", "axis", "=", "None", ")", ":", "if", "axis", "is", "None", ":", "return", "tf", ".", "cast", "(", "tf", ".", "size", "(", "input", "=", "x", ")", ",", "x", ".", "dtype", ")", "return", "tf", ".", "cast", "(...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_broadcast_maybelist_arg
Broadcast a listable secondary_arg to that of states.
tensorflow_probability/python/mcmc/diagnostic.py
def _broadcast_maybelist_arg(states, secondary_arg, name): """Broadcast a listable secondary_arg to that of states.""" if _is_list_like(secondary_arg): if len(secondary_arg) != len(states): raise ValueError('Argument `%s` was a list of different length ({}) than ' '`states` ({})'.fo...
def _broadcast_maybelist_arg(states, secondary_arg, name): """Broadcast a listable secondary_arg to that of states.""" if _is_list_like(secondary_arg): if len(secondary_arg) != len(states): raise ValueError('Argument `%s` was a list of different length ({}) than ' '`states` ({})'.fo...
[ "Broadcast", "a", "listable", "secondary_arg", "to", "that", "of", "states", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/diagnostic.py#L401-L410
[ "def", "_broadcast_maybelist_arg", "(", "states", ",", "secondary_arg", ",", "name", ")", ":", "if", "_is_list_like", "(", "secondary_arg", ")", ":", "if", "len", "(", "secondary_arg", ")", "!=", "len", "(", "states", ")", ":", "raise", "ValueError", "(", ...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
quadrature_scheme_lognormal_gauss_hermite
Use Gauss-Hermite quadrature to form quadrature on positive-reals. Note: for a given `quadrature_size`, this method is generally less accurate than `quadrature_scheme_lognormal_quantiles`. Args: loc: `float`-like (batch of) scalar `Tensor`; the location parameter of the LogNormal prior. scale: `fl...
tensorflow_probability/python/distributions/poisson_lognormal.py
def quadrature_scheme_lognormal_gauss_hermite( loc, scale, quadrature_size, validate_args=False, name=None): # pylint: disable=unused-argument """Use Gauss-Hermite quadrature to form quadrature on positive-reals. Note: for a given `quadrature_size`, this method is generally less accurate than `quadratur...
def quadrature_scheme_lognormal_gauss_hermite( loc, scale, quadrature_size, validate_args=False, name=None): # pylint: disable=unused-argument """Use Gauss-Hermite quadrature to form quadrature on positive-reals. Note: for a given `quadrature_size`, this method is generally less accurate than `quadratur...
[ "Use", "Gauss", "-", "Hermite", "quadrature", "to", "form", "quadrature", "on", "positive", "-", "reals", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/poisson_lognormal.py#L45-L85
[ "def", "quadrature_scheme_lognormal_gauss_hermite", "(", "loc", ",", "scale", ",", "quadrature_size", ",", "validate_args", "=", "False", ",", "name", "=", "None", ")", ":", "# pylint: disable=unused-argument", "with", "tf", ".", "name_scope", "(", "name", "or", "...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
quadrature_scheme_lognormal_quantiles
Use LogNormal quantiles to form quadrature on positive-reals. Args: loc: `float`-like (batch of) scalar `Tensor`; the location parameter of the LogNormal prior. scale: `float`-like (batch of) scalar `Tensor`; the scale parameter of the LogNormal prior. quadrature_size: Python `int` scalar rep...
tensorflow_probability/python/distributions/poisson_lognormal.py
def quadrature_scheme_lognormal_quantiles( loc, scale, quadrature_size, validate_args=False, name=None): """Use LogNormal quantiles to form quadrature on positive-reals. Args: loc: `float`-like (batch of) scalar `Tensor`; the location parameter of the LogNormal prior. scale: `float`-like (bat...
def quadrature_scheme_lognormal_quantiles( loc, scale, quadrature_size, validate_args=False, name=None): """Use LogNormal quantiles to form quadrature on positive-reals. Args: loc: `float`-like (batch of) scalar `Tensor`; the location parameter of the LogNormal prior. scale: `float`-like (bat...
[ "Use", "LogNormal", "quantiles", "to", "form", "quadrature", "on", "positive", "-", "reals", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/poisson_lognormal.py#L88-L152
[ "def", "quadrature_scheme_lognormal_quantiles", "(", "loc", ",", "scale", ",", "quadrature_size", ",", "validate_args", "=", "False", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "name", "or", "\"quadrature_scheme_lognormal_quantiles\"",...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_Mapping.merge
Returns new _Mapping with args merged with self. Args: x: `Tensor` or None. Input to forward; output of inverse. y: `Tensor` or None. Input to inverse; output of forward. ildj: `Tensor`. This is the (un-reduce_sum'ed) inverse log det jacobian. kwargs: Python dictionary. Extra args supplied ...
tensorflow_probability/python/bijectors/bijector.py
def merge(self, x=None, y=None, ildj=None, kwargs=None, mapping=None): """Returns new _Mapping with args merged with self. Args: x: `Tensor` or None. Input to forward; output of inverse. y: `Tensor` or None. Input to inverse; output of forward. ildj: `Tensor`. This is the (un-reduce_sum'ed) i...
def merge(self, x=None, y=None, ildj=None, kwargs=None, mapping=None): """Returns new _Mapping with args merged with self. Args: x: `Tensor` or None. Input to forward; output of inverse. y: `Tensor` or None. Input to inverse; output of forward. ildj: `Tensor`. This is the (un-reduce_sum'ed) i...
[ "Returns", "new", "_Mapping", "with", "args", "merged", "with", "self", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/bijectors/bijector.py#L74-L102
[ "def", "merge", "(", "self", ",", "x", "=", "None", ",", "y", "=", "None", ",", "ildj", "=", "None", ",", "kwargs", "=", "None", ",", "mapping", "=", "None", ")", ":", "if", "mapping", "is", "None", ":", "mapping", "=", "_Mapping", "(", "x", "=...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_Mapping.remove
To support weak referencing, removes cache key from the cache value.
tensorflow_probability/python/bijectors/bijector.py
def remove(self, field): """To support weak referencing, removes cache key from the cache value.""" return _Mapping( x=None if field == "x" else self.x, y=None if field == "y" else self.y, ildj=self.ildj, kwargs=self.kwargs)
def remove(self, field): """To support weak referencing, removes cache key from the cache value.""" return _Mapping( x=None if field == "x" else self.x, y=None if field == "y" else self.y, ildj=self.ildj, kwargs=self.kwargs)
[ "To", "support", "weak", "referencing", "removes", "cache", "key", "from", "the", "cache", "value", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/bijectors/bijector.py#L104-L110
[ "def", "remove", "(", "self", ",", "field", ")", ":", "return", "_Mapping", "(", "x", "=", "None", "if", "field", "==", "\"x\"", "else", "self", ".", "x", ",", "y", "=", "None", "if", "field", "==", "\"y\"", "else", "self", ".", "y", ",", "ildj",...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_Mapping._merge
Helper to merge which handles merging one value.
tensorflow_probability/python/bijectors/bijector.py
def _merge(self, old, new, use_equals=False): """Helper to merge which handles merging one value.""" if old is None: return new if new is None: return old if (old == new) if use_equals else (old is new): return old raise ValueError("Incompatible values: %s != %s" % (old, new))
def _merge(self, old, new, use_equals=False): """Helper to merge which handles merging one value.""" if old is None: return new if new is None: return old if (old == new) if use_equals else (old is new): return old raise ValueError("Incompatible values: %s != %s" % (old, new))
[ "Helper", "to", "merge", "which", "handles", "merging", "one", "value", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/bijectors/bijector.py#L112-L120
[ "def", "_merge", "(", "self", ",", "old", ",", "new", ",", "use_equals", "=", "False", ")", ":", "if", "old", "is", "None", ":", "return", "new", "if", "new", "is", "None", ":", "return", "old", "if", "(", "old", "==", "new", ")", "if", "use_equa...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_Mapping._deep_tuple
Converts nested `tuple`, `list`, or `dict` to nested `tuple`.
tensorflow_probability/python/bijectors/bijector.py
def _deep_tuple(self, x): """Converts nested `tuple`, `list`, or `dict` to nested `tuple`.""" if isinstance(x, dict): return self._deep_tuple(tuple(sorted(x.items()))) elif isinstance(x, (list, tuple)): return tuple(map(self._deep_tuple, x)) return x
def _deep_tuple(self, x): """Converts nested `tuple`, `list`, or `dict` to nested `tuple`.""" if isinstance(x, dict): return self._deep_tuple(tuple(sorted(x.items()))) elif isinstance(x, (list, tuple)): return tuple(map(self._deep_tuple, x)) return x
[ "Converts", "nested", "tuple", "list", "or", "dict", "to", "nested", "tuple", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/bijectors/bijector.py#L122-L129
[ "def", "_deep_tuple", "(", "self", ",", "x", ")", ":", "if", "isinstance", "(", "x", ",", "dict", ")", ":", "return", "self", ".", "_deep_tuple", "(", "tuple", "(", "sorted", "(", "x", ".", "items", "(", ")", ")", ")", ")", "elif", "isinstance", ...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_left_doubling_increments
Computes the doubling increments for the left end point. The doubling procedure expands an initial interval to find a superset of the true slice. At each doubling iteration, the interval width is doubled to either the left or the right hand side with equal probability. If, initially, the left end point is at `...
tensorflow_probability/python/mcmc/internal/slice_sampler_utils.py
def _left_doubling_increments(batch_shape, max_doublings, step_size, seed=None, name=None): """Computes the doubling increments for the left end point. The doubling procedure expands an initial interval to find a superset of the true slice. At each doubling iteration, the interval w...
def _left_doubling_increments(batch_shape, max_doublings, step_size, seed=None, name=None): """Computes the doubling increments for the left end point. The doubling procedure expands an initial interval to find a superset of the true slice. At each doubling iteration, the interval w...
[ "Computes", "the", "doubling", "increments", "for", "the", "left", "end", "point", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/internal/slice_sampler_utils.py#L26-L87
[ "def", "_left_doubling_increments", "(", "batch_shape", ",", "max_doublings", ",", "step_size", ",", "seed", "=", "None", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "compat", ".", "v1", ".", "name_scope", "(", "name", ",", "'left_doubling_increme...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_find_best_interval_idx
Finds the index of the optimal set of bounds for each chain. For each chain, finds the smallest set of bounds for which both edges lie outside the slice. This is equivalent to the point at which a for loop implementation (P715 of Neal (2003)) of the algorithm would terminate. Performs the following calculatio...
tensorflow_probability/python/mcmc/internal/slice_sampler_utils.py
def _find_best_interval_idx(x, name=None): """Finds the index of the optimal set of bounds for each chain. For each chain, finds the smallest set of bounds for which both edges lie outside the slice. This is equivalent to the point at which a for loop implementation (P715 of Neal (2003)) of the algorithm would...
def _find_best_interval_idx(x, name=None): """Finds the index of the optimal set of bounds for each chain. For each chain, finds the smallest set of bounds for which both edges lie outside the slice. This is equivalent to the point at which a for loop implementation (P715 of Neal (2003)) of the algorithm would...
[ "Finds", "the", "index", "of", "the", "optimal", "set", "of", "bounds", "for", "each", "chain", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/internal/slice_sampler_utils.py#L90-L126
[ "def", "_find_best_interval_idx", "(", "x", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "compat", ".", "v1", ".", "name_scope", "(", "name", ",", "'find_best_interval_idx'", ",", "[", "x", "]", ")", ":", "# Returns max_doublings + 1. Positive int32....
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
slice_bounds_by_doubling
Returns the bounds of the slice at each stage of doubling procedure. Precomputes the x coordinates of the left (L) and right (R) endpoints of the interval `I` produced in the "doubling" algorithm [Neal 2003][1] P713. Note that we simultaneously compute all possible doubling values for each chain, for the reaso...
tensorflow_probability/python/mcmc/internal/slice_sampler_utils.py
def slice_bounds_by_doubling(x_initial, target_log_prob, log_slice_heights, max_doublings, step_size, seed=None, name=None): """Returns the boun...
def slice_bounds_by_doubling(x_initial, target_log_prob, log_slice_heights, max_doublings, step_size, seed=None, name=None): """Returns the boun...
[ "Returns", "the", "bounds", "of", "the", "slice", "at", "each", "stage", "of", "doubling", "procedure", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/internal/slice_sampler_utils.py#L129-L222
[ "def", "slice_bounds_by_doubling", "(", "x_initial", ",", "target_log_prob", ",", "log_slice_heights", ",", "max_doublings", ",", "step_size", ",", "seed", "=", "None", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "compat", ".", "v1", ".", "name_sc...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_sample_with_shrinkage
Samples from the slice by applying shrinkage for rejected points. Implements the one dimensional slice sampling algorithm of Neal (2003), with a doubling algorithm (Neal 2003 P715 Fig. 4), which doubles the size of the interval at each iteration and shrinkage (Neal 2003 P716 Fig. 5), which reduces the width of...
tensorflow_probability/python/mcmc/internal/slice_sampler_utils.py
def _sample_with_shrinkage(x_initial, target_log_prob, log_slice_heights, step_size, lower_bounds, upper_bounds, seed=None, name=None): """Samples from the slice by applying shrinkage for rejected points. Implements the one dimensional slice sampling algorithm ...
def _sample_with_shrinkage(x_initial, target_log_prob, log_slice_heights, step_size, lower_bounds, upper_bounds, seed=None, name=None): """Samples from the slice by applying shrinkage for rejected points. Implements the one dimensional slice sampling algorithm ...
[ "Samples", "from", "the", "slice", "by", "applying", "shrinkage", "for", "rejected", "points", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/internal/slice_sampler_utils.py#L304-L376
[ "def", "_sample_with_shrinkage", "(", "x_initial", ",", "target_log_prob", ",", "log_slice_heights", ",", "step_size", ",", "lower_bounds", ",", "upper_bounds", ",", "seed", "=", "None", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "compat", ".", "...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
slice_sampler_one_dim
For a given x position in each Markov chain, returns the next x. Applies the one dimensional slice sampling algorithm as defined in Neal (2003) to an input tensor x of shape (num_chains,) where num_chains is the number of simulataneous Markov chains, and returns the next tensor x of shape (num_chains,) when th...
tensorflow_probability/python/mcmc/internal/slice_sampler_utils.py
def slice_sampler_one_dim(target_log_prob, x_initial, step_size=0.01, max_doublings=30, seed=None, name=None): """For a given x position in each Markov chain, returns the next x. Applies the one dimensional slice sampling algorithm as defined in Neal (2003) to an input tensor x of shape...
def slice_sampler_one_dim(target_log_prob, x_initial, step_size=0.01, max_doublings=30, seed=None, name=None): """For a given x position in each Markov chain, returns the next x. Applies the one dimensional slice sampling algorithm as defined in Neal (2003) to an input tensor x of shape...
[ "For", "a", "given", "x", "position", "in", "each", "Markov", "chain", "returns", "the", "next", "x", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/internal/slice_sampler_utils.py#L379-L431
[ "def", "slice_sampler_one_dim", "(", "target_log_prob", ",", "x_initial", ",", "step_size", "=", "0.01", ",", "max_doublings", "=", "30", ",", "seed", "=", "None", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "compat", ".", "v1", ".", "name_sco...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
sample_annealed_importance_chain
Runs annealed importance sampling (AIS) to estimate normalizing constants. This function uses an MCMC transition operator (e.g., Hamiltonian Monte Carlo) to sample from a series of distributions that slowly interpolates between an initial "proposal" distribution: `exp(proposal_log_prob_fn(x) - proposal_log_no...
tensorflow_probability/python/mcmc/sample_annealed_importance.py
def sample_annealed_importance_chain( num_steps, proposal_log_prob_fn, target_log_prob_fn, current_state, make_kernel_fn, parallel_iterations=10, name=None): """Runs annealed importance sampling (AIS) to estimate normalizing constants. This function uses an MCMC transition operator (e.g...
def sample_annealed_importance_chain( num_steps, proposal_log_prob_fn, target_log_prob_fn, current_state, make_kernel_fn, parallel_iterations=10, name=None): """Runs annealed importance sampling (AIS) to estimate normalizing constants. This function uses an MCMC transition operator (e.g...
[ "Runs", "annealed", "importance", "sampling", "(", "AIS", ")", "to", "estimate", "normalizing", "constants", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/sample_annealed_importance.py#L43-L272
[ "def", "sample_annealed_importance_chain", "(", "num_steps", ",", "proposal_log_prob_fn", ",", "target_log_prob_fn", ",", "current_state", ",", "make_kernel_fn", ",", "parallel_iterations", "=", "10", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "compat", ...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
make_value_setter
Creates a value-setting interceptor. This function creates an interceptor that sets values of Edward2 random variable objects. This is useful for a range of tasks, including conditioning on observed data, sampling from posterior predictive distributions, and as a building block of inference primitives such as ...
tensorflow_probability/python/edward2/program_transformations.py
def make_value_setter(**model_kwargs): """Creates a value-setting interceptor. This function creates an interceptor that sets values of Edward2 random variable objects. This is useful for a range of tasks, including conditioning on observed data, sampling from posterior predictive distributions, and as a bui...
def make_value_setter(**model_kwargs): """Creates a value-setting interceptor. This function creates an interceptor that sets values of Edward2 random variable objects. This is useful for a range of tasks, including conditioning on observed data, sampling from posterior predictive distributions, and as a bui...
[ "Creates", "a", "value", "-", "setting", "interceptor", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/edward2/program_transformations.py#L34-L135
[ "def", "make_value_setter", "(", "*", "*", "model_kwargs", ")", ":", "def", "set_values", "(", "f", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Sets random variable values to its aligned value.\"\"\"", "name", "=", "kwargs", ".", "get", "(", "\...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
make_log_joint_fn
Takes Edward probabilistic program and returns its log joint function. Args: model: Python callable which executes the generative process of a computable probability distribution using `ed.RandomVariable`s. Returns: A log-joint probability function. Its inputs are `model`'s original inputs and r...
tensorflow_probability/python/edward2/program_transformations.py
def make_log_joint_fn(model): """Takes Edward probabilistic program and returns its log joint function. Args: model: Python callable which executes the generative process of a computable probability distribution using `ed.RandomVariable`s. Returns: A log-joint probability function. Its inputs are ...
def make_log_joint_fn(model): """Takes Edward probabilistic program and returns its log joint function. Args: model: Python callable which executes the generative process of a computable probability distribution using `ed.RandomVariable`s. Returns: A log-joint probability function. Its inputs are ...
[ "Takes", "Edward", "probabilistic", "program", "and", "returns", "its", "log", "joint", "function", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/edward2/program_transformations.py#L138-L223
[ "def", "make_log_joint_fn", "(", "model", ")", ":", "def", "log_joint_fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Log-probability of inputs according to a joint probability distribution.\n\n Args:\n *args: Positional arguments. They are the model's orig...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_get_function_inputs
Filters inputs to be compatible with function `f`'s signature. Args: f: Function according to whose input signature we filter arguments. src_kwargs: Keyword arguments to filter according to `f`. Returns: kwargs: Dict of key-value pairs in `src_kwargs` which exist in `f`'s signature.
tensorflow_probability/python/edward2/program_transformations.py
def _get_function_inputs(f, src_kwargs): """Filters inputs to be compatible with function `f`'s signature. Args: f: Function according to whose input signature we filter arguments. src_kwargs: Keyword arguments to filter according to `f`. Returns: kwargs: Dict of key-value pairs in `src_kwargs` whic...
def _get_function_inputs(f, src_kwargs): """Filters inputs to be compatible with function `f`'s signature. Args: f: Function according to whose input signature we filter arguments. src_kwargs: Keyword arguments to filter according to `f`. Returns: kwargs: Dict of key-value pairs in `src_kwargs` whic...
[ "Filters", "inputs", "to", "be", "compatible", "with", "function", "f", "s", "signature", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/edward2/program_transformations.py#L226-L246
[ "def", "_get_function_inputs", "(", "f", ",", "src_kwargs", ")", ":", "if", "hasattr", "(", "f", ",", "\"_func\"", ")", ":", "# functions returned by tf.make_template", "f", "=", "f", ".", "_func", "# pylint: disable=protected-access", "try", ":", "# getargspec was ...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_vggconv_block
Network block for VGG.
tensorflow_probability/examples/models/bayesian_vgg.py
def _vggconv_block(x, filters, kernel, stride, kernel_posterior_fn): """Network block for VGG.""" out = tfp.layers.Convolution2DFlipout( filters, kernel, padding='same', kernel_posterior_fn=kernel_posterior_fn)(x) out = tf.keras.layers.BatchNormalization()(out) out = tf.keras.layers.Acti...
def _vggconv_block(x, filters, kernel, stride, kernel_posterior_fn): """Network block for VGG.""" out = tfp.layers.Convolution2DFlipout( filters, kernel, padding='same', kernel_posterior_fn=kernel_posterior_fn)(x) out = tf.keras.layers.BatchNormalization()(out) out = tf.keras.layers.Acti...
[ "Network", "block", "for", "VGG", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/models/bayesian_vgg.py#L85-L105
[ "def", "_vggconv_block", "(", "x", ",", "filters", ",", "kernel", ",", "stride", ",", "kernel_posterior_fn", ")", ":", "out", "=", "tfp", ".", "layers", ".", "Convolution2DFlipout", "(", "filters", ",", "kernel", ",", "padding", "=", "'same'", ",", "kernel...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_DenseVariational.compute_output_shape
Computes the output shape of the layer. Args: input_shape: Shape tuple (tuple of integers) or list of shape tuples (one per output tensor of the layer). Shape tuples can include None for free dimensions, instead of an integer. Returns: output_shape: A tuple representing the output ...
tensorflow_probability/python/layers/dense_variational.py
def compute_output_shape(self, input_shape): """Computes the output shape of the layer. Args: input_shape: Shape tuple (tuple of integers) or list of shape tuples (one per output tensor of the layer). Shape tuples can include None for free dimensions, instead of an integer. Returns: ...
def compute_output_shape(self, input_shape): """Computes the output shape of the layer. Args: input_shape: Shape tuple (tuple of integers) or list of shape tuples (one per output tensor of the layer). Shape tuples can include None for free dimensions, instead of an integer. Returns: ...
[ "Computes", "the", "output", "shape", "of", "the", "layer", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/layers/dense_variational.py#L193-L213
[ "def", "compute_output_shape", "(", "self", ",", "input_shape", ")", ":", "input_shape", "=", "tf", ".", "TensorShape", "(", "input_shape", ")", "input_shape", "=", "input_shape", ".", "with_rank_at_least", "(", "2", ")", "if", "tf", ".", "compat", ".", "dim...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_DenseVariational.get_config
Returns the config of the layer. A layer config is a Python dictionary (serializable) containing the configuration of a layer. The same layer can be reinstantiated later (without its trained weights) from this configuration. Returns: config: A Python dictionary of class keyword arguments and the...
tensorflow_probability/python/layers/dense_variational.py
def get_config(self): """Returns the config of the layer. A layer config is a Python dictionary (serializable) containing the configuration of a layer. The same layer can be reinstantiated later (without its trained weights) from this configuration. Returns: config: A Python dictionary of cl...
def get_config(self): """Returns the config of the layer. A layer config is a Python dictionary (serializable) containing the configuration of a layer. The same layer can be reinstantiated later (without its trained weights) from this configuration. Returns: config: A Python dictionary of cl...
[ "Returns", "the", "config", "of", "the", "layer", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/layers/dense_variational.py#L215-L254
[ "def", "get_config", "(", "self", ")", ":", "config", "=", "{", "'units'", ":", "self", ".", "units", ",", "'activation'", ":", "(", "tf", ".", "keras", ".", "activations", ".", "serialize", "(", "self", ".", "activation", ")", "if", "self", ".", "ac...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
kernel
Simulates a No-U-Turn Sampler (NUTS) trajectory. Args: target_log_prob_fn: Python callable which takes an argument like `*current_state` and returns its (possibly unnormalized) log-density under the target distribution. current_state: List of `Tensor`s representing the states to simulate from. ...
experimental/no_u_turn_sampler/nuts.py
def kernel(target_log_prob_fn, current_state, step_size, seed=None, current_target_log_prob=None, current_grads_target_log_prob=None, name=None): """Simulates a No-U-Turn Sampler (NUTS) trajectory. Args: target_log_prob_fn: Python callable which...
def kernel(target_log_prob_fn, current_state, step_size, seed=None, current_target_log_prob=None, current_grads_target_log_prob=None, name=None): """Simulates a No-U-Turn Sampler (NUTS) trajectory. Args: target_log_prob_fn: Python callable which...
[ "Simulates", "a", "No", "-", "U", "-", "Turn", "Sampler", "(", "NUTS", ")", "trajectory", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/experimental/no_u_turn_sampler/nuts.py#L48-L222
[ "def", "kernel", "(", "target_log_prob_fn", ",", "current_state", ",", "step_size", ",", "seed", "=", "None", ",", "current_target_log_prob", "=", "None", ",", "current_grads_target_log_prob", "=", "None", ",", "name", "=", "None", ")", ":", "if", "not", "tf",...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_build_tree
Builds a tree at a given tree depth and at a given state. The `current` state is immediately adjacent to, but outside of, the subtrajectory spanned by the returned `forward` and `reverse` states. Args: value_and_gradients_fn: Python callable which takes an argument like `*current_state` and returns a ...
experimental/no_u_turn_sampler/nuts.py
def _build_tree(value_and_gradients_fn, current_state, current_target_log_prob, current_grads_target_log_prob, current_momentum, direction, depth, step_size, log_slice_sample, ...
def _build_tree(value_and_gradients_fn, current_state, current_target_log_prob, current_grads_target_log_prob, current_momentum, direction, depth, step_size, log_slice_sample, ...
[ "Builds", "a", "tree", "at", "a", "given", "tree", "depth", "and", "at", "a", "given", "state", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/experimental/no_u_turn_sampler/nuts.py#L225-L454
[ "def", "_build_tree", "(", "value_and_gradients_fn", ",", "current_state", ",", "current_target_log_prob", ",", "current_grads_target_log_prob", ",", "current_momentum", ",", "direction", ",", "depth", ",", "step_size", ",", "log_slice_sample", ",", "max_simulation_error", ...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_embed_no_none_gradient_check
Wraps value and gradients function to assist with None gradients.
experimental/no_u_turn_sampler/nuts.py
def _embed_no_none_gradient_check(value_and_gradients_fn): """Wraps value and gradients function to assist with None gradients.""" @functools.wraps(value_and_gradients_fn) def func_wrapped(*args, **kwargs): """Wrapped function which checks for None gradients.""" value, grads = value_and_gradients_fn(*args...
def _embed_no_none_gradient_check(value_and_gradients_fn): """Wraps value and gradients function to assist with None gradients.""" @functools.wraps(value_and_gradients_fn) def func_wrapped(*args, **kwargs): """Wrapped function which checks for None gradients.""" value, grads = value_and_gradients_fn(*args...
[ "Wraps", "value", "and", "gradients", "function", "to", "assist", "with", "None", "gradients", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/experimental/no_u_turn_sampler/nuts.py#L457-L466
[ "def", "_embed_no_none_gradient_check", "(", "value_and_gradients_fn", ")", ":", "@", "functools", ".", "wraps", "(", "value_and_gradients_fn", ")", "def", "func_wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Wrapped function which checks for No...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_has_no_u_turn
If two given states and momentum do not exhibit a U-turn pattern.
experimental/no_u_turn_sampler/nuts.py
def _has_no_u_turn(state_one, state_two, momentum): """If two given states and momentum do not exhibit a U-turn pattern.""" dot_product = sum([ tf.reduce_sum(input_tensor=(s1 - s2) * m) for s1, s2, m in zip(state_one, state_two, momentum) ]) return dot_product > 0
def _has_no_u_turn(state_one, state_two, momentum): """If two given states and momentum do not exhibit a U-turn pattern.""" dot_product = sum([ tf.reduce_sum(input_tensor=(s1 - s2) * m) for s1, s2, m in zip(state_one, state_two, momentum) ]) return dot_product > 0
[ "If", "two", "given", "states", "and", "momentum", "do", "not", "exhibit", "a", "U", "-", "turn", "pattern", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/experimental/no_u_turn_sampler/nuts.py#L469-L475
[ "def", "_has_no_u_turn", "(", "state_one", ",", "state_two", ",", "momentum", ")", ":", "dot_product", "=", "sum", "(", "[", "tf", ".", "reduce_sum", "(", "input_tensor", "=", "(", "s1", "-", "s2", ")", "*", "m", ")", "for", "s1", ",", "s2", ",", "...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_leapfrog
Runs one step of leapfrog integration.
experimental/no_u_turn_sampler/nuts.py
def _leapfrog(value_and_gradients_fn, current_state, current_grads_target_log_prob, current_momentum, step_size): """Runs one step of leapfrog integration.""" mid_momentum = [ m + 0.5 * step * g for m, step, g in zip(current_momentum, step_size, cu...
def _leapfrog(value_and_gradients_fn, current_state, current_grads_target_log_prob, current_momentum, step_size): """Runs one step of leapfrog integration.""" mid_momentum = [ m + 0.5 * step * g for m, step, g in zip(current_momentum, step_size, cu...
[ "Runs", "one", "step", "of", "leapfrog", "integration", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/experimental/no_u_turn_sampler/nuts.py#L478-L500
[ "def", "_leapfrog", "(", "value_and_gradients_fn", ",", "current_state", ",", "current_grads_target_log_prob", ",", "current_momentum", ",", "step_size", ")", ":", "mid_momentum", "=", "[", "m", "+", "0.5", "*", "step", "*", "g", "for", "m", ",", "step", ",", ...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_log_joint
Log-joint probability given a state's log-probability and momentum.
experimental/no_u_turn_sampler/nuts.py
def _log_joint(current_target_log_prob, current_momentum): """Log-joint probability given a state's log-probability and momentum.""" momentum_log_prob = -sum( [tf.reduce_sum(input_tensor=0.5 * (m**2.)) for m in current_momentum]) return current_target_log_prob + momentum_log_prob
def _log_joint(current_target_log_prob, current_momentum): """Log-joint probability given a state's log-probability and momentum.""" momentum_log_prob = -sum( [tf.reduce_sum(input_tensor=0.5 * (m**2.)) for m in current_momentum]) return current_target_log_prob + momentum_log_prob
[ "Log", "-", "joint", "probability", "given", "a", "state", "s", "log", "-", "probability", "and", "momentum", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/experimental/no_u_turn_sampler/nuts.py#L503-L507
[ "def", "_log_joint", "(", "current_target_log_prob", ",", "current_momentum", ")", ":", "momentum_log_prob", "=", "-", "sum", "(", "[", "tf", ".", "reduce_sum", "(", "input_tensor", "=", "0.5", "*", "(", "m", "**", "2.", ")", ")", "for", "m", "in", "curr...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_random_bernoulli
Returns samples from a Bernoulli distribution.
experimental/no_u_turn_sampler/nuts.py
def _random_bernoulli(shape, probs, dtype=tf.int32, seed=None, name=None): """Returns samples from a Bernoulli distribution.""" with tf.compat.v1.name_scope(name, "random_bernoulli", [shape, probs]): probs = tf.convert_to_tensor(value=probs) random_uniform = tf.random.uniform(shape, dtype=probs.dtype, seed=...
def _random_bernoulli(shape, probs, dtype=tf.int32, seed=None, name=None): """Returns samples from a Bernoulli distribution.""" with tf.compat.v1.name_scope(name, "random_bernoulli", [shape, probs]): probs = tf.convert_to_tensor(value=probs) random_uniform = tf.random.uniform(shape, dtype=probs.dtype, seed=...
[ "Returns", "samples", "from", "a", "Bernoulli", "distribution", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/experimental/no_u_turn_sampler/nuts.py#L510-L515
[ "def", "_random_bernoulli", "(", "shape", ",", "probs", ",", "dtype", "=", "tf", ".", "int32", ",", "seed", "=", "None", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "compat", ".", "v1", ".", "name_scope", "(", "name", ",", "\"random_bernou...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
default_loc_scale_fn
Makes closure which creates `loc`, `scale` params from `tf.get_variable`. This function produces a closure which produces `loc`, `scale` using `tf.get_variable`. The closure accepts the following arguments: dtype: Type of parameter's event. shape: Python `list`-like representing the parameter's event shap...
tensorflow_probability/python/layers/util.py
def default_loc_scale_fn( is_singular=False, loc_initializer=tf.compat.v1.initializers.random_normal(stddev=0.1), untransformed_scale_initializer=tf.compat.v1.initializers.random_normal( mean=-3., stddev=0.1), loc_regularizer=None, untransformed_scale_regularizer=None, loc_constraint=Non...
def default_loc_scale_fn( is_singular=False, loc_initializer=tf.compat.v1.initializers.random_normal(stddev=0.1), untransformed_scale_initializer=tf.compat.v1.initializers.random_normal( mean=-3., stddev=0.1), loc_regularizer=None, untransformed_scale_regularizer=None, loc_constraint=Non...
[ "Makes", "closure", "which", "creates", "loc", "scale", "params", "from", "tf", ".", "get_variable", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/layers/util.py#L39-L116
[ "def", "default_loc_scale_fn", "(", "is_singular", "=", "False", ",", "loc_initializer", "=", "tf", ".", "compat", ".", "v1", ".", "initializers", ".", "random_normal", "(", "stddev", "=", "0.1", ")", ",", "untransformed_scale_initializer", "=", "tf", ".", "co...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
default_mean_field_normal_fn
Creates a function to build Normal distributions with trainable params. This function produces a closure which produces `tfd.Normal` parameterized by a loc` and `scale` each created using `tf.get_variable`. Args: is_singular: Python `bool` if `True`, forces the special case limit of `scale->0`, i.e., ...
tensorflow_probability/python/layers/util.py
def default_mean_field_normal_fn( is_singular=False, loc_initializer=tf.compat.v1.initializers.random_normal(stddev=0.1), untransformed_scale_initializer=tf.compat.v1.initializers.random_normal( mean=-3., stddev=0.1), loc_regularizer=None, untransformed_scale_regularizer=None, loc_constr...
def default_mean_field_normal_fn( is_singular=False, loc_initializer=tf.compat.v1.initializers.random_normal(stddev=0.1), untransformed_scale_initializer=tf.compat.v1.initializers.random_normal( mean=-3., stddev=0.1), loc_regularizer=None, untransformed_scale_regularizer=None, loc_constr...
[ "Creates", "a", "function", "to", "build", "Normal", "distributions", "with", "trainable", "params", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/layers/util.py#L119-L193
[ "def", "default_mean_field_normal_fn", "(", "is_singular", "=", "False", ",", "loc_initializer", "=", "tf", ".", "compat", ".", "v1", ".", "initializers", ".", "random_normal", "(", "stddev", "=", "0.1", ")", ",", "untransformed_scale_initializer", "=", "tf", "....
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
default_multivariate_normal_fn
Creates multivariate standard `Normal` distribution. Args: dtype: Type of parameter's event. shape: Python `list`-like representing the parameter's event shape. name: Python `str` name prepended to any created (or existing) `tf.Variable`s. trainable: Python `bool` indicating all created `tf.Var...
tensorflow_probability/python/layers/util.py
def default_multivariate_normal_fn(dtype, shape, name, trainable, add_variable_fn): """Creates multivariate standard `Normal` distribution. Args: dtype: Type of parameter's event. shape: Python `list`-like representing the parameter's event shape. name: Python `str` n...
def default_multivariate_normal_fn(dtype, shape, name, trainable, add_variable_fn): """Creates multivariate standard `Normal` distribution. Args: dtype: Type of parameter's event. shape: Python `list`-like representing the parameter's event shape. name: Python `str` n...
[ "Creates", "multivariate", "standard", "Normal", "distribution", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/layers/util.py#L196-L216
[ "def", "default_multivariate_normal_fn", "(", "dtype", ",", "shape", ",", "name", ",", "trainable", ",", "add_variable_fn", ")", ":", "del", "name", ",", "trainable", ",", "add_variable_fn", "# unused", "dist", "=", "tfd", ".", "Normal", "(", "loc", "=", "tf...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
deserialize_function
Deserializes the Keras-serialized function. (De)serializing Python functions from/to bytecode is unsafe. Therefore we also use the function's type as an anonymous function ('lambda') or named function in the Python environment ('function'). In the latter case, this lets us use the Python scope to obtain the fu...
tensorflow_probability/python/layers/util.py
def deserialize_function(serial, function_type): """Deserializes the Keras-serialized function. (De)serializing Python functions from/to bytecode is unsafe. Therefore we also use the function's type as an anonymous function ('lambda') or named function in the Python environment ('function'). In the latter case...
def deserialize_function(serial, function_type): """Deserializes the Keras-serialized function. (De)serializing Python functions from/to bytecode is unsafe. Therefore we also use the function's type as an anonymous function ('lambda') or named function in the Python environment ('function'). In the latter case...
[ "Deserializes", "the", "Keras", "-", "serialized", "function", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/layers/util.py#L219-L257
[ "def", "deserialize_function", "(", "serial", ",", "function_type", ")", ":", "if", "function_type", "==", "'function'", ":", "# Simple lookup in custom objects", "function", "=", "tf", ".", "keras", ".", "utils", ".", "deserialize_keras_object", "(", "serial", ")",...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
serialize_function
Serializes function for Keras. (De)serializing Python functions from/to bytecode is unsafe. Therefore we return the function's type as an anonymous function ('lambda') or named function in the Python environment ('function'). In the latter case, this lets us use the Python scope to obtain the function rather t...
tensorflow_probability/python/layers/util.py
def serialize_function(func): """Serializes function for Keras. (De)serializing Python functions from/to bytecode is unsafe. Therefore we return the function's type as an anonymous function ('lambda') or named function in the Python environment ('function'). In the latter case, this lets us use the Python sc...
def serialize_function(func): """Serializes function for Keras. (De)serializing Python functions from/to bytecode is unsafe. Therefore we return the function's type as an anonymous function ('lambda') or named function in the Python environment ('function'). In the latter case, this lets us use the Python sc...
[ "Serializes", "function", "for", "Keras", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/layers/util.py#L260-L281
[ "def", "serialize_function", "(", "func", ")", ":", "if", "isinstance", "(", "func", ",", "types", ".", "LambdaType", ")", ":", "return", "generic_utils", ".", "func_dump", "(", "func", ")", ",", "'lambda'", "return", "func", ".", "__name__", ",", "'functi...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
broadcast_structure
Broadcasts `from_structure` to `to_structure`. This is useful for downstream usage of `zip` or `tf.nest.map_structure`. If `from_structure` is a singleton, it is tiled to match the structure of `to_structure`. Note that the elements in `from_structure` are not copied if this tiling occurs. Args: to_str...
tensorflow_probability/python/internal/nest_util.py
def broadcast_structure(to_structure, from_structure): """Broadcasts `from_structure` to `to_structure`. This is useful for downstream usage of `zip` or `tf.nest.map_structure`. If `from_structure` is a singleton, it is tiled to match the structure of `to_structure`. Note that the elements in `from_structure`...
def broadcast_structure(to_structure, from_structure): """Broadcasts `from_structure` to `to_structure`. This is useful for downstream usage of `zip` or `tf.nest.map_structure`. If `from_structure` is a singleton, it is tiled to match the structure of `to_structure`. Note that the elements in `from_structure`...
[ "Broadcasts", "from_structure", "to", "to_structure", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/nest_util.py#L36-L67
[ "def", "broadcast_structure", "(", "to_structure", ",", "from_structure", ")", ":", "from_parts", "=", "tf", ".", "nest", ".", "flatten", "(", "from_structure", ")", "if", "len", "(", "from_parts", ")", "==", "1", ":", "from_structure", "=", "tf", ".", "ne...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
expand_as_args
Returns `True` if `args` should be expanded as `*args`.
tensorflow_probability/python/internal/nest_util.py
def expand_as_args(args): """Returns `True` if `args` should be expanded as `*args`.""" return (isinstance(args, collections.Sequence) and not _is_namedtuple(args) and not _force_leaf(args))
def expand_as_args(args): """Returns `True` if `args` should be expanded as `*args`.""" return (isinstance(args, collections.Sequence) and not _is_namedtuple(args) and not _force_leaf(args))
[ "Returns", "True", "if", "args", "should", "be", "expanded", "as", "*", "args", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/nest_util.py#L76-L79
[ "def", "expand_as_args", "(", "args", ")", ":", "return", "(", "isinstance", "(", "args", ",", "collections", ".", "Sequence", ")", "and", "not", "_is_namedtuple", "(", "args", ")", "and", "not", "_force_leaf", "(", "args", ")", ")" ]
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_nested_convert_to_tensor
Eagerly converts struct to Tensor, recursing upon failure.
tensorflow_probability/python/internal/nest_util.py
def _nested_convert_to_tensor(struct, dtype=None, name=None): """Eagerly converts struct to Tensor, recursing upon failure.""" if dtype is not None or not tf.nest.is_nested(struct): return tf.convert_to_tensor(struct, dtype=dtype) if _maybe_convertible_to_tensor(struct): try: # Try converting the s...
def _nested_convert_to_tensor(struct, dtype=None, name=None): """Eagerly converts struct to Tensor, recursing upon failure.""" if dtype is not None or not tf.nest.is_nested(struct): return tf.convert_to_tensor(struct, dtype=dtype) if _maybe_convertible_to_tensor(struct): try: # Try converting the s...
[ "Eagerly", "converts", "struct", "to", "Tensor", "recursing", "upon", "failure", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/nest_util.py#L98-L113
[ "def", "_nested_convert_to_tensor", "(", "struct", ",", "dtype", "=", "None", ",", "name", "=", "None", ")", ":", "if", "dtype", "is", "not", "None", "or", "not", "tf", ".", "nest", ".", "is_nested", "(", "struct", ")", ":", "return", "tf", ".", "con...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
convert_args_to_tensor
Converts `args` to `Tensor`s. Use this when it is necessary to convert user-provided arguments that will then be passed to user-provided callables. When `dtype` is `None` this function behaves as follows: 1A. If the top-level structure is a `list`/`tuple` but not a `namedtuple`, then it is left as is a...
tensorflow_probability/python/internal/nest_util.py
def convert_args_to_tensor(args, dtype=None, name=None): """Converts `args` to `Tensor`s. Use this when it is necessary to convert user-provided arguments that will then be passed to user-provided callables. When `dtype` is `None` this function behaves as follows: 1A. If the top-level structure is a `list`...
def convert_args_to_tensor(args, dtype=None, name=None): """Converts `args` to `Tensor`s. Use this when it is necessary to convert user-provided arguments that will then be passed to user-provided callables. When `dtype` is `None` this function behaves as follows: 1A. If the top-level structure is a `list`...
[ "Converts", "args", "to", "Tensor", "s", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/nest_util.py#L116-L182
[ "def", "convert_args_to_tensor", "(", "args", ",", "dtype", "=", "None", ",", "name", "=", "None", ")", ":", "if", "dtype", "is", "None", ":", "if", "expand_as_args", "(", "args", ")", "or", "_expand_as_kwargs", "(", "args", ")", ":", "shallow_args", "="...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
call_fn
Calls `fn` with `args`, possibly expanding `args`. Use this function when calling a user-provided callable using user-provided arguments. The expansion rules are as follows: `fn(*args)` if `args` is a `list` or a `tuple`, but not a `namedtuple`. `fn(**args)` if `args` is a `dict`. `fn(args)` otherwise. ...
tensorflow_probability/python/internal/nest_util.py
def call_fn(fn, args): """Calls `fn` with `args`, possibly expanding `args`. Use this function when calling a user-provided callable using user-provided arguments. The expansion rules are as follows: `fn(*args)` if `args` is a `list` or a `tuple`, but not a `namedtuple`. `fn(**args)` if `args` is a `dict...
def call_fn(fn, args): """Calls `fn` with `args`, possibly expanding `args`. Use this function when calling a user-provided callable using user-provided arguments. The expansion rules are as follows: `fn(*args)` if `args` is a `list` or a `tuple`, but not a `namedtuple`. `fn(**args)` if `args` is a `dict...
[ "Calls", "fn", "with", "args", "possibly", "expanding", "args", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/nest_util.py#L185-L210
[ "def", "call_fn", "(", "fn", ",", "args", ")", ":", "if", "expand_as_args", "(", "args", ")", ":", "return", "fn", "(", "*", "args", ")", "elif", "_expand_as_kwargs", "(", "args", ")", ":", "return", "fn", "(", "*", "*", "args", ")", "else", ":", ...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_wrap_method
Replaces member function's first arg, `self`, to `self._value()`. This function is used by `_get_tensor_like_attributes` to take existing `Tensor` member functions and make them operate on `self._value()`, i.e., the concretization of a `Distribution`. Args: cls: The `class` from which we will look up the ...
tensorflow_probability/python/layers/internal/distribution_tensor_coercible.py
def _wrap_method(cls, attr): """Replaces member function's first arg, `self`, to `self._value()`. This function is used by `_get_tensor_like_attributes` to take existing `Tensor` member functions and make them operate on `self._value()`, i.e., the concretization of a `Distribution`. Args: cls: The `clas...
def _wrap_method(cls, attr): """Replaces member function's first arg, `self`, to `self._value()`. This function is used by `_get_tensor_like_attributes` to take existing `Tensor` member functions and make them operate on `self._value()`, i.e., the concretization of a `Distribution`. Args: cls: The `clas...
[ "Replaces", "member", "function", "s", "first", "arg", "self", "to", "self", ".", "_value", "()", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/layers/internal/distribution_tensor_coercible.py#L32-L54
[ "def", "_wrap_method", "(", "cls", ",", "attr", ")", ":", "fn", "=", "getattr", "(", "cls", ",", "attr", ")", "is_property", "=", "isinstance", "(", "fn", ",", "property", ")", "if", "is_property", ":", "fn", "=", "fn", ".", "fget", "@", "functools",...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_get_tensor_like_attributes
Returns `Tensor` attributes related to shape and Python builtins.
tensorflow_probability/python/layers/internal/distribution_tensor_coercible.py
def _get_tensor_like_attributes(): """Returns `Tensor` attributes related to shape and Python builtins.""" # Enable "Tensor semantics" for distributions. # See tensorflow/python/framework/ops.py `class Tensor` for details. attrs = dict() # Setup overloadable operators and white-listed members / properties. ...
def _get_tensor_like_attributes(): """Returns `Tensor` attributes related to shape and Python builtins.""" # Enable "Tensor semantics" for distributions. # See tensorflow/python/framework/ops.py `class Tensor` for details. attrs = dict() # Setup overloadable operators and white-listed members / properties. ...
[ "Returns", "Tensor", "attributes", "related", "to", "shape", "and", "Python", "builtins", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/layers/internal/distribution_tensor_coercible.py#L57-L68
[ "def", "_get_tensor_like_attributes", "(", ")", ":", "# Enable \"Tensor semantics\" for distributions.", "# See tensorflow/python/framework/ops.py `class Tensor` for details.", "attrs", "=", "dict", "(", ")", "# Setup overloadable operators and white-listed members / properties.", "attrs",...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
_value
Get the value returned by `tf.convert_to_tensor(distribution)`. Note: this function may mutate the distribution instance state by caching the concretized `Tensor` value. Args: dtype: Must return a `Tensor` with the given `dtype` if specified. name: If the conversion function creates a new `Tensor`, it s...
tensorflow_probability/python/layers/internal/distribution_tensor_coercible.py
def _value(self, dtype=None, name=None, as_ref=False): # pylint: disable=g-doc-args """Get the value returned by `tf.convert_to_tensor(distribution)`. Note: this function may mutate the distribution instance state by caching the concretized `Tensor` value. Args: dtype: Must return a `Tensor` with the giv...
def _value(self, dtype=None, name=None, as_ref=False): # pylint: disable=g-doc-args """Get the value returned by `tf.convert_to_tensor(distribution)`. Note: this function may mutate the distribution instance state by caching the concretized `Tensor` value. Args: dtype: Must return a `Tensor` with the giv...
[ "Get", "the", "value", "returned", "by", "tf", ".", "convert_to_tensor", "(", "distribution", ")", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/layers/internal/distribution_tensor_coercible.py#L71-L128
[ "def", "_value", "(", "self", ",", "dtype", "=", "None", ",", "name", "=", "None", ",", "as_ref", "=", "False", ")", ":", "# pylint: disable=g-doc-args", "# pylint: disable=protected-access", "if", "as_ref", ":", "raise", "NotImplementedError", "(", "'Cannot conve...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
make_encoder
Creates the encoder function. Args: activation: Activation function in hidden layers. latent_size: The dimensionality of the encoding. base_depth: The lowest depth for a layer. Returns: encoder: A `callable` mapping a `Tensor` of images to a `tfd.Distribution` instance over encodings.
tensorflow_probability/examples/vae.py
def make_encoder(activation, latent_size, base_depth): """Creates the encoder function. Args: activation: Activation function in hidden layers. latent_size: The dimensionality of the encoding. base_depth: The lowest depth for a layer. Returns: encoder: A `callable` mapping a `Tensor` of images t...
def make_encoder(activation, latent_size, base_depth): """Creates the encoder function. Args: activation: Activation function in hidden layers. latent_size: The dimensionality of the encoding. base_depth: The lowest depth for a layer. Returns: encoder: A `callable` mapping a `Tensor` of images t...
[ "Creates", "the", "encoder", "function", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/vae.py#L191-L225
[ "def", "make_encoder", "(", "activation", ",", "latent_size", ",", "base_depth", ")", ":", "conv", "=", "functools", ".", "partial", "(", "tf", ".", "keras", ".", "layers", ".", "Conv2D", ",", "padding", "=", "\"SAME\"", ",", "activation", "=", "activation...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
make_decoder
Creates the decoder function. Args: activation: Activation function in hidden layers. latent_size: Dimensionality of the encoding. output_shape: The output image shape. base_depth: Smallest depth for a layer. Returns: decoder: A `callable` mapping a `Tensor` of encodings to a `tfd.Distri...
tensorflow_probability/examples/vae.py
def make_decoder(activation, latent_size, output_shape, base_depth): """Creates the decoder function. Args: activation: Activation function in hidden layers. latent_size: Dimensionality of the encoding. output_shape: The output image shape. base_depth: Smallest depth for a layer. Returns: de...
def make_decoder(activation, latent_size, output_shape, base_depth): """Creates the decoder function. Args: activation: Activation function in hidden layers. latent_size: Dimensionality of the encoding. output_shape: The output image shape. base_depth: Smallest depth for a layer. Returns: de...
[ "Creates", "the", "decoder", "function", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/vae.py#L228-L268
[ "def", "make_decoder", "(", "activation", ",", "latent_size", ",", "output_shape", ",", "base_depth", ")", ":", "deconv", "=", "functools", ".", "partial", "(", "tf", ".", "keras", ".", "layers", ".", "Conv2DTranspose", ",", "padding", "=", "\"SAME\"", ",", ...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
make_mixture_prior
Creates the mixture of Gaussians prior distribution. Args: latent_size: The dimensionality of the latent representation. mixture_components: Number of elements of the mixture. Returns: random_prior: A `tfd.Distribution` instance representing the distribution over encodings in the absence of any ...
tensorflow_probability/examples/vae.py
def make_mixture_prior(latent_size, mixture_components): """Creates the mixture of Gaussians prior distribution. Args: latent_size: The dimensionality of the latent representation. mixture_components: Number of elements of the mixture. Returns: random_prior: A `tfd.Distribution` instance representin...
def make_mixture_prior(latent_size, mixture_components): """Creates the mixture of Gaussians prior distribution. Args: latent_size: The dimensionality of the latent representation. mixture_components: Number of elements of the mixture. Returns: random_prior: A `tfd.Distribution` instance representin...
[ "Creates", "the", "mixture", "of", "Gaussians", "prior", "distribution", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/vae.py#L271-L300
[ "def", "make_mixture_prior", "(", "latent_size", ",", "mixture_components", ")", ":", "if", "mixture_components", "==", "1", ":", "# See the module docstring for why we don't learn the parameters here.", "return", "tfd", ".", "MultivariateNormalDiag", "(", "loc", "=", "tf",...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
pack_images
Helper utility to make a field of images.
tensorflow_probability/examples/vae.py
def pack_images(images, rows, cols): """Helper utility to make a field of images.""" shape = tf.shape(input=images) width = shape[-3] height = shape[-2] depth = shape[-1] images = tf.reshape(images, (-1, width, height, depth)) batch = tf.shape(input=images)[0] rows = tf.minimum(rows, batch) cols = tf....
def pack_images(images, rows, cols): """Helper utility to make a field of images.""" shape = tf.shape(input=images) width = shape[-3] height = shape[-2] depth = shape[-1] images = tf.reshape(images, (-1, width, height, depth)) batch = tf.shape(input=images)[0] rows = tf.minimum(rows, batch) cols = tf....
[ "Helper", "utility", "to", "make", "a", "field", "of", "images", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/vae.py#L303-L317
[ "def", "pack_images", "(", "images", ",", "rows", ",", "cols", ")", ":", "shape", "=", "tf", ".", "shape", "(", "input", "=", "images", ")", "width", "=", "shape", "[", "-", "3", "]", "height", "=", "shape", "[", "-", "2", "]", "depth", "=", "s...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
model_fn
Builds the model function for use in an estimator. Arguments: features: The input features for the estimator. labels: The labels, unused here. mode: Signifies whether it is train or test or predict. params: Some hyperparameters as a dictionary. config: The RunConfig, unused here. Returns: ...
tensorflow_probability/examples/vae.py
def model_fn(features, labels, mode, params, config): """Builds the model function for use in an estimator. Arguments: features: The input features for the estimator. labels: The labels, unused here. mode: Signifies whether it is train or test or predict. params: Some hyperparameters as a dictionar...
def model_fn(features, labels, mode, params, config): """Builds the model function for use in an estimator. Arguments: features: The input features for the estimator. labels: The labels, unused here. mode: Signifies whether it is train or test or predict. params: Some hyperparameters as a dictionar...
[ "Builds", "the", "model", "function", "for", "use", "in", "an", "estimator", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/vae.py#L325-L428
[ "def", "model_fn", "(", "features", ",", "labels", ",", "mode", ",", "params", ",", "config", ")", ":", "del", "labels", ",", "config", "if", "params", "[", "\"analytic_kl\"", "]", "and", "params", "[", "\"mixture_components\"", "]", "!=", "1", ":", "rai...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
download
Downloads a file.
tensorflow_probability/examples/vae.py
def download(directory, filename): """Downloads a file.""" filepath = os.path.join(directory, filename) if tf.io.gfile.exists(filepath): return filepath if not tf.io.gfile.exists(directory): tf.io.gfile.makedirs(directory) url = os.path.join(ROOT_PATH, filename) print("Downloading %s to %s" % (url, ...
def download(directory, filename): """Downloads a file.""" filepath = os.path.join(directory, filename) if tf.io.gfile.exists(filepath): return filepath if not tf.io.gfile.exists(directory): tf.io.gfile.makedirs(directory) url = os.path.join(ROOT_PATH, filename) print("Downloading %s to %s" % (url, ...
[ "Downloads", "a", "file", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/vae.py#L435-L445
[ "def", "download", "(", "directory", ",", "filename", ")", ":", "filepath", "=", "os", ".", "path", ".", "join", "(", "directory", ",", "filename", ")", "if", "tf", ".", "io", ".", "gfile", ".", "exists", "(", "filepath", ")", ":", "return", "filepat...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
build_fake_input_fns
Builds fake MNIST-style data for unit testing.
tensorflow_probability/examples/vae.py
def build_fake_input_fns(batch_size): """Builds fake MNIST-style data for unit testing.""" random_sample = np.random.rand(batch_size, *IMAGE_SHAPE).astype("float32") def train_input_fn(): dataset = tf.data.Dataset.from_tensor_slices( random_sample).map(lambda row: (row, 0)).batch(batch_size).repeat()...
def build_fake_input_fns(batch_size): """Builds fake MNIST-style data for unit testing.""" random_sample = np.random.rand(batch_size, *IMAGE_SHAPE).astype("float32") def train_input_fn(): dataset = tf.data.Dataset.from_tensor_slices( random_sample).map(lambda row: (row, 0)).batch(batch_size).repeat()...
[ "Builds", "fake", "MNIST", "-", "style", "data", "for", "unit", "testing", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/vae.py#L462-L476
[ "def", "build_fake_input_fns", "(", "batch_size", ")", ":", "random_sample", "=", "np", ".", "random", ".", "rand", "(", "batch_size", ",", "*", "IMAGE_SHAPE", ")", ".", "astype", "(", "\"float32\"", ")", "def", "train_input_fn", "(", ")", ":", "dataset", ...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5
test
build_input_fns
Builds an Iterator switching between train and heldout data.
tensorflow_probability/examples/vae.py
def build_input_fns(data_dir, batch_size): """Builds an Iterator switching between train and heldout data.""" # Build an iterator over training batches. def train_input_fn(): dataset = static_mnist_dataset(data_dir, "train") dataset = dataset.shuffle(50000).repeat().batch(batch_size) return tf.compat...
def build_input_fns(data_dir, batch_size): """Builds an Iterator switching between train and heldout data.""" # Build an iterator over training batches. def train_input_fn(): dataset = static_mnist_dataset(data_dir, "train") dataset = dataset.shuffle(50000).repeat().batch(batch_size) return tf.compat...
[ "Builds", "an", "Iterator", "switching", "between", "train", "and", "heldout", "data", "." ]
tensorflow/probability
python
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/vae.py#L479-L494
[ "def", "build_input_fns", "(", "data_dir", ",", "batch_size", ")", ":", "# Build an iterator over training batches.", "def", "train_input_fn", "(", ")", ":", "dataset", "=", "static_mnist_dataset", "(", "data_dir", ",", "\"train\"", ")", "dataset", "=", "dataset", "...
e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5