Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def run_all(logdir, steps, thresholds, verbose=False): # First, we generate data for a PR curve that assigns even weights for # predictions of all classes. run_name = 'colors' if verbose: print('--- Running: %s' % run_name) start_runs( logdir=logdir, ...
[ "Generate PR curve summaries.\n\n Arguments:\n logdir: The directory into which to store all the runs' data.\n steps: The number of steps to run for.\n verbose: Whether to print the names of runs into stdout during execution.\n thresholds: The number of thresholds to use for PR curves.\n " ]
Please provide a description of the function:def image(name, data, step=None, max_outputs=3, description=None): summary_metadata = metadata.create_summary_metadata( display_name=None, description=description) # TODO(https://github.com/tensorflow/tensorboard/issues/21...
[ "Write an image summary.\n\n Arguments:\n name: A name for this summary. The summary tag used for TensorBoard will\n be this name prefixed by any active name scopes.\n data: 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...
Please provide a description of the function:def set_examples(self, examples): self.store('examples', examples) if len(examples) > 0: self.store('are_sequence_examples', isinstance(examples[0], tf.train.SequenceExample)) return self
[ "Sets the examples to be displayed in WIT.\n\n Args:\n examples: List of example protos.\n\n Returns:\n self, in order to enabled method chaining.\n " ]
Please provide a description of the function:def set_estimator_and_feature_spec(self, estimator, feature_spec): # If custom function is set, remove it before setting estimator self.delete('custom_predict_fn') self.store('estimator_and_spec', { 'estimator': estimator, 'feature_spec': feature_spec...
[ "Sets the model for inference as a TF Estimator.\n\n Instead of using TF Serving to host a model for WIT to query, WIT can\n directly use a TF Estimator object as the model to query. In order to\n accomplish this, a feature_spec must also be provided to parse the\n example protos for input into the esti...
Please provide a description of the function:def set_compare_estimator_and_feature_spec(self, estimator, feature_spec): # If custom function is set, remove it before setting estimator self.delete('compare_custom_predict_fn') self.store('compare_estimator_and_spec', { 'estimator': estimator, 'fea...
[ "Sets a second model for inference as a TF Estimator.\n\n If you wish to compare the results of two models in WIT, use this method\n to setup the details of the second model.\n\n Instead of using TF Serving to host a model for WIT to query, WIT can\n directly use a TF Estimator object as the model to qu...
Please provide a description of the function:def set_custom_predict_fn(self, predict_fn): # If estimator is set, remove it before setting predict_fn self.delete('estimator_and_spec') self.store('custom_predict_fn', predict_fn) self.set_inference_address('custom_predict_fn') # If no model name ...
[ "Sets a custom function for inference.\n\n Instead of using TF Serving to host a model for WIT to query, WIT can\n directly use a custom function as the model to query. In this case, the\n provided function should accept example protos and return:\n - For classification: A 2D list of numbers. The firs...
Please provide a description of the function:def set_compare_custom_predict_fn(self, predict_fn): # If estimator is set, remove it before setting predict_fn self.delete('compare_estimator_and_spec') self.store('compare_custom_predict_fn', predict_fn) self.set_compare_inference_address('custom_pred...
[ "Sets a second custom function for inference.\n\n If you wish to compare the results of two models in WIT, use this method\n to setup the details of the second model.\n\n Instead of using TF Serving to host a model for WIT to query, WIT can\n directly use a custom function as the model to query. In this...
Please provide a description of the function:def _reshape_conv_array(self, array, section_height, image_width): '''Reshape a rank 4 array to be rank 2, where each column of block_width is a filter, and each row of block height is an input channel. For example: [[[[ 11, 21, 31, 41], [ 51, 61, 71...
[]
Please provide a description of the function:def _reshape_irregular_array(self, array, section_height, image_width): '''Reshapes arrays of ranks not in {1, 2, 4} ''' section_area = section_height * image_width flattened_array = np.ravel(array) if not self.config['show_all']: flattened_array =...
[]
Please provide a description of the function:def _arrays_to_sections(self, arrays): ''' input: unprocessed numpy arrays. returns: columns of the size that they will appear in the image, not scaled for display. That needs to wait until after variance is computed. ''' sections = [] se...
[]
Please provide a description of the function:def _sections_to_variance_sections(self, sections_over_time): '''Computes the variance of corresponding sections over time. Returns: a list of np arrays. ''' variance_sections = [] for i in range(len(sections_over_time[0])): time_sections = ...
[]
Please provide a description of the function:def _maybe_clear_deque(self): '''Clears the deque if certain parts of the config have changed.''' for config_item in ['values', 'mode', 'show_all']: if self.config[config_item] != self.old_config[config_item]: self.sections_over_time.clear() br...
[]
Please provide a description of the function:def lazy_load(name): def wrapper(load_fn): # Wrap load_fn to call it exactly once and update __dict__ afterwards to # make future lookups efficient (only failed lookups call __getattr__). @_memoize def load_once(self): if load_once.loading: ...
[ "Decorator to define a function that lazily loads the module 'name'.\n\n This can be used to defer importing troublesome dependencies - e.g. ones that\n are large and infrequently used, or that cause a dependency cycle -\n until they are actually used.\n\n Args:\n name: the fully-qualified name of the module...
Please provide a description of the function:def _memoize(f): nothing = object() # Unique "no value" sentinel object. cache = {} # Use a reentrant lock so that if f references the resulting wrapper we die # with recursion depth exceeded instead of deadlocking. lock = threading.RLock() @functools.wraps(f...
[ "Memoizing decorator for f, which must have exactly 1 hashable argument." ]
Please provide a description of the function:def tf(): try: from tensorboard.compat import notf # pylint: disable=g-import-not-at-top except ImportError: try: import tensorflow # pylint: disable=g-import-not-at-top return tensorflow except ImportError: pass from tensorboard.comp...
[ "Provide the root module of a TF-like API for use within TensorBoard.\n\n By default this is equivalent to `import tensorflow as tf`, but it can be used\n in combination with //tensorboard/compat:tensorflow (to fall back to a stub TF\n API implementation if the real one is not available) or with\n //tensorboard...
Please provide a description of the function:def tf2(): # Import the `tf` compat API from this file and check if it's already TF 2.0. if tf.__version__.startswith('2.'): return tf elif hasattr(tf, 'compat') and hasattr(tf.compat, 'v2'): # As a fallback, try `tensorflow.compat.v2` if it's defined. r...
[ "Provide the root module of a TF-2.0 API for use within TensorBoard.\n\n Returns:\n The root module of a TF-2.0 API, if available.\n\n Raises:\n ImportError: if a TF-2.0 API is not available.\n " ]
Please provide a description of the function:def _pywrap_tensorflow(): try: from tensorboard.compat import notf # pylint: disable=g-import-not-at-top except ImportError: try: from tensorflow.python import pywrap_tensorflow # pylint: disable=g-import-not-at-top return pywrap_tensorflow e...
[ "Provide pywrap_tensorflow access in TensorBoard.\n\n pywrap_tensorflow cannot be accessed from tf.python.pywrap_tensorflow\n and needs to be imported using\n `from tensorflow.python import pywrap_tensorflow`. Therefore, we provide\n a separate accessor function for it here.\n\n NOTE: pywrap_tensorflow is not ...
Please provide a description of the function:def create_experiment_summary(): # Convert TEMPERATURE_LIST to google.protobuf.ListValue temperature_list = struct_pb2.ListValue() temperature_list.extend(TEMPERATURE_LIST) materials = struct_pb2.ListValue() materials.extend(HEAT_COEFFICIENTS.keys()) return s...
[ "Returns a summary proto buffer holding this experiment." ]
Please provide a description of the function:def run(logdir, session_id, hparams, group_name): tf.reset_default_graph() tf.set_random_seed(0) initial_temperature = hparams['initial_temperature'] ambient_temperature = hparams['ambient_temperature'] heat_coefficient = HEAT_COEFFICIENTS[hparams['material']] ...
[ "Runs a temperature simulation.\n\n This will simulate an object at temperature `initial_temperature`\n sitting at rest in a large room at temperature `ambient_temperature`.\n The object has some intrinsic `heat_coefficient`, which indicates\n how much thermal conductivity it has: for instance, metals have high...
Please provide a description of the function:def run_all(logdir, verbose=False): writer = tf.summary.FileWriter(logdir) writer.add_summary(create_experiment_summary()) writer.close() session_num = 0 num_sessions = (len(TEMPERATURE_LIST)*len(TEMPERATURE_LIST)* len(HEAT_COEFFICIENTS)*2) f...
[ "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 get_filesystem(filename): filename = compat.as_str_any(filename) prefix = "" index = filename.find("://") if index >= 0: prefix = filename[:index] fs = _REGISTERED_FILESYSTEMS.get(prefix, None) if fs is None: raise ValueError(...
[ "Return the registered filesystem for the given file." ]
Please provide a description of the function:def walk(top, topdown=True, onerror=None): top = compat.as_str_any(top) fs = get_filesystem(top) try: listing = listdir(top) except errors.NotFoundError as err: if onerror: onerror(err) else: return fi...
[ "Recursive directory tree generator for directories.\n\n Args:\n top: string, a Directory name\n topdown: bool, Traverse pre order if True, post order if False.\n onerror: optional handler for errors. Should be a function, it will be\n called with the error as argument. Rethrowing the error...
Please provide a description of the function:def read(self, filename, binary_mode=False, size=None, offset=None): mode = "rb" if binary_mode else "r" with io.open(filename, mode) as f: if offset is not None: f.seek(offset) if size is not None: ...
[ "Reads contents of a file to a string.\n\n Args:\n filename: string, a path\n binary_mode: bool, read as binary if True, otherwise text\n size: int, number of bytes or characters to read, otherwise\n read all the contents of the file from the offset\n ...
Please provide a description of the function:def glob(self, filename): if isinstance(filename, six.string_types): return [ # Convert the filenames to string from bytes. compat.as_str_any(matching_filename) for matching_filename in py_glob.glob...
[ "Returns a list of files that match the given pattern(s)." ]
Please provide a description of the function:def listdir(self, dirname): if not self.isdir(dirname): raise errors.NotFoundError(None, None, "Could not find directory") entries = os.listdir(compat.as_str_any(dirname)) entries = [compat.as_str_any(item) for item in entries] ...
[ "Returns a list of entries contained within a directory." ]
Please provide a description of the function:def stat(self, filename): # NOTE: Size of the file is given by .st_size as returned from # os.stat(), but we convert to .length try: len = os.stat(compat.as_bytes(filename)).st_size except OSError: raise errors...
[ "Returns file statistics for a given path." ]
Please provide a description of the function:def bucket_and_path(self, url): url = compat.as_str_any(url) if url.startswith("s3://"): url = url[len("s3://"):] idx = url.index("/") bucket = url[:idx] path = url[(idx + 1):] return bucket, path
[ "Split an S3-prefixed URL into bucket and path." ]
Please provide a description of the function:def exists(self, filename): client = boto3.client("s3") bucket, path = self.bucket_and_path(filename) r = client.list_objects(Bucket=bucket, Prefix=path, Delimiter="/") if r.get("Contents") or r.get("CommonPrefixes"): retu...
[ "Determines whether a path exists or not." ]
Please provide a description of the function:def read(self, filename, binary_mode=False, size=None, offset=None): s3 = boto3.resource("s3") bucket, path = self.bucket_and_path(filename) args = {} endpoint = 0 if size is not None or offset is not None: if offs...
[ "Reads contents of a file to a string.\n\n Args:\n filename: string, a path\n binary_mode: bool, read as binary if True, otherwise text\n size: int, number of bytes or characters to read, otherwise\n read all the contents of the file from the offset\n ...
Please provide a description of the function:def glob(self, filename): # Only support prefix with * at the end and no ? in the string star_i = filename.find('*') quest_i = filename.find('?') if quest_i >= 0: raise NotImplementedError( "{} not supporte...
[ "Returns a list of files that match the given pattern(s)." ]
Please provide a description of the function:def isdir(self, dirname): client = boto3.client("s3") bucket, path = self.bucket_and_path(dirname) if not path.endswith("/"): path += "/" # This will now only retrieve subdir content r = client.list_objects(Bucket=bucket,...
[ "Returns whether the path is a directory or not." ]
Please provide a description of the function:def listdir(self, dirname): client = boto3.client("s3") bucket, path = self.bucket_and_path(dirname) p = client.get_paginator("list_objects") if not path.endswith("/"): path += "/" # This will now only retrieve subdir con...
[ "Returns a list of entries contained within a directory." ]
Please provide a description of the function:def stat(self, filename): # NOTE: Size of the file is given by ContentLength from S3, # but we convert to .length client = boto3.client("s3") bucket, path = self.bucket_and_path(filename) try: obj = client.head_obj...
[ "Returns file statistics for a given path." ]
Please provide a description of the function:def _get_context(): # In Colab, the `google.colab` module is available, but the shell # returned by `IPython.get_ipython` does not have a `get_trait` # method. try: import google.colab import IPython except ImportError: pass else: if IPython.ge...
[ "Determine the most specific context that we're in.\n\n Returns:\n _CONTEXT_COLAB: If in Colab with an IPython notebook context.\n _CONTEXT_IPYTHON: If not in Colab, but we are in an IPython notebook\n context (e.g., from running `jupyter notebook` at the command\n line).\n _CONTEXT_NONE: Otherw...
Please provide a description of the function:def start(args_string): context = _get_context() try: import IPython import IPython.display except ImportError: IPython = None if context == _CONTEXT_NONE: handle = None print("Launching TensorBoard...") else: handle = IPython.display.di...
[ "Launch and display a TensorBoard instance as if at the command line.\n\n Args:\n args_string: Command-line arguments to TensorBoard, to be\n interpreted by `shlex.split`: e.g., \"--logdir ./logs --port 0\".\n Shell metacharacters are not supported: e.g., \"--logdir 2>&1\" will\n point the logdir...
Please provide a description of the function:def _time_delta_from_info(info): delta_seconds = int(time.time()) - info.start_time return str(datetime.timedelta(seconds=delta_seconds))
[ "Format the elapsed time for the given TensorBoardInfo.\n\n Args:\n info: A TensorBoardInfo value.\n\n Returns:\n A human-readable string describing the time since the server\n described by `info` started: e.g., \"2 days, 0:48:58\".\n " ]
Please provide a description of the function:def display(port=None, height=None): _display(port=port, height=height, print_message=True, display_handle=None)
[ "Display a TensorBoard instance already running on this machine.\n\n Args:\n port: The port on which the TensorBoard server is listening, as an\n `int`, or `None` to automatically select the most recently\n launched TensorBoard.\n height: The height of the frame into which to render the TensorBoard...
Please provide a description of the function:def _display(port=None, height=None, print_message=False, display_handle=None): if height is None: height = 800 if port is None: infos = manager.get_all() if not infos: raise ValueError("Can't display TensorBoard: no known instances running.") e...
[ "Internal version of `display`.\n\n Args:\n port: As with `display`.\n height: As with `display`.\n print_message: True to print which TensorBoard instance was selected\n for display (if applicable), or False otherwise.\n display_handle: If not None, an IPython display handle into which to\n ...
Please provide a description of the function:def _display_colab(port, height, display_handle): import IPython.display shell = .replace("%PORT%", "%d" % port).replace("%HEIGHT%", "%d" % height) html = IPython.display.HTML(shell) if display_handle: display_handle.update(html) else: IPython.display.di...
[ "Display a TensorBoard instance in a Colab output frame.\n\n The Colab VM is not directly exposed to the network, so the Colab\n runtime provides a service worker tunnel to proxy requests from the\n end user's browser through to servers running on the Colab VM: the\n output frame may issue requests to https://l...
Please provide a description of the function:def list(): infos = manager.get_all() if not infos: print("No known TensorBoard instances running.") return print("Known TensorBoard instances:") for info in infos: template = " - port {port}: {data_source} (started {delta} ago; pid {pid})" print...
[ "Print a listing of known running TensorBoard instances.\n\n TensorBoard instances that were killed uncleanly (e.g., with SIGKILL\n or SIGQUIT) may appear in this list even if they are no longer\n running. Conversely, this list may be missing some entries if your\n operating system's temporary directory has bee...
Please provide a description of the function:def IsTensorFlowEventsFile(path): if not path: raise ValueError('Path must be a nonempty string') return 'tfevents' in tf.compat.as_str_any(os.path.basename(path))
[ "Check the path name to see if it is probably a TF Events file.\n\n Args:\n path: A file path to check if it is an event file.\n\n Raises:\n ValueError: If the path is an empty string.\n\n Returns:\n If path is formatted like a TensorFlowEventsFile.\n " ]
Please provide a description of the function:def ListDirectoryAbsolute(directory): return (os.path.join(directory, path) for path in tf.io.gfile.listdir(directory))
[ "Yields all files in the given directory. The paths are absolute." ]
Please provide a description of the function:def _EscapeGlobCharacters(path): drive, path = os.path.splitdrive(path) return '%s%s' % (drive, _ESCAPE_GLOB_CHARACTERS_REGEX.sub(r'[\1]', path))
[ "Escapes the glob characters in a path.\n\n Python 3 has a glob.escape method, but python 2 lacks it, so we manually\n implement this method.\n\n Args:\n path: The absolute path to escape.\n\n Returns:\n The escaped path string.\n " ]
Please provide a description of the function:def ListRecursivelyViaGlobbing(top): current_glob_string = os.path.join(_EscapeGlobCharacters(top), '*') level = 0 while True: logger.info('GlobAndListFiles: Starting to glob level %d', level) glob = tf.io.gfile.glob(current_glob_string) logger.info( ...
[ "Recursively lists all files within the directory.\n\n This method does not list subdirectories (in addition to regular files), and\n the file paths are all absolute. If the directory does not exist, this yields\n nothing.\n\n This method does so by glob-ing deeper and deeper directories, ie\n foo/*, foo/*/*, ...
Please provide a description of the function:def ListRecursivelyViaWalking(top): for dir_path, _, filenames in tf.io.gfile.walk(top, topdown=True): yield (dir_path, (os.path.join(dir_path, filename) for filename in filenames))
[ "Walks a directory tree, yielding (dir_path, file_paths) tuples.\n\n For each of `top` and its subdirectories, yields a tuple containing the path\n to the directory and the path to each of the contained files. Note that\n unlike os.Walk()/tf.io.gfile.walk()/ListRecursivelyViaGlobbing, this does not\n list subd...
Please provide a description of the function:def GetLogdirSubdirectories(path): if not tf.io.gfile.exists(path): # No directory to traverse. return () if not tf.io.gfile.isdir(path): raise ValueError('GetLogdirSubdirectories: path exists and is not a ' 'directory, %s' % path) ...
[ "Obtains all subdirectories with events files.\n\n The order of the subdirectories returned is unspecified. The internal logic\n that determines order varies by scenario.\n\n Args:\n path: The path to a directory under which to find subdirectories.\n\n Returns:\n A tuple of absolute paths of all subdirect...
Please provide a description of the function:def audio(name, data, sample_rate, step=None, max_outputs=3, encoding=None, description=None): audio_ops = getattr(tf, 'audio', None) if audio_ops is None: # Fallback for older versions of TF without tf.a...
[ "Write an audio summary.\n\n Arguments:\n name: A name for this summary. The summary tag used for TensorBoard will\n be this name prefixed by any active name scopes.\n data: A `Tensor` representing audio data with shape `[k, t, c]`,\n where `k` is the number of audio clips, `t` is the number of\n ...
Please provide a description of the function:def extract_numerics_alert(event): value = event.summary.value[0] debugger_plugin_metadata_content = None if value.HasField("metadata"): plugin_data = value.metadata.plugin_data if plugin_data.plugin_name == constants.DEBUGGER_PLUGIN_NAME: debugger_plu...
[ "Determines whether a health pill event contains bad values.\n\n A bad value is one of NaN, -Inf, or +Inf.\n\n Args:\n event: (`Event`) A `tensorflow.Event` proto from `DebugNumericSummary`\n ops.\n\n Returns:\n An instance of `NumericsAlert`, if bad values are found.\n `None`, if no bad values are...
Please provide a description of the function:def first_timestamp(self, event_key=None): if event_key is None: timestamps = [self._trackers[key].first_timestamp for key in self._trackers] return min(timestamp for timestamp in timestamps if timestamp >= 0) else: return s...
[ "Obtain the first timestamp.\n\n Args:\n event_key: the type key of the sought events (e.g., constants.NAN_KEY).\n If None, includes all event type keys.\n\n Returns:\n First (earliest) timestamp of all the events of the given type (or all\n event types if event_key is None).\n " ]
Please provide a description of the function:def last_timestamp(self, event_key=None): if event_key is None: timestamps = [self._trackers[key].first_timestamp for key in self._trackers] return max(timestamp for timestamp in timestamps if timestamp >= 0) else: return se...
[ "Obtain the last timestamp.\n\n Args:\n event_key: the type key of the sought events (e.g., constants.NAN_KEY). If\n None, includes all event type keys.\n\n Returns:\n Last (latest) timestamp of all the events of the given type (or all\n event types if event_key is None).\n " ]
Please provide a description of the function:def create_jsonable_history(self): return {value_category_key: tracker.get_description() for (value_category_key, tracker) in self._trackers.items()}
[ "Creates a JSON-able representation of this object.\n\n Returns:\n A dictionary mapping key to EventTrackerDescription (which can be used to\n create event trackers).\n " ]
Please provide a description of the function:def register(self, numerics_alert): key = (numerics_alert.device_name, numerics_alert.tensor_name) if key in self._data: self._data[key].add(numerics_alert) else: if len(self._data) < self._capacity: history = NumericsAlertHistory() ...
[ "Register an alerting numeric event.\n\n Args:\n numerics_alert: An instance of `NumericsAlert`.\n " ]
Please provide a description of the function:def report(self, device_name_filter=None, tensor_name_filter=None): report = [] for key in self._data: device_name, tensor_name = key history = self._data[key] report.append( NumericsAlertReportRow( device_name=device_na...
[ "Get a report of offending device/tensor names.\n\n The report includes information about the device name, tensor name, first\n (earliest) timestamp of the alerting events from the tensor, in addition to\n counts of nan, positive inf and negative inf events.\n\n Args:\n device_name_filter: regex fi...
Please provide a description of the function:def create_jsonable_registry(self): # JSON does not support tuples as keys. Only strings. Therefore, we store # the device name, tensor name, and dictionary data within a 3-item list. return [HistoryTriplet(pair[0], pair[1], history.create_jsonable_history()...
[ "Creates a JSON-able representation of this object.\n\n Returns:\n A dictionary mapping (device, tensor name) to JSON-able object\n representations of NumericsAlertHistory.\n " ]
Please provide a description of the function:def run(logdir, run_name, wave_name, wave_constructor): tf.compat.v1.reset_default_graph() tf.compat.v1.set_random_seed(0) # On each step `i`, we'll set this placeholder to `i`. This allows us # to know "what time it is" at each step. step_placeholder = tf.comp...
[ "Generate wave data of the given form.\n\n The provided function `wave_constructor` should accept a scalar tensor\n of type float32, representing the frequency (in Hz) at which to\n construct a wave, and return a tensor of shape [1, _samples(), `n`]\n representing audio data (for some number of channels `n`).\n...
Please provide a description of the function:def sine_wave(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 sine wave at the given frequency." ]
Please provide a description of the function:def triangle_wave(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 a triangle wave at the given frequency." ]
Please provide a description of the function:def bisine_wave(frequency): # # 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_wave(f_hi) with tf.name_scope('lo'): sine_lo = sine_wave(f_lo...
[ "Emit two sine waves, in stereo at different octaves." ]
Please provide a description of the function:def bisine_wahwah_wave(frequency): # # This is clearly intended to build on the bisine wave defined above, # so we can start by generating that. waves_a = bisine_wave(frequency) # # Then, by reversing axis 2, we swap the stereo channels. By mixing # this wit...
[ "Emit two sine waves with balance oscillating left and right." ]
Please provide a description of the function:def run_all(logdir, verbose=False): waves = [sine_wave, square_wave, triangle_wave, bisine_wave, bisine_wahwah_wave] for (i, wave_constructor) in enumerate(waves): wave_name = wave_constructor.__name__ run_name = 'wave:%02d,%s' % (i + 1, wave_name) ...
[ "Generate waves of the shapes defined above.\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 prepare_graph_for_ui(graph, limit_attr_size=1024, large_attrs_key='_too_large_attrs'): # Check input for validity. if limit_attr_size is not None: if large_attrs_key is None: raise ValueError('large_attrs_key must be != None when...
[ "Prepares (modifies in-place) the graph to be served to the front-end.\n\n For now, it supports filtering out attributes that are\n too large to be shown in the graph UI.\n\n Args:\n graph: The GraphDef proto message.\n limit_attr_size: Maximum allowed size in bytes, before the attribute\n is consid...
Please provide a description of the function:def info_impl(self): result = {} def add_row_item(run, tag=None): run_item = result.setdefault(run, { 'run': run, 'tags': {}, # A run-wide GraphDef of ops. 'run_graph': False}) tag_item = None if tag: ...
[ "Returns a dict of all runs and tags and their data availabilities." ]
Please provide a description of the function:def graph_impl(self, run, tag, is_conceptual, limit_attr_size=None, large_attrs_key=None): if is_conceptual: tensor_events = self._multiplexer.Tensors(run, tag) # Take the first event if there are multiple events written from different # steps. ...
[ "Result of the form `(body, mime_type)`, or `None` if no graph exists." ]
Please provide a description of the function:def run_metadata_impl(self, run, tag): try: run_metadata = self._multiplexer.RunMetadata(run, tag) except ValueError: # TODO(stephanwlee): Should include whether FE is fetching for v1 or v2 RunMetadata # so we can remove this try/except. ...
[ "Result of the form `(body, mime_type)`, or `None` if no data exists." ]
Please provide a description of the function:def graph_route(self, request): run = request.args.get('run') tag = request.args.get('tag', '') conceptual_arg = request.args.get('conceptual', False) is_conceptual = True if conceptual_arg == 'true' else False if run is None: return http_util...
[ "Given a single run, return the graph definition in protobuf format." ]
Please provide a description of the function:def run_metadata_route(self, request): 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: return htt...
[ "Given a tag and a run, return the session.run() metadata." ]
Please provide a description of the function:def load(self, context): try: # pylint: disable=g-import-not-at-top,unused-import import tensorflow # Available in TensorFlow 1.14 or later, so do import check # pylint: disable=g-import-not-at-top,unused-import from tensorflow.python.e...
[ "Returns the plugin, if possible.\n\n Args:\n context: The TBContext flags.\n\n Returns:\n A ProfilePlugin instance or None if it couldn't be loaded.\n " ]
Please provide a description of the function:def model_fn(hparams, seed): rng = random.Random(seed) model = tf.keras.models.Sequential() model.add(tf.keras.layers.Input(INPUT_SHAPE)) model.add(tf.keras.layers.Reshape(INPUT_SHAPE + (1,))) # grayscale channel # Add convolutional layers. conv_filters = 8...
[ "Create a Keras model with the given hyperparameters.\n\n Args:\n hparams: A dict mapping hyperparameters in `HPARAMS` to values.\n seed: A hashable object to be used as a random seed (e.g., to\n construct dropout layers in the model).\n\n Returns:\n A compiled Keras model.\n " ]
Please provide a description of the function:def run(data, base_logdir, session_id, group_id, hparams): model = model_fn(hparams=hparams, seed=session_id) logdir = os.path.join(base_logdir, session_id) callback = tf.keras.callbacks.TensorBoard( logdir, update_freq=flags.FLAGS.summary_freq, p...
[ "Run a training/validation session.\n\n Flags must have been parsed for this function to behave.\n\n Args:\n data: The data as loaded by `prepare_data()`.\n base_logdir: The top-level logdir to which to write summary data.\n session_id: A unique string ID for this session.\n group_id: The string ID of...
Please provide a description of the function:def prepare_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))
[ "Load and normalize data." ]
Please provide a description of the function:def run_all(logdir, verbose=False): data = prepare_data() rng = random.Random(0) base_writer = tf.summary.create_file_writer(logdir) with base_writer.as_default(): experiment = hp.Experiment(hparams=HPARAMS, metrics=METRICS) experiment_string = experiment...
[ "Perform random search over the hyperparameter space.\n\n Arguments:\n logdir: The top-level directory into which to write data. This\n directory should be empty or nonexistent.\n verbose: If true, print out each run's name as it begins.\n " ]
Please provide a description of the function:def sample_uniform(domain, rng): if isinstance(domain, hp.IntInterval): return rng.randint(domain.min_value, domain.max_value) elif isinstance(domain, hp.RealInterval): return rng.uniform(domain.min_value, domain.max_value) elif isinstance(domain, hp.Discret...
[ "Sample a value uniformly from a domain.\n\n Args:\n domain: An `IntInterval`, `RealInterval`, or `Discrete` domain.\n rng: A `random.Random` object; defaults to the `random` module.\n\n Raises:\n TypeError: If `domain` is not a known kind of domain.\n IndexError: If the domain is empty.\n " ]
Please provide a description of the function:def pr_curves_route(self, request): runs = request.args.getlist('run') if not runs: return http_util.Respond( request, 'No runs provided when fetching PR curve data', 400) tag = request.args.get('tag') if not tag: return http_util....
[ "A route that returns a JSON mapping between runs and PR curve data.\n\n Returns:\n Given a tag and a comma-separated list of runs (both stored within GET\n parameters), fetches a JSON object that maps between run name and objects\n containing data required for PR curves for that run. Runs that ei...
Please provide a description of the function:def pr_curves_impl(self, runs, tag): if self._db_connection_provider: # Serve data from the database. db = self._db_connection_provider() # We select for steps greater than -1 because the writer inserts # placeholder rows en masse. The check...
[ "Creates the JSON object for the PR curves response for a run-tag combo.\n\n Arguments:\n runs: A list of runs to fetch the curves for.\n tag: The tag to fetch the curves for.\n\n Raises:\n ValueError: If no PR curves could be fetched for a run and tag.\n\n Returns:\n The JSON object fo...
Please provide a description of the function:def tags_impl(self): if self._db_connection_provider: # Read tags from the database. db = self._db_connection_provider() cursor = db.execute(''' SELECT Tags.tag_name, Tags.display_name, Runs.run_name FR...
[ "Creates the JSON object for the tags route response.\n\n Returns:\n The JSON object for the tags route response.\n " ]
Please provide a description of the function:def available_time_entries_impl(self): result = {} if self._db_connection_provider: db = self._db_connection_provider() # For each run, pick a tag. cursor = db.execute( ''' SELECT TagPickingTable.run_name, ...
[ "Creates the JSON object for the available time entries route response.\n\n Returns:\n The JSON object for the available time entries route response.\n " ]
Please provide a description of the function:def is_active(self): if self._db_connection_provider: # The plugin is active if one relevant tag can be found in the database. db = self._db_connection_provider() cursor = db.execute( ''' SELECT 1 FROM Tags W...
[ "Determines whether this plugin is active.\n\n This plugin is active only if PR curve summary data is read by TensorBoard.\n\n Returns:\n Whether this plugin is active.\n " ]
Please provide a description of the function:def _process_tensor_event(self, event, thresholds): return self._make_pr_entry( event.step, event.wall_time, tensor_util.make_ndarray(event.tensor_proto), thresholds)
[ "Converts a TensorEvent into a dict that encapsulates information on it.\n\n Args:\n event: The TensorEvent to convert.\n thresholds: An array of floats that ranges from 0 to 1 (in that\n direction and inclusive of 0 and 1).\n\n Returns:\n A JSON-able dictionary of PR curve data for 1 st...
Please provide a description of the function:def _make_pr_entry(self, step, wall_time, data_array, thresholds): # Trim entries for which TP + FP = 0 (precision is undefined) at the tail of # the data. true_positives = [int(v) for v in data_array[metadata.TRUE_POSITIVES_INDEX]] false_positives = [ ...
[ "Creates an entry for PR curve data. Each entry corresponds to 1 step.\n\n Args:\n step: The step.\n wall_time: The wall time.\n data_array: A numpy array of PR curve data stored in the summary format.\n thresholds: An array of floating point thresholds.\n\n Returns:\n A PR curve entr...
Please provide a description of the function:def _normalize_hparams(hparams): result = {} for (k, v) in six.iteritems(hparams): if isinstance(k, HParam): k = k.name if k in result: raise ValueError("multiple values specified for hparam %r" % (k,)) result[k] = v return result
[ "Normalize a dict keyed by `HParam`s and/or raw strings.\n\n Args:\n hparams: A `dict` whose keys are `HParam` objects and/or strings\n representing hyperparameter names, and whose values are\n hyperparameter values. No two keys may have the same name.\n\n Returns:\n A `dict` whose keys are hyperp...
Please provide a description of the function:def summary_pb(self): hparam_infos = [] for hparam in self._hparams: info = api_pb2.HParamInfo( name=hparam.name, description=hparam.description, display_name=hparam.display_name, ) domain = hparam.domain if ...
[ "Create a top-level experiment summary describing this experiment.\n\n The resulting summary should be written to a log directory that\n encloses all the individual sessions' log directories.\n\n Analogous to the low-level `experiment_pb` function in the\n `hparams.summary` module.\n " ]
Please provide a description of the function:def run_all(logdir, verbose=False, num_summaries=400): 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=[1000], mean=(5*k), stdd...
[ "Generate a bunch of histogram data, and write it to logdir." ]
Please provide a description of the function:def _parse_positive_int_param(request, param_name): param = request.args.get(param_name) if not param: return None try: param = int(param) if param <= 0: raise ValueError() return param except ValueError: return -1
[ "Parses and asserts a positive (>0) integer query parameter.\n\n Args:\n request: The Werkzeug Request object\n param_name: Name of the parameter.\n\n Returns:\n Param, or None, or -1 if parameter is not a positive integer.\n " ]
Please provide a description of the function:def is_active(self): if not self.multiplexer: return False if self._is_active: # We have already determined that the projector plugin should be active. # Do not re-compute that. We have no reason to later set this plugin to be # inactive...
[ "Determines whether this plugin is active.\n\n This plugin is only active if any run has an embedding.\n\n Returns:\n Whether any run has embedding data to show in the projector.\n " ]
Please provide a description of the function:def configs(self): 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 directory. ...
[ "Returns a map of run paths to `ProjectorConfig` protos." ]
Please provide a description of the function:def Reload(self): 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 = list(...
[ "Call `Reload` on every `EventAccumulator`." ]
Please provide a description of the function:def Histograms(self, run, tag): accumulator = self.GetAccumulator(run) return accumulator.Histograms(tag)
[ "Retrieve the histogram events associated with a run and tag.\n\n Args:\n run: A string name of the run for which values are retrieved.\n tag: A string name of the tag for which values are retrieved.\n\n Raises:\n KeyError: If the run is not found, or the tag is not available for\n the g...
Please provide a description of the function:def CompressedHistograms(self, run, tag): accumulator = self.GetAccumulator(run) return accumulator.CompressedHistograms(tag)
[ "Retrieve the compressed histogram events associated with a run and tag.\n\n Args:\n run: A string name of the run for which values are retrieved.\n tag: A string name of the tag for which values are retrieved.\n\n Raises:\n KeyError: If the run is not found, or the tag is not available for\n ...
Please provide a description of the function:def Images(self, run, tag): accumulator = self.GetAccumulator(run) return accumulator.Images(tag)
[ "Retrieve the image events associated with a run and tag.\n\n Args:\n run: A string name of the run for which values are retrieved.\n tag: A string name of the tag for which values are retrieved.\n\n Raises:\n KeyError: If the run is not found, or the tag is not available for\n the given...
Please provide a description of the function:def histogram(name, data, step=None, buckets=None, description=None): summary_metadata = metadata.create_summary_metadata( display_name=None, description=description) # TODO(https://github.com/tensorflow/tensorboard/issues/2109): remove fallback summary_scope ...
[ "Write a histogram summary.\n\n Arguments:\n name: A name for this summary. The summary tag used for TensorBoard will\n be this name prefixed by any active name scopes.\n data: A `Tensor` of any shape. Must be castable to `float64`.\n step: Explicit `int64`-castable monotonic step value for this summ...
Please provide a description of the function:def histogram_pb(tag, data, buckets=None, description=None): bucket_count = DEFAULT_BUCKET_COUNT if buckets is None else buckets data = np.array(data).flatten().astype(float) if data.size == 0: buckets = np.array([]).reshape((0, 3)) else: min_ = np.min(dat...
[ "Create a histogram summary protobuf.\n\n Arguments:\n tag: String tag for the summary.\n data: A `np.array` or array-like form of any shape. Must have type\n castable to `float`.\n buckets: Optional positive `int`. The output will have this\n many buckets, except in two edge cases. If there is ...
Please provide a description of the function:def setup_environment(): absl.logging.set_verbosity(absl.logging.WARNING) # The default is HTTP/1.0 for some strange reason. If we don't use # HTTP/1.1 then a new TCP socket and Python thread is created for # each HTTP request. The tradeoff is we must always spec...
[ "Makes recommended modifications to the environment.\n\n This functions changes global state in the Python process. Calling\n this function is a good idea, but it can't appropriately be called\n from library routines.\n " ]
Please provide a description of the function:def get_default_assets_zip_provider(): path = os.path.join(os.path.dirname(inspect.getfile(sys._getframe(1))), 'webfiles.zip') if not os.path.exists(path): logger.warning('webfiles.zip static assets not found: %s', path) return None ret...
[ "Opens stock TensorBoard web assets collection.\n\n Returns:\n Returns function that returns a newly opened file handle to zip file\n containing static assets for stock TensorBoard, or None if webfiles.zip\n could not be found. The value the callback returns must be closed. The\n paths inside the zip f...
Please provide a description of the function:def with_port_scanning(cls): def init(wsgi_app, flags): # base_port: what's the first port to which we should try to bind? # should_scan: if that fails, shall we try additional ports? # max_attempts: how many ports shall we try? should_scan = flags.port...
[ "Create a server factory that performs port scanning.\n\n This function returns a callable whose signature matches the\n specification of `TensorBoardServer.__init__`, using `cls` as an\n underlying implementation. It passes through `flags` unchanged except\n in the case that `flags.port is None`, in which case...
Please provide a description of the function:def configure(self, argv=('',), **kwargs): parser = argparse_flags.ArgumentParser( prog='tensorboard', description=('TensorBoard is a suite of web applications for ' 'inspecting and understanding your TensorFlow runs ' ...
[ "Configures TensorBoard behavior via flags.\n\n This method will populate the \"flags\" property with an argparse.Namespace\n representing flag values parsed from the provided argv list, overridden by\n explicit flags from remaining keyword arguments.\n\n Args:\n argv: Can be set to CLI args equiva...
Please provide a description of the function:def main(self, ignored_argv=('',)): self._install_signal_handler(signal.SIGTERM, "SIGTERM") if self.flags.inspect: logger.info('Not bringing up TensorBoard, but inspecting event files.') event_file = os.path.expanduser(self.flags.event_file) ef...
[ "Blocking main function for TensorBoard.\n\n This method is called by `tensorboard.main.run_main`, which is the\n standard entrypoint for the tensorboard command line program. The\n configure() method must be called first.\n\n Args:\n ignored_argv: Do not pass. Required for Abseil compatibility.\n\...
Please provide a description of the function:def launch(self): # Make it easy to run TensorBoard inside other programs, e.g. Colab. server = self._make_server() thread = threading.Thread(target=server.serve_forever, name='TensorBoard') thread.daemon = True thread.start() return server.get_u...
[ "Python API for launching TensorBoard.\n\n This method is the same as main() except it launches TensorBoard in\n a separate permanent thread. The configure() method must be called\n first.\n\n Returns:\n The URL of the TensorBoard web server.\n\n :rtype: str\n " ]
Please provide a description of the function:def _register_info(self, server): server_url = urllib.parse.urlparse(server.get_url()) info = manager.TensorBoardInfo( version=version.VERSION, start_time=int(time.time()), port=server_url.port, pid=os.getpid(), path_prefi...
[ "Write a TensorBoardInfo file and arrange for its cleanup.\n\n Args:\n server: The result of `self._make_server()`.\n " ]
Please provide a description of the function:def _install_signal_handler(self, signal_number, signal_name): old_signal_handler = None # set below def handler(handled_signal_number, frame): # In case we catch this signal again while running atexit # handlers, take the hint and actually die. ...
[ "Set a signal handler to gracefully exit on the given signal.\n\n When this process receives the given signal, it will run `atexit`\n handlers and then exit with `0`.\n\n Args:\n signal_number: The numeric code for the signal to handle, like\n `signal.SIGTERM`.\n signal_name: The human-rea...
Please provide a description of the function:def _make_server(self): app = application.standard_tensorboard_wsgi(self.flags, self.plugin_loaders, self.assets_zip_provider) return self.server_class(app, self.flag...
[ "Constructs the TensorBoard WSGI app and instantiates the server." ]