signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def _get_value(self, scalar_data_blob, dtype_enum): | tensorflow_dtype = tf.DType(dtype_enum)<EOL>buf = np.frombuffer(scalar_data_blob, dtype=tensorflow_dtype.as_numpy_dtype)<EOL>return np.asscalar(buf)<EOL> | Obtains value for scalar event given blob and dtype enum.
Args:
scalar_data_blob: The blob obtained from the database.
dtype_enum: The enum representing the dtype.
Returns:
The scalar value. | f7971:c1:m5 |
@wrappers.Request.application<EOL><INDENT>def scalars_route(self, request):<DEDENT> | <EOL>tag = request.args.get('<STR_LIT>')<EOL>run = request.args.get('<STR_LIT>')<EOL>experiment = request.args.get('<STR_LIT>')<EOL>output_format = request.args.get('<STR_LIT>')<EOL>(body, mime_type) = self.scalars_impl(tag, run, experiment, output_format)<EOL>return http_util.Respond(request, body, mime_type)<EOL> | Given a tag and single run, return array of ScalarEvents. | f7971:c1:m7 |
def create_summary_metadata(display_name, description): | content = plugin_data_pb2.ScalarPluginData(version=PROTO_VERSION)<EOL>metadata = summary_pb2.SummaryMetadata(<EOL>display_name=display_name,<EOL>summary_description=description,<EOL>plugin_data=summary_pb2.SummaryMetadata.PluginData(<EOL>plugin_name=PLUGIN_NAME,<EOL>content=content.SerializeToString()))<EOL>return meta... | Create a `summary_pb2.SummaryMetadata` proto for scalar plugin data.
Returns:
A `summary_pb2.SummaryMetadata` protobuf object. | f7972:m0 |
def parse_plugin_metadata(content): | if not isinstance(content, bytes):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>result = plugin_data_pb2.ScalarPluginData.FromString(content)<EOL>if result.version == <NUM_LIT:0>:<EOL><INDENT>return result<EOL><DEDENT>else:<EOL><INDENT>logger.warn(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>', result.version... | Parse summary metadata to a Python object.
Arguments:
content: The `content` field of a `SummaryMetadata` proto
corresponding to the scalar plugin.
Returns:
A `ScalarPluginData` protobuf object. | f7972:m1 |
def scalar(name, data, step=None, description=None): | summary_metadata = metadata.create_summary_metadata(<EOL>display_name=None, description=description)<EOL>summary_scope = (<EOL>getattr(tf.summary.experimental, '<STR_LIT>', None) or<EOL>tf.summary.summary_scope)<EOL>with summary_scope(<EOL>name, '<STR_LIT>', values=[data, step]) as (tag, _):<EOL><INDENT>tf.debugging.as... | Write a scalar 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 real numeric scalar value, convertible to a `float32` Tensor.
step: Explicit `int64`-castable monotonic step value for this ... | f7974:m0 |
def scalar_pb(tag, data, description=None): | arr = np.array(data)<EOL>if arr.shape != ():<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>% arr.shape)<EOL><DEDENT>if arr.dtype.kind not in ('<STR_LIT:b>', '<STR_LIT:i>', '<STR_LIT:u>', '<STR_LIT:f>'): <EOL><INDENT>raise ValueError('<STR_LIT>' % arr.dtype.name)<EOL><DEDENT>tensor_proto = tensor_util.make_tensor_proto(... | Create a scalar summary_pb2.Summary protobuf.
Arguments:
tag: String tag for the summary.
data: A 0-dimensional `np.array` or a compatible python number type.
description: Optional long-form description for this summary, as a
`str`. Markdown is supported. Defaults to empty.
Raises:
... | f7974:m1 |
def _DeserializeResponse(self, byte_content): | return json.loads(byte_content.decode("<STR_LIT:utf-8>"))<EOL> | Deserializes byte content that is a JSON encoding.
Args:
byte_content: The byte content of a response.
Returns:
The deserialized python object decoded from JSON. | f7976:c0:m2 |
def op(name,<EOL>audio,<EOL>sample_rate,<EOL>labels=None,<EOL>max_outputs=<NUM_LIT:3>,<EOL>encoding=None,<EOL>display_name=None,<EOL>description=None,<EOL>collections=None): | <EOL>import tensorflow <EOL>import tensorflow.compat.v1 as tf<EOL>if display_name is None:<EOL><INDENT>display_name = name<EOL><DEDENT>if encoding is None:<EOL><INDENT>encoding = '<STR_LIT>'<EOL><DEDENT>if encoding == '<STR_LIT>':<EOL><INDENT>encoding = metadata.Encoding.Value('<STR_LIT>')<EOL>encoder = functools.part... | Create a legacy audio summary op for use in a TensorFlow graph.
Arguments:
name: A unique name for the generated summary node.
audio: A `Tensor` representing audio data with shape `[k, t, c]`,
where `k` is the number of audio clips, `t` is the number of
frames, and `c` is the number of ... | f7977:m0 |
def pb(name,<EOL>audio,<EOL>sample_rate,<EOL>labels=None,<EOL>max_outputs=<NUM_LIT:3>,<EOL>encoding=None,<EOL>display_name=None,<EOL>description=None): | <EOL>import tensorflow.compat.v1 as tf<EOL>audio = np.array(audio)<EOL>if audio.ndim != <NUM_LIT:3>:<EOL><INDENT>raise ValueError('<STR_LIT>' % (audio.shape,))<EOL><DEDENT>if encoding is None:<EOL><INDENT>encoding = '<STR_LIT>'<EOL><DEDENT>if encoding == '<STR_LIT>':<EOL><INDENT>encoding = metadata.Encoding.Value('<STR... | Create a legacy audio summary protobuf.
This behaves as if you were to create an `op` with the same arguments
(wrapped with constant tensors where appropriate) and then execute
that summary op in a TensorFlow session.
Arguments:
name: A unique name for the generated summary node.
audio: An... | f7977:m1 |
def create_summary_metadata(display_name, description, encoding): | content = plugin_data_pb2.AudioPluginData(<EOL>version=PROTO_VERSION, encoding=encoding)<EOL>metadata = summary_pb2.SummaryMetadata(<EOL>display_name=display_name,<EOL>summary_description=description,<EOL>plugin_data=summary_pb2.SummaryMetadata.PluginData(<EOL>plugin_name=PLUGIN_NAME,<EOL>content=content.SerializeToStr... | Create a `SummaryMetadata` proto for audio plugin data.
Returns:
A `SummaryMetadata` protobuf object. | f7978:m0 |
def parse_plugin_metadata(content): | if not isinstance(content, bytes):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>result = plugin_data_pb2.AudioPluginData.FromString(content)<EOL>if result.version == <NUM_LIT:0>:<EOL><INDENT>return result<EOL><DEDENT>else:<EOL><INDENT>logger.warn(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>', result.version,... | Parse summary metadata to a Python object.
Arguments:
content: The `content` field of a `SummaryMetadata` proto
corresponding to the audio plugin.
Returns:
An `AudioPluginData` protobuf object. | f7978:m1 |
def _samples(): | return int(FLAGS.sample_rate * FLAGS.duration)<EOL> | Compute how many samples should be included in each waveform. | f7979:m0 |
def run(logdir, run_name, wave_name, wave_constructor): | tf.compat.v1.reset_default_graph()<EOL>tf.compat.v1.set_random_seed(<NUM_LIT:0>)<EOL>step_placeholder = tf.compat.v1.placeholder(tf.float32, shape=[])<EOL>with tf.name_scope('<STR_LIT>'):<EOL><INDENT>f_min = <NUM_LIT><EOL>f_max = <NUM_LIT><EOL>t = step_placeholder / (FLAGS.steps - <NUM_LIT:1>)<EOL>frequency = f_min * (... | Generate wave data of the given form.
The provided function `wave_constructor` should accept a scalar tensor
of type float32, representing the frequency (in Hz) at which to
construct a wave, and return a tensor of shape [1, _samples(), `n`]
representing audio data (for some number of channels `n`).
... | f7979:m1 |
def sine_wave(frequency): | xs = tf.reshape(tf.range(_samples(), dtype=tf.float32), [<NUM_LIT:1>, _samples(), <NUM_LIT:1>])<EOL>ts = xs / FLAGS.sample_rate<EOL>return tf.sin(<NUM_LIT:2> * math.pi * frequency * ts)<EOL> | Emit a sine wave at the given frequency. | f7979:m2 |
def square_wave(frequency): | <EOL>return tf.sign(sine_wave(frequency))<EOL> | Emit a square wave at the given frequency. | f7979:m3 |
def triangle_wave(frequency): | xs = tf.reshape(tf.range(_samples(), dtype=tf.float32), [<NUM_LIT:1>, _samples(), <NUM_LIT:1>])<EOL>ts = xs / FLAGS.sample_rate<EOL>half_pulse_index = ts * (frequency * <NUM_LIT:2>)<EOL>half_pulse_angle = half_pulse_index % <NUM_LIT:1.0> <EOL>absolute_amplitude = (<NUM_LIT:0.5> - tf.abs(half_pulse_angle - <NUM_LIT:0.5... | Emit a triangle wave at the given frequency. | f7979:m4 |
def bisine_wave(frequency): | <EOL>f_hi = frequency<EOL>f_lo = frequency / <NUM_LIT><EOL>with tf.name_scope('<STR_LIT>'):<EOL><INDENT>sine_hi = sine_wave(f_hi)<EOL><DEDENT>with tf.name_scope('<STR_LIT>'):<EOL><INDENT>sine_lo = sine_wave(f_lo)<EOL><DEDENT>return tf.concat([sine_lo, sine_hi], axis=<NUM_LIT:2>)<EOL> | Emit two sine waves, in stereo at different octaves. | f7979:m5 |
def bisine_wahwah_wave(frequency): | <EOL>waves_a = bisine_wave(frequency)<EOL>waves_b = tf.reverse(waves_a, axis=[<NUM_LIT:2>])<EOL>iterations = <NUM_LIT:4><EOL>xs = tf.reshape(tf.range(_samples(), dtype=tf.float32), [<NUM_LIT:1>, _samples(), <NUM_LIT:1>])<EOL>thetas = xs / _samples() * iterations<EOL>ts = (tf.sin(math.pi * <NUM_LIT:2> * thetas) + <NUM_L... | Emit two sine waves with balance oscillating left and right. | f7979:m6 |
def run_all(logdir, verbose=False): | waves = [sine_wave, square_wave, triangle_wave,<EOL>bisine_wave, bisine_wahwah_wave]<EOL>for (i, wave_constructor) in enumerate(waves):<EOL><INDENT>wave_name = wave_constructor.__name__<EOL>run_name = '<STR_LIT>' % (i + <NUM_LIT:1>, wave_name)<EOL>if verbose:<EOL><INDENT>print('<STR_LIT>' % run_name)<EOL><DEDENT>run(lo... | Generate waves of the shapes defined above.
Arguments:
logdir: the directory into which to store all the runs' data
verbose: if true, print out each run's name as it begins | f7979:m7 |
def __init__(self, context): | self._multiplexer = context.multiplexer<EOL> | Instantiates AudioPlugin via TensorBoard core.
Args:
context: A base_plugin.TBContext instance. | f7980:c0:m0 |
def is_active(self): | if not self._multiplexer:<EOL><INDENT>return False<EOL><DEDENT>return bool(self._multiplexer.PluginRunToTagToContent(metadata.PLUGIN_NAME))<EOL> | The audio plugin is active iff any run has at least one relevant tag. | f7980:c0:m2 |
def _index_impl(self): | runs = self._multiplexer.Runs()<EOL>result = {run: {} for run in runs}<EOL>mapping = self._multiplexer.PluginRunToTagToContent(metadata.PLUGIN_NAME)<EOL>for (run, tag_to_content) in six.iteritems(mapping):<EOL><INDENT>for tag in tag_to_content:<EOL><INDENT>summary_metadata = self._multiplexer.SummaryMetadata(run, tag)<... | Return information about the tags in each run.
Result is a dictionary of the form
{
"runName1": {
"tagName1": {
"displayName": "The first tag",
"description": "<p>Long ago there was just one tag...</p>",
"samples":... | f7980:c0:m3 |
def _number_of_samples(self, tensor_proto): | <EOL>return tensor_proto.tensor_shape.dim[<NUM_LIT:0>].size<EOL> | Count the number of samples of an audio TensorProto. | f7980:c0:m4 |
@wrappers.Request.application<EOL><INDENT>def _serve_audio_metadata(self, request):<DEDENT> | tag = request.args.get('<STR_LIT>')<EOL>run = request.args.get('<STR_LIT>')<EOL>sample = int(request.args.get('<STR_LIT>', <NUM_LIT:0>))<EOL>events = self._multiplexer.Tensors(run, tag)<EOL>response = self._audio_response_for_run(events, run, tag, sample)<EOL>return http_util.Respond(request, response, '<STR_LIT:applic... | Given a tag and list of runs, serve a list of metadata for audio.
Note that the actual audio data are not sent; instead, we respond
with URLs to the audio. The frontend should treat these URLs as
opaque and should not try to parse information about them or
generate them itself, as the f... | f7980:c0:m6 |
def _audio_response_for_run(self, tensor_events, run, tag, sample): | response = []<EOL>index = <NUM_LIT:0><EOL>filtered_events = self._filter_by_sample(tensor_events, sample)<EOL>content_type = self._get_mime_type(run, tag)<EOL>for (index, tensor_event) in enumerate(filtered_events):<EOL><INDENT>data = tensor_util.make_ndarray(tensor_event.tensor_proto)<EOL>label = data[sample, <NUM_LIT... | Builds a JSON-serializable object with information about audio.
Args:
tensor_events: A list of image event_accumulator.TensorEvent objects.
run: The name of the run.
tag: The name of the tag the audio entries all belong to.
sample: The zero-indexed sample of the audio sa... | f7980:c0:m7 |
def _query_for_individual_audio(self, run, tag, sample, index): | query_string = urllib.parse.urlencode({<EOL>'<STR_LIT>': run,<EOL>'<STR_LIT>': tag,<EOL>'<STR_LIT>': sample,<EOL>'<STR_LIT:index>': index,<EOL>})<EOL>return query_string<EOL> | Builds a URL for accessing the specified audio.
This should be kept in sync with _serve_audio_metadata. Note that the URL is
*not* guaranteed to always return the same audio, since audio may be
unloaded from the reservoir as new audio entries come in.
Args:
run: The name of t... | f7980:c0:m8 |
@wrappers.Request.application<EOL><INDENT>def _serve_individual_audio(self, request):<DEDENT> | tag = request.args.get('<STR_LIT>')<EOL>run = request.args.get('<STR_LIT>')<EOL>index = int(request.args.get('<STR_LIT:index>'))<EOL>sample = int(request.args.get('<STR_LIT>', <NUM_LIT:0>))<EOL>events = self._filter_by_sample(self._multiplexer.Tensors(run, tag), sample)<EOL>data = tensor_util.make_ndarray(events[index]... | Serve encoded audio data. | f7980:c0:m10 |
def audio(name,<EOL>data,<EOL>sample_rate,<EOL>step=None,<EOL>max_outputs=<NUM_LIT:3>,<EOL>encoding=None,<EOL>description=None): | audio_ops = getattr(tf, '<STR_LIT>', None)<EOL>if audio_ops is None:<EOL><INDENT>from tensorflow.python.ops import gen_audio_ops as audio_ops<EOL><DEDENT>if encoding is None:<EOL><INDENT>encoding = '<STR_LIT>'<EOL><DEDENT>if encoding != '<STR_LIT>':<EOL><INDENT>raise ValueError('<STR_LIT>' % encoding)<EOL><DEDENT>summa... | Write an audio summary.
Arguments:
name: A name for this summary. The summary tag used for TensorBoard will
be this name prefixed by any active name scopes.
data: A `Tensor` representing audio data with shape `[k, t, c]`,
where `k` is the number of audio clips, `t` is the number of
... | f7982:m0 |
def __init__(self, context): | self._logdir = context.logdir<EOL>self._db_uri = context.db_uri<EOL>self._window_title = context.window_title<EOL>self._multiplexer = context.multiplexer<EOL>self._db_connection_provider = context.db_connection_provider<EOL>self._assets_zip_provider = context.assets_zip_provider<EOL> | Instantiates CorePlugin.
Args:
context: A base_plugin.TBContext instance. | f7983:c0:m0 |
@wrappers.Request.application<EOL><INDENT>def _serve_asset(self, path, gzipped_asset_bytes, request):<DEDENT> | mimetype = mimetypes.guess_type(path)[<NUM_LIT:0>] or '<STR_LIT>'<EOL>return http_util.Respond(<EOL>request, gzipped_asset_bytes, mimetype, content_encoding='<STR_LIT>')<EOL> | Serves a pre-gzipped static asset from the zip file. | f7983:c0:m5 |
@wrappers.Request.application<EOL><INDENT>def _serve_environment(self, request):<DEDENT> | return http_util.Respond(<EOL>request,<EOL>{<EOL>'<STR_LIT>': self._logdir or self._db_uri,<EOL>'<STR_LIT>': '<STR_LIT>' if self._db_uri else '<STR_LIT>',<EOL>'<STR_LIT>': self._window_title,<EOL>},<EOL>'<STR_LIT:application/json>')<EOL> | Serve a JSON object containing some base properties used by the frontend.
* data_location is either a path to a directory or an address to a
database (depending on which mode TensorBoard is running in).
* window_title is the title of the TensorBoard web page. | f7983:c0:m6 |
@wrappers.Request.application<EOL><INDENT>def _serve_logdir(self, request):<DEDENT> | <EOL>return http_util.Respond(<EOL>request, {'<STR_LIT>': self._logdir}, '<STR_LIT:application/json>')<EOL> | Respond with a JSON object containing this TensorBoard's logdir. | f7983:c0:m7 |
@wrappers.Request.application<EOL><INDENT>def _serve_window_properties(self, request):<DEDENT> | <EOL>return http_util.Respond(<EOL>request, {'<STR_LIT>': self._window_title}, '<STR_LIT:application/json>')<EOL> | Serve a JSON object containing this TensorBoard's window properties. | f7983:c0:m8 |
@wrappers.Request.application<EOL><INDENT>def _serve_runs(self, request):<DEDENT> | if self._db_connection_provider:<EOL><INDENT>db = self._db_connection_provider()<EOL>cursor = db.execute( | Serve a JSON array of run names, ordered by run started time.
Sort order is by started time (aka first event time) with empty times sorted
last, and then ties are broken by sorting on the run name. | f7983:c0:m9 |
@wrappers.Request.application<EOL><INDENT>def _serve_experiments(self, request):<DEDENT> | results = self.list_experiments_impl()<EOL>return http_util.Respond(request, results, '<STR_LIT:application/json>')<EOL> | Serve a JSON array of experiments. Experiments are ordered by experiment
started time (aka first event time) with empty times sorted last, and then
ties are broken by sorting on the experiment name. | f7983:c0:m10 |
@wrappers.Request.application<EOL><INDENT>def _serve_experiment_runs(self, request):<DEDENT> | results = []<EOL>if self._db_connection_provider:<EOL><INDENT>exp_id = request.args.get('<STR_LIT>')<EOL>runs_dict = collections.OrderedDict()<EOL>db = self._db_connection_provider()<EOL>cursor = db.execute( | Serve a JSON runs of an experiment, specified with query param
`experiment`, with their nested data, tag, populated. Runs returned are
ordered by started time (aka first event time) with empty times sorted last,
and then ties are broken by sorting on the run name. Tags are sorted by
its ... | f7983:c0:m12 |
def define_flags(self, parser): | parser.add_argument(<EOL>'<STR_LIT>',<EOL>metavar='<STR_LIT>',<EOL>type=str,<EOL>default='<STR_LIT>',<EOL>help='''<STR_LIT>'''t to listen to. Defaults to serving on all interfaces. Other<EOL>used values are <NUM_LIT><NUM_LIT><NUM_LIT> (localhost) and :: (for IPv6).<EOL>parser.add_argument(<EOL>'<STR_LIT>',<EOL>metavar=... | Adds standard TensorBoard CLI flags to parser. | f7983:c1:m0 |
def fix_flags(self, flags): | FlagsError = base_plugin.FlagsError<EOL>if flags.version_tb:<EOL><INDENT>pass<EOL><DEDENT>elif flags.inspect:<EOL><INDENT>if flags.logdir and flags.event_file:<EOL><INDENT>raise FlagsError(<EOL>'<STR_LIT>')<EOL><DEDENT>if not (flags.logdir or flags.event_file):<EOL><INDENT>raise FlagsError('<STR_LIT>')<EOL><DEDENT><DED... | Fixes standard TensorBoard CLI flags to parser. | f7983:c1:m1 |
def load(self, context): | return CorePlugin(context)<EOL> | Creates CorePlugin instance. | f7983:c1:m2 |
def __init__(self, context): | self._db_connection_provider = context.db_connection_provider<EOL>self._multiplexer = context.multiplexer<EOL> | Instantiates a PrCurvesPlugin.
Args:
context: A base_plugin.TBContext instance. A magic container that
TensorBoard uses to make objects available to the plugin. | f7985:c0:m0 |
@wrappers.Request.application<EOL><INDENT>def pr_curves_route(self, request):<DEDENT> | runs = request.args.getlist('<STR_LIT>')<EOL>if not runs:<EOL><INDENT>return http_util.Respond(<EOL>request, '<STR_LIT>', <NUM_LIT>)<EOL><DEDENT>tag = request.args.get('<STR_LIT>')<EOL>if not tag:<EOL><INDENT>return http_util.Respond(<EOL>request, '<STR_LIT>', <NUM_LIT>)<EOL><DEDENT>try:<EOL><INDENT>response = http_uti... | A route that returns a JSON mapping between runs and PR curve data.
Returns:
Given a tag and a comma-separated list of runs (both stored within GET
parameters), fetches a JSON object that maps between run name and objects
containing data required for PR curves for that run. Runs t... | f7985:c0:m1 |
def pr_curves_impl(self, runs, tag): | if self._db_connection_provider:<EOL><INDENT>db = self._db_connection_provider()<EOL>cursor = db.execute( | Creates the JSON object for the PR curves response for a run-tag combo.
Arguments:
runs: A list of runs to fetch the curves for.
tag: The tag to fetch the curves for.
Raises:
ValueError: If no PR curves could be fetched for a run and tag.
Returns:
The J... | f7985:c0:m2 |
def _compute_thresholds(self, num_thresholds): | return [float(v) / num_thresholds for v in range(<NUM_LIT:1>, num_thresholds + <NUM_LIT:1>)]<EOL> | Computes a list of specific thresholds from the number of thresholds.
Args:
num_thresholds: The number of thresholds.
Returns:
A list of specific thresholds (floats). | f7985:c0:m3 |
@wrappers.Request.application<EOL><INDENT>def tags_route(self, request):<DEDENT> | return http_util.Respond(<EOL>request, self.tags_impl(), '<STR_LIT:application/json>')<EOL> | A route (HTTP handler) that returns a response with tags.
Returns:
A response that contains a JSON object. The keys of the object
are all the runs. Each run is mapped to a (potentially empty) dictionary
whose keys are tags associated with run and whose values are metadata
... | f7985:c0:m4 |
def tags_impl(self): | if self._db_connection_provider:<EOL><INDENT>db = self._db_connection_provider()<EOL>cursor = db.execute( | Creates the JSON object for the tags route response.
Returns:
The JSON object for the tags route response. | f7985:c0:m5 |
@wrappers.Request.application<EOL><INDENT>def available_time_entries_route(self, request):<DEDENT> | return http_util.Respond(<EOL>request, self.available_time_entries_impl(), '<STR_LIT:application/json>')<EOL> | Gets a dict mapping run to a list of time entries.
Returns:
A dict with string keys (all runs with PR curve data). The values of the
dict are lists of time entries (consisting of the fields below) to be
used in populating values within time sliders. | f7985:c0:m6 |
def available_time_entries_impl(self): | result = {}<EOL>if self._db_connection_provider:<EOL><INDENT>db = self._db_connection_provider()<EOL>cursor = db.execute(<EOL>'''<STR_LIT>''', (metadata.PLUGIN_NAME,))<EOL>for (run, step, wall_time) in cursor:<EOL><INDENT>if run not in result:<EOL><INDENT>result[run] = []<EOL><DEDENT>result[run].append(self._create_tim... | Creates the JSON object for the available time entries route response.
Returns:
The JSON object for the available time entries route response. | f7985:c0:m7 |
def _create_time_entry(self, step, wall_time): | return {<EOL>'<STR_LIT>': step,<EOL>'<STR_LIT>': wall_time,<EOL>}<EOL> | Creates a time entry given a tensor event.
Arguments:
step: The step for the time entry.
wall_time: The wall time for the time entry.
Returns:
A JSON-able time entry to be passed to the frontend in order to construct
the slider. | f7985:c0:m8 |
def get_plugin_apps(self): | return {<EOL>'<STR_LIT>': self.tags_route,<EOL>'<STR_LIT>': self.pr_curves_route,<EOL>'<STR_LIT>': self.available_time_entries_route,<EOL>}<EOL> | Gets all routes offered by the plugin.
Returns:
A dictionary mapping URL path to route that handles it. | f7985:c0:m9 |
def is_active(self): | if self._db_connection_provider:<EOL><INDENT>db = self._db_connection_provider()<EOL>cursor = db.execute(<EOL>'''<STR_LIT>''',<EOL>(metadata.PLUGIN_NAME,))<EOL>return bool(list(cursor))<EOL><DEDENT>if not self._multiplexer:<EOL><INDENT>return False<EOL><DEDENT>all_runs = self._multiplexer.PluginRunToTagToContent(metada... | 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. | f7985:c0:m10 |
def _process_tensor_event(self, event, thresholds): | return self._make_pr_entry(<EOL>event.step,<EOL>event.wall_time,<EOL>tensor_util.make_ndarray(event.tensor_proto),<EOL>thresholds)<EOL> | Converts a TensorEvent into a dict that encapsulates information on it.
Args:
event: The TensorEvent to convert.
thresholds: An array of floats that ranges from 0 to 1 (in that
direction and inclusive of 0 and 1).
Returns:
A JSON-able dictionary of PR curve da... | f7985:c0:m11 |
def _make_pr_entry(self, step, wall_time, data_array, thresholds): | <EOL>true_positives = [int(v) for v in data_array[metadata.TRUE_POSITIVES_INDEX]]<EOL>false_positives = [<EOL>int(v) for v in data_array[metadata.FALSE_POSITIVES_INDEX]]<EOL>tp_index = metadata.TRUE_POSITIVES_INDEX<EOL>fp_index = metadata.FALSE_POSITIVES_INDEX<EOL>positives = data_array[[tp_index, fp_index], :].astype(... | Creates an entry for PR curve data. Each entry corresponds to 1 step.
Args:
step: The step.
wall_time: The wall time.
data_array: A numpy array of PR curve data stored in the summary format.
thresholds: An array of floating point thresholds.
Returns:
A... | f7985:c0:m12 |
def op(<EOL>name,<EOL>labels,<EOL>predictions,<EOL>num_thresholds=None,<EOL>weights=None,<EOL>display_name=None,<EOL>description=None,<EOL>collections=None): | <EOL>import tensorflow.compat.v1 as tf<EOL>if num_thresholds is None:<EOL><INDENT>num_thresholds = _DEFAULT_NUM_THRESHOLDS<EOL><DEDENT>if weights is None:<EOL><INDENT>weights = <NUM_LIT:1.0><EOL><DEDENT>dtype = predictions.dtype<EOL>with tf.name_scope(name, values=[labels, predictions, weights]):<EOL><INDENT>tf.assert_... | Create a PR curve summary op for a single binary classifier.
Computes true/false positive/negative values for the given `predictions`
against the ground truth `labels`, against a list of evenly distributed
threshold values in `[0, 1]` of length `num_thresholds`.
Each number in `predictions`, a float i... | f7986:m0 |
def pb(name,<EOL>labels,<EOL>predictions,<EOL>num_thresholds=None,<EOL>weights=None,<EOL>display_name=None,<EOL>description=None): | <EOL>import tensorflow.compat.v1 as tf<EOL>if num_thresholds is None:<EOL><INDENT>num_thresholds = _DEFAULT_NUM_THRESHOLDS<EOL><DEDENT>if weights is None:<EOL><INDENT>weights = <NUM_LIT:1.0><EOL><DEDENT>bucket_indices = np.int32(np.floor(predictions * (num_thresholds - <NUM_LIT:1>)))<EOL>float_labels = labels.astype(np... | Create a PR curves summary protobuf.
Arguments:
name: A name for the generated node. Will also serve as a series name in
TensorBoard.
labels: The ground truth values. A bool numpy array.
predictions: A float32 numpy array whose values are in the range `[0, 1]`.
Dimensions must... | f7986:m1 |
def streaming_op(name,<EOL>labels,<EOL>predictions,<EOL>num_thresholds=None,<EOL>weights=None,<EOL>metrics_collections=None,<EOL>updates_collections=None,<EOL>display_name=None,<EOL>description=None): | <EOL>import tensorflow.compat.v1 as tf<EOL>if num_thresholds is None:<EOL><INDENT>num_thresholds = _DEFAULT_NUM_THRESHOLDS<EOL><DEDENT>thresholds = [i / float(num_thresholds - <NUM_LIT:1>)<EOL>for i in range(num_thresholds)]<EOL>with tf.name_scope(name, values=[labels, predictions, weights]):<EOL><INDENT>tp, update_tp ... | Computes a precision-recall curve summary across batches of data.
This function is similar to op() above, but can be used to compute the PR
curve across multiple batches of labels and predictions, in the same style
as the metrics found in tf.metrics.
This function creates multiple local variables for ... | f7986:m2 |
def raw_data_op(<EOL>name,<EOL>true_positive_counts,<EOL>false_positive_counts,<EOL>true_negative_counts,<EOL>false_negative_counts,<EOL>precision,<EOL>recall,<EOL>num_thresholds=None,<EOL>display_name=None,<EOL>description=None,<EOL>collections=None): | <EOL>import tensorflow.compat.v1 as tf<EOL>with tf.name_scope(name, values=[<EOL>true_positive_counts,<EOL>false_positive_counts,<EOL>true_negative_counts,<EOL>false_negative_counts,<EOL>precision,<EOL>recall,<EOL>]):<EOL><INDENT>return _create_tensor_summary(<EOL>name,<EOL>true_positive_counts,<EOL>false_positive_coun... | Create an op that collects data for visualizing PR curves.
Unlike the op above, this one avoids computing precision, recall, and the
intermediate counts. Instead, it accepts those tensors as arguments and
relies on the caller to ensure that the calculations are correct (and the
counts yield the provide... | f7986:m3 |
def raw_data_pb(<EOL>name,<EOL>true_positive_counts,<EOL>false_positive_counts,<EOL>true_negative_counts,<EOL>false_negative_counts,<EOL>precision,<EOL>recall,<EOL>num_thresholds=None,<EOL>display_name=None,<EOL>description=None): | <EOL>import tensorflow.compat.v1 as tf<EOL>if display_name is None:<EOL><INDENT>display_name = name<EOL><DEDENT>summary_metadata = metadata.create_summary_metadata(<EOL>display_name=display_name if display_name is not None else name,<EOL>description=description or '<STR_LIT>',<EOL>num_thresholds=num_thresholds)<EOL>tf_... | Create a PR curves summary protobuf from raw data values.
Args:
name: A tag attached to the summary. Used by TensorBoard for organization.
true_positive_counts: A rank-1 numpy array of true positive counts. Must
contain `num_thresholds` elements and be castable to float32.
false_positiv... | f7986:m4 |
def _create_tensor_summary(<EOL>name,<EOL>true_positive_counts,<EOL>false_positive_counts,<EOL>true_negative_counts,<EOL>false_negative_counts,<EOL>precision,<EOL>recall,<EOL>num_thresholds=None,<EOL>display_name=None,<EOL>description=None,<EOL>collections=None): | <EOL>import tensorflow.compat.v1 as tf<EOL>summary_metadata = metadata.create_summary_metadata(<EOL>display_name=display_name if display_name is not None else name,<EOL>description=description or '<STR_LIT>',<EOL>num_thresholds=num_thresholds)<EOL>combined_data = tf.stack([<EOL>tf.cast(true_positive_counts, tf.float32)... | A private helper method for generating a tensor summary.
We use a helper method instead of having `op` directly call `raw_data_op`
to prevent the scope of `raw_data_op` from being embedded within `op`.
Arguments are the same as for raw_data_op.
Returns:
A tensor summary that collects data for P... | f7986:m5 |
def start_runs(<EOL>logdir,<EOL>steps,<EOL>run_name,<EOL>thresholds,<EOL>mask_every_other_prediction=False): | tf.compat.v1.reset_default_graph()<EOL>tf.compat.v1.set_random_seed(<NUM_LIT>)<EOL>distribution = tf.compat.v1.distributions.Normal(loc=<NUM_LIT:0.>, scale=<NUM_LIT>)<EOL>number_of_reds = <NUM_LIT:100><EOL>true_reds = tf.clip_by_value(<EOL>tf.concat([<EOL><NUM_LIT:255> - tf.abs(distribution.sample([number_of_reds, <NUM... | Generate a PR curve with precision and recall evenly weighted.
Arguments:
logdir: The directory into which to store all the runs' data.
steps: The number of steps to run for.
run_name: The name of the run.
thresholds: The number of thresholds to use for PR curves.
mask_every_other_pre... | f7987:m0 |
def run_all(logdir, steps, thresholds, verbose=False): | <EOL>run_name = '<STR_LIT>'<EOL>if verbose:<EOL><INDENT>print('<STR_LIT>' % run_name)<EOL><DEDENT>start_runs(<EOL>logdir=logdir,<EOL>steps=steps,<EOL>run_name=run_name,<EOL>thresholds=thresholds)<EOL>run_name = '<STR_LIT>'<EOL>if verbose:<EOL><INDENT>print('<STR_LIT>' % run_name)<EOL><DEDENT>start_runs(<EOL>logdir=logd... | Generate PR curve summaries.
Arguments:
logdir: The directory into which to store all the runs' data.
steps: The number of steps to run for.
verbose: Whether to print the names of runs into stdout during execution.
thresholds: The number of thresholds to use for PR curves. | f7987:m1 |
def create_summary_metadata(display_name, description, num_thresholds): | pr_curve_plugin_data = plugin_data_pb2.PrCurvePluginData(<EOL>version=PROTO_VERSION, num_thresholds=num_thresholds)<EOL>content = pr_curve_plugin_data.SerializeToString()<EOL>return summary_pb2.SummaryMetadata(<EOL>display_name=display_name,<EOL>summary_description=description,<EOL>plugin_data=summary_pb2.SummaryMetada... | Create a `summary_pb2.SummaryMetadata` proto for pr_curves plugin data.
Arguments:
display_name: The display name used in TensorBoard.
description: The description to show in TensorBoard.
num_thresholds: The number of thresholds to use for PR curves.
Returns:
A `summary_pb2.SummaryMeta... | f7988:m0 |
def parse_plugin_metadata(content): | if not isinstance(content, bytes):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>result = plugin_data_pb2.PrCurvePluginData.FromString(content)<EOL>if result.version == <NUM_LIT:0>:<EOL><INDENT>return result<EOL><DEDENT>else:<EOL><INDENT>logger.warn(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>', result.versio... | Parse summary metadata to a Python object.
Arguments:
content: The `content` field of a `SummaryMetadata` proto
corresponding to the pr_curves plugin.
Returns:
A `PrCurvesPlugin` protobuf object. | f7988:m1 |
def normalize_summary_pb(self, pb): | result = summary_pb2.Summary()<EOL>if not isinstance(pb, summary_pb2.Summary):<EOL><INDENT>pb = test_util.ensure_tb_summary_proto(pb)<EOL><DEDENT>result.MergeFrom(pb)<EOL>for value in result.value:<EOL><INDENT>if value.HasField('<STR_LIT>'):<EOL><INDENT>new_tensor = tensor_util.make_tensor_proto(<EOL>tensor_util.make_n... | Pass `pb`'s `TensorProto` through a marshalling roundtrip.
`TensorProto`s can be equal in value even if they are not identical
in representation, because data can be stored in either the
`tensor_content` field or the `${dtype}_value` field. This
normalization ensures a canonical form, an... | f7989:c0:m2 |
def compute_and_check_summary_pb(self,<EOL>name,<EOL>labels,<EOL>predictions,<EOL>num_thresholds,<EOL>weights=None,<EOL>display_name=None,<EOL>description=None,<EOL>feed_dict=None): | labels_tensor = tf.constant(labels)<EOL>predictions_tensor = tf.constant(predictions)<EOL>weights_tensor = None if weights is None else tf.constant(weights)<EOL>op = summary.op(<EOL>name=name,<EOL>labels=labels_tensor,<EOL>predictions=predictions_tensor,<EOL>num_thresholds=num_thresholds,<EOL>weights=weights_tensor,<EO... | Use both `op` and `pb` to get a summary, asserting equality.
Returns:
a `Summary` protocol buffer | f7989:c0:m3 |
def validatePrCurveEntry(<EOL>self,<EOL>expected_step,<EOL>expected_precision,<EOL>expected_recall,<EOL>expected_true_positives,<EOL>expected_false_positives,<EOL>expected_true_negatives,<EOL>expected_false_negatives,<EOL>expected_thresholds,<EOL>pr_curve_entry): | self.assertEqual(expected_step, pr_curve_entry['<STR_LIT>'])<EOL>assert_allclose(expected_precision, pr_curve_entry['<STR_LIT>'])<EOL>assert_allclose(expected_recall, pr_curve_entry['<STR_LIT>'])<EOL>self.assertListEqual(<EOL>expected_true_positives, pr_curve_entry['<STR_LIT>'])<EOL>self.assertListEqual(<EOL>expected_f... | Checks that the values stored within a tensor are correct.
Args:
expected_step: The expected step.
expected_precision: A list of float values.
expected_recall: A list of float values.
expected_true_positives: A list of int values.
expected_false_positives: A li... | f7990:c0:m1 |
def computeCorrectDescription(self, standard_deviation): | description = ('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>') % standard_deviation<EOL>return description<EOL> | Generates a correct description.
Arguments:
standard_deviation: An integer standard deviation value.
Returns:
The correct description given a standard deviation value. | f7990:c0:m2 |
def run_tag_from_session_and_metric(session_name, metric_name): | assert isinstance(session_name, six.string_types)<EOL>assert isinstance(metric_name, api_pb2.MetricName)<EOL>run = os.path.normpath(os.path.join(session_name, metric_name.group))<EOL>tag = metric_name.tag<EOL>return run, tag<EOL> | Returns a (run,tag) tuple storing the evaluations of the specified metric.
Args:
session_name: str.
metric_name: MetricName protobuffer.
Returns: (run, tag) tuple. | f7992:m0 |
def last_metric_eval(multiplexer, session_name, metric_name): | try:<EOL><INDENT>run, tag = run_tag_from_session_and_metric(session_name, metric_name)<EOL>tensor_events = multiplexer.Tensors(run=run, tag=tag)<EOL><DEDENT>except KeyError as e:<EOL><INDENT>raise KeyError(<EOL>'<STR_LIT>'<EOL>% (metric_name, session_name, e))<EOL><DEDENT>last_event = tensor_events[-<NUM_LIT:1>]<EOL>re... | Returns the last evaluations of the given metric at the given session.
Args:
multiplexer: The EventMultiplexer instance allowing access to
the exported summary data.
session_name: String. The session name for which to get the metric
evaluations.
metric_name: api_pb2.MetricName... | f7992:m1 |
def _find_longest_parent_path(path_set, path): | <EOL>while path not in path_set:<EOL><INDENT>if not path:<EOL><INDENT>return None<EOL><DEDENT>path = os.path.dirname(path)<EOL><DEDENT>return path<EOL> | Finds the longest "parent-path" of 'path' in 'path_set'.
This function takes and returns "path-like" strings which are strings
made of strings separated by os.sep. No file access is performed here, so
these strings need not correspond to actual files in some file-system..
This function returns the long... | f7994:m0 |
def _protobuf_value_type(value): | if value.HasField("<STR_LIT>"):<EOL><INDENT>return api_pb2.DATA_TYPE_FLOAT64<EOL><DEDENT>if value.HasField("<STR_LIT>"):<EOL><INDENT>return api_pb2.DATA_TYPE_STRING<EOL><DEDENT>if value.HasField("<STR_LIT>"):<EOL><INDENT>return api_pb2.DATA_TYPE_BOOL<EOL><DEDENT>return None<EOL> | Returns the type of the google.protobuf.Value message as an api.DataType.
Returns None if the type of 'value' is not one of the types supported in
api_pb2.DataType.
Args:
value: google.protobuf.Value message. | f7994:m1 |
def _protobuf_value_to_string(value): | value_in_json = json_format.MessageToJson(value)<EOL>if value.HasField("<STR_LIT>"):<EOL><INDENT>return value_in_json[<NUM_LIT:1>:-<NUM_LIT:1>]<EOL><DEDENT>return value_in_json<EOL> | Returns a string representation of given google.protobuf.Value message.
Args:
value: google.protobuf.Value message. Assumed to be of type 'number',
'string' or 'bool'. | f7994:m2 |
def __init__(self,<EOL>tb_context,<EOL>max_domain_discrete_len=<NUM_LIT:10>): | self._tb_context = tb_context<EOL>self._experiment_from_tag = None<EOL>self._experiment_from_tag_lock = threading.Lock()<EOL>self._max_domain_discrete_len = max_domain_discrete_len<EOL> | Instantiates a context.
Args:
tb_context: base_plugin.TBContext. The "base" context we extend.
max_domain_discrete_len: int. Only used when computing the experiment
from the session runs. The maximum number of disticnt values a string
hyperparameter can have for us t... | f7994:c0:m0 |
def experiment(self): | experiment = self._find_experiment_tag()<EOL>if experiment is None:<EOL><INDENT>return self._compute_experiment_from_runs()<EOL><DEDENT>return experiment<EOL> | Returns the experiment protobuffer defining the experiment.
This method first attempts to find a metadata.EXPERIMENT_TAG tag and
retrieve the associated protobuffer. If no such tag is found, the method
will attempt to build a minimal experiment protobuffer by scanning for
all metadata.S... | f7994:c0:m1 |
def _find_experiment_tag(self): | with self._experiment_from_tag_lock:<EOL><INDENT>if self._experiment_from_tag is None:<EOL><INDENT>mapping = self.multiplexer.PluginRunToTagToContent(<EOL>metadata.PLUGIN_NAME)<EOL>for tag_to_content in mapping.values():<EOL><INDENT>if metadata.EXPERIMENT_TAG in tag_to_content:<EOL><INDENT>self._experiment_from_tag = m... | Finds the experiment associcated with the metadata.EXPERIMENT_TAG tag.
Caches the experiment if it was found.
Returns:
The experiment or None if no such experiment is found. | f7994:c0:m4 |
def _compute_experiment_from_runs(self): | hparam_infos = self._compute_hparam_infos()<EOL>if not hparam_infos:<EOL><INDENT>return None<EOL><DEDENT>metric_infos = self._compute_metric_infos()<EOL>return api_pb2.Experiment(hparam_infos=hparam_infos,<EOL>metric_infos=metric_infos)<EOL> | Computes a minimal Experiment protocol buffer by scanning the runs. | f7994:c0:m5 |
def _compute_hparam_infos(self): | run_to_tag_to_content = self.multiplexer.PluginRunToTagToContent(<EOL>metadata.PLUGIN_NAME)<EOL>hparams = collections.defaultdict(list)<EOL>for tag_to_content in run_to_tag_to_content.values():<EOL><INDENT>if metadata.SESSION_START_INFO_TAG not in tag_to_content:<EOL><INDENT>continue<EOL><DEDENT>start_info = metadata.p... | Computes a list of api_pb2.HParamInfo from the current run, tag info.
Finds all the SessionStartInfo messages and collects the hparams values
appearing in each one. For each hparam attempts to deduce a type that fits
all its values. Finally, sets the 'domain' of the resulting HParamInfo
... | f7994:c0:m6 |
def _compute_hparam_info_from_values(self, name, values): | <EOL>result = api_pb2.HParamInfo(name=name, type=api_pb2.DATA_TYPE_UNSET)<EOL>distinct_values = set(<EOL>_protobuf_value_to_string(v) for v in values if _protobuf_value_type(v))<EOL>for v in values:<EOL><INDENT>v_type = _protobuf_value_type(v)<EOL>if not v_type:<EOL><INDENT>continue<EOL><DEDENT>if result.type == api_pb... | Builds an HParamInfo message from the hparam name and list of values.
Args:
name: string. The hparam name.
values: list of google.protobuf.Value messages. The list of values for the
hparam.
Returns:
An api_pb2.HParamInfo message. | f7994:c0:m7 |
def _compute_metric_names(self): | session_runs = self._build_session_runs_set()<EOL>metric_names_set = set()<EOL>run_to_tag_to_content = self.multiplexer.PluginRunToTagToContent(<EOL>scalar_metadata.PLUGIN_NAME)<EOL>for (run, tag_to_content) in six.iteritems(run_to_tag_to_content):<EOL><INDENT>session = _find_longest_parent_path(session_runs, run)<EOL>... | Computes the list of metric names from all the scalar (run, tag) pairs.
The return value is a list of (tag, group) pairs representing the metric
names. The list is sorted in Python tuple-order (lexicographical).
For example, if the scalar (run, tag) pairs are:
("exp/session1", "loss")
... | f7994:c0:m9 |
def model_fn(hparams, seed): | rng = random.Random(seed)<EOL>model = tf.keras.models.Sequential()<EOL>model.add(tf.keras.layers.Input(INPUT_SHAPE))<EOL>model.add(tf.keras.layers.Reshape(INPUT_SHAPE + (<NUM_LIT:1>,))) <EOL>conv_filters = <NUM_LIT:8><EOL>for _ in xrange(hparams[HP_CONV_LAYERS]):<EOL><INDENT>model.add(tf.keras.layers.Conv2D(<EOL>filte... | 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. | f7995:m0 |
def run(data, base_logdir, session_id, group_id, hparams): | model = model_fn(hparams=hparams, seed=session_id)<EOL>logdir = os.path.join(base_logdir, session_id)<EOL>callback = tf.keras.callbacks.TensorBoard(<EOL>logdir,<EOL>update_freq=flags.FLAGS.summary_freq,<EOL>profile_batch=<NUM_LIT:0>, <EOL>)<EOL>hparams_callback = hp.KerasCallback(logdir, hparams, group_name=group_id)<... | Run a training/validation session.
Flags must have been parsed for this function to behave.
Args:
data: The data as loaded by `prepare_data()`.
base_logdir: The top-level logdir to which to write summary data.
session_id: A unique string ID for this session.
group_id: The string ID of ... | f7995:m1 |
def prepare_data(): | ((x_train, y_train), (x_test, y_test)) = DATASET.load_data()<EOL>x_train = x_train.astype("<STR_LIT>")<EOL>x_test = x_test.astype("<STR_LIT>")<EOL>x_train /= <NUM_LIT><EOL>x_test /= <NUM_LIT><EOL>return ((x_train, y_train), (x_test, y_test))<EOL> | Load and normalize data. | f7995:m2 |
def run_all(logdir, verbose=False): | data = prepare_data()<EOL>rng = random.Random(<NUM_LIT:0>)<EOL>base_writer = tf.summary.create_file_writer(logdir)<EOL>with base_writer.as_default():<EOL><INDENT>experiment = hp.Experiment(hparams=HPARAMS, metrics=METRICS)<EOL>experiment_string = experiment.summary_pb().SerializeToString()<EOL>tf.summary.experimental.w... | 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. | f7995:m3 |
def sample_uniform(domain, rng): | if isinstance(domain, hp.IntInterval):<EOL><INDENT>return rng.randint(domain.min_value, domain.max_value)<EOL><DEDENT>elif isinstance(domain, hp.RealInterval):<EOL><INDENT>return rng.uniform(domain.min_value, domain.max_value)<EOL><DEDENT>elif isinstance(domain, hp.Discrete):<EOL><INDENT>return rng.choice(domain.values... | Sample a value uniformly from a domain.
Args:
domain: An `IntInterval`, `RealInterval`, or `Discrete` domain.
rng: A `random.Random` object; defaults to the `random` module.
Raises:
TypeError: If `domain` is not a known kind of domain.
IndexError: If the domain is empty. | f7995:m4 |
def load(self, context): | try:<EOL><INDENT>import tensorflow<EOL><DEDENT>except ImportError:<EOL><INDENT>return<EOL><DEDENT>from tensorboard.plugins.hparams.hparams_plugin import HParamsPlugin<EOL>return HParamsPlugin(context)<EOL> | Returns the plugin, if possible.
Args:
context: The TBContext flags.
Returns:
A HParamsPlugin instance or None if it couldn't be loaded. | f7996:c0:m0 |
def _create_key_func(extractor, none_is_largest): | if none_is_largest:<EOL><INDENT>def key_func_none_is_largest(session_group):<EOL><INDENT>value = extractor(session_group)<EOL>return (value is None, value)<EOL><DEDENT>return key_func_none_is_largest<EOL><DEDENT>def key_func_none_is_smallest(session_group):<EOL><INDENT>value = extractor(session_group)<EOL>return (value... | Returns a key_func to be used in list.sort().
Returns a key_func to be used in list.sort() that sorts session groups
by the value extracted by extractor. 'None' extracted values will either
be considered largest or smallest as specified by the "none_is_largest"
boolean parameter.
Args:
extra... | f7997:m0 |
def _create_extractors(col_params): | result = []<EOL>for col_param in col_params:<EOL><INDENT>result.append(_create_extractor(col_param))<EOL><DEDENT>return result<EOL> | Creates extractors to extract properties corresponding to 'col_params'.
Args:
col_params: List of ListSessionGroupsRequest.ColParam protobufs.
Returns:
A list of extractor functions. The ith element in the
returned list extracts the column corresponding to the ith element of
_request.co... | f7997:m1 |
def _create_metric_extractor(metric_name): | def extractor_fn(session_or_group):<EOL><INDENT>metric_value = _find_metric_value(session_or_group,<EOL>metric_name)<EOL>return metric_value.value if metric_value else None<EOL><DEDENT>return extractor_fn<EOL> | Returns function that extracts a metric from a session group or a session.
Args:
metric_name: tensorboard.hparams.MetricName protobuffer. Identifies the
metric to extract from the session group.
Returns:
A function that takes a tensorboard.hparams.SessionGroup or
tensorborad.hparams.Ses... | f7997:m3 |
def _find_metric_value(session_or_group, metric_name): | <EOL>for metric_value in session_or_group.metric_values:<EOL><INDENT>if (metric_value.name.tag == metric_name.tag and<EOL>metric_value.name.group == metric_name.group):<EOL><INDENT>return metric_value<EOL><DEDENT><DEDENT> | Returns the metric_value for a given metric in a session or session group.
Args:
session_or_group: A Session protobuffer or SessionGroup protobuffer.
metric_name: A MetricName protobuffer. The metric to search for.
Returns:
A MetricValue protobuffer representing the value of the given metric ... | f7997:m4 |
def _create_hparam_extractor(hparam_name): | def extractor_fn(session_group):<EOL><INDENT>if hparam_name in session_group.hparams:<EOL><INDENT>return _value_to_python(session_group.hparams[hparam_name])<EOL><DEDENT>return None<EOL><DEDENT>return extractor_fn<EOL> | Returns an extractor function that extracts an hparam from a session group.
Args:
hparam_name: str. Identies the hparam to extract from the session group.
Returns:
A function that takes a tensorboard.hparams.SessionGroup protobuffer and
returns the value, as a native Python object, of the hpa... | f7997:m5 |
def _create_filters(col_params, extractors): | result = []<EOL>for col_param, extractor in zip(col_params, extractors):<EOL><INDENT>a_filter = _create_filter(col_param, extractor)<EOL>if a_filter:<EOL><INDENT>result.append(a_filter)<EOL><DEDENT><DEDENT>return result<EOL> | Creates filters for the given col_params.
Args:
col_params: List of ListSessionGroupsRequest.ColParam protobufs.
extractors: list of extractor functions of the same length as col_params.
Each element should extract the column described by the corresponding
element of col_params.
Ret... | f7997:m6 |
def _create_filter(col_param, extractor): | include_missing_values = not col_param.exclude_missing_values<EOL>if col_param.HasField('<STR_LIT>'):<EOL><INDENT>value_filter_fn = _create_regexp_filter(col_param.filter_regexp)<EOL><DEDENT>elif col_param.HasField('<STR_LIT>'):<EOL><INDENT>value_filter_fn = _create_interval_filter(col_param.filter_interval)<EOL><DEDEN... | Creates a filter for the given col_param and extractor.
Args:
col_param: A tensorboard.hparams.ColParams object identifying the column
and describing the filter to apply.
extractor: A function that extract the column value identified by
'col_param' from a tensorboard.hparams.SessionGrou... | f7997:m7 |
def _create_regexp_filter(regex): | <EOL>compiled_regex = re.compile(regex)<EOL>def filter_fn(value):<EOL><INDENT>if not isinstance(value, six.string_types):<EOL><INDENT>raise error.HParamsError(<EOL>'<STR_LIT>' %<EOL>(type(value), value))<EOL><DEDENT>return re.search(compiled_regex, value) is not None<EOL><DEDENT>return filter_fn<EOL> | Returns a boolean function that filters strings based on a regular exp.
Args:
regex: A string describing the regexp to use.
Returns:
A function taking a string and returns True if any of its substrings
matches regex. | f7997:m8 |
def _create_interval_filter(interval): | def filter_fn(value):<EOL><INDENT>if (not isinstance(value, six.integer_types) and<EOL>not isinstance(value, float)):<EOL><INDENT>raise error.HParamsError(<EOL>'<STR_LIT>' %<EOL>(type(value), value))<EOL><DEDENT>return interval.min_value <= value and value <= interval.max_value<EOL><DEDENT>return filter_fn<EOL> | Returns a function that checkes whether a number belongs to an interval.
Args:
interval: A tensorboard.hparams.Interval protobuf describing the interval.
Returns:
A function taking a number (a float or an object of a type in
six.integer_types) that returns True if the number belongs to (the c... | f7997:m9 |
def _create_discrete_set_filter(discrete_set): | def filter_fn(value):<EOL><INDENT>return value in discrete_set<EOL><DEDENT>return filter_fn<EOL> | Returns a function that checks whether a value belongs to a set.
Args:
discrete_set: A list of objects representing the set.
Returns:
A function taking an object and returns True if its in the set. Membership
is tested using the Python 'in' operator (thus, equality of distinct
objects i... | f7997:m10 |
def _value_to_python(value): | assert isinstance(value, struct_pb2.Value)<EOL>field = value.WhichOneof('<STR_LIT>')<EOL>if field == '<STR_LIT>':<EOL><INDENT>return value.number_value<EOL><DEDENT>elif field == '<STR_LIT>':<EOL><INDENT>return value.string_value<EOL><DEDENT>elif field == '<STR_LIT>':<EOL><INDENT>return value.bool_value<EOL><DEDENT>else... | Converts a google.protobuf.Value to a native Python object. | f7997:m11 |
def _set_avg_session_metrics(session_group): | assert session_group.sessions, '<STR_LIT>'<EOL>metric_stats = collections.defaultdict(_MetricStats)<EOL>for session in session_group.sessions:<EOL><INDENT>for metric_value in session.metric_values:<EOL><INDENT>metric_name = _MetricIdentifier(group=metric_value.name.group,<EOL>tag=metric_value.name.tag)<EOL>stats = metr... | Sets the metrics for the group to be the average of its sessions.
The resulting session group metrics consist of the union of metrics across
the group's sessions. The value of each session group metric is the average
of that metric values across the sessions in the group. The 'step' and
'wall_time_secs... | f7997:m12 |
def _set_median_session_metrics(session_group, aggregation_metric): | measurements = sorted(_measurements(session_group, aggregation_metric),<EOL>key=operator.attrgetter('<STR_LIT>'))<EOL>median_session = measurements[(len(measurements) - <NUM_LIT:1>) // <NUM_LIT:2>].session_index<EOL>del session_group.metric_values[:]<EOL>session_group.metric_values.MergeFrom(<EOL>session_group.sessions... | Sets the metrics for session_group to those of its "median session".
The median session is the session in session_group with the median value
of the metric given by 'aggregation_metric'. The median is taken over the
subset of sessions in the group whose 'aggregation_metric' was measured
at the largest ... | f7997:m13 |
def _set_extremum_session_metrics(session_group, aggregation_metric,<EOL>extremum_fn): | measurements = _measurements(session_group, aggregation_metric)<EOL>ext_session = extremum_fn(<EOL>measurements,<EOL>key=operator.attrgetter('<STR_LIT>')).session_index<EOL>del session_group.metric_values[:]<EOL>session_group.metric_values.MergeFrom(<EOL>session_group.sessions[ext_session].metric_values)<EOL> | Sets the metrics for session_group to those of its "extremum session".
The extremum session is the session in session_group with the extremum value
of the metric given by 'aggregation_metric'. The extremum is taken over the
subset of sessions in the group whose 'aggregation_metric' was measured
at the ... | f7997:m14 |
def _measurements(session_group, metric_name): | for session_index, session in enumerate(session_group.sessions):<EOL><INDENT>metric_value = _find_metric_value(session, metric_name)<EOL>if not metric_value:<EOL><INDENT>continue<EOL><DEDENT>yield _Measurement(metric_value, session_index)<EOL><DEDENT> | A generator for the values of the metric across the sessions in the group.
Args:
session_group: A SessionGroup protobuffer.
metric_name: A MetricName protobuffer.
Yields:
The next metric value wrapped in a _Measurement instance. | f7997:m15 |
def __init__(self, context, request): | self._context = context<EOL>self._request = request<EOL>self._extractors = _create_extractors(request.col_params)<EOL>self._filters = _create_filters(request.col_params, self._extractors)<EOL>self._experiment = context.experiment()<EOL> | Constructor.
Args:
context: A backend_context.Context instance.
request: A ListSessionGroupsRequest protobuf. | f7997:c0:m0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.