_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
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-sql"] if self._conf: for conf_el in self._conf.split(","): connection_cmd += ["--conf", conf_el] if self._total_executor_cores: connection_cmd += ["--total-executor-cores", str(self._total_executor_cores)] if self._executor_cores: connection_cmd += ["--executor-cores", str(self._executor_cores)] if self._executor_memory: connection_cmd += ["--executor-memory", self._executor_memory] if self._keytab: connection_cmd += ["--keytab", self._keytab] if self._principal: connection_cmd += ["--principal", self._principal] if self._num_executors: connection_cmd += ["--num-executors", str(self._num_executors)] if self._sql: sql = self._sql.strip() if sql.endswith(".sql") or sql.endswith(".hql"):
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)): raise TypeError('pic should be PIL Image or ndarray. Got {}'.format(type(pic))) if isinstance(pic, np.ndarray): # handle numpy array if pic.ndim == 2: pic = pic[:, :, None] img = torch.from_numpy(pic.transpose((2, 0, 1))) # backward compatibility if isinstance(img, torch.ByteTensor): return img.float().div(255) else: return img if accimage is not None and isinstance(pic, accimage.Image):
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: tensor (Tensor): Tensor image of size (C, H, W) to be normalized. mean (sequence): Sequence of means for each channel. std (sequence): Sequence of standard deviations for each channel. Returns: Tensor: Normalized Tensor image. """ if not _is_tensor_image(tensor): raise TypeError('tensor is
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 int, the smaller edge of the image will be matched to this number maintaing the aspect ratio. i.e, if height > width, then image will be rescaled to :math:`\left(\text{size} \times \frac{\text{height}}{\text{width}}, \text{size}\right)` interpolation (int, optional): Desired interpolation. Default is ``PIL.Image.BILINEAR`` Returns: PIL Image: Resized image. """ if not _is_pil_image(img): raise TypeError('img should be PIL Image. Got
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 borders. If tuple of length 2 is provided this is the padding on left/right and top/bottom respectively. If a tuple of length 4 is provided this is the padding for the left, top, right and bottom borders respectively. fill: Pixel fill value for constant fill. Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively. This value is only used when the padding_mode is constant padding_mode: Type of padding. Should be: constant, edge, reflect or symmetric. Default is constant. - constant: pads with a constant value, this value is specified with fill - edge: pads with the last value on the edge of the image - reflect: pads with reflection of image (without repeating the last value on the edge) padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode will result in [3, 2, 1, 2, 3, 4, 3, 2] - symmetric: pads with reflection of image (repeating the last value on the edge) padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode will result in [2, 1, 1, 2, 3, 4, 4, 3] Returns: PIL Image: Padded image. """ if not _is_pil_image(img): raise TypeError('img should be PIL Image. Got {}'.format(type(img))) if not isinstance(padding, (numbers.Number, tuple)): raise TypeError('Got inappropriate padding arg') if not isinstance(fill, (numbers.Number, str, tuple)): raise TypeError('Got inappropriate fill arg') if not isinstance(padding_mode, str): raise TypeError('Got inappropriate padding_mode arg') if isinstance(padding, Sequence) and len(padding) not in [2, 4]: raise ValueError("Padding must be an int or a 2, or 4 element tuple, not a " + "{} element tuple".format(len(padding))) assert padding_mode in ['constant', 'edge', 'reflect', 'symmetric'], \ 'Padding mode should be either constant, edge, reflect or symmetric' if padding_mode == 'constant': if img.mode == 'P': palette = img.getpalette() image = ImageOps.expand(img, border=padding, fill=fill) image.putpalette(palette)
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): Width of the cropped image.
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 left corner j (int): j in (i,j) i.e coordinates of
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. """
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 a perspective transform. interpolation: Default- Image.BICUBIC Returns: PIL Image: Perspectively transformed Image. """ if not
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
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 size of the crop. If size is an int instead of sequence like (h, w), a square crop (size, size) is made. Returns: tuple: tuple (tl, tr, bl, br, center) Corresponding top left, top right, bottom left, bottom right and center crop. """ if isinstance(size, numbers.Number): size = (int(size), int(size)) else: assert len(size) == 2, "Please provide only two dimensions (h, w) for size." w, h = img.size
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 image while 2 increases the brightness by a factor of 2.
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 while 2 increases the contrast by a factor of 2.
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 2 will enhance the saturation by a factor of 2.
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 in the interval `[-0.5, 0.5]`. See `Hue`_ for more details. .. _Hue: https://en.wikipedia.org/wiki/Hue Args: img (PIL Image): PIL Image to be adjusted. hue_factor (float): How much to shift the hue channel. Should be in [-0.5, 0.5]. 0.5 and -0.5 give complete reversal of hue channel in
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} See `Gamma Correction`_ for more details. .. _Gamma Correction: https://en.wikipedia.org/wiki/Gamma_correction Args: img (PIL Image): PIL Image to be adjusted. gamma (float): Non negative real number, same as :math:`\gamma` in the equation. gamma larger than 1 make the shadows darker, while gamma smaller than 1 make dark regions lighter. gain (float): The constant
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.BICUBIC``, optional): An optional resampling filter. See `filters`_ for more information. If omitted, or if the image has mode "1" or "P", it is set to ``PIL.Image.NEAREST``. expand (bool, optional): Optional expansion flag. If true, expands the output image to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the input image.
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. translate (list or tuple of integers): horizontal and vertical translations (post-rotation translation) scale (float): overall scale shear (float): shear angle value in degrees between -180 to 180, clockwise direction. resample (``PIL.Image.NEAREST`` or ``PIL.Image.BILINEAR`` or ``PIL.Image.BICUBIC``, optional): An optional resampling filter. See `filters`_ for more information. If omitted, or if the image has mode "1" or "P", it is set to ``PIL.Image.NEAREST``. fillcolor (int): Optional
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 if num_output_channels = 3 : returned image is 3 channel with r = g = b """ if not _is_pil_image(img): raise TypeError('img should be PIL Image. Got {}'.format(type(img))) if num_output_channels == 1: img = img.convert('L') elif num_output_channels == 3:
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 calling ``make_grid``. **kwargs: Other arguments are documented in ``make_grid``. """ from PIL import Image grid = make_grid(tensor, nrow=nrow,
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 is a subdirectory of another. """ if sys.version_info >= (3, 5): # Faster and available in Python 3.5 and above classes = [d.name for
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): """Return a list with the file names of the images containing the patches """ files = [] # find those files with the specified extension for file_dir in os.listdir(_data_dir): if file_dir.endswith(_image_ext): files.append(os.path.join(_data_dir, file_dir)) return sorted(files) # sort files in ascend order to keep relations
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 = []
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 line in f:
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
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):
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 URL md5 (str, optional): MD5 checksum of the download. If None, do not check """ from six.moves import urllib root = os.path.expanduser(root) if not filename: filename = os.path.basename(url) fpath = os.path.join(root, filename)
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 = os.path.expanduser(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.endswith" method and is passed
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 under. If None, use the id of the file. md5 (str, optional): MD5 checksum of the download. If None, do not check """ # Based on https://stackoverflow.com/questions/38511444/python-download-files-from-google-drive-using-url import requests url = "https://docs.google.com/uc?export=download" root = os.path.expanduser(root) if not filename: filename = file_id fpath = os.path.join(root, filename) makedir_exist_ok(root) if os.path.isfile(fpath) and check_integrity(fpath, md5): print('Using downloaded
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.
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-left] of the orignal image, List containing [top-left, top-right, bottom-right, bottom-left] of the transformed image. """ half_height = int(height / 2) half_width = int(width / 2) topleft = (random.randint(0, int(distortion_scale * half_width)), random.randint(0, int(distortion_scale * half_height))) topright = (random.randint(width - int(distortion_scale * half_width) - 1, width - 1), random.randint(0, int(distortion_scale * half_height)))
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 Returns: tuple: params (i, j, h, w) to be passed to ``crop`` for a random sized crop. """ area = img.size[0] * img.size[1] for attempt in range(10): target_area = random.uniform(*scale) * area log_ratio = (math.log(ratio[0]), math.log(ratio[1]))
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. """ transforms = [] if brightness is not None: brightness_factor = random.uniform(brightness[0], brightness[1]) transforms.append(Lambda(lambda img: F.adjust_brightness(img, brightness_factor))) if contrast is not None: contrast_factor = random.uniform(contrast[0], contrast[1]) transforms.append(Lambda(lambda img: F.adjust_contrast(img, contrast_factor))) if saturation is not None:
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: max_dx = translate[0] * img_size[0] max_dy = translate[1] * img_size[1] translations = (np.round(random.uniform(-max_dx, max_dx)), np.round(random.uniform(-max_dy, max_dy))) else:
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) # Extract file with tarfile.open(os.path.join(self.root, self.filename), 'r:gz') as tar: tar.extractall(path=self.root) # Download individual photos with open(os.path.join(self.root, 'dataset', 'SBU_captioned_photo_dataset_urls.txt')) as fh: for line in fh:
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: filename = url.rpartition('/')[2] file_path = os.path.join(self.raw_folder, filename) download_url(url, root=self.raw_folder, filename=filename, md5=None) self.extract_gzip(gzip_path=file_path, remove_finished=True) # process and save as torch files print('Processing...') training_set = ( read_image_file(os.path.join(self.raw_folder, 'train-images-idx3-ubyte')), read_label_file(os.path.join(self.raw_folder, 'train-labels-idx1-ubyte'))
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 files filename = self.url.rpartition('/')[2] file_path = os.path.join(self.raw_folder, filename) download_url(self.url, root=self.raw_folder, filename=filename, md5=None) print('Extracting zip archive') with zipfile.ZipFile(file_path) as zip_f: zip_f.extractall(self.raw_folder) os.unlink(file_path) gzip_folder = os.path.join(self.raw_folder, 'gzip') for gzip_file in os.listdir(gzip_folder): if gzip_file.endswith('.gz'): self.extract_gzip(gzip_path=os.path.join(gzip_folder, gzip_file)) # process and save as torch files for split in self.splits: print('Processing ' + split) training_set = ( read_image_file(os.path.join(gzip_folder, 'emnist-{}-train-images-idx3-ubyte'.format(split))), read_label_file(os.path.join(gzip_folder, 'emnist-{}-train-labels-idx1-ubyte'.format(split))) )
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
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(request.form.get('q', u'').encode('utf-8'), disabled_engines) raw_text_query.parse_query() # check if search query is set if not raw_text_query.getSearchQuery(): return '', 400 # run autocompleter completer = autocomplete_backends.get(request.preferences.get_value('autocomplete')) # parse searx specific autocompleter results like !bang raw_results = searx_bang(raw_text_query) #
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 ValidationException: request.errors.append(gettext('Invalid settings, please edit your preferences')) return resp return request.preferences.save(resp) # render preferences image_proxy = request.preferences.get_value('image_proxy') lang = request.preferences.get_value('language') disabled_engines = request.preferences.engines.get_disabled() allowed_plugins = request.preferences.plugins.get_enabled() # stats for preferences page stats = {} for c in categories: for e in categories[c]: stats[e.name] = {'time': None, 'warn_timeout': False, 'warn_time': False} if e.timeout > settings['outgoing']['request_timeout']: stats[e.name]['warn_timeout'] = True stats[e.name]['supports_selected_language'] = _is_selected_language_supported(e, request.preferences) # get first element [0], the engine time, # and then the second element [1] : the time (the first one is the label) for engine_stat in get_engines_stats()[0][1]: stats[engine_stat.get('name')]['time'] = round(engine_stat.get('avg'), 3) if engine_stat.get('avg') > settings['outgoing']['request_timeout']: stats[engine_stat.get('name')]['warn_time'] = True # end of stats return render('preferences.html',
python
{ "resource": "" }
q266341
get_themes
test
def get_themes(templates_path): """Returns available themes list.""" themes = os.listdir(templates_path) if '__common__' in
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 = full_query.getSearchQuery()[0] if first_char == '!' or first_char == '?': if len(full_query.getSearchQuery()) == 1: # show some example queries # TODO, check if engine is not avaliable results.append(first_char + "images") results.append(first_char + "wikipedia") results.append(first_char + "osm") else: engine_query = full_query.getSearchQuery()[1:] # check if query starts with categorie name for categorie in categories: if categorie.startswith(engine_query): results.append(first_char + '{categorie}'.format(categorie=categorie)) # check if query starts with engine name for engine in engines: if engine.startswith(engine_query.replace('_', ' ')): results.append(first_char + '{engine}'.format(engine=engine.replace(' ', '_'))) # check if query starts with engine shortcut for engine_shortcut in engine_shortcuts: if engine_shortcut.startswith(engine_query): results.append(first_char + '{engine_shortcut}'.format(engine_shortcut=engine_shortcut)) # check if current query stats with :bang elif first_char == ':': if len(full_query.getSearchQuery()) == 1: # show some example queries results.append(":en") results.append(":en_us") results.append(":english") results.append(":united_kingdom") else: engine_query = full_query.getSearchQuery()[1:] for lc in language_codes: lang_id, lang_name, country, english_name = map(unicode.lower, lc) # check if query starts with language-id if lang_id.startswith(engine_query):
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} {1} = {2} {3}, 1 {1} ({5}) = {4} {3} ({6})'.format( resp.search_params['amount'], resp.search_params['from'], resp.search_params['amount'] * conversion_rate,
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) == stop_gradient(f(x))` and `grad[h(x), x] == stop_gradient(g(x)).` In addition to scalar-domain/scalar-range functions, this function also supports tensor-domain/scalar-range functions. Partial Custom Gradient: Suppose `h(x) = htilde(x, y)`. Note that `dh/dx = stop(g(x))` but `dh/dy = None`. This is because a `Tensor` cannot have only a portion of its gradient stopped. To circumvent this issue, one must manually `stop_gradient` the relevant portions of `f`, `g`. For example see the unit-test, `test_works_correctly_fx_gx_manually_stopped`. Args: fx: `Tensor`. Output of function evaluated at `x`. gx: `Tensor` or list of `Tensor`s. Gradient of function at (each) `x`. x: `Tensor` or list of `Tensor`s. Args of evaluation for `f`. fx_gx_manually_stopped: Python `bool` indicating that `fx`, `gx` manually have `stop_gradient` applied. name: Python `str` name prefixed to Ops created by this function. Returns: fx: Floating-type `Tensor` equal to `f(x)` but which has gradient `stop_gradient(g(x))`. """ def maybe_stop(x): if fx_gx_manually_stopped: return x return tf.stop_gradient(x) with tf.compat.v1.name_scope(name, 'custom_gradient', [fx, gx, x]): fx = tf.convert_to_tensor(value=fx, name='fx') # We don't want to bother eagerly computing `gx` since we may not even need # it. with tf.control_dependencies([fx]): if is_list_like(x): x = [identity(x_, name='x') for x_ in x] else: x = [identity(x, name='x')] if is_list_like(gx): gx = [identity(gx_, dtype=fx.dtype, name='gx') for gx_ in gx] else: gx = [identity(gx, dtype=fx.dtype, name='gx')] override_grad = [] for x_, gx_ in zip(x, gx): # Observe: tf.gradients(f(x), x)[i].shape == x[i].shape # thus we check that the user is supplying correct shapes. equal_shape = tf.compat.v1.assert_equal( tf.shape(input=x_), tf.shape(input=gx_), message='Each `x` must have the same shape as each `gx`.') with tf.control_dependencies([equal_shape]): # IEEE754 ensures `(x-x)==0.` and that `0.*x==0.` so we make sure to
python
{ "resource": "" }
q266345
mvn
test
def mvn(*args, **kwargs): """Convenience function to efficiently construct a MultivariateNormalDiag.""" # Faster than using `tfd.MultivariateNormalDiag`. return
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(
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, name='treatment_effects') treatment_stddevs = tf.constant( [15, 10, 16, 11, 9, 11, 10, 18], dtype=np.float32, name='treatment_stddevs') def unnormalized_posterior_log_prob( avg_effect, avg_stddev, school_effects_standard): """Eight-schools unnormalized log posterior.""" return eight_schools_joint_log_prob( treatment_effects, treatment_stddevs, avg_effect, avg_stddev, school_effects_standard) if tf.executing_eagerly(): sample_chain = tf.function(tfp.mcmc.sample_chain) else: sample_chain = tfp.mcmc.sample_chain def computation(): """The benchmark computation.""" _, kernel_results = sample_chain( num_results=num_results, num_burnin_steps=num_burnin_steps, current_state=( tf.zeros([], name='init_avg_effect'), tf.zeros([], name='init_avg_stddev'), tf.ones([num_schools], name='init_school_effects_standard'), ), kernel=tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=unnormalized_posterior_log_prob, step_size=step_size, num_leapfrog_steps=num_leapfrog_steps))
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): """Original function with modified `__doc__` attribute.""" doc = inspect.cleandoc(fn.__doc__) for k, v in six.iteritems(kwargs): # Capture each ${k} reference to
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, user-visible name kwarg. Args: distribution: a tfd.Distribution instance.
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 name. # User-defined RVs inherit their name from the provided # distribution; this helper method exposes the name as a dummy kwarg
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 wraps the constructor so it is included in the Edward trace and its values can be properly intercepted and overridden. Where possible, you should prefer the built-in constructors (`ed.Normal`, etc); these simultaneously construct a Distribution and a RandomVariable object so that the distribution parameters themselves may be intercepted and overridden. RVs constructed via `as_random_variable()` have a fixed distribution and may not support program transformations (e.g, conjugate marginalization) that rely on overriding distribution parameters. Args: distribution: tfd.Distribution governing the distribution of the random variable, such as sampling and log-probabilities. sample_shape: tf.TensorShape of samples to draw from the random variable. Default is `()` corresponding to a single sample. value: Fixed tf.Tensor
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(distribution_cls.__init__.__doc__ or '')) def func(*args, **kwargs):
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`. Args: model: An instance of `StructuralTimeSeries` representing a time-series model. This represents a joint distribution over time-series and their parameters with batch shape `[b1, ..., bN]`. observed_time_series: `float` `Tensor` of shape `concat([sample_shape, model.batch_shape, [num_timesteps, 1]]) where `sample_shape` corresponds to i.i.d. observations, and the trailing `[1]` dimension may (optionally) be omitted if `num_timesteps > 1`. May optionally be an instance of `tfp.sts.MaskedTimeSeries` including a mask `Tensor` to encode the locations of missing observations. parameter_samples: Python `list` of `Tensors` representing posterior samples of model parameters, with shapes `[concat([[num_posterior_draws], param.prior.batch_shape, param.prior.event_shape]) for param in model.parameters]`. This may optionally also be a map (Python `dict`) of parameter names to `Tensor` values. Returns: forecast_dist: a `tfd.MixtureSameFamily` instance with event shape [num_timesteps] and batch shape `concat([sample_shape, model.batch_shape])`, with `num_posterior_draws` mixture components. The `t`th step represents the forecast distribution `p(observed_time_series[t] | observed_time_series[0:t-1], parameter_samples)`. #### Examples Suppose we've built a model and fit it to data using HMC: ```python day_of_week = tfp.sts.Seasonal( num_seasons=7, observed_time_series=observed_time_series, name='day_of_week') local_linear_trend = tfp.sts.LocalLinearTrend( observed_time_series=observed_time_series, name='local_linear_trend') model = tfp.sts.Sum(components=[day_of_week, local_linear_trend], observed_time_series=observed_time_series) samples, kernel_results = tfp.sts.fit_with_hmc(model, observed_time_series) ``` Passing the posterior samples into `one_step_predictive`, we construct a one-step-ahead predictive distribution: ```python one_step_predictive_dist = tfp.sts.one_step_predictive( model, observed_time_series, parameter_samples=samples) predictive_means = one_step_predictive_dist.mean() predictive_scales = one_step_predictive_dist.stddev() ``` If using variational inference instead of HMC, we'd construct a forecast using samples from the variational posterior: ```python (variational_loss, variational_distributions) = tfp.sts.build_factored_variational_loss( model=model, observed_time_series=observed_time_series) # OMITTED: take steps to optimize variational loss samples = {k: q.sample(30) for (k, q) in variational_distributions.items()} one_step_predictive_dist = tfp.sts.one_step_predictive( model, observed_time_series, parameter_samples=samples) ``` We can visualize the forecast by plotting: ```python from matplotlib import pylab as plt def plot_one_step_predictive(observed_time_series, forecast_mean, forecast_scale): plt.figure(figsize=(12, 6)) num_timesteps = forecast_mean.shape[-1] c1, c2 = (0.12, 0.47, 0.71), (1.0, 0.5, 0.05) plt.plot(observed_time_series, label="observed time
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_forecast timesteps. Args: model: An instance of `StructuralTimeSeries` representing a time-series model. This represents a joint distribution over time-series and their parameters with batch shape `[b1, ..., bN]`. observed_time_series: `float` `Tensor` of shape `concat([sample_shape, model.batch_shape, [num_timesteps, 1]])` where `sample_shape` corresponds to i.i.d. observations, and the trailing `[1]` dimension may (optionally) be omitted if `num_timesteps > 1`. May optionally be an instance of `tfp.sts.MaskedTimeSeries` including a mask `Tensor` to encode the locations of missing observations. parameter_samples: Python `list` of `Tensors` representing posterior samples of model parameters, with shapes `[concat([[num_posterior_draws], param.prior.batch_shape, param.prior.event_shape]) for param in model.parameters]`. This may optionally also be a map (Python `dict`) of parameter names to `Tensor` values. num_steps_forecast: scalar `int` `Tensor` number of steps to forecast. Returns: forecast_dist: a `tfd.MixtureSameFamily` instance with event shape [num_steps_forecast, 1] and batch shape `concat([sample_shape, model.batch_shape])`, with `num_posterior_draws` mixture components. #### Examples Suppose we've built a model and fit it to data using HMC: ```python day_of_week = tfp.sts.Seasonal( num_seasons=7, observed_time_series=observed_time_series, name='day_of_week') local_linear_trend = tfp.sts.LocalLinearTrend( observed_time_series=observed_time_series, name='local_linear_trend') model = tfp.sts.Sum(components=[day_of_week, local_linear_trend], observed_time_series=observed_time_series) samples, kernel_results = tfp.sts.fit_with_hmc(model, observed_time_series) ``` Passing the posterior samples into `forecast`, we construct a forecast distribution: ```python forecast_dist = tfp.sts.forecast(model, observed_time_series, parameter_samples=samples, num_steps_forecast=50) forecast_mean = forecast_dist.mean()[..., 0] # shape: [50] forecast_scale = forecast_dist.stddev()[..., 0] # shape: [50] forecast_samples = forecast_dist.sample(10)[..., 0] # shape: [10, 50] ``` If using variational inference instead of HMC, we'd construct a forecast using samples from the variational posterior: ```python (variational_loss, variational_distributions) = tfp.sts.build_factored_variational_loss( model=model, observed_time_series=observed_time_series) # OMITTED: take steps to optimize variational loss samples = {k: q.sample(30) for (k, q) in variational_distributions.items()} forecast_dist = tfp.sts.forecast(model, observed_time_series, parameter_samples=samples, num_steps_forecast=50) ``` We can visualize the forecast by plotting: ```python from matplotlib import pylab as plt def plot_forecast(observed_time_series, forecast_mean, forecast_scale, forecast_samples): plt.figure(figsize=(12, 6)) num_steps = observed_time_series.shape[-1] num_steps_forecast = forecast_mean.shape[-1] num_steps_train = num_steps - num_steps_forecast c1, c2 = (0.12, 0.47, 0.71), (1.0, 0.5, 0.05) plt.plot(np.arange(num_steps), observed_time_series, lw=2, color=c1, label='ground truth') forecast_steps = np.arange(num_steps_train, num_steps_train+num_steps_forecast) plt.plot(forecast_steps, forecast_samples.T, lw=1, color=c2, alpha=0.1) plt.plot(forecast_steps, forecast_mean, lw=2, ls='--', color=c2, label='forecast') plt.fill_between(forecast_steps, forecast_mean - 2 * forecast_scale, forecast_mean + 2 * forecast_scale, color=c2, alpha=0.2) plt.xlim([0, num_steps]) plt.legend() plot_forecast(observed_time_series, forecast_mean=forecast_mean, forecast_scale=forecast_scale, forecast_samples=forecast_samples) ``` """ with tf.compat.v1.name_scope( 'forecast', values=[observed_time_series, parameter_samples, num_steps_forecast]): [ observed_time_series, mask ] = sts_util.canonicalize_observed_time_series_with_mask( observed_time_series) # Run filtering over the observed timesteps to extract the # latent state posterior at timestep T+1 (i.e., the final # filtering distribution, pushed through the transition model). # This is the prior for the forecast model ("today's prior # is yesterday's posterior"). num_observed_steps = dist_util.prefer_static_value( tf.shape(input=observed_time_series))[-2] observed_data_ssm = model.make_state_space_model( num_timesteps=num_observed_steps, param_vals=parameter_samples) (_, _, _, predictive_means, predictive_covs, _, _ ) = observed_data_ssm.forward_filter(observed_time_series, mask=mask) # Build a batch of state-space models over the forecast period. Because # we'll use MixtureSameFamily to
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)
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 each tensor. message: A string to prefix to the default message. name: A name for this operation (optional). Defaults to "assert_finite". Returns:
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) ``` Args: x: Numeric `Tensor`. rank: Scalar `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 each tensor. message: A string to prefix to the default message. name: A name for this operation (optional). Defaults to "assert_rank_at_most". Returns: Op raising `InvalidArgumentError` unless `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 elements in `tensor_shape`. Returns a numpy int when the number of elements can be computed immediately. Otherwise, returns a scalar tensor. """ with tf.compat.v1.name_scope(name, 'event_size',
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): return _deserialize(identifier)
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 create a single component distribution. name: The name to use for the op to compute the number of parameters (if such an op needs to be created). Returns: params_size: The number of parameters needed to create the mixture distribution. """ with tf.compat.v1.name_scope(name, 'MixtureSameFamily_params_size', [num_components, component_params_size]):
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-wrapping their first argument (`f`) as an `interceptable`. To avoid nesting, manipulate the computation without using `interceptable`. This function allows for nesting by manipulating the thread-local interceptor stack, so that operations are intercepted in the order of interceptor nesting. #### Examples ```python from tensorflow_probability import edward2 as ed def model(): x = ed.Normal(loc=0., scale=1., name="x") y = ed.Normal(loc=x, scale=1., name="y") return x + y def double(f, *args, **kwargs): return 2. * interceptable(f)(*args, **kwargs) def set_y(f, *args, **kwargs): if kwargs.get("name") == "y": kwargs["value"] = 0.42 return interceptable(f)(*args, **kwargs) with interception(double): with interception(set_y): z = model() ``` This will firstly put `double` on the stack, and then `set_y`, resulting in the stack: (TOP) set_y -> double -> apply (BOTTOM) The execution of `model` is then (top lines are current stack state): 1) (TOP) set_y -> double -> apply (BOTTOM); `ed.Normal(0., 1., "x")` is intercepted by `set_y`, and as the name is not "y" the operation is simply forwarded to the next interceptor on the stack. 2) (TOP) double -> apply (BOTTOM); `ed.Normal(0., 1., "x")` is intercepted by `double`, to produce `2*ed.Normal(0., 1., "x")`, with the operation being forwarded down the stack. 3) (TOP) apply (BOTTOM); `ed.Normal(0., 1., "x")` is intercepted by `apply`, which simply calls the constructor. (At this point, the nested calls to `get_next_interceptor()`,
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 interceptor. Args: func: Function to wrap. Returns: The
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 operations are recorded in sequence. Keys are the `name` keyword argument to the operation (typically, a random variable's `name`) and values are the corresponding output of the operation. If the operation has no name, it is not recorded. #### Examples ```python from tensorflow_probability import edward2 as ed def probabilistic_matrix_factorization(): users = ed.Normal(0., 1., sample_shape=[5000, 128], name="users") items = ed.Normal(0., 1., sample_shape=[7500, 128], name="items") ratings = ed.Normal(loc=tf.matmul(users, items, transpose_b=True), scale=0.1,
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 standard deviation of the weight vector. (scalar Python `float`). Returns: random_weights: Sampled weights as a Numpy `array` of shape `[input_size]`. random_bias: Sampled bias as a scalar Python `float`. design_matrix: Points sampled uniformly from the cube `[-1, 1]^{input_size}`, as a Numpy `array` of shape `(num_examples, input_size)`. labels: Labels sampled from the logistic model `p(label=1) = logistic(dot(features, random_weights) + random_bias)`, as a Numpy `int32` `array` of shape `(num_examples,
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 point. true_w_b: A `tuple` `(w, b)` where `w` is a Numpy array of shape `[2]` and `b` is a scalar `float`, interpreted as a decision rule of the form `dot(features, w) + b > 0`. candidate_w_bs: Python `iterable` containing tuples of the same form as true_w_b. fname: The filename to save the plot as a PNG image (Python `str`). """ fig = figure.Figure(figsize=(6, 6)) canvas = backend_agg.FigureCanvasAgg(fig) ax = fig.add_subplot(1, 1, 1) ax.scatter(features[:, 0], features[:, 1], c=np.float32(labels[:, 0]), cmap=cm.get_cmap("binary"),
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: batch_features: `Tensor` feed features, of shape `[batch_size] + x.shape[1:]`. batch_labels: `Tensor` feed of labels, of shape `[batch_size] + y.shape[1:]`.
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(message) elif validate_args: assertions.append(assert_util.assert_rank(map_values, 1, message=message)) message = 'Size of map_values must be greater than 0.' if tensorshape_util.num_elements(map_values.shape) is not None: if tensorshape_util.num_elements(map_values.shape) == 0: raise ValueError(message)
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 `TransitionOperator`. num_steps: Number of steps to run the function for. Must be greater than 1. trace_fn: Callable that the unpacked outputs of `fn` and returns a nest of `Tensor`s. These will be stacked
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
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 of `fn`. extra: Second output of `fn`.
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. Args: from_structure: A structure. to_structure: A structure. Returns: new_from_structure:
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 and creates a new log-prob function that now takes takes state in the domain of the bijector, forward transforms that state and calls the original log-prob function. It then returns the log-probability that correctly accounts for this transformation. The forward-transformed state is pre-pended to the original log-prob function's extra returns and returned as the new extra return. For convenience you can also pass the initial state (in the original space), and this function will return the inverse transformed as the 2nd return value. You'd use this to initialize MCMC operators that operate in the transformed space. Args: log_prob_fn: Log prob fn. bijector: Bijector(s), must be of the same structure as the `log_prob_fn` inputs. init_state: Initial state, in the original space. Returns: transformed_log_prob_fn: Transformed log prob fn. transformed_init_state: If `init_state` is provided. Initial state in the transformed space. """ def wrapper(*args): """Transformed wrapper.""" bijector_ = bijector args = tf.nest.map_structure(lambda x: 0. + x, args) if len(args) == 1: args = args[0] elif isinstance(bijector_, list): bijector_ = tuple(bijector_)
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: LeapFrogStepState. step_size: Step size, structure broadcastable to the `target_log_prob_fn` state. target_log_prob_fn: Target log prob fn. kinetic_energy_fn: Kinetic energy fn. Returns: leapfrog_step_state: LeapFrogStepState. leapfrog_step_extras: LeapFrogStepExtras. """ state = leapfrog_step_state.state state_grads = leapfrog_step_state.state_grads momentum = leapfrog_step_state.momentum step_size = maybe_broadcast_structure(step_size, state) state = tf.nest.map_structure(tf.convert_to_tensor, state) momentum = tf.nest.map_structure(tf.convert_to_tensor, momentum) state = tf.nest.map_structure(tf.convert_to_tensor, state) if state_grads is None: _, _, state_grads = call_and_grads(target_log_prob_fn, state) else: state_grads = tf.nest.map_structure(tf.convert_to_tensor, state_grads) momentum = tf.nest.map_structure(lambda m, sg, s: m + 0.5 * sg * s, momentum,
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_state` and `proposed_state` based on the `energy_change` so as to preserve detailed balance. Energy change is the negative of `log_accept_ratio`. Args: current_state: Current state. proposed_state: Proposed state. energy_change: E(proposed_state) - E(previous_state). seed: For reproducibility. Returns: new_state: The chosen state. is_accepted: Whether the proposed state was accepted. log_uniform: The random number that was used to select between the two states. """ flat_current = tf.nest.flatten(current_state) flat_proposed = nest.flatten_up_to(current_state, proposed_state) # Impute the None's in the current state. flat_current = [ p if c is None else c for p, c in zip(flat_proposed,
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[[LeapFrogStepState, LeapFrogStepExtras], TensorNest] = lambda *args: (), seed=None, ) -> Tuple[HamiltonianMonteCarloState, HamiltonianMonteCarloExtra]: """Hamiltonian Monte Carlo `TransitionOperator`. #### Example ```python step_size = 0.2 num_steps = 2000 num_leapfrog_steps = 10 state = tf.ones([16, 2]) base_mean = [1., 0] base_cov = [[1, 0.5], [0.5, 1]] bijector = tfb.Softplus() base_dist = tfd.MultivariateNormalFullCovariance( loc=base_mean, covariance_matrix=base_cov) target_dist = bijector(base_dist) def orig_target_log_prob_fn(x): return target_dist.log_prob(x), () target_log_prob_fn, state = fun_mcmc.transform_log_prob_fn( orig_target_log_prob_fn, bijector, state) kernel = tf.function(lambda state: fun_mcmc.hamiltonian_monte_carlo( state, step_size=step_size, num_leapfrog_steps=num_leapfrog_steps, target_log_prob_fn=target_log_prob_fn, seed=tfp_test_util.test_seed())) _, chain = fun_mcmc.trace( state=fun_mcmc.HamiltonianMonteCarloState( state=state, state_grads=None, target_log_prob=None, state_extra=None), fn=kernel, num_steps=num_steps, trace_fn=lambda state, extra: state.state_extra[0]) ``` Args: hmc_state: HamiltonianMonteCarloState. target_log_prob_fn: Target log prob fn. step_size: Step size, structure broadcastable to the `target_log_prob_fn` state. num_leapfrog_steps: Number of leapfrog steps to take. momentum: Initial momentum, passed to `momentum_sample_fn`. Default: zeroes. kinetic_energy_fn: Kinetic energy function. momentum_sample_fn: Sampler for the momentum. leapfrog_trace_fn: Trace function for the leapfrog integrator. seed: For reproducibility. Returns: hmc_state: HamiltonianMonteCarloState hmc_extra: HamiltonianMonteCarloExtra """ state = hmc_state.state state_grads = hmc_state.state_grads target_log_prob = hmc_state.target_log_prob state_extra = hmc_state.state_extra if kinetic_energy_fn is None: # pylint: disable=function-redefined def kinetic_energy_fn(*momentum): return tf.add_n([ tf.reduce_sum(input_tensor=tf.square(x), axis=-1) / 2. for x in tf.nest.flatten(momentum) ]), () if momentum_sample_fn is None: # pylint: disable=function-redefined def momentum_sample_fn(*momentum): ret = tf.nest.map_structure( lambda x: tf.random.normal(tf.shape(input=x), dtype=x.dtype), momentum) if len(ret) == 1: return ret[0] else: return ret if momentum is None: momentum = call_fn(momentum_sample_fn, tf.nest.map_structure(tf.zeros_like, state)) if target_log_prob is None: target_log_prob, state_extra, state_grads = call_and_grads( target_log_prob_fn, state) kinetic_energy, _ = call_fn(kinetic_energy_fn, momentum) current_energy = -target_log_prob + kinetic_energy current_state = HamiltonianMonteCarloState(
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(output - set_point) ``` Args: control: The control variable. output: The output variable. set_point: The set point for `output`. This function will adjust `control` so that `output` matches `set_point`. adaptation_rate: Adaptation rate. Returns: control: New control. """ def _get_new_control(control, output, set_point): new_control = mcmc_util.choose(output > set_point,
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. """ config = config.copy() function_keys = [ 'kernel_posterior_fn', 'kernel_posterior_tensor_fn', 'kernel_prior_fn', 'kernel_divergence_fn', 'bias_posterior_fn', 'bias_posterior_tensor_fn', 'bias_prior_fn', 'bias_divergence_fn',
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
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 scaling done to the identity matrix. diag: Floating-point `Tensor` representing the diagonal matrix.`diag` has shape `[N1, N2, ... k]`, which represents a k x k diagonal matrix. tril: Floating-point `Tensor` representing the lower triangular matrix. `tril` has shape `[N1, N2, ... k, k]`, which represents a k x k lower triangular matrix. perturb_diag: Floating-point `Tensor` representing the diagonal matrix of the low rank update. perturb_factor: Floating-point `Tensor` representing factor matrix. shift: Floating-point `Tensor` representing `shift in `scale @ X + shift`. validate_args: Python `bool` indicating whether arguments should be checked for correctness. dtype: `DType` for arg `Tensor` conversions. Returns: scale. In the case of scaling by a constant, scale is a floating point `Tensor`. Otherwise, scale is a `LinearOperator`. Raises: ValueError: if all of `tril`, `diag` and `identity_multiplier` are `None`. """ identity_multiplier = _as_tensor(identity_multiplier, "identity_multiplier", dtype) diag = _as_tensor(diag, "diag", dtype) tril = _as_tensor(tril, "tril", dtype) perturb_diag = _as_tensor(perturb_diag, "perturb_diag", dtype) perturb_factor = _as_tensor(perturb_factor, "perturb_factor", dtype) # If possible, use the low rank update to infer the shape of # the identity matrix, when scale represents a scaled identity matrix
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 argument `scale` must be a `Tensor` or Python `list` of `Tensor`s representing the scale of the generated proposal. `scale` must broadcast with the state parts of `current_state`. The callable adds a sample from a zero-mean normal distribution with the supplied scales to each state part and returns a same-type `list` of `Tensor`s as the state parts of `current_state`. Args: scale: a `Tensor` or Python `list` of `Tensor`s of any shapes and `dtypes` controlling the scale of the normal proposal distribution. name: Python `str` name prefixed to Ops created by this function. Default value: 'random_walk_normal_fn'. Returns: random_walk_normal_fn: A callable accepting a Python `list` of `Tensor`s representing the state parts of the `current_state` and an `int` representing the random seed to be used to generate the proposal. The callable returns the same-type `list` of `Tensor`s as the input and represents the proposal for the RWM algorithm. """ def _fn(state_parts, seed): """Adds a normal perturbation to the input state. Args: state_parts: A list of `Tensor`s of any shape and real dtype representing the state parts of the `current_state` of the Markov chain. seed: `int` or None. The random seed for this `Op`. If `None`, no seed is applied.
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_state`. The generated uniform perturbation is sampled as a uniform point on the rectangle `[-scale, scale]`. Args: scale: a `Tensor` or Python `list` of `Tensor`s of any shapes and `dtypes` controlling the upper and lower bound of the uniform proposal distribution. name: Python `str` name prefixed to Ops created by this function. Default value: 'random_walk_uniform_fn'. Returns: random_walk_uniform_fn: A callable accepting a Python `list` of `Tensor`s representing the state parts of the `current_state` and an `int` representing the random seed used to generate the proposal. The callable returns the same-type `list` of `Tensor`s as the input and represents the proposal for the RWM algorithm. """ def _fn(state_parts, seed): """Adds a uniform perturbation to the input state. Args: state_parts: A list of `Tensor`s of any shape and real dtype representing the state parts of the `current_state` of the Markov chain. seed: `int` or None. The random seed for this `Op`. If `None`, no seed is applied. Default value: `None`. Returns: perturbed_state_parts: A Python `list` of The `Tensor`s. Has the same
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.
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 variational distribution: \\( \log p(x) >= ELBO = \int q(z) \log p(x, z) dz + H[q] \\) where \\( p \\) is the prior distribution, \\( q \\) is the variational, and \\( H[q] \\) is the entropy of \\( q \\). If there is a lower bound \\( G[q] \\) such that \\( H[q] \geq G[q] \\) then it can be used in place of \\( H[q] \\). For a mixture of distributions \\( q(Z) = \sum_i c_i q_i(Z) \\) with \\( \sum_i c_i = 1 \\), by the concavity of \\( f(x) = -x \log x \\), a simple lower bound is: \\( \begin{align} H[q] & = - \int q(z) \log q(z) dz \\\ & = - \int (\sum_i c_i q_i(z)) \log(\sum_i c_i q_i(z)) dz \\\ & \geq - \sum_i c_i \int q_i(z) \log q_i(z) dz \\\ & = \sum_i c_i H[q_i] \end{align} \\) This is the term we calculate below for \\( G[q] \\). Args:
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
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] != tensor_b.shape[-1]: raise ValueError(message) elif validate_args: assertions.append( tf.compat.v1.assert_equal( tf.shape(input=tensor_a)[-1], tf.shape(input=tensor_b)[-1], message=message)) if logits is not None: validate_equal_last_dim( outcomes, logits, message='Last dimension of outcomes and logits must be equal size.') if probs is not None: validate_equal_last_dim( outcomes, probs, message='Last dimension of outcomes and probs must be equal size.') message = 'Rank of outcomes must be 1.' if outcomes.shape.ndims is
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 more informative error message, then reraise. print("\n\nFailed to import TensorFlow. Please note that TensorFlow is not " "installed by default when you install TensorFlow Probability. This " "is so that users can decide whether to install the GPU-enabled " "TensorFlow package. To use TensorFlow Probability, please install " "the most recent version of TensorFlow, by following instructions at " "https://tensorflow.org/install.\n\n") raise import distutils.version #
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")
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.distributions # Assume data.shape = (1000, 2). 1000 samples of a random variable in R^2. observed_data = read_data_samples(...) # The mean is easy mu = tf.reduce_mean(observed_data, axis=0) # Get the scale matrix L = tfp.stats.cholesky_covariance(observed_data) # Make the best fit multivariate normal (under maximum likelihood condition). mvn = tfd.MultivariateNormalTriL(loc=mu, scale_tril=L) # Plot contours of the pdf. xs, ys = tf.meshgrid( tf.linspace(-5., 5., 50), tf.linspace(-5., 5., 50), indexing='ij') xy = tf.stack((tf.reshape(xs, [-1]), tf.reshape(ys, [-1])), axis=-1) pdf = tf.reshape(mvn.prob(xy), (50, 50)) CS = plt.contour(xs, ys, pdf, 10) plt.clabel(CS, inline=1, fontsize=10) ``` Why does this work? Given vector-variate random variables `X = (X1, ..., Xd)`, one may obtain the sample covariance matrix in `R^{d x d}` (see `tfp.stats.covariance`). The [Cholesky factor](https://en.wikipedia.org/wiki/Cholesky_decomposition) of this matrix is analogous to standard deviation for scalar random variables: Suppose `X` has covariance matrix `C`, with Cholesky factorization `C = L L^T` Then multiplying a vector of iid random variables which have unit variance by `L` produces a vector with covariance `L L^T`, which is the same as `X`. ```python observed_data = read_data_samples(...) L = tfp.stats.cholesky_covariance(observed_data, sample_axis=0) # Make fake_data with the same covariance as observed_data. uncorrelated_normal = tf.random_normal(shape=(500, 10)) fake_data = tf.linalg.matvec(L, uncorrelated_normal) ``` Args: x: Numeric `Tensor`. The rightmost dimension of `x` indexes events. E.g.
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^{-1} sum_{n=1}^N X_n ``` ```python x = tf.random_normal(shape=(100, 2, 3)) # stddev[i, j] is the sample standard deviation of the (i, j) batch member. stddev = tfp.stats.stddev(x, sample_axis=0) ``` Scaling a unit normal by a standard deviation produces normal samples with that standard deviation. ```python observed_data = read_data_samples(...) stddev = tfp.stats.stddev(observed_data) # Make fake_data with the same standard deviation as observed_data. fake_data = stddev * tf.random_normal(shape=(100,)) ``` Notice we divide by `N` (the numpy default), which does not create `NaN` when `N = 1`, but is slightly biased. Args: x: A numeric `Tensor` holding samples.
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 = tf.random_normal(shape=(100, 2, 3)) # var[i, j] is the sample variance of the (i, j) batch member of x. var = tfp.stats.variance(x, sample_axis=0) ``` Notice we divide by `N` (the numpy default), which does not create `NaN` when `N = 1`, but is slightly biased. Args: x: A numeric `Tensor` holding samples. sample_axis: Scalar or vector `Tensor` designating axis holding samples, or `None` (meaning all axis hold samples). Default value: `0` (leftmost dimension). keepdims:
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: # Static case positive_axis = [] for a in axis:
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
python
{ "resource": "" }
q266395
Normal._z
test
def _z(self, x): """Standardize input `x` to a unit normal."""
python
{ "resource": "" }
q266396
Normal._inv_z
test
def _inv_z(self, z): """Reconstruct input `x` from a its normalized version."""
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 slightly tricky to properly incorporate the batch shape of # autoregressive_coef. E.g., if autoregressive_coef has shape [4,6], we want # to return shape [4, 6, 2, 2]. We do this by breaking the matrix into its # fixed entries, written explicitly, and then the autoregressive_coef part # which we add in after using a mask to broadcast to the correct matrix shape. fixed_entries = tf.constant( [[1., 1.], [0., 0.]], dtype=autoregressive_coef.dtype)
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.""" # At each timestep, the stochasticity of `level` and `slope` are given # by `level_scale` and `slope_scale` respectively. broadcast_batch_shape = dist_util.get_broadcast_shape( level_scale, slope_mean, slope_scale, autoregressive_coef) broadcast_ones = tf.ones(broadcast_batch_shape, dtype=level_scale.dtype) scale_diag = tf.stack([level_scale * broadcast_ones, slope_scale * broadcast_ones], axis=-1) # We additionally fold in a bias term implementing the nonzero `slope_mean`. # The overall `slope` update is (from `SemiLocalLinearTrend` docstring) # slope[t] = (slope_mean + # autoregressive_coef * (slope[t-1] - slope_mean) + # Normal(0., slope_scale)) # which we rewrite as
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 the `dim` dimensional Halton sequence. Warning: The sequence elements take values only between 0 and 1. Care must be taken to appropriately transform the domain of a function if it differs from the unit cube before evaluating integrals using Halton samples. It is also important to remember that quasi-random numbers without randomization are not a replacement for pseudo-random numbers in every context. Quasi random numbers are completely deterministic and typically have significant negative autocorrelation unless randomization is used. Computes the members of the low discrepancy Halton sequence in dimension `dim`. The `dim`-dimensional sequence takes values in the unit hypercube in `dim` dimensions. Currently, only dimensions up to 1000 are supported. The prime base for the k-th axes is the k-th prime starting from 2. For example, if `dim` = 3, then the bases will be [2, 3, 5] respectively and the first element of the non-randomized sequence will be: [0.5, 0.333, 0.2]. For a more complete description of the Halton sequences see [here](https://en.wikipedia.org/wiki/Halton_sequence). For low discrepancy sequences and their applications see [here](https://en.wikipedia.org/wiki/Low-discrepancy_sequence). If `randomized` is true, this function produces a scrambled version of the Halton sequence introduced by [Owen (2017)][1]. For the advantages of randomization of low discrepancy sequences see [here]( https://en.wikipedia.org/wiki/Quasi-Monte_Carlo_method#Randomization_of_quasi-Monte_Carlo). The number of samples produced is controlled by the `num_results` and `sequence_indices` parameters. The user must supply either `num_results` or `sequence_indices` but not both. The former is the number of samples to produce starting from the first element. If `sequence_indices` is given instead, the specified elements of the sequence are generated. For example, sequence_indices=tf.range(10) is equivalent to specifying n=10. #### Examples ```python import tensorflow as tf import tensorflow_probability as tfp # Produce the first 1000 members of the Halton sequence in 3 dimensions. num_results = 1000 dim = 3 sample = tfp.mcmc.sample_halton_sequence( dim, num_results=num_results, seed=127) # Evaluate the integral of x_1 * x_2^2 * x_3^3 over the three dimensional # hypercube. powers = tf.range(1.0, limit=dim + 1) integral = tf.reduce_mean(tf.reduce_prod(sample ** powers, axis=-1)) true_value = 1.0 / tf.reduce_prod(powers + 1.0) with tf.Session() as session: values = session.run((integral, true_value)) # Produces a relative absolute error of 1.7%. print ("Estimated: %f, True Value: %f" % values) # Now skip the first 1000 samples and recompute the integral with the next # thousand samples. The sequence_indices argument can be used to do this. sequence_indices = tf.range(start=1000, limit=1000 + num_results, dtype=tf.int32) sample_leaped = tfp.mcmc.sample_halton_sequence( dim, sequence_indices=sequence_indices, seed=111217) integral_leaped = tf.reduce_mean(tf.reduce_prod(sample_leaped ** powers, axis=-1)) with tf.Session() as session: values = session.run((integral_leaped, true_value)) # Now produces a relative absolute error of 0.05%. print ("Leaped Estimated: %f, True Value: %f" % values) ``` Args: dim: Positive Python `int` representing each sample's `event_size.` Must not be greater than 1000. num_results: (Optional) Positive scalar `Tensor` of dtype int32. The number of samples to generate. Either this parameter or sequence_indices must be specified but not both. If this parameter is None, then the behaviour is determined by the `sequence_indices`. Default value: `None`. sequence_indices: (Optional) `Tensor` of dtype int32 and rank 1. The elements of the sequence to compute specified by their position in the sequence. The entries index into the Halton sequence starting with 0 and hence, must be whole numbers. For example, sequence_indices=[0, 5, 6] will produce the first, sixth and seventh elements of the sequence. If this parameter is None, then the `num_results` parameter must be specified which gives the number of desired samples starting from the first sample. Default value: `None`. dtype: (Optional) The dtype of the sample. One of: `float16`, `float32` or `float64`. Default value: `tf.float32`. randomized: (Optional) bool indicating whether to produce a randomized Halton sequence. If True, applies the randomization described in [Owen (2017)][1]. Default value: `True`. seed: (Optional) Python integer to seed the random number generator. Only used if `randomized` is True. If not supplied and `randomized` is True, no seed is set. Default value: `None`. name: (Optional) Python `str` describing ops managed by this function. If not supplied the name of this function is used. Default value: "sample_halton_sequence". Returns: halton_elements: Elements of the Halton sequence. `Tensor` of supplied dtype and `shape` `[num_results, dim]` if `num_results` was specified or shape `[s, dim]` where s is the size of `sequence_indices` if `sequence_indices` were specified. Raises: ValueError: if both `sequence_indices` and `num_results` were specified or if dimension `dim` is less than 1 or greater than 1000. #### References [1]: Art B. Owen. A randomized Halton algorithm in R. _arXiv preprint arXiv:1706.02808_, 2017. https://arxiv.org/abs/1706.02808 """ if dim < 1 or dim > _MAX_DIMENSION: raise ValueError( 'Dimension must be between 1 and {}. Supplied {}'.format(_MAX_DIMENSION, dim)) if (num_results is None) == (sequence_indices is None): raise ValueError('Either `num_results` or `sequence_indices` must be' ' specified but not both.')
python
{ "resource": "" }