INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
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 parameter "tag" is required', 'text/plain', 400) if run is None...
Returns the plugin if possible.
def load(self, context): """Returns the plugin, if possible. Args: context: The TBContext flags. Returns: A ProfilePlugin instance or None if it couldn't be loaded. """ try: # pylint: disable=g-import-not-at-top,unused-import import tensorflow # Available in TensorFlo...
Create a Keras model with the given hyperparameters.
def model_fn(hparams, seed): """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. ""...
Run a training/ validation session.
def run(data, base_logdir, session_id, group_id, hparams): """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 ...
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.
def run_all(logdir, verbose=False): """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. """ data = prepare_data() rng...
Sample a value uniformly from a domain.
def sample_uniform(domain, rng): """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 domai...
A route that returns a JSON mapping between runs and PR curve data.
def pr_curves_route(self, request): """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 ...
Creates the JSON object for the PR curves response for a run - tag combo.
def pr_curves_impl(self, runs, tag): """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. Retu...
Creates 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: # Read tags from the database. db = self._db_connection_provider() cursor = db.execute(''' SELECT ...
Creates 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 available time entries route response. """ result = {} if self._db_connection_provider: db = self._db_connection_provider() # For each ...
Determines 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 TensorBoard. Returns: Whether this plugin is active. """ if self._db_connection_provider: # The plugin is active if one relevant tag can be found in the data...
Converts a TensorEvent into a dict that encapsulates information on it.
def _process_tensor_event(self, event, thresholds): """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 ...
Creates an entry for PR curve data. Each entry corresponds to 1 step.
def _make_pr_entry(self, step, wall_time, data_array, thresholds): """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 fl...
Normalize a dict keyed by HParam s and/ or raw strings.
def _normalize_hparams(hparams): """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 `di...
Create a top - level experiment summary describing this experiment.
def summary_pb(self): """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. ...
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 shifting mean mean_moving_normal = tf.random.normal(shape=[100...
Parses and asserts a positive ( > 0 ) integer query parameter.
def _parse_positive_int_param(request, param_name): """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. """ param = request.args.get(par...
Adds a named column of metadata values.
def add_column(self, column_name, column_values): """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: ...
Determines whether this plugin is active.
def is_active(self): """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. """ if not self.multiplexer: return False if self._is_active: # We have already det...
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 work, # treating the `logdir` as the model checkpoint...
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. with self._accumulators_mutex: items = li...
Retrieve the histogram events associated with a run and tag.
def Histograms(self, run, tag): """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 a...
Retrieve the compressed histogram events associated with a run and tag.
def CompressedHistograms(self, run, tag): """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...
Retrieve the image events associated with a run and tag.
def Images(self, run, tag): """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...
Write a histogram summary.
def histogram(name, data, step=None, buckets=None, description=None): """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`. st...
Create a histogram summary protobuf.
def histogram_pb(tag, data, buckets=None, description=None): """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 ...
Makes recommended modifications to the environment.
def setup_environment(): """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. """ absl.logging.set_verbosity(absl.logging.WARNING) # The default ...
Opens stock TensorBoard web assets collection.
def get_default_assets_zip_provider(): """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 close...
Create a server factory that performs port scanning.
def with_port_scanning(cls): """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...
Configures TensorBoard behavior via flags.
def configure(self, argv=('',), **kwargs): """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: ...
Blocking main function for TensorBoard.
def main(self, ignored_argv=('',)): """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. Requir...
Python API for launching TensorBoard.
def launch(self): """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 """ # Make it easy...
Write a TensorBoardInfo file and arrange for its cleanup.
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.urlparse(server.get_url()) info = manager.TensorBoardInfo( version=version.VERSION, start_time=int(ti...
Set a signal handler to gracefully exit on the given signal.
def _install_signal_handler(self, signal_number, signal_name): """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 ...
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, self.assets_zip_provider) return self.se...
Returns a wildcard address for the port in question.
def _get_wildcard_address(self, port): """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 f...
Override to enable IPV4 mapping for IPV6 sockets when desired.
def server_bind(self): """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...
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. For # example, `curl -N http://localhost...
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, name='process_name', args=dict(name=device.name...
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.0) if event.duration_ps: result['ph'] = _TYPE_COMPLETE ...
Create a legacy scalar summary op.
def op(name, data, display_name=None, description=None, collections=None): """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: ...
Create a legacy scalar summary protobuf.
def pb(name, data, display_name=None, description=None): """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_...
Creates temp symlink tree runs program and copies back outputs.
def run(inputs, program, outputs): """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 la...
Invokes run function using a JSON file config.
def main(args): """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 non...
Initializes the TensorBoard sqlite schema using the given connection.
def initialize_schema(connection): """Initializes the TensorBoard sqlite schema using the given connection. Args: connection: A sqlite DB connection. """ cursor = connection.cursor() cursor.execute("PRAGMA application_id={}".format(_TENSORBOARD_APPLICATION_ID)) cursor.execute("PRAGMA user_version={}".f...
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 Users WHERE user_name = ?', (user_name,)) row ...
Returns the ID for the given experiment creating the row if needed.
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. """ user_id = self._maybe_init_user() cursor = self._db.cursor() cursor.execute( """ SELECT experiment_id F...
Returns the ID for the given run creating the row if needed.
def _maybe_init_run(self, experiment_name, run_name): """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. """ experiment_id = self._maybe_init_experiment(experiment_name) cursor = self._db...
Returns a tag - to - ID map for the given tags creating rows if needed.
def _maybe_init_tags(self, run_id, tag_to_metadata): """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. """ cursor = self._db.cursor() # TODO...
Transactionally writes the given tagged summary data to the DB.
def write_summaries(self, tagged_data, experiment_name, run_name): """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. """ logger.debug('Writing summaries f...
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: if verbose: logger.info("--- Downloading image.") wi...
Perform a 2D pixel convolution on the given image.
def convolve(image, pixel_filter, channels=3, name=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. pix...
Get the image as a TensorFlow variable.
def get_image(verbose=False): """Get the image as a TensorFlow variable. Returns: A `tf.Variable`, which must be initialized prior to use: invoke `sess.run(result.initializer)`.""" base_data = tf.constant(image_data(verbose=verbose)) base_image = tf.image.decode_image(base_data, channels=3) base_imag...
Run a box - blur - to - Gaussian - blur demonstration.
def run_box_to_gaussian(logdir, verbose=False): """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. """ if verbose: logger.info('--- Starting run:...
Run a Sobel edge detection demonstration.
def run_sobel(logdir, verbose=False): """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. """ if verbose: logger.info('--- Starting run: sobel') tf....
Run simulations on a reasonable set of parameters.
def run_all(logdir, verbose=False): """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 """ run_box_to_gaussian(logdir, verbose=verbose) run_sobel(logdir, verbose=verbose...
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 example proto.'.format(feature_name)) feature_type = feature.WhichOne...
Returns an OriginalFeatureList for the specified feature_name.
def parse_original_feature_from_example(example, feature_name): """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. """ feature = get_exampl...
Returns packaged inference results from the provided proto.
def wrap_inference_results(inference_result_proto): """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. """ inference_proto = inference_pb2.I...
Returns a list of feature names for float and int64 type features.
def get_numeric_feature_names(example): """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. """ numeric_features = ('float_list', 'int64_list') features = get_example_features(example) retur...
Returns a list of feature names for byte type features.
def get_categorical_feature_names(example): """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'] ) """ features = get_example_features(example) return sorted([ feature_name for...
Returns numerical features and their observed ranges.
def get_numeric_features_to_observed_range(examples): """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. """ observed_featu...
Returns categorical features and a sampling of their most - common values.
def get_categorical_features_to_sampling(examples, top_k): """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: ...
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_mutants = viz_params.num_mutants if original_feature.feature_type == 'flo...
Return a list of MutantFeatureValue s and a list of mutant Examples.
def make_mutant_tuples(example_protos, original_feature, index_to_mutate, viz_params): """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 ...
Returns JSON formatted for rendering all charts for a feature.
def mutant_charts_for_feature(example_protos, feature_name, serving_bundles, viz_params): """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: ...
Returns JSON formatted for a single mutant chart.
def make_json_formatted_for_single_chart(mutant_features, inference_result_proto, index_to_mutate): """Returns JSON formatted for a single mutant chart. Args: mutant_features: An iterable of `MutantFeatureValue`s representing the...
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_format.MessageToJson( inferences, including_def...
Returns a list of JSON objects for each feature in the examples.
def get_eligible_features(examples, num_mutants): """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...
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.NotFoundError as err: tf.logging.error('error reading vocab fi...
Returns an encoded sprite image for use in Facets Dive.
def create_sprite_image(examples): """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 generate_image_from_thubnails(thumbnails, thumbnail_dims): """Generates a sprite ...
Run inference on examples given model information
def run_inference(examples, serving_bundle): """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 ClassificationRespo...
Return items associated with given key.
def Items(self, key): """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. """ with self._mutex: if key ...
Add a new item to the Reservoir with the given tag.
def AddItem(self, key, item, f=lambda x: x): """Add a new item to the Reservoir with the given tag. If the reservoir has not yet reached full size, the new item is guaranteed to be added. If the reservoir is full, then behavior depends on the always_keep_last boolean. If always_keep_last was set t...
Filter items within a Reservoir using a filtering function.
def FilterItems(self, filterFn, key=None): """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 num...
Add an item to the ReservoirBucket replacing an old item if necessary.
def AddItem(self, item, f=lambda x: x): """Add an item to the ReservoirBucket, replacing an old item if necessary. The new item is guaranteed to be added to the bucket, and to be the last element in the bucket. If the bucket has reached capacity, then an old item will be replaced. With probability (_ma...
Filter items in a ReservoirBucket using a filtering function.
def FilterItems(self, filterFn): """Filter items in a ReservoirBucket, using a filtering function. Filtering items from the reservoir bucket must update the internal state variable self._num_items_seen, which is used for determining the rate of replacement in reservoir sampling. Ideally, self._num_item...
Returns the inferred dense dimensions of a list of lists.
def _GetDenseDimensions(list_of_lists): """Returns the inferred dense dimensions of a 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])
Create a TensorProto.
def make_tensor_proto(values, dtype=None, shape=None, verify_shape=False): """Create a TensorProto. Args: values: Values to put in the TensorProto. dtype: Optional tensor_pb2 DataType value. shape: List of integers representing the dimensions of tensor. verify_shape: B...
Create a numpy ndarray from a tensor.
def make_ndarray(tensor): """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. """ shape = [d.size fo...
Creates a summary that contains a layout.
def op(scalars_layout, collections=None): """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. ...
Creates a summary that contains a layout.
def pb(scalars_layout): """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 summ...
Returns true if other is convertible with this Dimension.
def is_convertible_with(self, other): """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. Retur...
Returns a Dimension that combines the information in self and other.
def merge_with(self, other): """Returns a Dimension that combines the information in `self` and `other`. Dimensions are combined as follows: ```python tf.Dimension(n) .merge_with(tf.Dimension(n)) == tf.Dimension(n) tf.Dimension(n) .merge_with(tf.Dimension(None)) == tf.Di...
Returns the rank of this shape or None if it is unspecified.
def ndims(self): """Returns the rank of this shape, or None if it is unspecified.""" if self._dims is None: return None else: if self._ndims is None: self._ndims = len(self._dims) return self._ndims
Returns the total number of elements or none for incomplete shapes.
def num_elements(self): """Returns the total number of elements, or none for incomplete shapes.""" if self.is_fully_defined(): size = 1 for dim in self._dims: size *= dim.value return size else: return None
Returns a TensorShape combining the information in self and other.
def merge_with(self, other): """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`. Retu...
Returns the concatenation of the dimension in self and other.
def concatenate(self, other): """Returns the concatenation of the dimension in `self` and `other`. *N.B.* If either `self` or `other` is completely unknown, concatenation will discard information about the other shape. In future, we might support concatenation that preserves this ...
Raises an exception if self and other do not have convertible ranks.
def assert_same_rank(self, other): """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. """ other = a...
Returns a shape based on self with the given rank.
def with_rank(self, rank): """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....
Returns a shape based on self with at least the given rank.
def with_rank_at_least(self, rank): """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...
Returns a shape based on self with at most the given rank.
def with_rank_at_most(self, rank): """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 no...
Returns True iff self is convertible with other.
def is_convertible_with(self, other): """Returns True iff `self` is convertible with `other`. Two possibly-partially-defined shapes are convertible if there exists a fully-defined shape that both shapes can represent. Thus, convertibility allows the shape inference code to reason about ...
Returns the most specific TensorShape convertible with self and other.
def most_specific_convertible_shape(self, other): """Returns the most specific TensorShape convertible with `self` and `other`. * TensorShape([None, 1]) is the most specific TensorShape convertible with both TensorShape([2, 1]) and TensorShape([5, 1]). Note that TensorShape(None) is...
Returns True iff self is fully defined in every dimension.
def is_fully_defined(self): """Returns True iff `self` is fully defined in every dimension.""" return self._dims is not None and all( dim.value is not None for dim in self._dims )
Returns a list of integers or None for each dimension.
def as_list(self): """Returns a list of integers or `None` for each dimension. Returns: A list of integers or `None` for each dimension. Raises: ValueError: If `self` is an unknown shape with an unknown rank. """ if self._dims is None: raise Valu...
Returns this shape as a TensorShapeProto.
def as_proto(self): """Returns this shape as a `TensorShapeProto`.""" if self._dims is None: return tensor_shape_pb2.TensorShapeProto(unknown_rank=True) else: return tensor_shape_pb2.TensorShapeProto( dim=[ tensor_shape_pb2.TensorShapeP...