INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
same as requests/ requests/ api. py request (... ) | def request(method, url, **kwargs):
"""same as requests/requests/api.py request(...)"""
time_before_request = time()
# session start
session = SessionSinglePool()
# proxies
kwargs['proxies'] = settings['outgoing'].get('proxies') or None
# timeout
if 'timeout' in kwargs:
timeou... |
Returns theme name. | def get_current_theme_name(override=None):
"""Returns theme name.
Checks in this order:
1. override
2. cookies
3. settings"""
if override and (override in themes or override == '__common__'):
return override
theme_name = request.args.get('theme', request.preferences.get_value('them... |
Render index page. | def index():
"""Render index page.
Supported outputs: html, json, csv, rss.
"""
# output_format
output_format = request.form.get('format', 'html')
if output_format not in ['html', 'csv', 'json', 'rss']:
output_format = 'html'
# check if there is query
if request.form.get('q') ... |
Return autocompleter results | def autocompleter():
"""Return autocompleter results"""
# set blocked engines
disabled_engines = request.preferences.engines.get_disabled()
# parse query
if PY3:
raw_text_query = RawTextQuery(request.form.get('q', b''), disabled_engines)
else:
raw_text_query = RawTextQuery(requ... |
Render preferences page && save user preferences | def preferences():
"""Render preferences page && save user preferences"""
# save preferences
if request.method == 'POST':
resp = make_response(redirect(urljoin(settings['server']['base_url'], url_for('index'))))
try:
request.preferences.parse_form(request.form)
except Va... |
pre - request callback params<dict >: method: POST/ GET headers: {} data: {} # if method == POST url: category: search category pageno: 1 # number of the requested page | def request(query, params):
'''pre-request callback
params<dict>:
method : POST/GET
headers : {}
data : {} # if method == POST
url : ''
category: 'search category'
pageno : 1 # number of the requested page
'''
offset = (params['pageno'] - 1)
params['url'... |
post - response callback resp: requests response object | def response(resp):
'''post-response callback
resp: requests response object
'''
results = []
dom = html.fromstring(resp.text)
try:
number_of_results_string = re.sub('[^0-9]', '', dom.xpath(
'//a[@class="active" and contains(@href,"/suchen/dudenonline")]/span/text()')[0]
... |
Returns available themes list. | def get_themes(templates_path):
"""Returns available themes list."""
themes = os.listdir(templates_path)
if '__common__' in themes:
themes.remove('__common__')
return themes |
check if the searchQuery contain a bang and create fitting autocompleter results | def searx_bang(full_query):
'''check if the searchQuery contain a bang, and create fitting autocompleter results'''
# check if there is a query which can be parsed
if len(full_query.getSearchQuery()) == 0:
return []
results = []
# check if current query stats with !bang
first_char = fu... |
remove first and last lines to get only json | def response(resp):
"""remove first and last lines to get only json"""
json_resp = resp.text[resp.text.find('\n') + 1:resp.text.rfind('\n') - 2]
results = []
try:
conversion_rate = float(json.loads(json_resp)['conversion']['converted-amount'])
except:
return results
answer = '{0}... |
Embeds a custom gradient into a Tensor. | def custom_gradient(fx, gx, x, fx_gx_manually_stopped=False, name=None):
"""Embeds a custom gradient into a `Tensor`.
This function works by clever application of `stop_gradient`. I.e., observe
that:
```none
h(x) = stop_gradient(f(x)) + stop_gradient(g(x)) * (x - stop_gradient(x))
```
is such that `h(x... |
Computes f ( * xs ) and its gradients wrt to * xs. | def value_and_gradient(f, xs, use_gradient_tape=False, name=None):
"""Computes `f(*xs)` and its gradients wrt to `*xs`.
Args:
f: Python `callable` to be differentiated. If `f` returns a scalar, this
scalar will be differentiated. If `f` returns a tensor or list of tensors,
by default a scalar will ... |
Convenience function to efficiently construct a MultivariateNormalDiag. | def mvn(*args, **kwargs):
"""Convenience function to efficiently construct a MultivariateNormalDiag."""
# Faster than using `tfd.MultivariateNormalDiag`.
return tfd.Independent(tfd.Normal(*args, **kwargs),
reinterpreted_batch_ndims=1) |
Eight - schools joint log - prob. | def eight_schools_joint_log_prob(
treatment_effects, treatment_stddevs,
avg_effect, avg_stddev, school_effects_standard):
"""Eight-schools joint log-prob."""
rv_avg_effect = tfd.Normal(loc=0., scale=10.)
rv_avg_stddev = tfd.Normal(loc=5., scale=1.)
rv_school_effects_standard = mvn(
loc=tf.zeros_li... |
Runs HMC on the eight - schools unnormalized posterior. | def benchmark_eight_schools_hmc(
num_results=int(5e3),
num_burnin_steps=int(3e3),
num_leapfrog_steps=3,
step_size=0.4):
"""Runs HMC on the eight-schools unnormalized posterior."""
num_schools = 8
treatment_effects = tf.constant(
[28, 8, -3, 7, -1, 1, 18, 12],
dtype=np.float32,
n... |
Decorator to programmatically expand the docstring. | def expand_docstring(**kwargs):
"""Decorator to programmatically expand the docstring.
Args:
**kwargs: Keyword arguments to set. For each key-value pair `k` and `v`,
the key is found as `${k}` in the docstring and replaced with `v`.
Returns:
Decorated function.
"""
def _fn_wrapped(fn):
"""... |
Infer the original name passed into a distribution constructor. | def _simple_name(distribution):
"""Infer the original name passed into a distribution constructor.
Distributions typically follow the pattern of
with.name_scope(name) as name:
super(name=name)
so we attempt to reverse the name-scope transformation to allow
addressing of RVs by the distribution's original... |
RandomVariable constructor with a dummy name argument. | def _build_custom_rv(distribution, sample_shape, value, name):
"""RandomVariable constructor with a dummy name argument."""
# Program transformations (e.g., `make_log_joint_fn`) assume that
# the traced constructor has `name` and `value` kwargs, enabling
# them to override the value of an RV according to its na... |
Wrap an existing distribution as a traceable random variable. | def as_random_variable(distribution,
sample_shape=(),
value=None):
"""Wrap an existing distribution as a traceable random variable.
This enables the use of custom or user-provided distributions in
Edward models. Unlike a bare `RandomVariable` object, this method
wr... |
Factory function to make random variable given distribution class. | def _make_random_variable(distribution_cls):
"""Factory function to make random variable given distribution class."""
@interceptable
@functools.wraps(distribution_cls, assigned=('__module__', '__name__'))
@docstring_util.expand_docstring(
cls=distribution_cls.__name__,
doc=inspect.cleandoc(distribu... |
Shape for the mode/ mean Tensors. | def _mode_mean_shape(self):
"""Shape for the mode/mean Tensors."""
shape = tensorshape_util.concatenate(self.batch_shape, self.event_shape)
has_static_shape = tensorshape_util.is_fully_defined(shape)
if not has_static_shape:
shape = tf.concat([
self.batch_shape_tensor(),
self.e... |
Compute one - step - ahead predictive distributions for all timesteps. | def one_step_predictive(model, observed_time_series, parameter_samples):
"""Compute one-step-ahead predictive distributions for all timesteps.
Given samples from the posterior over parameters, return the predictive
distribution over observations at each time `T`, given observations up
through time `T-1`.
Ar... |
Construct predictive distribution over future observations. | def forecast(model,
observed_time_series,
parameter_samples,
num_steps_forecast):
"""Construct predictive distribution over future observations.
Given samples from the posterior over parameters, return the predictive
distribution over future observations for num_steps_forec... |
Returns max or mask if max is not finite. | def _max_mask_non_finite(x, axis=-1, keepdims=False, mask=0):
"""Returns `max` or `mask` if `max` is not finite."""
m = np.max(x, axis=_astuple(axis), keepdims=keepdims)
needs_masking = ~np.isfinite(m)
if needs_masking.ndim > 0:
m[needs_masking] = mask
elif needs_masking:
m = mask
return m |
Computes log ( sum ( exp ( input_tensor ))) along the specified axis. | def _reduce_logsumexp(input_tensor, axis=None, keepdims=False, name=None): # pylint: disable=unused-argument
"""Computes `log(sum(exp(input_tensor))) along the specified axis."""
try:
return scipy_special.logsumexp(
input_tensor, axis=_astuple(axis), keepdims=keepdims)
except NotImplementedError:
... |
Assert all elements of x are finite. | def assert_finite(x, data=None, summarize=None, message=None, name=None):
"""Assert all elements of `x` are finite.
Args:
x: Numeric `Tensor`.
data: The tensors to print out if the condition is False. Defaults to
error message and first few entries of `x`.
summarize: Print this many entries of... |
Assert x has rank equal to rank or smaller. | def assert_rank_at_most(x, rank, data=None, summarize=None, message=None,
name=None):
"""Assert `x` has rank equal to `rank` or smaller.
Example of adding a dependency to an operation:
```python
with tf.control_dependencies([tf.assert_rank_at_most(x, 2)]):
output = tf.reduce_sum(x)... |
Computes the number of elements in a tensor with shape event_shape. | def _event_size(event_shape, name=None):
"""Computes the number of elements in a tensor with shape `event_shape`.
Args:
event_shape: A tensor shape.
name: The name to use for the tensor op to compute the number of elements
(if such an op needs to be created).
Returns:
event_size: The number of... |
OneHotCategorical helper computing probs cdf etc over its support. | def _eval_all_one_hot(fn, dist, name=None):
"""OneHotCategorical helper computing probs, cdf, etc over its support."""
with tf.compat.v1.name_scope(name, 'eval_all_one_hot'):
event_size = dist.event_shape_tensor()[-1]
batch_ndims = tf.size(input=dist.batch_shape_tensor())
# Reshape `eye(d)` to: `[d] + [... |
Creates a callable computing KL [ a b ] from a a tfd. Distribution. | def _make_kl_divergence_fn(
distribution_b,
use_exact_kl=False,
test_points_reduce_axis=(), # `None` == "all"; () == "none".
test_points_fn=tf.convert_to_tensor,
weight=None):
"""Creates a callable computing `KL[a,b]` from `a`, a `tfd.Distribution`."""
if use_exact_kl is None:
kl_divergenc... |
Return a convert - to - tensor func given a name config callable etc. | def _get_convert_to_tensor_fn(identifier):
"""Return a convert-to-tensor func, given a name, config, callable, etc."""
if identifier is None:
return None
if isinstance(identifier, six.string_types):
identifier = str(identifier)
return _deserialize(identifier)
if isinstance(identifier, dict):
r... |
Returns the config of this layer. | def get_config(self):
"""Returns the config of this layer.
This Layer's `make_distribution_fn` is serialized via a library built on
Python pickle. This serialization of Python functions is provided for
convenience, but:
1. The use of this format for long-term storage of models is discouraged.
... |
Create the distribution instance from a params vector. | def new(params, event_size, validate_args=False, name=None):
"""Create the distribution instance from a `params` vector."""
with tf.compat.v1.name_scope(name, 'MultivariateNormalTriL',
[params, event_size]):
params = tf.convert_to_tensor(value=params, name='params')
... |
The number of params needed to create a single distribution. | def params_size(event_size, name=None):
"""The number of `params` needed to create a single distribution."""
with tf.compat.v1.name_scope(name, 'MultivariateNormalTriL_params_size',
[event_size]):
return event_size + event_size * (event_size + 1) // 2 |
Create the distribution instance from a params vector. | def new(params, event_size, dtype=None, validate_args=False, name=None):
"""Create the distribution instance from a `params` vector."""
with tf.compat.v1.name_scope(name, 'OneHotCategorical',
[params, event_size]):
return tfd.OneHotCategorical(
logits=params,
... |
Create the distribution instance from a params vector. | def new(params, event_size, num_components,
dtype=None, validate_args=False, name=None):
"""Create the distribution instance from a `params` vector."""
with tf.compat.v1.name_scope(name, 'CategoricalMixtureOfOneHotCategorical',
[params, event_size, num_components]):
... |
The number of params needed to create a single distribution. | def params_size(event_size, num_components, name=None):
"""The number of `params` needed to create a single distribution."""
with tf.compat.v1.name_scope(
name, 'CategoricalMixtureOfOneHotCategorical_params_size',
[event_size, num_components]):
return MixtureSameFamily.params_size(
... |
Create the distribution instance from a params vector. | def new(params, event_shape=(), dtype=None, validate_args=False, name=None):
"""Create the distribution instance from a `params` vector."""
with tf.compat.v1.name_scope(name, 'IndependentBernoulli',
[params, event_shape]):
params = tf.convert_to_tensor(value=params, name='... |
Returns the config of this layer. | def get_config(self):
"""Returns the config of this layer.
NOTE: At the moment, this configuration can only be serialized if the
Layer's `convert_to_tensor_fn` is a serializable Keras object (i.e.,
implements `get_config`) or one of the standard values:
- `Distribution.sample` (or `"sample"`)
... |
Create the distribution instance from a params vector. | def new(params, event_shape=(), validate_args=False, name=None):
"""Create the distribution instance from a `params` vector."""
with tf.compat.v1.name_scope(name, 'IndependentLogistic',
[params, event_shape]):
params = tf.convert_to_tensor(value=params, name='params')
... |
The number of params needed to create a single distribution. | def params_size(event_shape=(), name=None):
"""The number of `params` needed to create a single distribution."""
with tf.compat.v1.name_scope(name, 'IndependentNormal_params_size',
[event_shape]):
event_shape = tf.convert_to_tensor(
value=event_shape, name='event... |
Create the distribution instance from a params vector. | def new(params, event_shape=(), validate_args=False, name=None):
"""Create the distribution instance from a `params` vector."""
with tf.compat.v1.name_scope(name, 'IndependentPoisson',
[params, event_shape]):
params = tf.convert_to_tensor(value=params, name='params')
... |
Create the distribution instance from a params vector. | def new(params, num_components, component_layer,
validate_args=False, name=None):
"""Create the distribution instance from a `params` vector."""
with tf.compat.v1.name_scope(name, 'MixtureSameFamily',
[params, num_components, component_layer]):
params = tf.conver... |
Number of params needed to create a MixtureSameFamily distribution. | def params_size(num_components, component_params_size, name=None):
"""Number of `params` needed to create a `MixtureSameFamily` distribution.
Arguments:
num_components: Number of component distributions in the mixture
distribution.
component_params_size: Number of parameters needed to creat... |
The number of params needed to create a single distribution. | def params_size(num_components, event_shape=(), name=None):
"""The number of `params` needed to create a single distribution."""
return MixtureSameFamily.params_size(
num_components,
IndependentNormal.params_size(event_shape, name=name),
name=name) |
Create the distribution instance from a params vector. | def new(params, num_components, event_shape=(),
validate_args=False, name=None):
"""Create the distribution instance from a `params` vector."""
return MixtureSameFamily.new(
params,
num_components,
IndependentLogistic(
event_shape, validate_args=validate_args, name=... |
The number of params needed to create a single distribution. | def params_size(num_components, event_shape=(), name=None):
"""The number of `params` needed to create a single distribution."""
return MixtureSameFamily.params_size(
num_components,
IndependentLogistic.params_size(event_shape, name=name),
name=name) |
Yields the top - most interceptor on the thread - local interceptor stack. | def get_next_interceptor():
"""Yields the top-most interceptor on the thread-local interceptor stack.
Operations may be intercepted by multiple nested interceptors. Once reached,
an operation can be forwarded through nested interceptors until resolved.
To allow for nesting, implement interceptors by re-wrappin... |
Decorator that wraps func so that its execution is intercepted. | def interceptable(func):
"""Decorator that wraps `func` so that its execution is intercepted.
The wrapper passes `func` to the interceptor for the current thread.
If there is no next interceptor, we perform an "immediate" call to `func`.
That is, `func` terminates without forwarding its execution to another
... |
Context manager for recording interceptable executions onto a tape. | def tape():
"""Context manager for recording interceptable executions onto a tape.
Similar to `tf.GradientTape`, operations are recorded if they are executed
within this context manager. In addition, the operation must be registered
(wrapped) as `ed.interceptable`.
Yields:
tape: OrderedDict where operat... |
Generates synthetic data for binary classification. | def toy_logistic_data(num_examples, input_size=2, weights_prior_stddev=5.0):
"""Generates synthetic data for binary classification.
Args:
num_examples: The number of samples to generate (scalar Python `int`).
input_size: The input space dimension (scalar Python `int`).
weights_prior_stddev: The prior s... |
Utility method to visualize decision boundaries in R^2. | def visualize_decision(features, labels, true_w_b, candidate_w_bs, fname):
"""Utility method to visualize decision boundaries in R^2.
Args:
features: Input points, as a Numpy `array` of shape `[num_examples, 2]`.
labels: Numpy `float`-like array of shape `[num_examples, 1]` giving a
label for each po... |
Build a Dataset iterator for supervised classification. | def build_input_pipeline(x, y, batch_size):
"""Build a Dataset iterator for supervised classification.
Args:
x: Numpy `array` of features, indexed by the first dimension.
y: Numpy `array` of labels, with the same first dimension as `x`.
batch_size: Number of elements in each training batch.
Returns:... |
Validate map_values if validate_args == True. | def _maybe_check_valid_map_values(map_values, validate_args):
"""Validate `map_values` if `validate_args`==True."""
assertions = []
message = 'Rank of map_values must be 1.'
if tensorshape_util.rank(map_values.shape) is not None:
if tensorshape_util.rank(map_values.shape) != 1:
raise ValueError(messa... |
TransitionOperator that runs fn repeatedly and traces its outputs. | def trace(state: State, fn: TransitionOperator, num_steps: IntTensor,
trace_fn: Callable[[State, TensorNest], TensorNest]
) -> Tuple[State, TensorNest]:
"""`TransitionOperator` that runs `fn` repeatedly and traces its outputs.
Args:
state: A nest of `Tensor`s or None.
fn: A `TransitionOp... |
Calls a transition operator with args unpacking args if its a sequence. | def call_fn(fn: TransitionOperator, args: Union[Tuple[Any], Any]) -> Any:
"""Calls a transition operator with args, unpacking args if its a sequence.
Args:
fn: A `TransitionOperator`.
args: Arguments to `fn`
Returns:
ret: Return value of `fn`.
"""
if isinstance(args, (list, tuple)) and not mcmc... |
Calls fn and returns the gradients with respect to fn s first output. | def call_and_grads(fn: TransitionOperator, args: Union[Tuple[Any], Any]
) -> Tuple[tf.Tensor, TensorNest, TensorNest]:
"""Calls `fn` and returns the gradients with respect to `fn`'s first output.
Args:
fn: A `TransitionOperator`.
args: Arguments to `fn`
Returns:
ret: First output o... |
Maybe broadcasts from_structure to to_structure. | def maybe_broadcast_structure(from_structure: Any, to_structure: Any) -> Any:
"""Maybe broadcasts `from_structure` to `to_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.
Arg... |
Transforms a log - prob function using a bijector. | def transform_log_prob_fn(log_prob_fn: PotentialFn,
bijector: BijectorNest,
init_state: State = None
) -> Union[PotentialFn, Tuple[PotentialFn, State]]:
"""Transforms a log-prob function using a bijector.
This takes a log-prob function an... |
Leapfrog TransitionOperator. | def leapfrog_step(leapfrog_step_state: LeapFrogStepState,
step_size: FloatTensor, target_log_prob_fn: PotentialFn,
kinetic_energy_fn: PotentialFn
) -> Tuple[LeapFrogStepState, LeapFrogStepExtras]:
"""Leapfrog `TransitionOperator`.
Args:
leapfrog_step_state: ... |
Metropolis - Hastings step. | def metropolis_hastings_step(current_state: State,
proposed_state: State,
energy_change: FloatTensor,
seed=None) -> Tuple[State, tf.Tensor, tf.Tensor]:
"""Metropolis-Hastings step.
This probabilistically chooses between `current... |
Hamiltonian Monte Carlo TransitionOperator. | def hamiltonian_monte_carlo(
hmc_state: HamiltonianMonteCarloState,
target_log_prob_fn: PotentialFn,
step_size: Any,
num_leapfrog_steps: IntTensor,
momentum: State = None,
kinetic_energy_fn: PotentialFn = None,
momentum_sample_fn: MomentumSampleFn = None,
leapfrog_trace_fn: Callable[[Lea... |
A function to do simple sign - based control of a variable. | def sign_adaptation(control: FloatNest,
output: FloatTensor,
set_point: FloatTensor,
adaptation_rate: FloatTensor = 0.01) -> FloatNest:
"""A function to do simple sign-based control of a variable.
```
control = control * (1. + adaptation_rate) ** sign(o... |
Computes the output shape of the layer. | 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:
... |
Returns the config of the layer. | 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... |
Creates a layer from its config. | def from_config(cls, config):
"""Creates a layer from its config.
This method is the reverse of `get_config`, capable of instantiating the
same layer from the config dictionary.
Args:
config: A Python dictionary, typically the output of `get_config`.
Returns:
layer: A layer instance.
... |
Returns the config of the layer. | 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... |
Convenience to convert to Tensor or leave as None. | def _as_tensor(x, name, dtype):
"""Convenience to convert to `Tensor` or leave as `None`."""
return None if x is None else tf.convert_to_tensor(
value=x, name=name, dtype=dtype) |
Construct scale from various components. | def _create_scale_operator(self, identity_multiplier, diag, tril,
perturb_diag, perturb_factor, shift, validate_args,
dtype):
"""Construct `scale` from various components.
Args:
identity_multiplier: floating point rank 0 `Tensor` representing a sc... |
Returns a callable that adds a random normal perturbation to the input. | def random_walk_normal_fn(scale=1., name=None):
"""Returns a callable that adds a random normal perturbation to the input.
This function returns a callable that accepts a Python `list` of `Tensor`s of
any shapes and `dtypes` representing the state parts of the `current_state`
and a random seed. The supplied a... |
Returns a callable that adds a random uniform perturbation to the input. | def random_walk_uniform_fn(scale=1., name=None):
"""Returns a callable that adds a random uniform perturbation to the input.
For more details on `random_walk_uniform_fn`, see
`random_walk_normal_fn`. `scale` might
be a `Tensor` or a list of `Tensor`s that should broadcast with state parts
of the `current_sta... |
Batched KL divergence KL ( a || b ) for Independent distributions. | def _kl_independent(a, b, name="kl_independent"):
"""Batched KL divergence `KL(a || b)` for Independent distributions.
We can leverage the fact that
```
KL(Independent(a) || Independent(b)) = sum(KL(a || b))
```
where the sum is over the `reinterpreted_batch_ndims`.
Args:
a: Instance of `Independent... |
Computes the default value for reinterpreted_batch_ndim __init__ arg. | def _get_default_reinterpreted_batch_ndims(self, distribution):
"""Computes the default value for reinterpreted_batch_ndim __init__ arg."""
ndims = prefer_static.rank_from_shape(
distribution.batch_shape_tensor, distribution.batch_shape)
return prefer_static.maximum(0, ndims - 1) |
Expand the rank of x up to static_event_rank times for broadcasting. | def _expand_to_event_rank(self, x):
"""Expand the rank of x up to static_event_rank times for broadcasting.
The static event rank was checked to not be None at construction time.
Args:
x: A tensor to expand.
Returns:
The expanded tensor.
"""
expanded_x = x
for _ in range(tensor... |
r A lower bound on the entropy of this mixture model. | def entropy_lower_bound(self, name="entropy_lower_bound"):
r"""A lower bound on the entropy of this mixture model.
The bound below is not always very tight, and its usefulness depends
on the mixture probabilities and the components in use.
A lower bound is useful for ELBO when the `Mixture` is the var... |
Get a list of num_components batchwise probabilities. | def _cat_probs(self, log_probs):
"""Get a list of num_components batchwise probabilities."""
which_softmax = tf.nn.log_softmax if log_probs else tf.nn.softmax
cat_probs = which_softmax(self.cat.logits)
cat_probs = tf.unstack(cat_probs, num=self.num_components, axis=-1)
return cat_probs |
Validate outcomes logits and probs s shapes. | def _maybe_validate_args(outcomes, logits, probs, validate_args):
"""Validate `outcomes`, `logits` and `probs`'s shapes."""
assertions = []
def validate_equal_last_dim(tensor_a, tensor_b, message):
if tensor_a.shape.is_fully_defined() and tensor_b.shape.is_fully_defined():
if tensor_a.shape[-1] != tens... |
Attempt to import tensorflow and ensure its version is sufficient. | def _ensure_tf_install(): # pylint: disable=g-statement-before-imports
"""Attempt to import tensorflow, and ensure its version is sufficient.
Raises:
ImportError: if either tensorflow is not importable or its version is
inadequate.
"""
try:
import tensorflow as tf
except ImportError:
# Print... |
Bayesian logistic regression which returns labels given features. | def logistic_regression(features):
"""Bayesian logistic regression, which returns labels given features."""
coeffs = ed.MultivariateNormalDiag(
loc=tf.zeros(features.shape[1]), name="coeffs")
labels = ed.Bernoulli(
logits=tf.tensordot(features, coeffs, [[1], [0]]), name="labels")
return labels |
Builds the Covertype data set. | def covertype():
"""Builds the Covertype data set."""
import sklearn.datasets # pylint: disable=g-import-not-at-top
data = sklearn.datasets.covtype.fetch_covtype()
features = data.data
labels = data.target
# Normalize features and append a column of ones for the intercept.
features -= features.mean(0)
... |
Batchwise KL divergence KL ( d1 || d2 ) with d1 and d2 Dirichlet. | def _kl_dirichlet_dirichlet(d1, d2, name=None):
"""Batchwise KL divergence KL(d1 || d2) with d1 and d2 Dirichlet.
Args:
d1: instance of a Dirichlet distribution object.
d2: instance of a Dirichlet distribution object.
name: (optional) Name to use for created operations.
default is "kl_dirichlet_d... |
Checks the validity of the concentration parameter. | def _maybe_assert_valid_concentration(self, concentration, validate_args):
"""Checks the validity of the concentration parameter."""
if not validate_args:
return concentration
return distribution_util.with_dependencies([
assert_util.assert_positive(
concentration, message="Concentr... |
Checks the validity of a sample. | def _maybe_assert_valid_sample(self, x):
"""Checks the validity of a sample."""
if not self.validate_args:
return x
return distribution_util.with_dependencies([
assert_util.assert_positive(x, message="samples must be positive"),
assert_util.assert_near(
tf.ones([], dtype=se... |
Auto correlation along one axis. | def auto_correlation(x,
axis=-1,
max_lags=None,
center=True,
normalize=True,
name='auto_correlation'):
"""Auto correlation along one axis.
Given a `1-D` wide sense stationary (WSS) sequence `X`, the auto correl... |
Cholesky factor of the covariance matrix of vector - variate random samples. | def cholesky_covariance(x, sample_axis=0, keepdims=False, name=None):
"""Cholesky factor of the covariance matrix of vector-variate random samples.
This function can be use to fit a multivariate normal to data.
```python
tf.enable_eager_execution()
import tensorflow_probability as tfp
tfd = tfp.distributi... |
Sample covariance between observations indexed by event_axis. | def covariance(x,
y=None,
sample_axis=0,
event_axis=-1,
keepdims=False,
name=None):
"""Sample covariance between observations indexed by `event_axis`.
Given `N` samples of scalar random variables `X` and `Y`, covariance may be
estimated a... |
Sample correlation ( Pearson ) between observations indexed by event_axis. | def correlation(x,
y=None,
sample_axis=0,
event_axis=-1,
keepdims=False,
name=None):
"""Sample correlation (Pearson) between observations indexed by `event_axis`.
Given `N` samples of scalar random variables `X` and `Y`, correlation ma... |
Estimate standard deviation using samples. | def stddev(x, sample_axis=0, keepdims=False, name=None):
"""Estimate standard deviation using samples.
Given `N` samples of scalar valued random variable `X`, standard deviation may
be estimated as
```none
Stddev[X] := Sqrt[Var[X]],
Var[X] := N^{-1} sum_{n=1}^N (X_n - Xbar) Conj{(X_n - Xbar)},
Xbar := N... |
Estimate variance using samples. | def variance(x, sample_axis=0, keepdims=False, name=None):
"""Estimate variance using samples.
Given `N` samples of scalar valued random variable `X`, variance may
be estimated as
```none
Var[X] := N^{-1} sum_{n=1}^N (X_n - Xbar) Conj{(X_n - Xbar)}
Xbar := N^{-1} sum_{n=1}^N X_n
```
```python
x = t... |
Return a list ( preferred ) or 1d Tensor from values if values. ndims < 2. | def _make_list_or_1d_tensor(values):
"""Return a list (preferred) or 1d Tensor from values, if values.ndims < 2."""
values = tf.convert_to_tensor(value=values, name='values')
values_ = tf.get_static_value(values)
# Static didn't work.
if values_ is None:
# Cheap way to bring to at least 1d.
return va... |
Rectify possibly negatively axis. Prefer return Python list. | def _make_positive_axis(axis, ndims):
"""Rectify possibly negatively axis. Prefer return Python list."""
axis = _make_list_or_1d_tensor(axis)
ndims = tf.convert_to_tensor(value=ndims, name='ndims', dtype=tf.int32)
ndims_ = tf.get_static_value(ndims)
if _is_list_like(axis) and ndims_ is not None:
# Stati... |
A version of squeeze that works with dynamic axis. | def _squeeze(x, axis):
"""A version of squeeze that works with dynamic axis."""
x = tf.convert_to_tensor(value=x, name='x')
if axis is None:
return tf.squeeze(x, axis=None)
axis = tf.convert_to_tensor(value=axis, name='axis', dtype=tf.int32)
axis += tf.zeros([1], dtype=axis.dtype) # Make axis at least 1d... |
Calculate the batched KL divergence KL ( n_a || n_b ) with n_a and n_b Normal. | def _kl_normal_normal(n_a, n_b, name=None):
"""Calculate the batched KL divergence KL(n_a || n_b) with n_a and n_b Normal.
Args:
n_a: instance of a Normal distribution object.
n_b: instance of a Normal distribution object.
name: (optional) Name to use for created operations.
default is "kl_normal... |
Standardize input x to a unit normal. | def _z(self, x):
"""Standardize input `x` to a unit normal."""
with tf.name_scope("standardize"):
return (x - self.loc) / self.scale |
Reconstruct input x from a its normalized version. | def _inv_z(self, z):
"""Reconstruct input `x` from a its normalized version."""
with tf.name_scope("reconstruct"):
return z * self.scale + self.loc |
Build the transition matrix for a semi - local linear trend model. | def semilocal_linear_trend_transition_matrix(autoregressive_coef):
"""Build the transition matrix for a semi-local linear trend model."""
# We want to write the following 2 x 2 matrix:
# [[1., 1., ], # level(t+1) = level(t) + slope(t)
# [0., ar_coef], # slope(t+1) = ar_coef * slope(t)
# but it's slightl... |
Build the transition noise model for a semi - local linear trend model. | def semilocal_linear_trend_transition_noise(level_scale,
slope_mean,
slope_scale,
autoregressive_coef):
"""Build the transition noise model for a semi-local linear trend model."""
# A... |
r Returns a sample from the dim dimensional Halton sequence. | def sample_halton_sequence(dim,
num_results=None,
sequence_indices=None,
dtype=tf.float32,
randomized=True,
seed=None,
name=None):
r"""Returns a sample from... |
Applies the Owen ( 2017 ) randomization to the coefficients. | def _randomize(coeffs, radixes, seed=None):
"""Applies the Owen (2017) randomization to the coefficients."""
given_dtype = coeffs.dtype
coeffs = tf.cast(coeffs, dtype=tf.int32)
num_coeffs = tf.shape(input=coeffs)[-1]
radixes = tf.reshape(tf.cast(radixes, dtype=tf.int32), shape=[-1])
stream = distributions.S... |
Uniform iid sample from the space of permutations. | def _get_permutations(num_results, dims, seed=None):
"""Uniform iid sample from the space of permutations.
Draws a sample of size `num_results` from the group of permutations of degrees
specified by the `dims` tensor. These are packed together into one tensor
such that each row is one sample from each of the d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.