_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q266300 | SparkSqlHook._prepare_command | test | def _prepare_command(self, cmd):
"""
Construct the spark-sql command to execute. Verbose output is enabled
as default.
:param cmd: command to append to the spark-sql command
:type cmd: str
:return: full command to be executed
"""
connection_cmd = ["spark-... | python | {
"resource": ""
} |
q266301 | to_tensor | test | def to_tensor(pic):
"""Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor.
See ``ToTensor`` for more details.
Args:
pic (PIL Image or numpy.ndarray): Image to be converted to tensor.
Returns:
Tensor: Converted image.
"""
if not(_is_pil_image(pic) or _is_numpy_image(pic)):
... | python | {
"resource": ""
} |
q266302 | normalize | test | def normalize(tensor, mean, std, inplace=False):
"""Normalize a tensor image with mean and standard deviation.
.. note::
This transform acts out of place by default, i.e., it does not mutates the input tensor.
See :class:`~torchvision.transforms.Normalize` for more details.
Args:
tens... | python | {
"resource": ""
} |
q266303 | resize | test | def resize(img, size, interpolation=Image.BILINEAR):
r"""Resize the input PIL Image to the given size.
Args:
img (PIL Image): Image to be resized.
size (sequence or int): Desired output size. If size is a sequence like
(h, w), the output size will be matched to this. If size is an i... | python | {
"resource": ""
} |
q266304 | pad | test | def pad(img, padding, fill=0, padding_mode='constant'):
r"""Pad the given PIL Image on all sides with specified padding mode and fill value.
Args:
img (PIL Image): Image to be padded.
padding (int or tuple): Padding on each border. If a single int is provided this
is used to pad all... | python | {
"resource": ""
} |
q266305 | crop | test | def crop(img, i, j, h, w):
"""Crop the given PIL Image.
Args:
img (PIL Image): Image to be cropped.
i (int): i in (i,j) i.e coordinates of the upper left corner.
j (int): j in (i,j) i.e coordinates of the upper left corner.
h (int): Height of the cropped image.
w (int): ... | python | {
"resource": ""
} |
q266306 | resized_crop | test | def resized_crop(img, i, j, h, w, size, interpolation=Image.BILINEAR):
"""Crop the given PIL Image and resize it to desired size.
Notably used in :class:`~torchvision.transforms.RandomResizedCrop`.
Args:
img (PIL Image): Image to be cropped.
i (int): i in (i,j) i.e coordinates of the upper... | python | {
"resource": ""
} |
q266307 | hflip | test | def hflip(img):
"""Horizontally flip the given PIL Image.
Args:
img (PIL Image): Image to be flipped.
Returns:
PIL Image: Horizontall flipped image.
"""
if not _is_pil_image(img):
raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
return img.transpos... | python | {
"resource": ""
} |
q266308 | perspective | test | def perspective(img, startpoints, endpoints, interpolation=Image.BICUBIC):
"""Perform perspective transform of the given PIL Image.
Args:
img (PIL Image): Image to be transformed.
coeffs (tuple) : 8-tuple (a, b, c, d, e, f, g, h) which contains the coefficients.
for ... | python | {
"resource": ""
} |
q266309 | vflip | test | def vflip(img):
"""Vertically flip the given PIL Image.
Args:
img (PIL Image): Image to be flipped.
Returns:
PIL Image: Vertically flipped image.
"""
if not _is_pil_image(img):
raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
return img.transpose(I... | python | {
"resource": ""
} |
q266310 | five_crop | test | def five_crop(img, size):
"""Crop the given PIL Image into four corners and the central crop.
.. Note::
This transform returns a tuple of images and there may be a
mismatch in the number of inputs and targets your ``Dataset`` returns.
Args:
size (sequence or int): Desired output siz... | python | {
"resource": ""
} |
q266311 | adjust_brightness | test | def adjust_brightness(img, brightness_factor):
"""Adjust brightness of an Image.
Args:
img (PIL Image): PIL Image to be adjusted.
brightness_factor (float): How much to adjust the brightness. Can be
any non negative number. 0 gives a black image, 1 gives the
original im... | python | {
"resource": ""
} |
q266312 | adjust_contrast | test | def adjust_contrast(img, contrast_factor):
"""Adjust contrast of an Image.
Args:
img (PIL Image): PIL Image to be adjusted.
contrast_factor (float): How much to adjust the contrast. Can be any
non negative number. 0 gives a solid gray image, 1 gives the
original image wh... | python | {
"resource": ""
} |
q266313 | adjust_saturation | test | def adjust_saturation(img, saturation_factor):
"""Adjust color saturation of an image.
Args:
img (PIL Image): PIL Image to be adjusted.
saturation_factor (float): How much to adjust the saturation. 0 will
give a black and white image, 1 will give the original image while
... | python | {
"resource": ""
} |
q266314 | adjust_hue | test | def adjust_hue(img, hue_factor):
"""Adjust hue of an image.
The image hue is adjusted by converting the image to HSV and
cyclically shifting the intensities in the hue channel (H).
The image is then converted back to original image mode.
`hue_factor` is the amount of shift in H channel and must be... | python | {
"resource": ""
} |
q266315 | adjust_gamma | test | def adjust_gamma(img, gamma, gain=1):
r"""Perform gamma correction on an image.
Also known as Power Law Transform. Intensities in RGB mode are adjusted
based on the following equation:
.. math::
I_{\text{out}} = 255 \times \text{gain} \times \left(\frac{I_{\text{in}}}{255}\right)^{\gamma}
... | python | {
"resource": ""
} |
q266316 | rotate | test | def rotate(img, angle, resample=False, expand=False, center=None):
"""Rotate the image by angle.
Args:
img (PIL Image): PIL Image to be rotated.
angle (float or int): In degrees degrees counter clockwise order.
resample (``PIL.Image.NEAREST`` or ``PIL.Image.BILINEAR`` or ``PIL.Image.BI... | python | {
"resource": ""
} |
q266317 | affine | test | def affine(img, angle, translate, scale, shear, resample=0, fillcolor=None):
"""Apply affine transformation on the image keeping image center invariant
Args:
img (PIL Image): PIL Image to be rotated.
angle (float or int): rotation angle in degrees between -180 and 180, clockwise direction.
... | python | {
"resource": ""
} |
q266318 | to_grayscale | test | def to_grayscale(img, num_output_channels=1):
"""Convert image to grayscale version of image.
Args:
img (PIL Image): Image to be converted to grayscale.
Returns:
PIL Image: Grayscale version of the image.
if num_output_channels = 1 : returned image is single channel
... | python | {
"resource": ""
} |
q266319 | save_image | test | def save_image(tensor, filename, nrow=8, padding=2,
normalize=False, range=None, scale_each=False, pad_value=0):
"""Save a given Tensor into an image file.
Args:
tensor (Tensor or list): Image to be saved. If given a mini-batch tensor,
saves the tensor as a grid of images by ... | python | {
"resource": ""
} |
q266320 | DatasetFolder._find_classes | test | def _find_classes(self, dir):
"""
Finds the class folders in a dataset.
Args:
dir (string): Root directory path.
Returns:
tuple: (classes, class_to_idx) where classes are relative to (dir), and class_to_idx is a dictionary.
Ensures:
No class... | python | {
"resource": ""
} |
q266321 | read_image_file | test | def read_image_file(data_dir, image_ext, n):
"""Return a Tensor containing the patches
"""
def PIL2array(_img):
"""Convert PIL image type to numpy 2D array
"""
return np.array(_img.getdata(), dtype=np.uint8).reshape(64, 64)
def find_files(_data_dir, _image_ext):
"""Retu... | python | {
"resource": ""
} |
q266322 | read_info_file | test | def read_info_file(data_dir, info_file):
"""Return a Tensor containing the list of labels
Read the file and keep only the ID of the 3D point.
"""
labels = []
with open(os.path.join(data_dir, info_file), 'r') as f:
labels = [int(line.split()[0]) for line in f]
return torch.LongTensor(l... | python | {
"resource": ""
} |
q266323 | read_matches_files | test | def read_matches_files(data_dir, matches_file):
"""Return a Tensor containing the ground truth matches
Read the file and keep only 3D point ID.
Matches are represented with a 1, non matches with a 0.
"""
matches = []
with open(os.path.join(data_dir, matches_file), 'r') as f:
for li... | python | {
"resource": ""
} |
q266324 | accuracy | test | def accuracy(output, target, topk=(1,)):
"""Computes the accuracy over the k top predictions for the specified values of k"""
with torch.no_grad():
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(t... | python | {
"resource": ""
} |
q266325 | setup_for_distributed | test | def setup_for_distributed(is_master):
"""
This function disables printing when not in master process
"""
import builtins as __builtin__
builtin_print = __builtin__.print
def print(*args, **kwargs):
force = kwargs.pop('force', False)
if is_master or force:
builtin_pri... | python | {
"resource": ""
} |
q266326 | download_url | test | def download_url(url, root, filename=None, md5=None):
"""Download a file from a url and place it in root.
Args:
url (str): URL to download file from
root (str): Directory to place downloaded file in
filename (str, optional): Name to save the file under. If None, use the basename of the ... | python | {
"resource": ""
} |
q266327 | list_dir | test | def list_dir(root, prefix=False):
"""List all directories at a given root
Args:
root (str): Path to directory whose folders need to be listed
prefix (bool, optional): If true, prepends the path to each result, otherwise
only returns the name of the directories found
"""
root... | python | {
"resource": ""
} |
q266328 | list_files | test | def list_files(root, suffix, prefix=False):
"""List all files ending with a suffix at a given root
Args:
root (str): Path to directory whose folders need to be listed
suffix (str or tuple): Suffix of the files to match, e.g. '.png' or ('.jpg', '.png').
It uses the Python "str.endswi... | python | {
"resource": ""
} |
q266329 | download_file_from_google_drive | test | def download_file_from_google_drive(file_id, root, filename=None, md5=None):
"""Download a Google Drive file from and place it in root.
Args:
file_id (str): id of file to be downloaded
root (str): Directory to place downloaded file in
filename (str, optional): Name to save the file und... | python | {
"resource": ""
} |
q266330 | RandomCrop.get_params | test | def get_params(img, output_size):
"""Get parameters for ``crop`` for a random crop.
Args:
img (PIL Image): Image to be cropped.
output_size (tuple): Expected output size of the crop.
Returns:
tuple: params (i, j, h, w) to be passed to ``crop`` for random cro... | python | {
"resource": ""
} |
q266331 | RandomPerspective.get_params | test | def get_params(width, height, distortion_scale):
"""Get parameters for ``perspective`` for a random perspective transform.
Args:
width : width of the image.
height : height of the image.
Returns:
List containing [top-left, top-right, bottom-right, bottom-lef... | python | {
"resource": ""
} |
q266332 | RandomResizedCrop.get_params | test | def get_params(img, scale, ratio):
"""Get parameters for ``crop`` for a random sized crop.
Args:
img (PIL Image): Image to be cropped.
scale (tuple): range of size of the origin size cropped
ratio (tuple): range of aspect ratio of the origin aspect ratio cropped
... | python | {
"resource": ""
} |
q266333 | ColorJitter.get_params | test | def get_params(brightness, contrast, saturation, hue):
"""Get a randomized transform to be applied on image.
Arguments are same as that of __init__.
Returns:
Transform which randomly adjusts brightness, contrast and
saturation in a random order.
"""
tran... | python | {
"resource": ""
} |
q266334 | RandomAffine.get_params | test | def get_params(degrees, translate, scale_ranges, shears, img_size):
"""Get parameters for affine transformation
Returns:
sequence: params to be passed to the affine transformation
"""
angle = random.uniform(degrees[0], degrees[1])
if translate is not None:
... | python | {
"resource": ""
} |
q266335 | SBU.download | test | def download(self):
"""Download and extract the tarball, and download each individual photo."""
import tarfile
if self._check_integrity():
print('Files already downloaded and verified')
return
download_url(self.url, self.root, self.filename, self.md5_checksum)
... | python | {
"resource": ""
} |
q266336 | MNIST.download | test | def download(self):
"""Download the MNIST data if it doesn't exist in processed_folder already."""
if self._check_exists():
return
makedir_exist_ok(self.raw_folder)
makedir_exist_ok(self.processed_folder)
# download files
for url in self.urls:
f... | python | {
"resource": ""
} |
q266337 | EMNIST.download | test | def download(self):
"""Download the EMNIST data if it doesn't exist in processed_folder already."""
import shutil
import zipfile
if self._check_exists():
return
makedir_exist_ok(self.raw_folder)
makedir_exist_ok(self.processed_folder)
# download fil... | python | {
"resource": ""
} |
q266338 | get_current_theme_name | test | 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... | python | {
"resource": ""
} |
q266339 | autocompleter | test | 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... | python | {
"resource": ""
} |
q266340 | preferences | test | 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... | python | {
"resource": ""
} |
q266341 | get_themes | test | def get_themes(templates_path):
"""Returns available themes list."""
themes = os.listdir(templates_path)
if '__common__' in themes:
themes.remove('__common__')
return themes | python | {
"resource": ""
} |
q266342 | searx_bang | test | 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... | python | {
"resource": ""
} |
q266343 | response | test | 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}... | python | {
"resource": ""
} |
q266344 | custom_gradient | test | 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... | python | {
"resource": ""
} |
q266345 | mvn | test | 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) | python | {
"resource": ""
} |
q266346 | eight_schools_joint_log_prob | test | 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... | python | {
"resource": ""
} |
q266347 | benchmark_eight_schools_hmc | test | 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... | python | {
"resource": ""
} |
q266348 | expand_docstring | test | 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):
"""... | python | {
"resource": ""
} |
q266349 | _simple_name | test | 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... | python | {
"resource": ""
} |
q266350 | _build_custom_rv | test | 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... | python | {
"resource": ""
} |
q266351 | as_random_variable | test | 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... | python | {
"resource": ""
} |
q266352 | _make_random_variable | test | 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... | python | {
"resource": ""
} |
q266353 | one_step_predictive | test | 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... | python | {
"resource": ""
} |
q266354 | forecast | test | 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... | python | {
"resource": ""
} |
q266355 | _max_mask_non_finite | test | 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 | python | {
"resource": ""
} |
q266356 | assert_finite | test | 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... | python | {
"resource": ""
} |
q266357 | assert_rank_at_most | test | 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)... | python | {
"resource": ""
} |
q266358 | _event_size | test | 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... | python | {
"resource": ""
} |
q266359 | _eval_all_one_hot | test | 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] + [... | python | {
"resource": ""
} |
q266360 | _get_convert_to_tensor_fn | test | 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... | python | {
"resource": ""
} |
q266361 | MixtureSameFamily.params_size | test | 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... | python | {
"resource": ""
} |
q266362 | get_next_interceptor | test | 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... | python | {
"resource": ""
} |
q266363 | interceptable | test | 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
... | python | {
"resource": ""
} |
q266364 | tape | test | 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... | python | {
"resource": ""
} |
q266365 | toy_logistic_data | test | 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... | python | {
"resource": ""
} |
q266366 | visualize_decision | test | 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... | python | {
"resource": ""
} |
q266367 | build_input_pipeline | test | 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:... | python | {
"resource": ""
} |
q266368 | _maybe_check_valid_map_values | test | 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... | python | {
"resource": ""
} |
q266369 | trace | test | 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... | python | {
"resource": ""
} |
q266370 | call_fn | test | 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... | python | {
"resource": ""
} |
q266371 | call_and_grads | test | 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... | python | {
"resource": ""
} |
q266372 | maybe_broadcast_structure | test | 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... | python | {
"resource": ""
} |
q266373 | transform_log_prob_fn | test | 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... | python | {
"resource": ""
} |
q266374 | leapfrog_step | test | 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: ... | python | {
"resource": ""
} |
q266375 | metropolis_hastings_step | test | 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... | python | {
"resource": ""
} |
q266376 | hamiltonian_monte_carlo | test | 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... | python | {
"resource": ""
} |
q266377 | sign_adaptation | test | 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... | python | {
"resource": ""
} |
q266378 | _ConvVariational.from_config | test | 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.
... | python | {
"resource": ""
} |
q266379 | _as_tensor | test | 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) | python | {
"resource": ""
} |
q266380 | Affine._create_scale_operator | test | 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... | python | {
"resource": ""
} |
q266381 | random_walk_normal_fn | test | 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... | python | {
"resource": ""
} |
q266382 | random_walk_uniform_fn | test | 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... | python | {
"resource": ""
} |
q266383 | Mixture._expand_to_event_rank | test | 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... | python | {
"resource": ""
} |
q266384 | Mixture.entropy_lower_bound | test | 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... | python | {
"resource": ""
} |
q266385 | Mixture._cat_probs | test | 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 | python | {
"resource": ""
} |
q266386 | _maybe_validate_args | test | 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... | python | {
"resource": ""
} |
q266387 | _ensure_tf_install | test | 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... | python | {
"resource": ""
} |
q266388 | logistic_regression | test | 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 | python | {
"resource": ""
} |
q266389 | covertype | test | 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)
... | python | {
"resource": ""
} |
q266390 | cholesky_covariance | test | 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... | python | {
"resource": ""
} |
q266391 | stddev | test | 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... | python | {
"resource": ""
} |
q266392 | variance | test | 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... | python | {
"resource": ""
} |
q266393 | _make_positive_axis | test | 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... | python | {
"resource": ""
} |
q266394 | _squeeze | test | 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... | python | {
"resource": ""
} |
q266395 | Normal._z | test | def _z(self, x):
"""Standardize input `x` to a unit normal."""
with tf.name_scope("standardize"):
return (x - self.loc) / self.scale | python | {
"resource": ""
} |
q266396 | Normal._inv_z | test | def _inv_z(self, z):
"""Reconstruct input `x` from a its normalized version."""
with tf.name_scope("reconstruct"):
return z * self.scale + self.loc | python | {
"resource": ""
} |
q266397 | semilocal_linear_trend_transition_matrix | test | 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... | python | {
"resource": ""
} |
q266398 | semilocal_linear_trend_transition_noise | test | 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... | python | {
"resource": ""
} |
q266399 | sample_halton_sequence | test | 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... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.