Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def _get_wildcard_address(self, port):
fallback_address = '::' if socket.has_ipv6 else '0.0.0.0'
if hasattr(socket, 'AI_PASSIVE'):
try:
addrinfos = socket.getaddrinfo(None, port, socket.AF_UNSPEC,
socket.SOCK_... | [
"Returns a wildcard address for the port in question.\n\n This will attempt to follow the best practice of calling getaddrinfo() with\n a null host and AI_PASSIVE to request a server-side socket wildcard address.\n If that succeeds, this returns the first IPv6 address found, or if none,\n then returns t... |
Please provide a description of the function:def server_bind(self):
socket_is_v6 = (
hasattr(socket, 'AF_INET6') and self.socket.family == socket.AF_INET6)
has_v6only_option = (
hasattr(socket, 'IPPROTO_IPV6') and hasattr(socket, 'IPV6_V6ONLY'))
if self._auto_wildcard and socket_is_v6 a... | [
"Override to enable IPV4 mapping for IPV6 sockets when desired.\n\n The main use case for this is so that when no host is specified, TensorBoard\n can listen on all interfaces for both IPv4 and IPv6 connections, rather than\n having to choose v4 or v6 and hope the browser didn't choose the other one.\n ... |
Please provide a description of the function:def handle_error(self, request, client_address):
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. For
# example, `curl -N http://localhost:60... | [
"Override to get rid of noisy EPIPE errors."
] |
Please provide a description of the function:def _events(self):
for did, device in sorted(six.iteritems(self._proto.devices)):
if device.name:
yield dict(
ph=_TYPE_METADATA,
pid=did,
name='process_name',
args=dict(name=device.name))
yield dict... | [
"Iterator over all catapult trace events, as python values."
] |
Please provide a description of the function:def _event(self, event):
result = dict(
pid=event.device_id,
tid=event.resource_id,
name=event.name,
ts=event.timestamp_ps / 1000000.0)
if event.duration_ps:
result['ph'] = _TYPE_COMPLETE
result['dur'] = event.duration... | [
"Converts a TraceEvent proto into a catapult trace event python value."
] |
Please provide a description of the function:def op(name,
data,
display_name=None,
description=None,
collections=None):
# TODO(nickfelt): remove on-demand imports once dep situation is fixed.
import tensorflow.compat.v1 as tf
if display_name is None:
display_name = name
summa... | [
"Create a legacy scalar summary op.\n\n Arguments:\n name: A unique name for the generated summary node.\n data: A real numeric rank-0 `Tensor`. Must have `dtype` castable\n to `float32`.\n display_name: Optional name for this summary in TensorBoard, as a\n constant `str`. Defaults to `name`.\n ... |
Please provide a description of the function:def pb(name, data, display_name=None, description=None):
# TODO(nickfelt): remove on-demand imports once dep situation is fixed.
import tensorflow.compat.v1 as tf
data = np.array(data)
if data.shape != ():
raise ValueError('Expected scalar shape for data, saw... | [
"Create a legacy scalar summary protobuf.\n\n Arguments:\n name: A unique name for the generated summary, including any desired\n name scopes.\n data: A rank-0 `np.array` or array-like form (so raw `int`s and\n `float`s are fine, too).\n display_name: Optional name for this summary in TensorBoar... |
Please provide a description of the function: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 possi... | [
"Creates temp symlink tree, runs program, and copies back outputs.\n\n Args:\n inputs: List of fake paths to real paths, which are used for symlink tree.\n program: List containing real path of program and its arguments. The\n execroot directory will be appended as the last argument.\n outputs: Lis... |
Please provide a description of the function: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... | [
"Invokes run function using a JSON file config.\n\n Args:\n args: CLI args, which can be a JSON file containing an object whose\n attributes are the parameters to the run function. If multiple JSON\n files are passed, their contents are concatenated.\n Returns:\n 0 if succeeded or nonzero if f... |
Please provide a description of the function: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_... | [
"Initializes the TensorBoard sqlite schema using the given connection.\n\n Args:\n connection: A sqlite DB connection.\n "
] |
Please provide a description of the function:def _create_id(self):
cursor = self._db.cursor()
cursor.execute('INSERT INTO Ids DEFAULT VALUES')
return cursor.lastrowid | [
"Returns a freshly created DB-wide unique ID."
] |
Please provide a description of the function:def _maybe_init_user(self):
user_name = os.environ.get('USER', '') or os.environ.get('USERNAME', '')
cursor = self._db.cursor()
cursor.execute('SELECT user_id FROM Users WHERE user_name = ?',
(user_name,))
row = cursor.fetchone()
i... | [
"Returns the ID for the current user, creating the row if needed.",
"\n INSERT INTO USERS (user_id, user_name, inserted_time)\n VALUES (?, ?, ?)\n "
] |
Please provide a description of the function: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... | [
"Returns the ID for the given experiment, creating the row if needed.\n\n Args:\n experiment_name: name of experiment.\n ",
"\n SELECT experiment_id FROM Experiments\n WHERE user_id = ? AND experiment_name = ?\n ",
"\n INSERT INTO Experiments (\n user_id, experime... |
Please provide a description of the function: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 ro... | [
"Returns the ID for the given run, creating the row if needed.\n\n Args:\n experiment_name: name of experiment containing this run.\n run_name: name of run.\n ",
"\n SELECT run_id FROM Runs\n WHERE experiment_id = ? AND run_name = ?\n ",
"\n INSERT INTO Runs (\n ... |
Please provide a description of the function: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... | [
"Returns a tag-to-ID map for the given tags, creating rows if needed.\n\n Args:\n run_id: the ID of the run to which these tags belong.\n tag_to_metadata: map of tag name to SummaryMetadata for the tag.\n ",
"\n INSERT INTO Tags (\n run_id, tag_id, tag_name, inserted_time, display_... |
Please provide a description of the function: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... | [
"Transactionally writes the given tagged summary data to the DB.\n\n Args:\n tagged_data: map from tag to TagData instances.\n experiment_name: name of experiment.\n run_name: name of run.\n ",
"\n INSERT OR REPLACE INTO Tensors (\n series, step, computed_time, dtype, shap... |
Please provide a description of the function:def image_data(verbose=False):
# 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:
if verbose:
logger.info("--- Downloading image.")
with contextlib.closing... | [
"Get the raw encoded image data, downloading it if necessary."
] |
Please provide a description of the function:def convolve(image, pixel_filter, channels=3, name=None):
with tf.name_scope(name, 'convolve'):
tf.compat.v1.assert_type(image, tf.float32)
channel_filter = tf.eye(channels)
filter_ = (tf.expand_dims(tf.expand_dims(pixel_filter, -1), -1) *
tf.... | [
"Perform a 2D pixel convolution on the given image.\n\n Arguments:\n image: A 3D `float32` `Tensor` of shape `[height, width, channels]`,\n where `channels` is the third argument to this function and the\n first two dimensions are arbitrary.\n pixel_filter: A 2D `Tensor`, representing pixel weighti... |
Please provide a description of the function:def get_image(verbose=False):
base_data = tf.constant(image_data(verbose=verbose))
base_image = tf.image.decode_image(base_data, channels=3)
base_image.set_shape((IMAGE_HEIGHT, IMAGE_WIDTH, 3))
parsed_image = tf.Variable(base_image, name='image', dtype=tf.uint8)
... | [
"Get the image as a TensorFlow variable.\n\n Returns:\n A `tf.Variable`, which must be initialized prior to use:\n invoke `sess.run(result.initializer)`."
] |
Please provide a description of the function: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=... | [
"Run a box-blur-to-Gaussian-blur demonstration.\n\n See the summary description for more details.\n\n Arguments:\n logdir: Directory into which to write event logs.\n verbose: Boolean; whether to log any output.\n "
] |
Please provide a description of the function: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... | [
"Run a Sobel edge detection demonstration.\n\n See the summary description for more details.\n\n Arguments:\n logdir: Directory into which to write event logs.\n verbose: Boolean; whether to log any output.\n "
] |
Please provide a description of the function:def run_all(logdir, verbose=False):
run_box_to_gaussian(logdir, verbose=verbose)
run_sobel(logdir, verbose=verbose) | [
"Run simulations on a reasonable set of parameters.\n\n Arguments:\n logdir: the directory into which to store all the runs' data\n verbose: if true, print out each run's name as it begins\n "
] |
Please provide a description of the function:def proto_value_for_feature(example, feature_name):
feature = get_example_features(example)[feature_name]
if feature is None:
raise ValueError('Feature {} is not on example proto.'.format(feature_name))
feature_type = feature.WhichOneof('kind')
if feature_type... | [
"Get the value of a feature from Example regardless of feature type."
] |
Please provide a description of the function: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... | [
"Returns an `OriginalFeatureList` for the specified feature_name.\n\n Args:\n example: An example.\n feature_name: A string feature name.\n\n Returns:\n A filled in `OriginalFeatureList` object representing the feature.\n "
] |
Please provide a description of the function: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(
inferenc... | [
"Returns packaged inference results from the provided proto.\n\n Args:\n inference_result_proto: The classification or regression response proto.\n\n Returns:\n An InferenceResult proto with the result from the response.\n "
] |
Please provide a description of the function: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
... | [
"Returns a list of feature names for float and int64 type features.\n\n Args:\n example: An example.\n\n Returns:\n A list of strings of the names of numeric features.\n "
] |
Please provide a description of the function: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'
]) | [
"Returns a list of feature names for byte type features.\n\n Args:\n example: An example.\n\n Returns:\n A list of categorical feature names (e.g. ['education', 'marital_status'] )\n "
] |
Please provide a description of the function: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_examp... | [
"Returns numerical features and their observed ranges.\n\n Args:\n examples: Examples to read to get ranges.\n\n Returns:\n A dict mapping feature_name -> {'observedMin': 'observedMax': } dicts,\n with a key for each numerical feature.\n "
] |
Please provide a description of the function:def get_categorical_features_to_sampling(examples, top_k):
observed_features = collections.defaultdict(list) # name -> [value, ]
for example in examples:
for feature_name in get_categorical_feature_names(example):
original_feature = parse_original_feature_f... | [
"Returns categorical features and a sampling of their most-common values.\n\n The results of this slow function are used by the visualization repeatedly,\n so the results are cached.\n\n Args:\n examples: Examples to read to get feature samples.\n top_k: Max number of samples to return per feature.\n\n Re... |
Please provide a description of the function:def make_mutant_features(original_feature, index_to_mutate, viz_params):
lower = viz_params.x_min
upper = viz_params.x_max
examples = viz_params.examples
num_mutants = viz_params.num_mutants
if original_feature.feature_type == 'float_list':
return [
... | [
"Return a list of `MutantFeatureValue`s that are variants of original."
] |
Please provide a description of the function: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 exam... | [
"Return a list of `MutantFeatureValue`s and a list of mutant Examples.\n\n Args:\n example_protos: The examples to mutate.\n original_feature: A `OriginalFeatureList` that encapsulates the feature to\n mutate.\n index_to_mutate: The index of the int64_list or float_list to mutate.\n viz_params: A ... |
Please provide a description of the function:def mutant_charts_for_feature(example_protos, feature_name, serving_bundles,
viz_params):
def chart_for_index(index_to_mutate):
mutant_features, mutant_examples = make_mutant_tuples(
example_protos, original_feature, index_to_m... | [
"Returns JSON formatted for rendering all charts for a feature.\n\n Args:\n example_proto: The example protos to mutate.\n feature_name: The string feature name to mutate.\n serving_bundles: One `ServingBundle` object per model, that contains the\n information to make the serving request.\n viz_pa... |
Please provide a description of the function:def make_json_formatted_for_single_chart(mutant_features,
inference_result_proto,
index_to_mutate):
x_label = 'step'
y_label = 'scalar'
if isinstance(inference_result_proto,
... | [
"Returns JSON formatted for a single mutant chart.\n\n Args:\n mutant_features: An iterable of `MutantFeatureValue`s representing the\n X-axis.\n inference_result_proto: A ClassificationResponse or RegressionResponse\n returned by Servo, representing the Y-axis.\n It contains one 'classificati... |
Please provide a description of the function:def get_example_features(example):
return (example.features.feature if isinstance(example, tf.train.Example)
else example.context.feature) | [
"Returns the non-sequence features from the provided example."
] |
Please provide a description of the function:def run_inference_for_inference_results(examples, serving_bundle):
inference_result_proto = run_inference(examples, serving_bundle)
inferences = wrap_inference_results(inference_result_proto)
infer_json = json_format.MessageToJson(
inferences, including_default_... | [
"Calls servo and wraps the inference results."
] |
Please provide a description of the function: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 i... | [
"Returns a list of JSON objects for each feature in the examples.\n\n This list is used to drive partial dependence plots in the plugin.\n\n Args:\n examples: Examples to examine to determine the eligible features.\n num_mutants: The number of mutations to make over each feature.\n\n Returns:\n ... |
Please provide a description of the function:def get_label_vocab(vocab_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.NotFoundError as err:
tf.logging.error('error reading vocab file: %s', err)
return ... | [
"Returns a list of label strings loaded from the provided path."
] |
Please provide a description of the function: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]
... | [
"Returns an encoded sprite image for use in Facets Dive.\n\n Args:\n examples: A list of serialized example protos to get images for.\n\n Returns:\n An encoded PNG.\n ",
"Generates a sprite atlas image from a set of thumbnails."
] |
Please provide a description of the function: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.Da... | [
"Run inference on examples given model information\n\n Args:\n examples: A list of examples that matches the model spec.\n serving_bundle: A `ServingBundle` object that contains the information to\n make the inference request.\n\n Returns:\n A ClassificationResponse or RegressionResponse proto.\n "... |
Please provide a description of the function: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() | [
"Return items associated with given key.\n\n Args:\n key: The key for which we are finding associated items.\n\n Raises:\n KeyError: If the key is not found in the reservoir.\n\n Returns:\n [list, of, items] associated with that key.\n "
] |
Please provide a description of the function:def AddItem(self, key, item, f=lambda x: x):
with self._mutex:
bucket = self._buckets[key]
bucket.AddItem(item, f) | [
"Add a new item to the Reservoir with the given tag.\n\n If the reservoir has not yet reached full size, the new item is guaranteed\n to be added. If the reservoir is full, then behavior depends on the\n always_keep_last boolean.\n\n If always_keep_last was set to true, the new item is guaranteed to be ... |
Please provide a description of the function: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)
... | [
"Filter items within a Reservoir, using a filtering function.\n\n Args:\n filterFn: A function that returns True for the items to be kept.\n key: An optional bucket key to filter. If not specified, will filter all\n all buckets.\n\n Returns:\n The number of items removed.\n "
] |
Please provide a description of the function:def AddItem(self, item, f=lambda x: x):
with self._mutex:
if len(self.items) < self._max_size or self._max_size == 0:
self.items.append(f(item))
else:
r = self._random.randint(0, self._num_items_seen)
if r < self._max_size:
... | [
"Add an item to the ReservoirBucket, replacing an old item if necessary.\n\n The new item is guaranteed to be added to the bucket, and to be the last\n element in the bucket. If the bucket has reached capacity, then an old item\n will be replaced. With probability (_max_size/_num_items_seen) a random item\... |
Please provide a description of the function:def FilterItems(self, filterFn):
with self._mutex:
size_before = len(self.items)
self.items = list(filter(filterFn, self.items))
size_diff = size_before - len(self.items)
# Estimate a correction the number of items seen
prop_remaining ... | [
"Filter items in a ReservoirBucket, using a filtering function.\n\n Filtering items from the reservoir bucket must update the\n internal state variable self._num_items_seen, which is used for determining\n the rate of replacement in reservoir sampling. Ideally, self._num_items_seen\n would contain the e... |
Please provide a description of the function:def _GetDenseDimensions(list_of_lists):
if not isinstance(list_of_lists, (list, tuple)):
return []
elif not list_of_lists:
return [0]
else:
return [len(list_of_lists)] + _GetDenseDimensions(list_of_lists[0]) | [
"Returns the inferred dense dimensions of a list of lists."
] |
Please provide a description of the function:def make_tensor_proto(values, dtype=None, shape=None, verify_shape=False):
if isinstance(values, tensor_pb2.TensorProto):
return values
if dtype:
dtype = dtypes.as_dtype(dtype)
is_quantized = dtype in [
dtypes.qint8,
dtypes.... | [
"Create a TensorProto.\n\n Args:\n values: Values to put in the TensorProto.\n dtype: Optional tensor_pb2 DataType value.\n shape: List of integers representing the dimensions of tensor.\n verify_shape: Boolean that enables verification of a shape of values.\n\n Returns:\n ... |
Please provide a description of the function: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.fr... | [
"Create a numpy ndarray from a tensor.\n\n Create a numpy ndarray with the same shape and data as the tensor.\n\n Args:\n tensor: A TensorProto.\n\n Returns:\n A numpy array with the tensor contents.\n\n Raises:\n TypeError: if tensor has unsupported type.\n\n "
] |
Please provide a description of the function: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... | [
"Creates a summary that contains a layout.\n\n When users navigate to the custom scalars dashboard, they will see a layout\n based on the proto provided to this function.\n\n Args:\n scalars_layout: The scalars_layout_pb2.Layout proto that specifies the\n layout.\n collections: Optional list of grap... |
Please provide a description of the function: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=t... | [
"Creates a summary that contains a layout.\n\n When users navigate to the custom scalars dashboard, they will see a layout\n based on the proto provided to this function.\n\n Args:\n scalars_layout: The scalars_layout_pb2.Layout proto that specifies the\n layout.\n\n Returns:\n A summary proto cont... |
Please provide a description of the function: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 | [
"Returns true if `other` is convertible with this Dimension.\n\n Two known Dimensions are convertible if they have the same value.\n An unknown Dimension is convertible with all other Dimensions.\n\n Args:\n other: Another Dimension.\n\n Returns:\n True if this Dimensio... |
Please provide a description of the function:def merge_with(self, other):
other = as_dimension(other)
self.assert_is_convertible_with(other)
if self._value is None:
return Dimension(other.value)
else:
return Dimension(self._value) | [
"Returns a Dimension that combines the information in `self` and `other`.\n\n Dimensions are combined as follows:\n\n ```python\n tf.Dimension(n) .merge_with(tf.Dimension(n)) == tf.Dimension(n)\n tf.Dimension(n) .merge_with(tf.Dimension(None)) == tf.Dimension(n)\n tf.Dimens... |
Please provide a description of the function:def ndims(self):
if self._dims is None:
return None
else:
if self._ndims is None:
self._ndims = len(self._dims)
return self._ndims | [
"Returns the rank of this shape, or None if it is unspecified."
] |
Please provide a description of the function:def num_elements(self):
if self.is_fully_defined():
size = 1
for dim in self._dims:
size *= dim.value
return size
else:
return None | [
"Returns the total number of elements, or none for incomplete shapes."
] |
Please provide a description of the function: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(sel... | [
"Returns a `TensorShape` combining the information in `self` and `other`.\n\n The dimensions in `self` and `other` are merged elementwise,\n according to the rules defined for `Dimension.merge_with()`.\n\n Args:\n other: Another `TensorShape`.\n\n Returns:\n A `TensorSh... |
Please provide a description of the function:def concatenate(self, other):
# TODO(mrry): Handle the case where we concatenate a known shape with a
# completely unknown shape, so that we can use the partial information.
other = as_shape(other)
if self._dims is None or other.dims ... | [
"Returns the concatenation of the dimension in `self` and `other`.\n\n *N.B.* If either `self` or `other` is completely unknown,\n concatenation will discard information about the other shape. In\n future, we might support concatenation that preserves this\n information for use with slic... |
Please provide a description of the function: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 ran... | [
"Raises an exception if `self` and `other` do not have convertible ranks.\n\n Args:\n other: Another `TensorShape`.\n\n Raises:\n ValueError: If `self` and `other` do not represent shapes with the\n same rank.\n "
] |
Please provide a description of the function: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)) | [
"Returns a shape based on `self` with the given rank.\n\n This method promotes a completely unknown shape to one with a\n known rank.\n\n Args:\n rank: An integer.\n\n Returns:\n A shape that is at least as specific as `self` with the given rank.\n\n Raises:\n ... |
Please provide a description of the function: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 | [
"Returns a shape based on `self` with at least the given rank.\n\n Args:\n rank: An integer.\n\n Returns:\n A shape that is at least as specific as `self` with at least the given\n rank.\n\n Raises:\n ValueError: If `self` does not represent a shape with at l... |
Please provide a description of the function: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 | [
"Returns a shape based on `self` with at most the given rank.\n\n Args:\n rank: An integer.\n\n Returns:\n A shape that is at least as specific as `self` with at most the given\n rank.\n\n Raises:\n ValueError: If `self` does not represent a shape with at mos... |
Please provide a description of the function:def is_convertible_with(self, other):
other = as_shape(other)
if self._dims is not None and other.dims is not None:
if self.ndims != other.ndims:
return False
for x_dim, y_dim in zip(self._dims, other.dims):
... | [
"Returns True iff `self` is convertible with `other`.\n\n Two possibly-partially-defined shapes are convertible if there\n exists a fully-defined shape that both shapes can represent. Thus,\n convertibility allows the shape inference code to reason about\n partially-defined shapes. For e... |
Please provide a description of the function:def most_specific_convertible_shape(self, other):
other = as_shape(other)
if self._dims is None or other.dims is None or self.ndims != other.ndims:
return unknown_shape()
dims = [(Dimension(None))] * self.ndims
for i, (d... | [
"Returns the most specific TensorShape convertible with `self` and `other`.\n\n * TensorShape([None, 1]) is the most specific TensorShape convertible with\n both TensorShape([2, 1]) and TensorShape([5, 1]). Note that\n TensorShape(None) is also convertible with above mentioned TensorShapes.... |
Please provide a description of the function:def is_fully_defined(self):
return self._dims is not None and all(
dim.value is not None for dim in self._dims
) | [
"Returns True iff `self` is fully defined in every dimension."
] |
Please provide a description of the function:def as_list(self):
if self._dims is None:
raise ValueError("as_list() is not defined on an unknown TensorShape.")
return [dim.value for dim in self._dims] | [
"Returns a list of integers or `None` for each dimension.\n\n Returns:\n A list of integers or `None` for each dimension.\n\n Raises:\n ValueError: If `self` is an unknown shape with an unknown rank.\n "
] |
Please provide a description of the function:def as_proto(self):
if self._dims is None:
return tensor_shape_pb2.TensorShapeProto(unknown_rank=True)
else:
return tensor_shape_pb2.TensorShapeProto(
dim=[
tensor_shape_pb2.TensorShapeProto... | [
"Returns this shape as a `TensorShapeProto`."
] |
Please provide a description of the function: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].... | [
"Converts a PredictResponse to ClassificationResponse or RegressionResponse.\n\n Args:\n pred: PredictResponse to convert.\n serving_bundle: A `ServingBundle` object that contains the information about\n the serving request that the response was generated by.\n\n Returns:\n A ClassificationResponse ... |
Please provide a description of the function:def convert_prediction_values(values, serving_bundle, model_spec=None):
if serving_bundle.model_type == 'classification':
response = classification_pb2.ClassificationResponse()
for example_index in range(len(values)):
classification = response.result.class... | [
"Converts tensor values into ClassificationResponse or RegressionResponse.\n\n Args:\n values: For classification, a 2D list of numbers. The first dimension is for\n each example being predicted. The second dimension are the probabilities\n for each class ID in the prediction. For regression, a 1D lis... |
Please provide a description of the function:def _GetPurgeMessage(most_recent_step, most_recent_wall_time, event_step,
event_wall_time, num_expired):
return ('Detected out of order event.step likely caused by a TensorFlow '
'restart. Purging {} expired tensor events from Tensorboard ... | [
"Return the string message associated with TensorBoard purges."
] |
Please provide a description of the function: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 ... | [
"Returns a dict mapping tags to content specific to that plugin.\n\n Args:\n plugin_name: The name of the plugin for which to fetch plugin-specific\n content.\n\n Raises:\n KeyError: if the plugin name is not found.\n\n Returns:\n A dict mapping tags to plugin-specific content (which ... |
Please provide a description of the function:def _ProcessEvent(self, event):
if self._first_event_timestamp is None:
self._first_event_timestamp = event.wall_time
if event.HasField('file_version'):
new_file_version = _ParseFileVersion(event.file_version)
if self.file_version and self.fil... | [
"Called whenever an event is loaded."
] |
Please provide a description of the function:def Tags(self):
return {
TENSORS: list(self.tensors_by_tag.keys()),
# Use a heuristic: if the metagraph is available, but
# graph is not, then we assume the metagraph contains the graph.
GRAPH: self._graph is not None,
META_GR... | [
"Return all tags found in the value stream.\n\n Returns:\n A `{tagType: ['list', 'of', 'tags']}` dictionary.\n "
] |
Please provide a description of the function: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 ... | [
"Maybe purge orphaned data due to a TensorFlow crash.\n\n When TensorFlow crashes at step T+O and restarts at step T, any events\n written after step T are now \"orphaned\" and will be at best misleading if\n they are included in TensorBoard.\n\n This logic attempts to determine if there is orphaned dat... |
Please provide a description of the function:def _CheckForOutOfOrderStepAndMaybePurge(self, event):
if event.step < self.most_recent_step and event.HasField('summary'):
self._Purge(event, by_tags=True) | [
"Check for out-of-order event.step and discard expired events for tags.\n\n Check if the event is out of order relative to the global most recent step.\n If it is, purge outdated summaries for tags that the event contains.\n\n Args:\n event: The event to use as reference. If the event is out-of-order,... |
Please provide a description of the function:def _Purge(self, event, by_tags):
## Keep data in reservoirs that has a step less than event.step
_NotExpired = lambda x: x.step < event.step
num_expired = 0
if by_tags:
for value in event.summary.value:
if value.tag in self.tensors_by_tag... | [
"Purge all events that have occurred after the given event.step.\n\n If by_tags is True, purge all events that occurred after the given\n event.step, but only for the tags that the event has. Non-sequential\n event.steps suggest that a TensorFlow restart occurred, and we discard\n the out-of-order event... |
Please provide a description of the function: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... | [
"Returns the plugin, if possible.\n\n Args:\n context: The TBContext flags.\n\n Returns:\n A BeholderPlugin instance or None if it couldn't be loaded.\n "
] |
Please provide a description of the function: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(lay... | [
"Walks the nested keras layer configuration in preorder.\n Args:\n keras_layer: Keras configuration from model.to_json.\n\n Yields:\n A tuple of (name_scope, layer_config).\n name_scope: a string representing a scope name, similar to that of tf.name_scope.\n layer_config: a dict representing a Keras l... |
Please provide a description of the function:def _update_dicts(name_scope,
model_layer,
input_to_in_layer,
model_name_to_output,
prev_node_name):
layer_config = model_layer.get('config')
if not layer_config.get('layers'):
raise ValueErro... | [
"Updates input_to_in_layer, model_name_to_output, and prev_node_name\n based on the model_layer.\n\n Args:\n name_scope: a string representing a scope name, similar to that of tf.name_scope.\n model_layer: a dict representing a Keras model configuration.\n input_to_in_layer: a dict mapping Keras.layers.I... |
Please provide a description of the function: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_... | [
"Returns a GraphDef representation of the Keras model in a dict form.\n\n Note that it only supports models that implemented to_json().\n\n Args:\n keras_layer: A dict from Keras model.to_json().\n\n Returns:\n A GraphDef representation of the layers in the model.\n "
] |
Please provide a description of the function: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
... | [
"Returns the plugin, if possible.\n\n Args:\n context: The TBContext flags.\n\n Returns:\n A HParamsPlugin instance or None if it couldn't be loaded.\n "
] |
Please provide a description of the function: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... | [
"Convert Markdown to HTML that's safe to splice into the DOM.\n\n Arguments:\n markdown_string: A Unicode string or UTF-8--encoded bytestring\n containing Markdown source. Markdown tables are supported.\n\n Returns:\n A string containing safe HTML.\n "
] |
Please provide a description of the function: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:
... | [
"Converts the given `type_value` to a `DType`.\n\n Args:\n type_value: A value that can be converted to a `tf.DType` object. This may\n currently be a `tf.DType` object, a [`DataType`\n enum](https://www.tensorflow.org/code/tensorflow/core/framework/types.proto),\n a string type name, o... |
Please provide a description of the function:def real_dtype(self):
base = self.base_dtype
if base == complex64:
return float32
elif base == complex128:
return float64
else:
return self | [
"Returns the dtype correspond to this dtype's real part."
] |
Please provide a description of the function:def is_integer(self):
return (
self.is_numpy_compatible
and not self.is_quantized
and np.issubdtype(self.as_numpy_dtype, np.integer)
) | [
"Returns whether this is a (non-quantized) integer type."
] |
Please provide a description of the function:def is_floating(self):
return (
self.is_numpy_compatible and np.issubdtype(self.as_numpy_dtype, np.floating)
) or self.base_dtype == bfloat16 | [
"Returns whether this is a (non-quantized, real) floating point type."
] |
Please provide a description of the function:def min(self):
if self.is_quantized or self.base_dtype in (
bool,
string,
complex64,
complex128,
):
raise TypeError("Cannot find minimum value of %s." % self)
# there is no simple w... | [
"Returns the minimum representable value in this data type.\n\n Raises:\n TypeError: if this is a non-numeric, unordered, or quantized type.\n\n "
] |
Please provide a description of the function: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 | [
"Return intensity limits, i.e. (min, max) tuple, of the dtype.\n Args:\n clip_negative : bool, optional\n If True, clip the negative range (i.e. return 0 for min intensity)\n even if the image dtype allows negative values.\n Returns\n min, max : tuple\n ... |
Please provide a description of the function:def is_compatible_with(self, other):
other = as_dtype(other)
return self._type_enum in (
other.as_datatype_enum,
other.base_dtype.as_datatype_enum,
) | [
"Returns True if the `other` DType will be converted to this DType.\n\n The conversion rules are as follows:\n\n ```python\n DType(T) .is_compatible_with(DType(T)) == True\n DType(T) .is_compatible_with(DType(T).as_ref) == True\n DType(T).as_ref.is_compatible_wi... |
Please provide a description of the function: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 Interact... | [
"Start listening on the given gRPC port.\n\n This method of an instance of InteractiveDebuggerPlugin can be invoked at\n most once. This method is not thread safe.\n\n Args:\n grpc_port: port number to listen at.\n\n Raises:\n ValueError: If this instance is already listening at a gRPC port.\n... |
Please provide a description of the function:def get_plugin_apps(self):
return {
_ACK_ROUTE: self._serve_ack,
_COMM_ROUTE: self._serve_comm,
_DEBUGGER_GRPC_HOST_PORT_ROUTE: self._serve_debugger_grpc_host_port,
_DEBUGGER_GRAPH_ROUTE: self._serve_debugger_graph,
_GATED_GRP... | [
"Obtains a mapping between routes and handlers.\n\n This function also starts a debugger data server on separate thread if the\n plugin has not started one yet.\n\n Returns:\n A mapping between routes and handlers (functions that respond to\n requests).\n "
] |
Please provide a description of the function:def is_active(self):
if not self._multiplexer:
return False
return bool(self._multiplexer.PluginRunToTagToContent(metadata.PLUGIN_NAME)) | [
"The audio plugin is active iff any run has at least one relevant tag."
] |
Please provide a description of the function:def _index_impl(self):
runs = self._multiplexer.Runs()
result = {run: {} for run in runs}
mapping = self._multiplexer.PluginRunToTagToContent(metadata.PLUGIN_NAME)
for (run, tag_to_content) in six.iteritems(mapping):
for tag in tag_to_content:
... | [
"Return information about the tags in each run.\n\n Result is a dictionary of the form\n\n {\n \"runName1\": {\n \"tagName1\": {\n \"displayName\": \"The first tag\",\n \"description\": \"<p>Long ago there was just one tag...</p>\",\n \"samples\":... |
Please provide a description of the function: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, ... | [
"Given a tag and list of runs, serve a list of metadata for audio.\n\n Note that the actual audio data are not sent; instead, we respond\n with URLs to the audio. The frontend should treat these URLs as\n opaque and should not try to parse information about them or\n generate them itself, as the format ... |
Please provide a description of the function:def _audio_response_for_run(self, tensor_events, run, tag, sample):
response = []
index = 0
filtered_events = self._filter_by_sample(tensor_events, sample)
content_type = self._get_mime_type(run, tag)
for (index, tensor_event) in enumerate(filtered_e... | [
"Builds a JSON-serializable object with information about audio.\n\n Args:\n tensor_events: A list of image event_accumulator.TensorEvent objects.\n run: The name of the run.\n tag: The name of the tag the audio entries all belong to.\n sample: The zero-indexed sample of the audio sample for ... |
Please provide a description of the function:def _query_for_individual_audio(self, run, tag, sample, index):
query_string = urllib.parse.urlencode({
'run': run,
'tag': tag,
'sample': sample,
'index': index,
})
return query_string | [
"Builds a URL for accessing the specified audio.\n\n This should be kept in sync with _serve_audio_metadata. Note that the URL is\n *not* guaranteed to always return the same audio, since audio may be\n unloaded from the reservoir as new audio entries come in.\n\n Args:\n run: The name of the run.\... |
Please provide a description of the function:def _serve_individual_audio(self, request):
tag = request.args.get('tag')
run = request.args.get('run')
index = int(request.args.get('index'))
sample = int(request.args.get('sample', 0))
events = self._filter_by_sample(self._multiplexer.Tensors(run, ... | [
"Serve encoded audio data."
] |
Please provide a description of the function: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 al... | [
"Writes __main__'s docstring to stdout with some help text.\n\n Args:\n shorthelp: bool, if True, prints only flags from the main module,\n rather than all flags.\n "
] |
Please provide a description of the function:def run(main=None, argv=None):
# Define help flags.
_define_help_flags()
# Parse known flags.
argv = flags.FLAGS(_sys.argv if argv is None else argv, known_only=True)
main = main or _sys.modules['__main__'].main
# Call the main function, pass... | [
"Runs the program with an optional 'main' function and 'argv' list."
] |
Please provide a description of the function:def op(name,
images,
max_outputs=3,
display_name=None,
description=None,
collections=None):
# TODO(nickfelt): remove on-demand imports once dep situation is fixed.
import tensorflow.compat.v1 as tf
if display_name is None:
dis... | [
"Create a legacy image summary op for use in a TensorFlow graph.\n\n Arguments:\n name: A unique name for the generated summary node.\n images: A `Tensor` representing pixel data with shape `[k, h, w, c]`,\n where `k` is the number of images, `h` and `w` are the height and\n width of the images, an... |
Please provide a description of the function:def pb(name, images, max_outputs=3, display_name=None, description=None):
# TODO(nickfelt): remove on-demand imports once dep situation is fixed.
import tensorflow.compat.v1 as tf
images = np.array(images).astype(np.uint8)
if images.ndim != 4:
raise ValueErro... | [
"Create a legacy image summary protobuf.\n\n This behaves as if you were to create an `op` with the same arguments\n (wrapped with constant tensors where appropriate) and then execute\n that summary op in a TensorFlow session.\n\n Arguments:\n name: A unique name for the generated summary, including any desi... |
Please provide a description of the function:def tensor_size_guidance_from_flags(flags):
tensor_size_guidance = dict(DEFAULT_TENSOR_SIZE_GUIDANCE)
if not flags or not flags.samples_per_plugin:
return tensor_size_guidance
for token in flags.samples_per_plugin.split(','):
k, v = token.strip().split('='... | [
"Apply user per-summary size guidance overrides."
] |
Please provide a description of the function: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.pur... | [
"Construct a TensorBoardWSGIApp with standard plugins and multiplexer.\n\n Args:\n flags: An argparse.Namespace containing TensorBoard CLI flags.\n plugin_loaders: A list of TBLoader instances.\n assets_zip_provider: See TBContext documentation for more information.\n\n Returns:\n The new TensorBoard ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.