docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
Escapes the glob characters in a path.
Python 3 has a glob.escape method, but python 2 lacks it, so we manually
implement this method.
Args:
path: The absolute path to escape.
Returns:
The escaped path string. | def _EscapeGlobCharacters(path):
drive, path = os.path.splitdrive(path)
return '%s%s' % (drive, _ESCAPE_GLOB_CHARACTERS_REGEX.sub(r'[\1]', path)) | 57,673 |
Obtains all subdirectories with events files.
The order of the subdirectories returned is unspecified. The internal logic
that determines order varies by scenario.
Args:
path: The path to a directory under which to find subdirectories.
Returns:
A tuple of absolute paths of all subdirectories each wit... | def GetLogdirSubdirectories(path):
if not tf.io.gfile.exists(path):
# No directory to traverse.
return ()
if not tf.io.gfile.isdir(path):
raise ValueError('GetLogdirSubdirectories: path exists and is not a '
'directory, %s' % path)
if IsCloudPath(path):
# Glob-ing for fil... | 57,676 |
Determines whether a health pill event contains bad values.
A bad value is one of NaN, -Inf, or +Inf.
Args:
event: (`Event`) A `tensorflow.Event` proto from `DebugNumericSummary`
ops.
Returns:
An instance of `NumericsAlert`, if bad values are found.
`None`, if no bad values are found.
Rais... | def extract_numerics_alert(event):
value = event.summary.value[0]
debugger_plugin_metadata_content = None
if value.HasField("metadata"):
plugin_data = value.metadata.plugin_data
if plugin_data.plugin_name == constants.DEBUGGER_PLUGIN_NAME:
debugger_plugin_metadata_content = plugin_data.content
... | 57,678 |
Tracks events for a single category of values.
Args:
event_count: The initial event count to use.
first_timestamp: The timestamp of the first event with this value.
last_timestamp: The timestamp of the last event with this category of
values. | def __init__(self, event_count=0, first_timestamp=-1, last_timestamp=-1):
# When updating the properties of this class, make sure to keep
# EventTrackerDescription in sync so that data can be written to and from
# disk correctly.
self.event_count = event_count
self.first_timestamp = first_time... | 57,679 |
Stores alert history for a single device, tensor pair.
Args:
initialization_list: (`list`) An optional list parsed from JSON read
from disk. That entity is used to initialize this NumericsAlertHistory.
Use the create_jsonable_object method of this class to create such an
object. | def __init__(self, initialization_list=None):
if initialization_list:
# Use data to initialize this NumericsAlertHistory.
self._trackers = {}
for value_category_key, description_list in initialization_list.items():
description = EventTrackerDescription._make(description_list)
... | 57,681 |
Obtain the first timestamp.
Args:
event_key: the type key of the sought events (e.g., constants.NAN_KEY).
If None, includes all event type keys.
Returns:
First (earliest) timestamp of all the events of the given type (or all
event types if event_key is None). | def first_timestamp(self, event_key=None):
if event_key is None:
timestamps = [self._trackers[key].first_timestamp
for key in self._trackers]
return min(timestamp for timestamp in timestamps if timestamp >= 0)
else:
return self._trackers[event_key].first_timestamp | 57,683 |
Obtain the last timestamp.
Args:
event_key: the type key of the sought events (e.g., constants.NAN_KEY). If
None, includes all event type keys.
Returns:
Last (latest) timestamp of all the events of the given type (or all
event types if event_key is None). | def last_timestamp(self, event_key=None):
if event_key is None:
timestamps = [self._trackers[key].first_timestamp
for key in self._trackers]
return max(timestamp for timestamp in timestamps if timestamp >= 0)
else:
return self._trackers[event_key].last_timestamp | 57,684 |
Constructor.
Args:
capacity: (`int`) maximum number of device-tensor keys to store.
initialization_list: (`list`) An optional list (parsed from JSON) that
is used to initialize the data within this registry. Use the
create_jsonable_registry method of NumericsAlertRegistry to create such... | def __init__(self, capacity=100, initialization_list=None):
self._capacity = capacity
# A map from device-tensor key to a the TensorAlertRecord namedtuple.
# The device-tensor key is a 2-tuple of the format (device_name, node_name).
# E.g., ("/job:worker/replica:0/task:1/gpu:0", "cross_entropy/Log... | 57,686 |
Register an alerting numeric event.
Args:
numerics_alert: An instance of `NumericsAlert`. | def register(self, numerics_alert):
key = (numerics_alert.device_name, numerics_alert.tensor_name)
if key in self._data:
self._data[key].add(numerics_alert)
else:
if len(self._data) < self._capacity:
history = NumericsAlertHistory()
history.add(numerics_alert)
self._... | 57,687 |
Generate waves of the shapes defined above.
Arguments:
logdir: the directory into which to store all the runs' data
verbose: if true, print out each run's name as it begins | def run_all(logdir, verbose=False):
waves = [sine_wave, square_wave, triangle_wave,
bisine_wave, bisine_wahwah_wave]
for (i, wave_constructor) in enumerate(waves):
wave_name = wave_constructor.__name__
run_name = 'wave:%02d,%s' % (i + 1, wave_name)
if verbose:
print('--- Running: %s'... | 57,695 |
Returns the plugin, if possible.
Args:
context: The TBContext flags.
Returns:
A ProfilePlugin instance or None if it couldn't be loaded. | def load(self, context):
try:
# pylint: disable=g-import-not-at-top,unused-import
import tensorflow
# Available in TensorFlow 1.14 or later, so do import check
# pylint: disable=g-import-not-at-top,unused-import
from tensorflow.python.eager import profiler_client
except Import... | 57,709 |
Create a Keras model with the given hyperparameters.
Args:
hparams: A dict mapping hyperparameters in `HPARAMS` to values.
seed: A hashable object to be used as a random seed (e.g., to
construct dropout layers in the model).
Returns:
A compiled Keras model. | def model_fn(hparams, seed):
rng = random.Random(seed)
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Input(INPUT_SHAPE))
model.add(tf.keras.layers.Reshape(INPUT_SHAPE + (1,))) # grayscale channel
# Add convolutional layers.
conv_filters = 8
for _ in xrange(hparams[HP_CONV_LAYERS]):
... | 57,710 |
Run a training/validation session.
Flags must have been parsed for this function to behave.
Args:
data: The data as loaded by `prepare_data()`.
base_logdir: The top-level logdir to which to write summary data.
session_id: A unique string ID for this session.
group_id: The string ID of the session ... | def run(data, base_logdir, session_id, group_id, hparams):
model = model_fn(hparams=hparams, seed=session_id)
logdir = os.path.join(base_logdir, session_id)
callback = tf.keras.callbacks.TensorBoard(
logdir,
update_freq=flags.FLAGS.summary_freq,
profile_batch=0, # workaround for issue #2084... | 57,711 |
Perform random search over the hyperparameter space.
Arguments:
logdir: The top-level directory into which to write data. This
directory should be empty or nonexistent.
verbose: If true, print out each run's name as it begins. | def run_all(logdir, verbose=False):
data = prepare_data()
rng = random.Random(0)
base_writer = tf.summary.create_file_writer(logdir)
with base_writer.as_default():
experiment = hp.Experiment(hparams=HPARAMS, metrics=METRICS)
experiment_string = experiment.summary_pb().SerializeToString()
tf.summ... | 57,713 |
Sample a value uniformly from a domain.
Args:
domain: An `IntInterval`, `RealInterval`, or `Discrete` domain.
rng: A `random.Random` object; defaults to the `random` module.
Raises:
TypeError: If `domain` is not a known kind of domain.
IndexError: If the domain is empty. | def sample_uniform(domain, rng):
if isinstance(domain, hp.IntInterval):
return rng.randint(domain.min_value, domain.max_value)
elif isinstance(domain, hp.RealInterval):
return rng.uniform(domain.min_value, domain.max_value)
elif isinstance(domain, hp.Discrete):
return rng.choice(domain.values)
el... | 57,714 |
Creates the JSON object for the PR curves response for a run-tag combo.
Arguments:
runs: A list of runs to fetch the curves for.
tag: The tag to fetch the curves for.
Raises:
ValueError: If no PR curves could be fetched for a run and tag.
Returns:
The JSON object for the PR curves... | def pr_curves_impl(self, runs, tag):
if self._db_connection_provider:
# Serve data from the database.
db = self._db_connection_provider()
# We select for steps greater than -1 because the writer inserts
# placeholder rows en masse. The check for step filters out those rows.
curso... | 57,717 |
Converts a TensorEvent into a dict that encapsulates information on it.
Args:
event: The TensorEvent to convert.
thresholds: An array of floats that ranges from 0 to 1 (in that
direction and inclusive of 0 and 1).
Returns:
A JSON-able dictionary of PR curve data for 1 step. | def _process_tensor_event(self, event, thresholds):
return self._make_pr_entry(
event.step,
event.wall_time,
tensor_util.make_ndarray(event.tensor_proto),
thresholds) | 57,721 |
Creates an entry for PR curve data. Each entry corresponds to 1 step.
Args:
step: The step.
wall_time: The wall time.
data_array: A numpy array of PR curve data stored in the summary format.
thresholds: An array of floating point thresholds.
Returns:
A PR curve entry. | def _make_pr_entry(self, step, wall_time, data_array, thresholds):
# Trim entries for which TP + FP = 0 (precision is undefined) at the tail of
# the data.
true_positives = [int(v) for v in data_array[metadata.TRUE_POSITIVES_INDEX]]
false_positives = [
int(v) for v in data_array[metadata.FA... | 57,722 |
Normalize a dict keyed by `HParam`s and/or raw strings.
Args:
hparams: A `dict` whose keys are `HParam` objects and/or strings
representing hyperparameter names, and whose values are
hyperparameter values. No two keys may have the same name.
Returns:
A `dict` whose keys are hyperparameter name... | def _normalize_hparams(hparams):
result = {}
for (k, v) in six.iteritems(hparams):
if isinstance(k, HParam):
k = k.name
if k in result:
raise ValueError("multiple values specified for hparam %r" % (k,))
result[k] = v
return result | 57,733 |
Create an experiment object.
Args:
hparams: A list of `HParam` values.
metrics: A list of `Metric` values.
user: An optional string denoting the user or group that owns this
experiment.
description: An optional Markdown string describing this
experiment.
time_created_s... | def __init__(
self,
hparams,
metrics,
user=None,
description=None,
time_created_secs=None,
):
self._hparams = list(hparams)
self._metrics = list(metrics)
self._user = user
self._description = description
if time_created_secs is None:
time_created_secs... | 57,734 |
Create a hyperparameter object.
Args:
name: A string ID for this hyperparameter, which should be unique
within an experiment.
domain: An optional `Domain` object describing the values that
this hyperparameter can take on.
display_name: An optional human-readable display name (`str... | def __init__(self, name, domain=None, display_name=None, description=None):
self._name = name
self._domain = domain
self._display_name = display_name
self._description = description
if not isinstance(self._domain, (Domain, type(None))):
raise ValueError("not a domain: %r" % (self._domain,... | 57,736 |
Create a `RealInterval`.
Args:
min_value: The lower bound (inclusive) of the interval.
max_value: The upper bound (inclusive) of the interval.
Raises:
TypeError: If `min_value` or `max_value` is not an `float`.
ValueError: If `min_value > max_value`. | def __init__(self, min_value=None, max_value=None):
if not isinstance(min_value, float):
raise TypeError("min_value must be a float: %r" % (min_value,))
if not isinstance(max_value, float):
raise TypeError("max_value must be a float: %r" % (max_value,))
if min_value > max_value:
raise... | 57,739 |
Parses and asserts a positive (>0) integer query parameter.
Args:
request: The Werkzeug Request object
param_name: Name of the parameter.
Returns:
Param, or None, or -1 if parameter is not a positive integer. | def _parse_positive_int_param(request, param_name):
param = request.args.get(param_name)
if not param:
return None
try:
param = int(param)
if param <= 0:
raise ValueError()
return param
except ValueError:
return -1 | 57,752 |
Constructs a metadata for an embedding of the specified size.
Args:
num_points: Number of points in the embedding. | def __init__(self, num_points):
self.num_points = num_points
self.column_names = []
self.name_to_values = {} | 57,758 |
Adds a named column of metadata values.
Args:
column_name: Name of the column.
column_values: 1D array/list/iterable holding the column values. Must be
of length `num_points`. The i-th value corresponds to the i-th point.
Raises:
ValueError: If `column_values` is not 1D array, or o... | def add_column(self, column_name, column_values):
# Sanity checks.
if isinstance(column_values, list) and isinstance(column_values[0], list):
raise ValueError('"column_values" must be a flat list, but we detected '
'that its first entry is a list')
if isinstance(column_val... | 57,759 |
Instantiates ProjectorPlugin via TensorBoard core.
Args:
context: A base_plugin.TBContext instance. | def __init__(self, context):
self.multiplexer = context.multiplexer
self.logdir = context.logdir
self._handlers = None
self.readers = {}
self.run_paths = None
self._configs = {}
self.old_num_run_paths = None
self.config_fpaths = None
self.tensor_cache = LRUCache(_TENSOR_CACHE_CA... | 57,760 |
Retrieve the histogram events associated with a run and tag.
Args:
run: A string name of the run for which values are retrieved.
tag: A string name of the tag for which values are retrieved.
Raises:
KeyError: If the run is not found, or the tag is not available for
the given run.
... | def Histograms(self, run, tag):
accumulator = self.GetAccumulator(run)
return accumulator.Histograms(tag) | 57,778 |
Retrieve the compressed histogram events associated with a run and tag.
Args:
run: A string name of the run for which values are retrieved.
tag: A string name of the tag for which values are retrieved.
Raises:
KeyError: If the run is not found, or the tag is not available for
the giv... | def CompressedHistograms(self, run, tag):
accumulator = self.GetAccumulator(run)
return accumulator.CompressedHistograms(tag) | 57,779 |
Retrieve the image events associated with a run and tag.
Args:
run: A string name of the run for which values are retrieved.
tag: A string name of the tag for which values are retrieved.
Raises:
KeyError: If the run is not found, or the tag is not available for
the given run.
Re... | def Images(self, run, tag):
accumulator = self.GetAccumulator(run)
return accumulator.Images(tag) | 57,780 |
Write a TensorBoardInfo file and arrange for its cleanup.
Args:
server: The result of `self._make_server()`. | def _register_info(self, server):
server_url = urllib.parse.urlparse(server.get_url())
info = manager.TensorBoardInfo(
version=version.VERSION,
start_time=int(time.time()),
port=server_url.port,
pid=os.getpid(),
path_prefix=self.flags.path_prefix,
logdir=self... | 57,795 |
Set a signal handler to gracefully exit on the given signal.
When this process receives the given signal, it will run `atexit`
handlers and then exit with `0`.
Args:
signal_number: The numeric code for the signal to handle, like
`signal.SIGTERM`.
signal_name: The human-readable signal ... | def _install_signal_handler(self, signal_number, signal_name):
old_signal_handler = None # set below
def handler(handled_signal_number, frame):
# In case we catch this signal again while running atexit
# handlers, take the hint and actually die.
signal.signal(signal_number, signal.SIG_DF... | 57,796 |
Creates a new `OpError` indicating that a particular op failed.
Args:
node_def: The `node_def_pb2.NodeDef` proto representing the op that
failed, if known; otherwise None.
op: The `ops.Operation` that failed, if known; otherwise None.
message: The message string descri... | def __init__(self, node_def, op, message, error_code):
super(OpError, self).__init__()
self._message = message
self._node_def = node_def
self._op = op
self._error_code = error_code | 57,804 |
Creates temp symlink tree, runs program, and copies back outputs.
Args:
inputs: List of fake paths to real paths, which are used for symlink tree.
program: List containing real path of program and its arguments. The
execroot directory will be appended as the last argument.
outputs: List of fake o... | def run(inputs, program, outputs):
root = tempfile.mkdtemp()
try:
cwd = os.getcwd()
for fake, real in inputs:
parent = os.path.join(root, os.path.dirname(fake))
if not os.path.exists(parent):
os.makedirs(parent)
# Use symlink if possible and not on Windows, since on Windows 10
... | 57,826 |
Invokes run function using a JSON file config.
Args:
args: CLI args, which can be a JSON file containing an object whose
attributes are the parameters to the run function. If multiple JSON
files are passed, their contents are concatenated.
Returns:
0 if succeeded or nonzero if failed.
Rai... | def main(args):
if not args:
raise Exception('Please specify at least one JSON config path')
inputs = []
program = []
outputs = []
for arg in args:
with open(arg) as fd:
config = json.load(fd)
inputs.extend(config.get('inputs', []))
program.extend(config.get('program', []))
output... | 57,827 |
Initializes the TensorBoard sqlite schema using the given connection.
Args:
connection: A sqlite DB connection. | def initialize_schema(connection):
cursor = connection.cursor()
cursor.execute("PRAGMA application_id={}".format(_TENSORBOARD_APPLICATION_ID))
cursor.execute("PRAGMA user_version={}".format(_TENSORBOARD_USER_VERSION))
with connection:
for statement in _SCHEMA_STATEMENTS:
lines = statement.strip('\n... | 57,828 |
Returns the ID for the given experiment, creating the row if needed.
Args:
experiment_name: name of experiment. | def _maybe_init_experiment(self, experiment_name):
user_id = self._maybe_init_user()
cursor = self._db.cursor()
cursor.execute(
,
(user_id, experiment_name))
row = cursor.fetchone()
if row:
return row[0]
experiment_id = self._create_id()
# TODO: track computed time... | 57,831 |
Returns the ID for the given run, creating the row if needed.
Args:
experiment_name: name of experiment containing this run.
run_name: name of run. | def _maybe_init_run(self, experiment_name, run_name):
experiment_id = self._maybe_init_experiment(experiment_name)
cursor = self._db.cursor()
cursor.execute(
,
(experiment_id, run_name))
row = cursor.fetchone()
if row:
return row[0]
run_id = self._create_id()
# TOD... | 57,832 |
Returns a tag-to-ID map for the given tags, creating rows if needed.
Args:
run_id: the ID of the run to which these tags belong.
tag_to_metadata: map of tag name to SummaryMetadata for the tag. | def _maybe_init_tags(self, run_id, tag_to_metadata):
cursor = self._db.cursor()
# TODO: for huge numbers of tags (e.g. 1000+), this is slower than just
# querying for the known tag names explicitly; find a better tradeoff.
cursor.execute('SELECT tag_name, tag_id FROM Tags WHERE run_id = ?',
... | 57,833 |
Transactionally writes the given tagged summary data to the DB.
Args:
tagged_data: map from tag to TagData instances.
experiment_name: name of experiment.
run_name: name of run. | def write_summaries(self, tagged_data, experiment_name, run_name):
logger.debug('Writing summaries for %s tags', len(tagged_data))
# Connection used as context manager for auto commit/rollback on exit.
# We still need an explicit BEGIN, because it doesn't do one on enter,
# it waits until the first... | 57,834 |
Run a box-blur-to-Gaussian-blur demonstration.
See the summary description for more details.
Arguments:
logdir: Directory into which to write event logs.
verbose: Boolean; whether to log any output. | def run_box_to_gaussian(logdir, verbose=False):
if verbose:
logger.info('--- Starting run: box_to_gaussian')
tf.compat.v1.reset_default_graph()
tf.compat.v1.set_random_seed(0)
image = get_image(verbose=verbose)
blur_radius = tf.compat.v1.placeholder(shape=(), dtype=tf.int32)
with tf.name_scope('fil... | 57,838 |
Run a Sobel edge detection demonstration.
See the summary description for more details.
Arguments:
logdir: Directory into which to write event logs.
verbose: Boolean; whether to log any output. | def run_sobel(logdir, verbose=False):
if verbose:
logger.info('--- Starting run: sobel')
tf.compat.v1.reset_default_graph()
tf.compat.v1.set_random_seed(0)
image = get_image(verbose=verbose)
kernel_radius = tf.compat.v1.placeholder(shape=(), dtype=tf.int32)
with tf.name_scope('horizontal_kernel'):... | 57,839 |
Run simulations on a reasonable set of parameters.
Arguments:
logdir: the directory into which to store all the runs' data
verbose: if true, print out each run's name as it begins | def run_all(logdir, verbose=False):
run_box_to_gaussian(logdir, verbose=verbose)
run_sobel(logdir, verbose=verbose) | 57,840 |
Returns an `OriginalFeatureList` for the specified feature_name.
Args:
example: An example.
feature_name: A string feature name.
Returns:
A filled in `OriginalFeatureList` object representing the feature. | def parse_original_feature_from_example(example, feature_name):
feature = get_example_features(example)[feature_name]
feature_type = feature.WhichOneof('kind')
original_value = proto_value_for_feature(example, feature_name)
return OriginalFeatureList(feature_name, original_value, feature_type) | 57,842 |
Returns packaged inference results from the provided proto.
Args:
inference_result_proto: The classification or regression response proto.
Returns:
An InferenceResult proto with the result from the response. | def wrap_inference_results(inference_result_proto):
inference_proto = inference_pb2.InferenceResult()
if isinstance(inference_result_proto,
classification_pb2.ClassificationResponse):
inference_proto.classification_result.CopyFrom(
inference_result_proto.result)
elif isinstance(infe... | 57,843 |
Returns a list of feature names for float and int64 type features.
Args:
example: An example.
Returns:
A list of strings of the names of numeric features. | def get_numeric_feature_names(example):
numeric_features = ('float_list', 'int64_list')
features = get_example_features(example)
return sorted([
feature_name for feature_name in features
if features[feature_name].WhichOneof('kind') in numeric_features
]) | 57,844 |
Returns a list of feature names for byte type features.
Args:
example: An example.
Returns:
A list of categorical feature names (e.g. ['education', 'marital_status'] ) | def get_categorical_feature_names(example):
features = get_example_features(example)
return sorted([
feature_name for feature_name in features
if features[feature_name].WhichOneof('kind') == 'bytes_list'
]) | 57,845 |
Returns numerical features and their observed ranges.
Args:
examples: Examples to read to get ranges.
Returns:
A dict mapping feature_name -> {'observedMin': 'observedMax': } dicts,
with a key for each numerical feature. | def get_numeric_features_to_observed_range(examples):
observed_features = collections.defaultdict(list) # name -> [value, ]
for example in examples:
for feature_name in get_numeric_feature_names(example):
original_feature = parse_original_feature_from_example(
example, feature_name)
ob... | 57,846 |
Return a list of `MutantFeatureValue`s and a list of mutant Examples.
Args:
example_protos: The examples to mutate.
original_feature: A `OriginalFeatureList` that encapsulates the feature to
mutate.
index_to_mutate: The index of the int64_list or float_list to mutate.
viz_params: A `VizParams` ... | def make_mutant_tuples(example_protos, original_feature, index_to_mutate,
viz_params):
mutant_features = make_mutant_features(original_feature, index_to_mutate,
viz_params)
mutant_examples = []
for example_proto in example_protos:
for mutant_f... | 57,849 |
Returns a list of JSON objects for each feature in the examples.
This list is used to drive partial dependence plots in the plugin.
Args:
examples: Examples to examine to determine the eligible features.
num_mutants: The number of mutations to make over each feature.
Returns:
A list wit... | def get_eligible_features(examples, num_mutants):
features_dict = (
get_numeric_features_to_observed_range(
examples))
features_dict.update(
get_categorical_features_to_sampling(
examples, num_mutants))
# Massage the features_dict into a sorted list before returning because
... | 57,854 |
Returns an encoded sprite image for use in Facets Dive.
Args:
examples: A list of serialized example protos to get images for.
Returns:
An encoded PNG. | def create_sprite_image(examples):
def generate_image_from_thubnails(thumbnails, thumbnail_dims):
num_thumbnails = tf.shape(thumbnails)[0].eval()
images_per_row = int(math.ceil(math.sqrt(num_thumbnails)))
thumb_height = thumbnail_dims[0]
thumb_width = thumbnail_dims[1]
mas... | 57,856 |
Run inference on examples given model information
Args:
examples: A list of examples that matches the model spec.
serving_bundle: A `ServingBundle` object that contains the information to
make the inference request.
Returns:
A ClassificationResponse or RegressionResponse proto. | def run_inference(examples, serving_bundle):
batch_size = 64
if serving_bundle.estimator and serving_bundle.feature_spec:
# If provided an estimator and feature spec then run inference locally.
preds = serving_bundle.estimator.predict(
lambda: tf.data.Dataset.from_tensor_slices(
tf.parse_ex... | 57,857 |
Return items associated with given key.
Args:
key: The key for which we are finding associated items.
Raises:
KeyError: If the key is not found in the reservoir.
Returns:
[list, of, items] associated with that key. | def Items(self, key):
with self._mutex:
if key not in self._buckets:
raise KeyError('Key %s was not found in Reservoir' % key)
bucket = self._buckets[key]
return bucket.Items() | 57,863 |
Filter items within a Reservoir, using a filtering function.
Args:
filterFn: A function that returns True for the items to be kept.
key: An optional bucket key to filter. If not specified, will filter all
all buckets.
Returns:
The number of items removed. | def FilterItems(self, filterFn, key=None):
with self._mutex:
if key:
if key in self._buckets:
return self._buckets[key].FilterItems(filterFn)
else:
return 0
else:
return sum(bucket.FilterItems(filterFn)
for bucket in self._buckets.value... | 57,865 |
Create the _ReservoirBucket.
Args:
_max_size: The maximum size the reservoir bucket may grow to. If size is
zero, the bucket has unbounded size.
_random: The random number generator to use. If not specified, defaults to
random.Random(0).
always_keep_last: Whether the latest seen i... | def __init__(self, _max_size, _random=None, always_keep_last=True):
if _max_size < 0 or _max_size != round(_max_size):
raise ValueError('_max_size must be nonnegative int, was %s' % _max_size)
self.items = []
# This mutex protects the internal items, ensuring that calls to Items and
# AddItem... | 57,866 |
Create a numpy ndarray from a tensor.
Create a numpy ndarray with the same shape and data as the tensor.
Args:
tensor: A TensorProto.
Returns:
A numpy array with the tensor contents.
Raises:
TypeError: if tensor has unsupported type. | def make_ndarray(tensor):
shape = [d.size for d in tensor.tensor_shape.dim]
num_elements = np.prod(shape, dtype=np.int64)
tensor_dtype = dtypes.as_dtype(tensor.dtype)
dtype = tensor_dtype.as_numpy_dtype
if tensor.tensor_content:
return np.frombuffer(tensor.tensor_content, dtype=dtype).... | 57,896 |
Creates a summary that contains a layout.
When users navigate to the custom scalars dashboard, they will see a layout
based on the proto provided to this function.
Args:
scalars_layout: The scalars_layout_pb2.Layout proto that specifies the
layout.
collections: Optional list of graph collections... | def op(scalars_layout, collections=None):
# TODO(nickfelt): remove on-demand imports once dep situation is fixed.
import tensorflow.compat.v1 as tf
assert isinstance(scalars_layout, layout_pb2.Layout)
summary_metadata = metadata.create_summary_metadata()
return tf.summary.tensor_summary(name=metadata.CONF... | 57,897 |
Creates a summary that contains a layout.
When users navigate to the custom scalars dashboard, they will see a layout
based on the proto provided to this function.
Args:
scalars_layout: The scalars_layout_pb2.Layout proto that specifies the
layout.
Returns:
A summary proto containing the layo... | def pb(scalars_layout):
# TODO(nickfelt): remove on-demand imports once dep situation is fixed.
import tensorflow.compat.v1 as tf
assert isinstance(scalars_layout, layout_pb2.Layout)
tensor = tf.make_tensor_proto(
scalars_layout.SerializeToString(), dtype=tf.string)
tf_summary_metadata = tf.SummaryM... | 57,898 |
Returns true if `other` is convertible with this Dimension.
Two known Dimensions are convertible if they have the same value.
An unknown Dimension is convertible with all other Dimensions.
Args:
other: Another Dimension.
Returns:
True if this Dimension and `other` ... | def is_convertible_with(self, other):
other = as_dimension(other)
return self._value is None or other.value is None or self._value == other.value | 57,901 |
Returns the subtraction of `self` from `other`.
Args:
other: Another Dimension, or a value accepted by `as_dimension`.
Returns:
A Dimension whose value is the subtraction of `self` from `other`. | def __rsub__(self, other):
other = as_dimension(other)
if self._value is None or other.value is None:
return Dimension(None)
else:
return Dimension(other.value - self._value) | 57,905 |
Returns the quotient of `other` and `self` rounded down.
Args:
other: Another Dimension, or a value accepted by `as_dimension`.
Returns:
A `Dimension` whose value is the integer quotient of `self` and `other`. | def __rfloordiv__(self, other):
other = as_dimension(other)
if self._value is None or other.value is None:
return Dimension(None)
else:
return Dimension(other.value // self._value) | 57,906 |
Returns `other` modulo `self`.
Args:
other: Another Dimension, or a value accepted by `as_dimension`.
Returns:
A Dimension whose value is `other` modulo `self`. | def __rmod__(self, other):
try:
other = as_dimension(other)
except (TypeError, ValueError):
return NotImplemented
return other % self | 57,908 |
Creates a new TensorShape with the given dimensions.
Args:
dims: A list of Dimensions, or None if the shape is unspecified.
DEPRECATED: A single integer is treated as a singleton list.
Raises:
TypeError: If dims cannot be converted to a list of dimensions. | def __init__(self, dims):
# TODO(irving): Eliminate the single integer special case.
if dims is None:
self._dims = None
elif isinstance(dims, compat.bytes_or_text_types):
raise TypeError(
"A string has ambiguous TensorShape, please wrap in a "
... | 57,913 |
Returns a `TensorShape` combining the information in `self` and `other`.
The dimensions in `self` and `other` are merged elementwise,
according to the rules defined for `Dimension.merge_with()`.
Args:
other: Another `TensorShape`.
Returns:
A `TensorShape` containin... | def merge_with(self, other):
other = as_shape(other)
if self._dims is None:
return other
else:
try:
self.assert_same_rank(other)
new_dims = []
for i, dim in enumerate(self._dims):
new_dims.append... | 57,918 |
Raises an exception if `self` and `other` do not have convertible ranks.
Args:
other: Another `TensorShape`.
Raises:
ValueError: If `self` and `other` do not represent shapes with the
same rank. | def assert_same_rank(self, other):
other = as_shape(other)
if self.ndims is not None and other.ndims is not None:
if self.ndims != other.ndims:
raise ValueError(
"Shapes %s and %s must have the same rank" % (self, other)
) | 57,920 |
Returns a shape based on `self` with the given rank.
This method promotes a completely unknown shape to one with a
known rank.
Args:
rank: An integer.
Returns:
A shape that is at least as specific as `self` with the given rank.
Raises:
ValueError... | def with_rank(self, rank):
try:
return self.merge_with(unknown_shape(ndims=rank))
except ValueError:
raise ValueError("Shape %s must have rank %d" % (self, rank)) | 57,921 |
Returns a shape based on `self` with at least the given rank.
Args:
rank: An integer.
Returns:
A shape that is at least as specific as `self` with at least the given
rank.
Raises:
ValueError: If `self` does not represent a shape with at least the given
... | def with_rank_at_least(self, rank):
if self.ndims is not None and self.ndims < rank:
raise ValueError("Shape %s must have rank at least %d" % (self, rank))
else:
return self | 57,922 |
Returns a shape based on `self` with at most the given rank.
Args:
rank: An integer.
Returns:
A shape that is at least as specific as `self` with at most the given
rank.
Raises:
ValueError: If `self` does not represent a shape with at most the given
... | def with_rank_at_most(self, rank):
if self.ndims is not None and self.ndims > rank:
raise ValueError("Shape %s must have rank at most %d" % (self, rank))
else:
return self | 57,923 |
Converts a PredictResponse to ClassificationResponse or RegressionResponse.
Args:
pred: PredictResponse to convert.
serving_bundle: A `ServingBundle` object that contains the information about
the serving request that the response was generated by.
Returns:
A ClassificationResponse or Regression... | def convert_predict_response(pred, serving_bundle):
output = pred.outputs[serving_bundle.predict_output_tensor]
raw_output = output.float_val
if serving_bundle.model_type == 'classification':
values = []
for example_index in range(output.tensor_shape.dim[0].size):
start = example_index * output.t... | 57,931 |
Returns a dict mapping tags to content specific to that plugin.
Args:
plugin_name: The name of the plugin for which to fetch plugin-specific
content.
Raises:
KeyError: if the plugin name is not found.
Returns:
A dict mapping tags to plugin-specific content (which are always stri... | def PluginTagToContent(self, plugin_name):
if plugin_name not in self._plugin_to_tag_to_content:
raise KeyError('Plugin %r could not be found.' % plugin_name)
with self._plugin_tag_locks[plugin_name]:
# Return a snapshot to avoid concurrent mutation and iteration issues.
return dict(self.... | 57,935 |
Maybe purge orphaned data due to a TensorFlow crash.
When TensorFlow crashes at step T+O and restarts at step T, any events
written after step T are now "orphaned" and will be at best misleading if
they are included in TensorBoard.
This logic attempts to determine if there is orphaned data, and purge ... | def _MaybePurgeOrphanedData(self, event):
if not self.purge_orphaned_data:
return
## Check if the event happened after a crash, and purge expired tags.
if self.file_version and self.file_version >= 2:
## If the file_version is recent enough, use the SessionLog enum
## to check for res... | 57,938 |
Check for out-of-order event.step and discard expired events for tags.
Check if the event is out of order relative to the global most recent step.
If it is, purge outdated summaries for tags that the event contains.
Args:
event: The event to use as reference. If the event is out-of-order, all
... | def _CheckForOutOfOrderStepAndMaybePurge(self, event):
if event.step < self.most_recent_step and event.HasField('summary'):
self._Purge(event, by_tags=True) | 57,939 |
Returns the plugin, if possible.
Args:
context: The TBContext flags.
Returns:
A BeholderPlugin instance or None if it couldn't be loaded. | def load(self, context):
try:
# pylint: disable=g-import-not-at-top,unused-import
import tensorflow
except ImportError:
return
# pylint: disable=g-import-not-at-top
from tensorboard.plugins.beholder.beholder_plugin import BeholderPlugin
return BeholderPlugin(context) | 57,943 |
Walks the nested keras layer configuration in preorder.
Args:
keras_layer: Keras configuration from model.to_json.
Yields:
A tuple of (name_scope, layer_config).
name_scope: a string representing a scope name, similar to that of tf.name_scope.
layer_config: a dict representing a Keras layer configu... | def _walk_layers(keras_layer):
yield ('', keras_layer)
if keras_layer.get('config').get('layers'):
name_scope = keras_layer.get('config').get('name')
for layer in keras_layer.get('config').get('layers'):
for (sub_name_scope, sublayer) in _walk_layers(layer):
sub_name_scope = '%s/%s' % (
... | 57,944 |
Returns a GraphDef representation of the Keras model in a dict form.
Note that it only supports models that implemented to_json().
Args:
keras_layer: A dict from Keras model.to_json().
Returns:
A GraphDef representation of the layers in the model. | def keras_model_to_graph_def(keras_layer):
input_to_layer = {}
model_name_to_output = {}
g = GraphDef()
# Sequential model layers do not have a field "inbound_nodes" but
# instead are defined implicitly via order of layers.
prev_node_name = None
for (name_scope, layer) in _walk_layers(keras_layer):
... | 57,946 |
Returns the plugin, if possible.
Args:
context: The TBContext flags.
Returns:
A HParamsPlugin instance or None if it couldn't be loaded. | def load(self, context):
try:
# pylint: disable=g-import-not-at-top,unused-import
import tensorflow
except ImportError:
return
# pylint: disable=g-import-not-at-top
from tensorboard.plugins.hparams.hparams_plugin import HParamsPlugin
return HParamsPlugin(context) | 57,947 |
Convert Markdown to HTML that's safe to splice into the DOM.
Arguments:
markdown_string: A Unicode string or UTF-8--encoded bytestring
containing Markdown source. Markdown tables are supported.
Returns:
A string containing safe HTML. | def markdown_to_safe_html(markdown_string):
warning = ''
# Convert to utf-8 whenever we have a binary input.
if isinstance(markdown_string, six.binary_type):
markdown_string_decoded = markdown_string.decode('utf-8')
# Remove null bytes and warn if there were any, since it probably means
# we were g... | 57,953 |
Converts the given `type_value` to a `DType`.
Args:
type_value: A value that can be converted to a `tf.DType` object. This may
currently be a `tf.DType` object, a [`DataType`
enum](https://www.tensorflow.org/code/tensorflow/core/framework/types.proto),
a string type name, or a `numpy.... | def as_dtype(type_value):
if isinstance(type_value, DType):
return type_value
try:
return _INTERN_TABLE[type_value]
except KeyError:
pass
try:
return _STRING_TO_TF[type_value]
except KeyError:
pass
try:
return _PYTHON_TO_TF[type_value]
... | 57,954 |
Creates a new `DataType`.
NOTE(mrry): In normal circumstances, you should not need to
construct a `DataType` object directly. Instead, use the
`tf.as_dtype()` function.
Args:
type_enum: A `types_pb2.DataType` enum value.
Raises:
TypeError: If `type_enum` is... | def __init__(self, type_enum):
# TODO(mrry): Make the necessary changes (using __new__) to ensure
# that calling this returns one of the interned values.
type_enum = int(type_enum)
if (
type_enum not in types_pb2.DataType.values()
or type_enum == types_pb... | 57,955 |
Return intensity limits, i.e. (min, max) tuple, of the dtype.
Args:
clip_negative : bool, optional
If True, clip the negative range (i.e. return 0 for min intensity)
even if the image dtype allows negative values.
Returns
min, max : tuple
Lower... | def limits(self, clip_negative=True):
min, max = dtype_range[self.as_numpy_dtype] # pylint: disable=redefined-builtin
if clip_negative:
min = 0 # pylint: disable=redefined-builtin
return min, max | 57,960 |
Constructs a debugger plugin for TensorBoard.
This plugin adds handlers for retrieving debugger-related data. The plugin
also starts a debugger data server once the log directory is passed to the
plugin via the call to get_plugin_apps.
Args:
context: A base_plugin.TBContext instance. | def __init__(self, context):
del context # Unused.
self._debugger_data_server = None
self._server_thread = None
self._grpc_port = None | 57,965 |
Start listening on the given gRPC port.
This method of an instance of InteractiveDebuggerPlugin can be invoked at
most once. This method is not thread safe.
Args:
grpc_port: port number to listen at.
Raises:
ValueError: If this instance is already listening at a gRPC port. | def listen(self, grpc_port):
if self._grpc_port:
raise ValueError(
'This InteractiveDebuggerPlugin instance is already listening at '
'gRPC port %d' % self._grpc_port)
self._grpc_port = grpc_port
sys.stderr.write('Creating InteractiveDebuggerPlugin at port %d\n' %
... | 57,966 |
Given a tag and list of runs, serve a list of metadata for audio.
Note that the actual audio data are not sent; instead, we respond
with URLs to the audio. The frontend should treat these URLs as
opaque and should not try to parse information about them or
generate them itself, as the format may change... | def _serve_audio_metadata(self, request):
tag = request.args.get('tag')
run = request.args.get('run')
sample = int(request.args.get('sample', 0))
events = self._multiplexer.Tensors(run, tag)
response = self._audio_response_for_run(events, run, tag, sample)
return http_util.Respond(request,... | 57,986 |
Writes __main__'s docstring to stdout with some help text.
Args:
shorthelp: bool, if True, prints only flags from the main module,
rather than all flags. | def _usage(shorthelp):
doc = _sys.modules['__main__'].__doc__
if not doc:
doc = '\nUSAGE: %s [flags]\n' % _sys.argv[0]
doc = flags.text_wrap(doc, indent=' ', firstline_indent='')
else:
# Replace all '%s' with sys.argv[0], and all '%%' with '%'.
num_specifiers = doc... | 57,996 |
Construct a TensorBoardWSGIApp with standard plugins and multiplexer.
Args:
flags: An argparse.Namespace containing TensorBoard CLI flags.
plugin_loaders: A list of TBLoader instances.
assets_zip_provider: See TBContext documentation for more information.
Returns:
The new TensorBoard WSGI applicat... | def standard_tensorboard_wsgi(flags, plugin_loaders, assets_zip_provider):
multiplexer = event_multiplexer.EventMultiplexer(
size_guidance=DEFAULT_SIZE_GUIDANCE,
tensor_size_guidance=tensor_size_guidance_from_flags(flags),
purge_orphaned_data=flags.purge_orphaned_data,
max_reload_threads=fl... | 58,004 |
Returns TBContext fields relating to SQL database.
Args:
db_uri: A string URI expressing the DB file, e.g. "sqlite:~/tb.db".
Returns:
A tuple with the db_module and db_connection_provider TBContext fields. If
db_uri was empty, then (None, None) is returned.
Raises:
ValueError: If db_uri scheme ... | def get_database_info(db_uri):
if not db_uri:
return None, None
scheme = urlparse.urlparse(db_uri).scheme
if scheme == 'sqlite':
return sqlite3, create_sqlite_connection_provider(db_uri)
else:
raise ValueError('Only sqlite DB URIs are supported now: ' + db_uri) | 58,008 |
Returns function that returns SQLite Connection objects.
Args:
db_uri: A string URI expressing the DB file, e.g. "sqlite:~/tb.db".
Returns:
A function that returns a new PEP-249 DB Connection, which must be closed,
each time it is called.
Raises:
ValueError: If db_uri is not a valid sqlite file... | def create_sqlite_connection_provider(db_uri):
uri = urlparse.urlparse(db_uri)
if uri.scheme != 'sqlite':
raise ValueError('Scheme is not sqlite: ' + db_uri)
if uri.netloc:
raise ValueError('Can not connect to SQLite over network: ' + db_uri)
if uri.path == ':memory:':
raise ValueError('Memory mo... | 58,009 |
Serves an object mapping plugin name to whether it is enabled.
Args:
request: The werkzeug.Request object.
Returns:
A werkzeug.Response object. | def _serve_plugins_listing(self, request):
response = {}
for plugin in self._plugins:
start = time.time()
response[plugin.plugin_name] = plugin.is_active()
elapsed = time.time() - start
logger.info(
'Plugin listing: is_active() for %s took %0.3f seconds',
plugin.... | 58,012 |
Central entry point for the TensorBoard application.
This method handles routing to sub-applications. It does simple routing
using regular expression matching.
This __call__ method conforms to the WSGI spec, so that instances of this
class are WSGI applications.
Args:
environ: See WSGI spec... | def __call__(self, environ, start_response): # pylint: disable=invalid-name
request = wrappers.Request(environ)
parsed_url = urlparse.urlparse(request.path)
clean_path = _clean_path(parsed_url.path, self._path_prefix)
# pylint: disable=too-many-function-args
if clean_path in self.data_applica... | 58,013 |
Parse a string as time indices.
Args:
s: A valid slicing string for time indices. E.g., '-1', '[:]', ':', '2:10'
Returns:
A slice object.
Raises:
ValueError: If `s` does not represent valid time indices. | def parse_time_indices(s):
if not s.startswith('['):
s = '[' + s + ']'
parsed = command_parser._parse_slices(s)
if len(parsed) != 1:
raise ValueError(
'Invalid number of slicing objects in time indices (%d)' % len(parsed))
else:
return parsed[0] | 58,014 |
Convert an array into base64-enoded PNG image.
Args:
array: A 2D np.ndarray or nested list of items.
Returns:
A base64-encoded string the image. The image is grayscale if the array is
2D. The image is RGB color if the image is 3D with lsat dimension equal to
3.
Raises:
ValueError: If the in... | def array_to_base64_png(array):
# TODO(cais): Deal with 3D case.
# TODO(cais): If there are None values in here, replace them with all NaNs.
array = np.array(array, dtype=np.float32)
if len(array.shape) != 2:
raise ValueError(
"Expected rank-2 array; received rank-%d array." % len(array.shape))
... | 58,017 |
Create a scalar summary_pb2.Summary protobuf.
Arguments:
tag: String tag for the summary.
data: A 0-dimensional `np.array` or a compatible python number type.
description: Optional long-form description for this summary, as a
`str`. Markdown is supported. Defaults to empty.
Raises:
ValueErro... | def scalar_pb(tag, data, description=None):
arr = np.array(data)
if arr.shape != ():
raise ValueError('Expected scalar shape for tensor, got shape: %s.'
% arr.shape)
if arr.dtype.kind not in ('b', 'i', 'u', 'f'): # bool, int, uint, float
raise ValueError('Cast %s to float is not s... | 58,022 |
Creates a frame and writes it to disk.
Args:
arrays: a list of np arrays. Use the "custom" option in the client.
frame: a 2D np array. This way the plugin can be used for video of any
kind, not just the visualization that comes with the plugin.
frame can also be a function, w... | def update(self, session, arrays=None, frame=None):
new_config = self._get_config()
if self._enough_time_has_passed(self.previous_config['FPS']):
self.visualizer.update(new_config)
self.last_update_time = time.time()
final_image = self._update_frame(session, arrays, frame, new_config)
... | 58,033 |
A helper to get the gradients out at each step.
Args:
optimizer: the optimizer op.
loss: the op that computes your loss value.
Returns: the gradient tensors and the train_step op. | def gradient_helper(optimizer, loss, var_list=None):
if var_list is None:
var_list = tf.compat.v1.trainable_variables()
grads_and_vars = optimizer.compute_gradients(loss, var_list=var_list)
grads = [pair[0] for pair in grads_and_vars]
return grads, optimizer.apply_gradients(grads_and_vars) | 58,034 |
Returns a key_func to be used in list.sort().
Returns a key_func to be used in list.sort() that sorts session groups
by the value extracted by extractor. 'None' extracted values will either
be considered largest or smallest as specified by the "none_is_largest"
boolean parameter.
Args:
extractor: An ext... | def _create_key_func(extractor, none_is_largest):
if none_is_largest:
def key_func_none_is_largest(session_group):
value = extractor(session_group)
return (value is None, value)
return key_func_none_is_largest
def key_func_none_is_smallest(session_group):
value = extractor(session_group)
... | 58,035 |
Creates extractors to extract properties corresponding to 'col_params'.
Args:
col_params: List of ListSessionGroupsRequest.ColParam protobufs.
Returns:
A list of extractor functions. The ith element in the
returned list extracts the column corresponding to the ith element of
_request.col_params | def _create_extractors(col_params):
result = []
for col_param in col_params:
result.append(_create_extractor(col_param))
return result | 58,036 |
Returns function that extracts a metric from a session group or a session.
Args:
metric_name: tensorboard.hparams.MetricName protobuffer. Identifies the
metric to extract from the session group.
Returns:
A function that takes a tensorboard.hparams.SessionGroup or
tensorborad.hparams.Session protobu... | def _create_metric_extractor(metric_name):
def extractor_fn(session_or_group):
metric_value = _find_metric_value(session_or_group,
metric_name)
return metric_value.value if metric_value else None
return extractor_fn | 58,038 |
Returns the metric_value for a given metric in a session or session group.
Args:
session_or_group: A Session protobuffer or SessionGroup protobuffer.
metric_name: A MetricName protobuffer. The metric to search for.
Returns:
A MetricValue protobuffer representing the value of the given metric or
Non... | def _find_metric_value(session_or_group, metric_name):
# Note: We can speed this up by converting the metric_values field
# to a dictionary on initialization, to avoid a linear search here. We'll
# need to wrap the SessionGroup and Session protos in a python object for
# that.
for metric_value in session_o... | 58,039 |
Returns an extractor function that extracts an hparam from a session group.
Args:
hparam_name: str. Identies the hparam to extract from the session group.
Returns:
A function that takes a tensorboard.hparams.SessionGroup protobuffer and
returns the value, as a native Python object, of the hparam identi... | def _create_hparam_extractor(hparam_name):
def extractor_fn(session_group):
if hparam_name in session_group.hparams:
return _value_to_python(session_group.hparams[hparam_name])
return None
return extractor_fn | 58,040 |
Creates filters for the given col_params.
Args:
col_params: List of ListSessionGroupsRequest.ColParam protobufs.
extractors: list of extractor functions of the same length as col_params.
Each element should extract the column described by the corresponding
element of col_params.
Returns:
A ... | def _create_filters(col_params, extractors):
result = []
for col_param, extractor in zip(col_params, extractors):
a_filter = _create_filter(col_param, extractor)
if a_filter:
result.append(a_filter)
return result | 58,041 |
Returns a boolean function that filters strings based on a regular exp.
Args:
regex: A string describing the regexp to use.
Returns:
A function taking a string and returns True if any of its substrings
matches regex. | def _create_regexp_filter(regex):
# Warning: Note that python's regex library allows inputs that take
# exponential time. Time-limiting it is difficult. When we move to
# a true multi-tenant tensorboard server, the regexp implementation here
# would need to be replaced by something more secure.
compiled_re... | 58,043 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.