text stringlengths 81 112k |
|---|
Yields all files in the given directory. The paths are absolute.
def ListDirectoryAbsolute(directory):
"""Yields all files in the given directory. The paths are absolute."""
return (os.path.join(directory, path)
for path in tf.io.gfile.listdir(directory)) |
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):
"""Escapes the glob characters in a path.
Python 3 h... |
Recursively lists all files within the directory.
This method does not list subdirectories (in addition to regular files), and
the file paths are all absolute. If the directory does not exist, this yields
nothing.
This method does so by glob-ing deeper and deeper directories, ie
foo/*, foo/*/*, foo/*/*/* an... |
Walks a directory tree, yielding (dir_path, file_paths) tuples.
For each of `top` and its subdirectories, yields a tuple containing the path
to the directory and the path to each of the contained files. Note that
unlike os.Walk()/tf.io.gfile.walk()/ListRecursivelyViaGlobbing, this does not
list subdirectories... |
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... |
Write an audio summary.
Arguments:
name: A name for this summary. The summary tag used for TensorBoard will
be this name prefixed by any active name scopes.
data: A `Tensor` representing audio data with shape `[k, t, c]`,
where `k` is the number of audio clips, `t` is the number of
frames, ... |
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... |
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(sel... |
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, ev... |
Creates a JSON-able representation of this object.
Returns:
A dictionary mapping key to EventTrackerDescription (which can be used to
create event trackers).
def create_jsonable_history(self):
"""Creates a JSON-able representation of this object.
Returns:
A dictionary mapping key to Eve... |
Register an alerting numeric event.
Args:
numerics_alert: An instance of `NumericsAlert`.
def register(self, numerics_alert):
"""Register an alerting numeric event.
Args:
numerics_alert: An instance of `NumericsAlert`.
"""
key = (numerics_alert.device_name, numerics_alert.tensor_name)... |
Get a report of offending device/tensor names.
The report includes information about the device name, tensor name, first
(earliest) timestamp of the alerting events from the tensor, in addition to
counts of nan, positive inf and negative inf events.
Args:
device_name_filter: regex filter for dev... |
Creates a JSON-able representation of this object.
Returns:
A dictionary mapping (device, tensor name) to JSON-able object
representations of NumericsAlertHistory.
def create_jsonable_registry(self):
"""Creates a JSON-able representation of this object.
Returns:
A dictionary mapping (de... |
Generate wave data of the given form.
The provided function `wave_constructor` should accept a scalar tensor
of type float32, representing the frequency (in Hz) at which to
construct a wave, and return a tensor of shape [1, _samples(), `n`]
representing audio data (for some number of channels `n`).
Waves wi... |
Emit a sine wave at the given frequency.
def sine_wave(frequency):
"""Emit a sine wave at the given frequency."""
xs = tf.reshape(tf.range(_samples(), dtype=tf.float32), [1, _samples(), 1])
ts = xs / FLAGS.sample_rate
return tf.sin(2 * math.pi * frequency * ts) |
Emit a triangle wave at the given frequency.
def triangle_wave(frequency):
"""Emit a triangle wave at the given frequency."""
xs = tf.reshape(tf.range(_samples(), dtype=tf.float32), [1, _samples(), 1])
ts = xs / FLAGS.sample_rate
#
# A triangle wave looks like this:
#
# /\ /\
# / \ / ... |
Emit two sine waves, in stereo at different octaves.
def bisine_wave(frequency):
"""Emit two sine waves, in stereo at different octaves."""
#
# We can first our existing sine generator to generate two different
# waves.
f_hi = frequency
f_lo = frequency / 2.0
with tf.name_scope('hi'):
sine_hi = sine_... |
Emit two sine waves with balance oscillating left and right.
def bisine_wahwah_wave(frequency):
"""Emit two sine waves with balance oscillating left and right."""
#
# This is clearly intended to build on the bisine wave defined above,
# so we can start by generating that.
waves_a = bisine_wave(frequency)
#... |
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):
"""Generate waves of the shapes defined above.
Arguments:
logdir: the directory into which... |
Prepares (modifies in-place) the graph to be served to the front-end.
For now, it supports filtering out attributes that are
too large to be shown in the graph UI.
Args:
graph: The GraphDef proto message.
limit_attr_size: Maximum allowed size in bytes, before the attribute
is considered large. D... |
Returns a dict of all runs and tags and their data availabilities.
def info_impl(self):
"""Returns a dict of all runs and tags and their data availabilities."""
result = {}
def add_row_item(run, tag=None):
run_item = result.setdefault(run, {
'run': run,
'tags': {},
# A r... |
Result of the form `(body, mime_type)`, or `None` if no graph exists.
def graph_impl(self, run, tag, is_conceptual, limit_attr_size=None, large_attrs_key=None):
"""Result of the form `(body, mime_type)`, or `None` if no graph exists."""
if is_conceptual:
tensor_events = self._multiplexer.Tensors(run, tag... |
Result of the form `(body, mime_type)`, or `None` if no data exists.
def run_metadata_impl(self, run, tag):
"""Result of the form `(body, mime_type)`, or `None` if no data exists."""
try:
run_metadata = self._multiplexer.RunMetadata(run, tag)
except ValueError:
# TODO(stephanwlee): Should inclu... |
Given a single run, return the graph definition in protobuf format.
def graph_route(self, request):
"""Given a single run, return the graph definition in protobuf format."""
run = request.args.get('run')
tag = request.args.get('tag', '')
conceptual_arg = request.args.get('conceptual', False)
is_con... |
Given a tag and a run, return the session.run() metadata.
def run_metadata_route(self, request):
"""Given a tag and a run, return the session.run() metadata."""
tag = request.args.get('tag')
run = request.args.get('run')
if tag is None:
return http_util.Respond(
request, 'query paramete... |
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):
"""Returns the plugin, if possible.
Args:
context: The TBContext flags.
Returns:
A ProfilePlugin instance or ... |
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):
"""Cre... |
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 ... |
Load and normalize data.
def prepare_data():
"""Load and normalize data."""
((x_train, y_train), (x_test, y_test)) = DATASET.load_data()
x_train = x_train.astype("float32")
x_test = x_test.astype("float32")
x_train /= 255.0
x_test /= 255.0
return ((x_train, y_train), (x_test, y_test)) |
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):
"""Perform random search over the hyp... |
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... |
A route that returns a JSON mapping between runs and PR curve data.
Returns:
Given a tag and a comma-separated list of runs (both stored within GET
parameters), fetches a JSON object that maps between run name and objects
containing data required for PR curves for that run. Runs that either
... |
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... |
Creates the JSON object for the tags route response.
Returns:
The JSON object for the tags route response.
def tags_impl(self):
"""Creates the JSON object for the tags route response.
Returns:
The JSON object for the tags route response.
"""
if self._db_connection_provider:
# Re... |
Creates the JSON object for the available time entries route response.
Returns:
The JSON object for the available time entries route response.
def available_time_entries_impl(self):
"""Creates the JSON object for the available time entries route response.
Returns:
The JSON object for the avai... |
Determines whether this plugin is active.
This plugin is active only if PR curve summary data is read by TensorBoard.
Returns:
Whether this plugin is active.
def is_active(self):
"""Determines whether this plugin is active.
This plugin is active only if PR curve summary data is read by TensorB... |
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 _pro... |
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_... |
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... |
Create a top-level experiment summary describing this experiment.
The resulting summary should be written to a log directory that
encloses all the individual sessions' log directories.
Analogous to the low-level `experiment_pb` function in the
`hparams.summary` module.
def summary_pb(self):
"""Cr... |
Generate a bunch of histogram data, and write it to logdir.
def run_all(logdir, verbose=False, num_summaries=400):
"""Generate a bunch of histogram data, and write it to logdir."""
del verbose
tf.compat.v1.set_random_seed(0)
k = tf.compat.v1.placeholder(tf.float32)
# Make a normal distribution, with a shi... |
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):
"""Parses and asserts a positive (>0) ... |
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... |
Determines whether this plugin is active.
This plugin is only active if any run has an embedding.
Returns:
Whether any run has embedding data to show in the projector.
def is_active(self):
"""Determines whether this plugin is active.
This plugin is only active if any run has an embedding.
... |
Returns a map of run paths to `ProjectorConfig` protos.
def configs(self):
"""Returns a map of run paths to `ProjectorConfig` protos."""
run_path_pairs = list(self.run_paths.items())
self._append_plugin_asset_directories(run_path_pairs)
# If there are no summary event files, the projector should still ... |
Call `Reload` on every `EventAccumulator`.
def Reload(self):
"""Call `Reload` on every `EventAccumulator`."""
logger.info('Beginning EventMultiplexer.Reload()')
self._reload_called = True
# Build a list so we're safe even if the list of accumulators is modified
# even while we're reloading.
wit... |
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.
... |
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... |
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... |
Write a histogram summary.
Arguments:
name: A name for this summary. The summary tag used for TensorBoard will
be this name prefixed by any active name scopes.
data: A `Tensor` of any shape. Must be castable to `float64`.
step: Explicit `int64`-castable monotonic step value for this summary. If
... |
Create a histogram summary protobuf.
Arguments:
tag: String tag for the summary.
data: A `np.array` or array-like form of any shape. Must have type
castable to `float`.
buckets: Optional positive `int`. The output will have this
many buckets, except in two edge cases. If there is no data, the... |
Makes recommended modifications to the environment.
This functions changes global state in the Python process. Calling
this function is a good idea, but it can't appropriately be called
from library routines.
def setup_environment():
"""Makes recommended modifications to the environment.
This functions cha... |
Opens stock TensorBoard web assets collection.
Returns:
Returns function that returns a newly opened file handle to zip file
containing static assets for stock TensorBoard, or None if webfiles.zip
could not be found. The value the callback returns must be closed. The
paths inside the zip file are con... |
Create a server factory that performs port scanning.
This function returns a callable whose signature matches the
specification of `TensorBoardServer.__init__`, using `cls` as an
underlying implementation. It passes through `flags` unchanged except
in the case that `flags.port is None`, in which case it repeat... |
Configures TensorBoard behavior via flags.
This method will populate the "flags" property with an argparse.Namespace
representing flag values parsed from the provided argv list, overridden by
explicit flags from remaining keyword arguments.
Args:
argv: Can be set to CLI args equivalent to sys.ar... |
Blocking main function for TensorBoard.
This method is called by `tensorboard.main.run_main`, which is the
standard entrypoint for the tensorboard command line program. The
configure() method must be called first.
Args:
ignored_argv: Do not pass. Required for Abseil compatibility.
Returns:
... |
Python API for launching TensorBoard.
This method is the same as main() except it launches TensorBoard in
a separate permanent thread. The configure() method must be called
first.
Returns:
The URL of the TensorBoard web server.
:rtype: str
def launch(self):
"""Python API for launching ... |
Write a TensorBoardInfo file and arrange for its cleanup.
Args:
server: The result of `self._make_server()`.
def _register_info(self, server):
"""Write a TensorBoardInfo file and arrange for its cleanup.
Args:
server: The result of `self._make_server()`.
"""
server_url = urllib.parse.... |
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 ... |
Constructs the TensorBoard WSGI app and instantiates the server.
def _make_server(self):
"""Constructs the TensorBoard WSGI app and instantiates the server."""
app = application.standard_tensorboard_wsgi(self.flags,
self.plugin_loaders,
... |
Returns a wildcard address for the port in question.
This will attempt to follow the best practice of calling getaddrinfo() with
a null host and AI_PASSIVE to request a server-side socket wildcard address.
If that succeeds, this returns the first IPv6 address found, or if none,
then returns the first I... |
Override to enable IPV4 mapping for IPV6 sockets when desired.
The main use case for this is so that when no host is specified, TensorBoard
can listen on all interfaces for both IPv4 and IPv6 connections, rather than
having to choose v4 or v6 and hope the browser didn't choose the other one.
def server_bi... |
Override to get rid of noisy EPIPE errors.
def handle_error(self, request, client_address):
"""Override to get rid of noisy EPIPE errors."""
del request # unused
# Kludge to override a SocketServer.py method so we can get rid of noisy
# EPIPE errors. They're kind of a red herring as far as errors go. ... |
Iterator over all catapult trace events, as python values.
def _events(self):
"""Iterator over all catapult trace events, as python values."""
for did, device in sorted(six.iteritems(self._proto.devices)):
if device.name:
yield dict(
ph=_TYPE_METADATA,
pid=did,
... |
Converts a TraceEvent proto into a catapult trace event python value.
def _event(self, event):
"""Converts a TraceEvent proto into a catapult trace event python value."""
result = dict(
pid=event.device_id,
tid=event.resource_id,
name=event.name,
ts=event.timestamp_ps / 1000000.... |
Create a legacy scalar summary op.
Arguments:
name: A unique name for the generated summary node.
data: A real numeric rank-0 `Tensor`. Must have `dtype` castable
to `float32`.
display_name: Optional name for this summary in TensorBoard, as a
constant `str`. Defaults to `name`.
descriptio... |
Create a legacy scalar summary protobuf.
Arguments:
name: A unique name for the generated summary, including any desired
name scopes.
data: A rank-0 `np.array` or array-like form (so raw `int`s and
`float`s are fine, too).
display_name: Optional name for this summary in TensorBoard, as a
... |
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... |
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... |
Initializes the TensorBoard sqlite schema using the given connection.
Args:
connection: A sqlite DB connection.
def initialize_schema(connection):
"""Initializes the TensorBoard sqlite schema using the given connection.
Args:
connection: A sqlite DB connection.
"""
cursor = connection.cursor()
cu... |
Returns a freshly created DB-wide unique ID.
def _create_id(self):
"""Returns a freshly created DB-wide unique ID."""
cursor = self._db.cursor()
cursor.execute('INSERT INTO Ids DEFAULT VALUES')
return cursor.lastrowid |
Returns the ID for the current user, creating the row if needed.
def _maybe_init_user(self):
"""Returns the ID for the current user, creating the row if needed."""
user_name = os.environ.get('USER', '') or os.environ.get('USERNAME', '')
cursor = self._db.cursor()
cursor.execute('SELECT user_id FROM Use... |
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):
"""Returns the ID for the given experiment, creating the row if needed.
Args:
experiment_name: name of experiment.
"""
use... |
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):
"""Returns the ID for the given run, creating the row if needed.
Args:
experiment_nam... |
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):
"""Returns a tag-to-ID map for the given tags, crea... |
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):
"""Transactionally writes the given tagged summ... |
Get the raw encoded image data, downloading it if necessary.
def image_data(verbose=False):
"""Get the raw encoded image data, downloading it if necessary."""
# This is a principled use of the `global` statement; don't lint me.
global _IMAGE_DATA # pylint: disable=global-statement
if _IMAGE_DATA is None:
... |
Perform a 2D pixel convolution on the given image.
Arguments:
image: A 3D `float32` `Tensor` of shape `[height, width, channels]`,
where `channels` is the third argument to this function and the
first two dimensions are arbitrary.
pixel_filter: A 2D `Tensor`, representing pixel weightings for the... |
Get the image as a TensorFlow variable.
Returns:
A `tf.Variable`, which must be initialized prior to use:
invoke `sess.run(result.initializer)`.
def get_image(verbose=False):
"""Get the image as a TensorFlow variable.
Returns:
A `tf.Variable`, which must be initialized prior to use:
invoke `ses... |
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):
"""Run a box-blur-to-Gaussian-blur demonstration.
See... |
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):
"""Run a Sobel edge detection demonstration.
See the summary descrip... |
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 simulations on a reasonable set of parameters.
Arguments:
logdir: the direct... |
Get the value of a feature from Example regardless of feature type.
def proto_value_for_feature(example, feature_name):
"""Get the value of a feature from Example regardless of feature type."""
feature = get_example_features(example)[feature_name]
if feature is None:
raise ValueError('Feature {} is not on ex... |
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):
"""Returns an `OriginalFeature... |
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):
"""Returns packaged inference results from ... |
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):
"""Returns a list of feature names for float and int64 type features.
Args:
example: An example.
R... |
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):
"""Returns a list of feature names for byte type features.
Args:
example: An example... |
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):
"""Returns numerical fea... |
Returns categorical features and a sampling of their most-common values.
The results of this slow function are used by the visualization repeatedly,
so the results are cached.
Args:
examples: Examples to read to get feature samples.
top_k: Max number of samples to return per feature.
Returns:
A d... |
Return a list of `MutantFeatureValue`s that are variants of original.
def make_mutant_features(original_feature, index_to_mutate, viz_params):
"""Return a list of `MutantFeatureValue`s that are variants of original."""
lower = viz_params.x_min
upper = viz_params.x_max
examples = viz_params.examples
num_mutan... |
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` ... |
Returns JSON formatted for rendering all charts for a feature.
Args:
example_proto: The example protos to mutate.
feature_name: The string feature name to mutate.
serving_bundles: One `ServingBundle` object per model, that contains the
information to make the serving request.
viz_params: A `Viz... |
Returns JSON formatted for a single mutant chart.
Args:
mutant_features: An iterable of `MutantFeatureValue`s representing the
X-axis.
inference_result_proto: A ClassificationResponse or RegressionResponse
returned by Servo, representing the Y-axis.
It contains one 'classification' or 'regr... |
Returns the non-sequence features from the provided example.
def get_example_features(example):
"""Returns the non-sequence features from the provided example."""
return (example.features.feature if isinstance(example, tf.train.Example)
else example.context.feature) |
Calls servo and wraps the inference results.
def run_inference_for_inference_results(examples, serving_bundle):
"""Calls servo and wraps the inference results."""
inference_result_proto = run_inference(examples, serving_bundle)
inferences = wrap_inference_results(inference_result_proto)
infer_json = json_forma... |
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... |
Returns a list of label strings loaded from the provided path.
def get_label_vocab(vocab_path):
"""Returns a list of label strings loaded from the provided path."""
if vocab_path:
try:
with tf.io.gfile.GFile(vocab_path, 'r') as f:
return [line.rstrip('\n') for line in f]
except tf.errors.NotF... |
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):
"""Returns an encoded sprite image for use in Facets Dive.
Args:
examples: A list of serialized... |
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_inferenc... |
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):
"""Return items associated with given key.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.