signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def run(self):
session_groups = self._build_session_groups()<EOL>session_groups = self._filter(session_groups)<EOL>self._sort(session_groups)<EOL>return self._create_response(session_groups)<EOL>
Handles the request specified on construction. Returns: A ListSessionGroupsResponse object.
f7997:c0:m1
def _build_session_groups(self):
<EOL>groups_by_name = {}<EOL>run_to_tag_to_content = self._context.multiplexer.PluginRunToTagToContent(<EOL>metadata.PLUGIN_NAME)<EOL>for (run, tag_to_content) in six.iteritems(run_to_tag_to_content):<EOL><INDENT>if metadata.SESSION_START_INFO_TAG not in tag_to_content:<EOL><INDENT>continue<EOL><DEDENT>start_info = met...
Returns a list of SessionGroups protobuffers from the summary data.
f7997:c0:m2
def _add_session(self, session, start_info, groups_by_name):
<EOL>group_name = start_info.group_name or session.name<EOL>if group_name in groups_by_name:<EOL><INDENT>groups_by_name[group_name].sessions.extend([session])<EOL><DEDENT>else:<EOL><INDENT>group = api_pb2.SessionGroup(<EOL>name=group_name,<EOL>sessions=[session],<EOL>monitor_url=start_info.monitor_url)<EOL>for (key, va...
Adds a new Session protobuffer to the 'groups_by_name' dictionary. Called by _build_session_groups when we encounter a new session. Creates the Session protobuffer and adds it to the relevant group in the 'groups_by_name' dict. Creates the session group if this is the first time we enco...
f7997:c0:m3
def _build_session(self, name, start_info, end_info):
assert start_info is not None<EOL>result = api_pb2.Session(<EOL>name=name,<EOL>start_time_secs=start_info.start_time_secs,<EOL>model_uri=start_info.model_uri,<EOL>metric_values=self._build_session_metric_values(name),<EOL>monitor_url=start_info.monitor_url)<EOL>if end_info is not None:<EOL><INDENT>result.status = end_i...
Builds a session object.
f7997:c0:m4
def _build_session_metric_values(self, session_name):
<EOL>result = []<EOL>metric_infos = self._experiment.metric_infos<EOL>for metric_info in metric_infos:<EOL><INDENT>metric_name = metric_info.name<EOL>try:<EOL><INDENT>metric_eval = metrics.last_metric_eval(<EOL>self._context.multiplexer,<EOL>session_name,<EOL>metric_name)<EOL><DEDENT>except KeyError:<EOL><INDENT>contin...
Builds the session metric values.
f7997:c0:m5
def _aggregate_metrics(self, session_group):
if (self._request.aggregation_type == api_pb2.AGGREGATION_AVG or<EOL>self._request.aggregation_type == api_pb2.AGGREGATION_UNSET):<EOL><INDENT>_set_avg_session_metrics(session_group)<EOL><DEDENT>elif self._request.aggregation_type == api_pb2.AGGREGATION_MEDIAN:<EOL><INDENT>_set_median_session_metrics(session_group,<EOL...
Sets the metrics of the group based on aggregation_type.
f7997:c0:m6
def _sort(self, session_groups):
<EOL>session_groups.sort(key=operator.attrgetter('<STR_LIT:name>'))<EOL>for col_param, extractor in reversed(list(zip(self._request.col_params,<EOL>self._extractors))):<EOL><INDENT>if col_param.order == api_pb2.ORDER_UNSPECIFIED:<EOL><INDENT>continue<EOL><DEDENT>if col_param.order == api_pb2.ORDER_ASC:<EOL><INDENT>sess...
Sorts 'session_groups' in place according to _request.col_params.
f7997:c0:m9
def experiment_pb(<EOL>hparam_infos,<EOL>metric_infos,<EOL>user='<STR_LIT>',<EOL>description='<STR_LIT>',<EOL>time_created_secs=None):
if time_created_secs is None:<EOL><INDENT>time_created_secs = time.time()<EOL><DEDENT>experiment = api_pb2.Experiment(<EOL>description=description,<EOL>user=user,<EOL>time_created_secs=time_created_secs,<EOL>hparam_infos=hparam_infos,<EOL>metric_infos=metric_infos)<EOL>return _summary(metadata.EXPERIMENT_TAG,<EOL>plugi...
Creates a summary that defines a hyperparameter-tuning experiment. Args: hparam_infos: Array of api_pb2.HParamInfo messages. Describes the hyperparameters used in the experiment. metric_infos: Array of api_pb2.MetricInfo messages. Describes the metrics used in the experiment. See th...
f7998:m0
def session_start_pb(hparams,<EOL>model_uri='<STR_LIT>',<EOL>monitor_url='<STR_LIT>',<EOL>group_name='<STR_LIT>',<EOL>start_time_secs=None):
if start_time_secs is None:<EOL><INDENT>start_time_secs = time.time()<EOL><DEDENT>session_start_info = plugin_data_pb2.SessionStartInfo(<EOL>model_uri=model_uri,<EOL>monitor_url=monitor_url,<EOL>group_name=group_name,<EOL>start_time_secs=start_time_secs)<EOL>for (hp_name, hp_val) in six.iteritems(hparams):<EOL><INDENT>...
Constructs a SessionStartInfo protobuffer. Creates a summary that contains a training session metadata information. One such summary per training session should be created. Each should have a different run. Args: hparams: A dictionary with string keys. Describes the hyperparameter values ...
f7998:m1
def session_end_pb(status, end_time_secs=None):
if end_time_secs is None:<EOL><INDENT>end_time_secs = time.time()<EOL><DEDENT>session_end_info = plugin_data_pb2.SessionEndInfo(status=status,<EOL>end_time_secs=end_time_secs)<EOL>return _summary(metadata.SESSION_END_INFO_TAG,<EOL>plugin_data_pb2.HParamsPluginData(<EOL>session_end_info=session_end_info))<EOL>
Constructs a SessionEndInfo protobuffer. Creates a summary that contains status information for a completed training session. Should be exported after the training session is completed. One such summary per training session should be created. Each should have a different run. Args: status: A...
f7998:m2
def _summary(tag, hparams_plugin_data):
summary = tf.compat.v1.Summary()<EOL>summary.value.add(<EOL>tag=tag,<EOL>metadata=metadata.create_summary_metadata(hparams_plugin_data))<EOL>return summary<EOL>
Returns a summary holding the given HParamsPluginData message. Helper function. Args: tag: string. The tag to use. hparams_plugin_data: The HParamsPluginData message to use.
f7998:m3
def create_experiment_summary():
<EOL>temperature_list = struct_pb2.ListValue()<EOL>temperature_list.extend(TEMPERATURE_LIST)<EOL>materials = struct_pb2.ListValue()<EOL>materials.extend(HEAT_COEFFICIENTS.keys())<EOL>return summary.experiment_pb(<EOL>hparam_infos=[<EOL>api_pb2.HParamInfo(name='<STR_LIT>',<EOL>display_name='<STR_LIT>',<EOL>type=api_pb2....
Returns a summary proto buffer holding this experiment.
f7999:m2
def run(logdir, session_id, hparams, group_name):
tf.reset_default_graph()<EOL>tf.set_random_seed(<NUM_LIT:0>)<EOL>initial_temperature = hparams['<STR_LIT>']<EOL>ambient_temperature = hparams['<STR_LIT>']<EOL>heat_coefficient = HEAT_COEFFICIENTS[hparams['<STR_LIT>']]<EOL>session_dir = os.path.join(logdir, session_id)<EOL>writer = tf.summary.FileWriter(session_dir)<EOL...
Runs a temperature simulation. This will simulate an object at temperature `initial_temperature` sitting at rest in a large room at temperature `ambient_temperature`. The object has some intrinsic `heat_coefficient`, which indicates how much thermal conductivity it has: for instance, metals have high ...
f7999:m3
def run_all(logdir, verbose=False):
writer = tf.summary.FileWriter(logdir)<EOL>writer.add_summary(create_experiment_summary())<EOL>writer.close()<EOL>session_num = <NUM_LIT:0><EOL>num_sessions = (len(TEMPERATURE_LIST)*len(TEMPERATURE_LIST)*<EOL>len(HEAT_COEFFICIENTS)*<NUM_LIT:2>)<EOL>for initial_temperature in TEMPERATURE_LIST:<EOL><INDENT>for ambient_te...
Run simulations on a reasonable set of parameters. Arguments: logdir: the directory into which to store all the runs' data verbose: if true, print out each run's name as it begins.
f7999:m4
def create_summary_metadata(hparams_plugin_data_pb):
if not isinstance(hparams_plugin_data_pb, plugin_data_pb2.HParamsPluginData):<EOL><INDENT>raise TypeError('<STR_LIT>'<EOL>'<STR_LIT>' % type(hparams_plugin_data_pb))<EOL><DEDENT>content = plugin_data_pb2.HParamsPluginData()<EOL>content.CopyFrom(hparams_plugin_data_pb)<EOL>content.version = PLUGIN_DATA_VERSION<EOL>retur...
Returns a summary metadata for the HParams plugin. Returns a summary_pb2.SummaryMetadata holding a copy of the given HParamsPluginData message in its plugin_data.content field. Sets the version field of the hparams_plugin_data_pb copy to PLUGIN_DATA_VERSION. Args: hparams_plugin_data_pb: the...
f8001:m0
def parse_experiment_plugin_data(content):
return _parse_plugin_data_as(content, '<STR_LIT>')<EOL>
Returns the experiment from HParam's SummaryMetadata.plugin_data.content. Raises HParamsError if the content doesn't have 'experiment' set or this file is incompatible with the version of the metadata stored. Args: content: The SummaryMetadata.plugin_data.content to use.
f8001:m1
def parse_session_start_info_plugin_data(content):
return _parse_plugin_data_as(content, '<STR_LIT>')<EOL>
Returns session_start_info from the plugin_data.content. Raises HParamsError if the content doesn't have 'session_start_info' set or this file is incompatible with the version of the metadata stored. Args: content: The SummaryMetadata.plugin_data.content to use.
f8001:m2
def parse_session_end_info_plugin_data(content):
return _parse_plugin_data_as(content, '<STR_LIT>')<EOL>
Returns session_end_info from the plugin_data.content. Raises HParamsError if the content doesn't have 'session_end_info' set or this file is incompatible with the version of the metadata stored. Args: content: The SummaryMetadata.plugin_data.content to use.
f8001:m3
def _parse_plugin_data_as(content, data_oneof_field):
plugin_data = plugin_data_pb2.HParamsPluginData.FromString(content)<EOL>if plugin_data.version != PLUGIN_DATA_VERSION:<EOL><INDENT>raise error.HParamsError(<EOL>'<STR_LIT>' %<EOL>(PLUGIN_DATA_VERSION, plugin_data.version, plugin_data))<EOL><DEDENT>if not plugin_data.HasField(data_oneof_field):<EOL><INDENT>raise error.H...
Returns a data oneof's field from plugin_data.content. Raises HParamsError if the content doesn't have 'data_oneof_field' set or this file is incompatible with the version of the metadata stored. Args: content: The SummaryMetadata.plugin_data.content to use. data_oneof_field: string. The name ...
f8001:m4
def _canonicalize_experiment(exp):
exp.hparam_infos.sort(key=operator.attrgetter('<STR_LIT:name>'))<EOL>exp.metric_infos.sort(key=operator.attrgetter('<STR_LIT>', '<STR_LIT>'))<EOL>for hparam_info in exp.hparam_infos:<EOL><INDENT>if hparam_info.HasField('<STR_LIT>'):<EOL><INDENT>hparam_info.domain_discrete.values.sort(<EOL>key=operator.attrgetter('<STR_...
Sorts the repeated fields of an Experiment message.
f8002:m0
def __init__(self, context):
self._context = backend_context.Context(context)<EOL>
Instantiates HParams plugin via TensorBoard core. Args: context: A base_plugin.TBContext instance.
f8005:c0:m0
def get_plugin_apps(self):
return {<EOL>'<STR_LIT>': self.get_experiment_route,<EOL>'<STR_LIT>': self.list_session_groups_route,<EOL>'<STR_LIT>': self.list_metric_evals_route,<EOL>}<EOL>
See base class.
f8005:c0:m1
def is_active(self):
if not self._context.multiplexer:<EOL><INDENT>return False<EOL><DEDENT>scalars_plugin = self._get_scalars_plugin()<EOL>if not scalars_plugin or not scalars_plugin.is_active():<EOL><INDENT>return False<EOL><DEDENT>return bool(self._context.multiplexer.PluginRunToTagToContent(<EOL>metadata.PLUGIN_NAME))<EOL>
Returns True if the hparams plugin is active. The hparams plugin is active iff there is a tag with the hparams plugin name as its plugin name and the scalars plugin is registered and active.
f8005:c0:m2
def _get_scalars_plugin(self):
return self._context.tb_context.plugin_name_to_instance.get(<EOL>scalars_metadata.PLUGIN_NAME)<EOL>
Tries to get the scalars plugin. Returns: The scalars plugin or None if it is not yet registered.
f8005:c0:m6
def _normalize_hparams(hparams):
result = {}<EOL>for (k, v) in six.iteritems(hparams):<EOL><INDENT>if isinstance(k, HParam):<EOL><INDENT>k = k.name<EOL><DEDENT>if k in result:<EOL><INDENT>raise ValueError("<STR_LIT>" % (k,))<EOL><DEDENT>result[k] = v<EOL><DEDENT>return result<EOL>
Normalize a dict keyed by `HParam`s and/or raw strings. Args: hparams: A `dict` whose keys are `HParam` objects and/or strings representing hyperparameter names, and whose values are hyperparameter values. No two keys may have the same name. Returns: A `dict` whose keys are hyperpa...
f8006:m0
def __init__(<EOL>self,<EOL>hparams,<EOL>metrics,<EOL>user=None,<EOL>description=None,<EOL>time_created_secs=None,<EOL>):
self._hparams = list(hparams)<EOL>self._metrics = list(metrics)<EOL>self._user = user<EOL>self._description = description<EOL>if time_created_secs is None:<EOL><INDENT>time_created_secs = time.time()<EOL><DEDENT>self._time_created_secs = time_created_secs<EOL>
Create an experiment object. Args: hparams: A list of `HParam` values. metrics: A list of `Metric` values. user: An optional string denoting the user or group that owns this experiment. description: An optional Markdown string describing this expe...
f8006:c0:m0
def summary_pb(self):
hparam_infos = []<EOL>for hparam in self._hparams:<EOL><INDENT>info = api_pb2.HParamInfo(<EOL>name=hparam.name,<EOL>description=hparam.description,<EOL>display_name=hparam.display_name,<EOL>)<EOL>domain = hparam.domain<EOL>if domain is not None:<EOL><INDENT>domain.update_hparam_info(info)<EOL><DEDENT>hparam_infos.appen...
Create a top-level experiment summary describing this experiment. The resulting summary should be written to a log directory that encloses all the individual sessions' log directories. Analogous to the low-level `experiment_pb` function in the `hparams.summary` module.
f8006:c0:m6
def __init__(self, name, domain=None, display_name=None, description=None):
self._name = name<EOL>self._domain = domain<EOL>self._display_name = display_name<EOL>self._description = description<EOL>if not isinstance(self._domain, (Domain, type(None))):<EOL><INDENT>raise ValueError("<STR_LIT>" % (self._domain,))<EOL><DEDENT>
Create a hyperparameter object. Args: name: A string ID for this hyperparameter, which should be unique within an experiment. domain: An optional `Domain` object describing the values that this hyperparameter can take on. display_name: An optional human-rea...
f8006:c1:m0
@abc.abstractproperty<EOL><INDENT>def dtype(self):<DEDENT>
pass<EOL>
Data type of this domain: `float`, `int`, `str`, or `bool`.
f8006:c2:m0
@abc.abstractmethod<EOL><INDENT>def update_hparam_info(self, hparam_info):<DEDENT>
pass<EOL>
Update an `HParamInfo` proto to include this domain. This should update the `type` field on the proto and exactly one of the `domain` variants on the proto. Args: hparam_info: An `api_pb2.HParamInfo` proto to modify.
f8006:c2:m1
def __init__(self, min_value=None, max_value=None):
if not isinstance(min_value, int):<EOL><INDENT>raise TypeError("<STR_LIT>" % (min_value,))<EOL><DEDENT>if not isinstance(max_value, int):<EOL><INDENT>raise TypeError("<STR_LIT>" % (max_value,))<EOL><DEDENT>if min_value > max_value:<EOL><INDENT>raise ValueError("<STR_LIT>" % (min_value, max_value))<EOL><DEDENT>self._min...
Create an `IntInterval`. Args: min_value: The lower bound (inclusive) of the interval. max_value: The upper bound (inclusive) of the interval. Raises: TypeError: If `min_value` or `max_value` is not an `int`. ValueError: If `min_value > max_value`.
f8006:c3:m0
def __init__(self, min_value=None, max_value=None):
if not isinstance(min_value, float):<EOL><INDENT>raise TypeError("<STR_LIT>" % (min_value,))<EOL><DEDENT>if not isinstance(max_value, float):<EOL><INDENT>raise TypeError("<STR_LIT>" % (max_value,))<EOL><DEDENT>if min_value > max_value:<EOL><INDENT>raise ValueError("<STR_LIT>" % (min_value, max_value))<EOL><DEDENT>self....
Create a `RealInterval`. Args: min_value: The lower bound (inclusive) of the interval. max_value: The upper bound (inclusive) of the interval. Raises: TypeError: If `min_value` or `max_value` is not an `float`. ValueError: If `min_value > max_value`.
f8006:c4:m0
def __init__(self, values, dtype=None):
self._values = list(values)<EOL>if dtype is None:<EOL><INDENT>if self._values:<EOL><INDENT>dtype = type(self._values[<NUM_LIT:0>])<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>if dtype not in (int, float, bool, str):<EOL><INDENT>raise ValueError("<STR_LIT>" % (dtype,))<EOL><DEDENT>sel...
Construct a discrete domain. Args: values: A iterable of the values in this domain. dtype: The Python data type of values in this domain: one of `int`, `float`, `bool`, or `str`. If `values` is non-empty, `dtype` may be `None`, in which case it will be inferred as th...
f8006:c5:m0
def __init__(<EOL>self,<EOL>tag,<EOL>group=None,<EOL>display_name=None,<EOL>description=None,<EOL>dataset_type=None,<EOL>):
self._tag = tag<EOL>self._group = group<EOL>self._display_name = display_name<EOL>self._description = description<EOL>self._dataset_type = dataset_type<EOL>if self._dataset_type not in (None, Metric.TRAINING, Metric.VALIDATION):<EOL><INDENT>raise ValueError("<STR_LIT>" % (self._dataset_type,))<EOL><DEDENT>
Args: tag: The tag name of the scalar summary that corresponds to this metric (as a `str`). group: An optional string listing the subdirectory under the session's log directory containing summaries for this metric. For instance, if summaries for training runs are written to events files in `ROOT_LOG...
f8006:c6:m0
def __init__(<EOL>self,<EOL>writer,<EOL>hparams,<EOL>group_name=None,<EOL>):
self._hparams = _normalize_hparams(hparams)<EOL>self._group_name = group_name if group_name is not None else "<STR_LIT>"<EOL>if writer is None:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>elif isinstance(writer, str):<EOL><INDENT>self._writer = tf.compat.v2.summary.create_file_writer(writer)<EOL><DEDENT>else:<...
Create a callback for logging hyperparameters to TensorBoard. As with the standard `tf.keras.callbacks.TensorBoard` class, each callback object is valid for only one call to `model.fit`. Args: writer: The `SummaryWriter` object to which hparams should be written, or a log...
f8006:c7:m0
def value_to_python(value):
<EOL>l = struct_pb2.ListValue(values=[value])<EOL>return l[<NUM_LIT:0>]<EOL>
Converts a google.protobuf.Value to a native python object.
f8008:m3
def __init__(self, request, scalars_plugin_instance):
self._request = request<EOL>self._scalars_plugin_instance = scalars_plugin_instance<EOL>
Constructor. Args: request: A ListSessionGroupsRequest protobuf. scalars_plugin_instance: A scalars_plugin.ScalarsPlugin.
f8009:c0:m0
def run(self):
run, tag = metrics.run_tag_from_session_and_metric(<EOL>self._request.session_name, self._request.metric_name)<EOL>body, _ = self._scalars_plugin_instance.scalars_impl(<EOL>tag, run, None, scalars_plugin.OutputFormat.JSON)<EOL>return body<EOL>
Executes the request. Returns: An array of tuples representing the metric evaluations--each of the form (<wall time in secs>, <training step>, <metric value>).
f8009:c0:m1
def __init__(self, context):
self._context = context<EOL>
Constructor. Args: context: A backend_context.Context instance.
f8010:c0:m0
def run(self):
experiment = self._context.experiment()<EOL>if experiment is None:<EOL><INDENT>raise error.HParamsError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>return experiment<EOL>
Handles the request specified on construction. Returns: An Experiment object.
f8010:c0:m1
def make_table_row(contents, tag='<STR_LIT>'):
columns = ('<STR_LIT>' % (tag, s, tag) for s in contents)<EOL>return '<STR_LIT>' + '<STR_LIT>'.join(columns) + '<STR_LIT>'<EOL>
Given an iterable of string contents, make a table row. Args: contents: An iterable yielding strings. tag: The tag to place contents in. Defaults to 'td', you might want 'th'. Returns: A string containing the content strings, organized into a table row. Example: make_table_row(['one', '...
f8011:m0
def make_table(contents, headers=None):
if not isinstance(contents, np.ndarray):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if contents.ndim not in [<NUM_LIT:1>, <NUM_LIT:2>]:<EOL><INDENT>raise ValueError('<STR_LIT>' %<EOL>contents.ndim)<EOL><DEDENT>if headers:<EOL><INDENT>if isinstance(headers, (list, tuple)):<EOL><INDENT>headers = np.array(heade...
Given a numpy ndarray of strings, concatenate them into a html table. Args: contents: A np.ndarray of strings. May be 1d or 2d. In the 1d case, the table is laid out vertically (i.e. row-major). headers: A np.ndarray or list of string header names for the table. Returns: A string con...
f8011:m1
def reduce_to_2d(arr):
if not isinstance(arr, np.ndarray):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>ndims = len(arr.shape)<EOL>if ndims < <NUM_LIT:2>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>slices = ([<NUM_LIT:0>] * (ndims - <NUM_LIT:2>)) + [slice(None), slice(None)]<EOL>return arr[slices]<EOL>
Given a np.npdarray with nDims > 2, reduce it to 2d. It does this by selecting the zeroth coordinate for every dimension greater than two. Args: arr: a numpy ndarray of dimension at least 2. Returns: A two-dimensional subarray from the input array. Raises: ValueError: If the ar...
f8011:m2
def text_array_to_html(text_arr):
if not text_arr.shape:<EOL><INDENT>return plugin_util.markdown_to_safe_html(np.asscalar(text_arr))<EOL><DEDENT>warning = '<STR_LIT>'<EOL>if len(text_arr.shape) > <NUM_LIT:2>:<EOL><INDENT>warning = plugin_util.markdown_to_safe_html(WARNING_TEMPLATE<EOL>% len(text_arr.shape))<EOL>text_arr = reduce_to_2d(text_arr)<EOL><DE...
Take a numpy.ndarray containing strings, and convert it into html. If the ndarray contains a single scalar string, that string is converted to html via our sanitized markdown parser. If it contains an array of strings, the strings are individually converted to html and then composed into a table using ...
f8011:m3
def process_string_tensor_event(event):
string_arr = tensor_util.make_ndarray(event.tensor_proto)<EOL>html = text_array_to_html(string_arr)<EOL>return {<EOL>'<STR_LIT>': event.wall_time,<EOL>'<STR_LIT>': event.step,<EOL>'<STR_LIT:text>': html,<EOL>}<EOL>
Convert a TensorEvent into a JSON-compatible response.
f8011:m4
def __init__(self, context):
self._multiplexer = context.multiplexer<EOL>self._index_cached = None<EOL>self._index_impl_lock = threading.Lock()<EOL>self._index_impl_thread = None<EOL>
Instantiates TextPlugin via TensorBoard core. Args: context: A base_plugin.TBContext instance.
f8011:c0:m0
def is_active(self):
if not self._multiplexer:<EOL><INDENT>return False<EOL><DEDENT>if self._index_cached is not None:<EOL><INDENT>if any(self._index_cached.values()):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>if self._multiplexer.PluginRunToTagToContent(metadata.PLUGIN_NAME):<EOL><INDENT>return True<EOL><DEDENT>self._maybe_launch_index_...
Determines whether this plugin is active. This plugin is only active if TensorBoard sampled any text summaries. Returns: Whether this plugin is active.
f8011:c0:m1
def _maybe_launch_index_impl_thread(self):
<EOL>if self._index_impl_lock.acquire(False):<EOL><INDENT>self._index_impl_thread = threading.Thread(<EOL>target=self._async_index_impl,<EOL>name='<STR_LIT>')<EOL>self._index_impl_thread.start()<EOL><DEDENT>
Attempts to launch a thread to compute index_impl(). This may not launch a new thread if one is already running to compute index_impl(); in that case, this function is a no-op.
f8011:c0:m2
def _async_index_impl(self):
start = time.time()<EOL>logger.info('<STR_LIT>')<EOL>self._index_cached = self.index_impl()<EOL>self._index_impl_thread = None<EOL>self._index_impl_lock.release()<EOL>elapsed = time.time() - start<EOL>logger.info(<EOL>'<STR_LIT>', elapsed)<EOL>
Computes index_impl() asynchronously on a separate thread.
f8011:c0:m3
def op(name,<EOL>data,<EOL>display_name=None,<EOL>description=None,<EOL>collections=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, description=description)<EOL>with tf.name_scope(name):<EOL><INDENT>with tf.control_dependencies([tf.assert_type(data, tf.str...
Create a legacy text summary op. Text data summarized via this plugin will be visible in the Text Dashboard in TensorBoard. The standard TensorBoard Text Dashboard will render markdown in the strings, and will automatically organize 1D and 2D tensors into tables. If a tensor with more than 2 dimensions...
f8012:m0
def pb(name, data, display_name=None, description=None):
<EOL>import tensorflow.compat.v1 as tf<EOL>try:<EOL><INDENT>tensor = tf.make_tensor_proto(data, dtype=tf.string)<EOL><DEDENT>except TypeError as e:<EOL><INDENT>raise ValueError(e)<EOL><DEDENT>if display_name is None:<EOL><INDENT>display_name = name<EOL><DEDENT>summary_metadata = metadata.create_summary_metadata(<EOL>di...
Create a legacy text summary protobuf. Arguments: name: A name for the generated node. Will also serve as a series name in TensorBoard. data: A Python bytestring (of type bytes), or Unicode string. Or a numpy data array of those types. display_name: Optional name for this summary ...
f8012:m1
def assertIsActive(self, plugin, expected_finally_is_active):
patcher = tf.compat.v1.test.mock.patch('<STR_LIT>', autospec=True)<EOL>mock = patcher.start()<EOL>self.addCleanup(patcher.stop)<EOL>self.assertFalse(plugin.is_active())<EOL>thread = plugin._index_impl_thread<EOL>mock.assert_called_once_with(thread)<EOL>self.assertFalse(plugin.is_active())<EOL>mock.assert_called_once_wi...
Helper to simulate threading for asserting on is_active().
f8014:c0:m9
def create_summary_metadata(display_name, description):
content = plugin_data_pb2.TextPluginData(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 metada...
Create a `summary_pb2.SummaryMetadata` proto for text plugin data. Returns: A `summary_pb2.SummaryMetadata` protobuf object.
f8015:m0
def parse_plugin_metadata(content):
if not isinstance(content, bytes):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>result = plugin_data_pb2.TextPluginData.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 text plugin. Returns: A `TextPluginData` protobuf object.
f8015:m1
def text(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 text 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 UTF-8 string tensor value. step: Explicit `int64`-castable monotonic step value for this summary. If omitted, this def...
f8017:m0
def text_pb(tag, data, description=None):
try:<EOL><INDENT>tensor = tensor_util.make_tensor_proto(data, dtype=np.object)<EOL><DEDENT>except TypeError as e:<EOL><INDENT>raise TypeError('<STR_LIT>', e)<EOL><DEDENT>summary_metadata = metadata.create_summary_metadata(<EOL>display_name=None, description=description)<EOL>summary = summary_pb2.Summary()<EOL>summary.v...
Create a text tf.Summary protobuf. Arguments: tag: String tag for the summary. data: A Python bytestring (of type bytes), a Unicode string, or a numpy data array of those types. description: Optional long-form description for this summary, as a `str`. Markdown is supported. Defaul...
f8017:m1
def __init__(self, examples):
self.config = {}<EOL>self.set_examples(examples)<EOL>self.set_model_type('<STR_LIT>')<EOL>self.set_label_vocab([])<EOL>
Constructs the WitConfigBuilder object. Args: examples: A list of tf.Example or tf.SequenceExample proto objects. These are the examples that will be displayed in WIT. If not model to infer these examples with is specified through the methods on this class, then WIT will...
f8020:c0:m0
def build(self):
return self.config<EOL>
Returns the configuration set through use of this builder object. Used by WitWidget to set the settings on an instance of the What-If Tool.
f8020:c0:m1
def set_examples(self, examples):
self.store('<STR_LIT>', examples)<EOL>if len(examples) > <NUM_LIT:0>:<EOL><INDENT>self.store('<STR_LIT>',<EOL>isinstance(examples[<NUM_LIT:0>], tf.train.SequenceExample))<EOL><DEDENT>return self<EOL>
Sets the examples to be displayed in WIT. Args: examples: List of example protos. Returns: self, in order to enabled method chaining.
f8020:c0:m4
def set_model_type(self, model):
self.store('<STR_LIT>', model)<EOL>return self<EOL>
Sets the type of the model being used for inference. Args: model: The model type, such as "classification" or "regression". The model type defaults to "classification". Returns: self, in order to enabled method chaining.
f8020:c0:m5
def set_inference_address(self, address):
self.store('<STR_LIT>', address)<EOL>return self<EOL>
Sets the inference address for model inference through TF Serving. Args: address: The address of the served model, including port, such as "localhost:8888". Returns: self, in order to enabled method chaining.
f8020:c0:m6
def set_model_name(self, name):
self.store('<STR_LIT>', name)<EOL>return self<EOL>
Sets the model name for model inference through TF Serving. Setting a model name is required if inferring through a model hosted by TF Serving. Args: name: The name of the model to be queried through TF Serving at the address provided by set_inference_address. Retu...
f8020:c0:m7
def set_model_version(self, version):
self.store('<STR_LIT>', version)<EOL>return self<EOL>
Sets the optional model version for model inference through TF Serving. Args: version: The string version number of the model to be queried through TF Serving. This is optional, as TF Serving will use the latest model version if none is provided. Returns: self, ...
f8020:c0:m9
def set_model_signature(self, signature):
self.store('<STR_LIT>', signature)<EOL>return self<EOL>
Sets the optional model signature for model inference through TF Serving. Args: signature: The string signature of the model to be queried through TF Serving. This is optional, as TF Serving will use the default model signature if none is provided. Returns: self...
f8020:c0:m10
def set_compare_inference_address(self, address):
self.store('<STR_LIT>', address)<EOL>return self<EOL>
Sets the inference address for model inference for a second model hosted by TF Serving. If you wish to compare the results of two models in WIT, use this method to setup the details of the second model. Args: address: The address of the served model, including port, such as ...
f8020:c0:m11
def set_compare_model_name(self, name):
self.store('<STR_LIT>', name)<EOL>return self<EOL>
Sets the model name for a second model hosted by TF Serving. If you wish to compare the results of two models in WIT, use this method to setup the details of the second model. Setting a model name is required if inferring through a model hosted by TF Serving. Args: n...
f8020:c0:m12
def set_compare_model_version(self, version):
self.store('<STR_LIT>', version)<EOL>return self<EOL>
Sets the optional model version for a second model hosted by TF Serving. If you wish to compare the results of two models in WIT, use this method to setup the details of the second model. Args: version: The string version number of the model to be queried through TF Serving...
f8020:c0:m14
def set_compare_model_signature(self, signature):
self.store('<STR_LIT>', signature)<EOL>return self<EOL>
Sets the optional model signature for a second model hosted by TF Serving. If you wish to compare the results of two models in WIT, use this method to setup the details of the second model. Args: signature: The string signature of the model to be queried through TF ...
f8020:c0:m15
def set_uses_predict_api(self, predict):
self.store('<STR_LIT>', predict)<EOL>return self<EOL>
Indicates that the model uses the Predict API, as opposed to the Classification or Regression API. If the model doesn't use the standard Classification or Regression APIs provided through TF Serving, but instead uses the more flexible Predict API, then use this method to indicate that. ...
f8020:c0:m16
def set_max_classes_to_display(self, max_classes):
self.store('<STR_LIT>', max_classes)<EOL>return self<EOL>
Sets the maximum number of class results to display for multiclass classification models. When using WIT with a multiclass model with a large number of possible classes, it can be helpful to restrict WIT to only display some smaller number of the highest-scoring classes as inference res...
f8020:c0:m17
def set_multi_class(self, multiclass):
self.store('<STR_LIT>', multiclass)<EOL>return self<EOL>
Sets if the model(s) to query are mutliclass classification models. Args: multiclass: True if the model or models are multiclass classififcation models. Defaults to false. Returns: self, in order to enabled method chaining.
f8020:c0:m18
def set_predict_input_tensor(self, tensor):
self.store('<STR_LIT>', tensor)<EOL>return self<EOL>
Sets the name of the input tensor for models that use the Predict API. If using WIT with set_uses_predict_api(True), then call this to specify the name of the input tensor of the model or models that accepts the example proto for inference. Args: tensor: The name of the input...
f8020:c0:m19
def set_predict_output_tensor(self, tensor):
self.store('<STR_LIT>', tensor)<EOL>return self<EOL>
Sets the name of the output tensor for models that use the Predict API. If using WIT with set_uses_predict_api(True), then call this to specify the name of the output tensor of the model or models that returns the inference results to be explored by WIT. Args: tensor: The nam...
f8020:c0:m20
def set_label_vocab(self, vocab):
self.store('<STR_LIT>', vocab)<EOL>return self<EOL>
Sets the string value of numeric labels for classification models. For classification models, the model returns scores for each class ID number (classes 0 and 1 for binary classification models). In order for WIT to visually display the results in a more-readable way, you can specify st...
f8020:c0:m21
def set_estimator_and_feature_spec(self, estimator, feature_spec):
<EOL>self.delete('<STR_LIT>')<EOL>self.store('<STR_LIT>', {<EOL>'<STR_LIT>': estimator, '<STR_LIT>': feature_spec})<EOL>self.set_inference_address('<STR_LIT>')<EOL>if not self.has_model_name():<EOL><INDENT>self.set_model_name('<STR_LIT:1>')<EOL><DEDENT>return self<EOL>
Sets the model for inference as a TF Estimator. Instead of using TF Serving to host a model for WIT to query, WIT can directly use a TF Estimator object as the model to query. In order to accomplish this, a feature_spec must also be provided to parse the example protos for input into th...
f8020:c0:m22
def set_compare_estimator_and_feature_spec(self, estimator, feature_spec):
<EOL>self.delete('<STR_LIT>')<EOL>self.store('<STR_LIT>', {<EOL>'<STR_LIT>': estimator, '<STR_LIT>': feature_spec})<EOL>self.set_compare_inference_address('<STR_LIT>')<EOL>if not self.has_compare_model_name():<EOL><INDENT>self.set_compare_model_name('<STR_LIT:2>')<EOL><DEDENT>return self<EOL>
Sets a second model for inference as a TF Estimator. If you wish to compare the results of two models in WIT, use this method to setup the details of the second model. Instead of using TF Serving to host a model for WIT to query, WIT can directly use a TF Estimator object as the model ...
f8020:c0:m23
def set_custom_predict_fn(self, predict_fn):
<EOL>self.delete('<STR_LIT>')<EOL>self.store('<STR_LIT>', predict_fn)<EOL>self.set_inference_address('<STR_LIT>')<EOL>if not self.has_model_name():<EOL><INDENT>self.set_model_name('<STR_LIT:1>')<EOL><DEDENT>return self<EOL>
Sets a custom function for inference. Instead of using TF Serving to host a model for WIT to query, WIT can directly use a custom function as the model to query. In this case, the provided function should accept example protos and return: - For classification: A 2D list of numbers. Th...
f8020:c0:m24
def set_compare_custom_predict_fn(self, predict_fn):
<EOL>self.delete('<STR_LIT>')<EOL>self.store('<STR_LIT>', predict_fn)<EOL>self.set_compare_inference_address('<STR_LIT>')<EOL>if not self.has_compare_model_name():<EOL><INDENT>self.set_compare_model_name('<STR_LIT:2>')<EOL><DEDENT>return self<EOL>
Sets a second custom function for inference. If you wish to compare the results of two models in WIT, use this method to setup the details of the second model. Instead of using TF Serving to host a model for WIT to query, WIT can directly use a custom function as the model to query. In...
f8020:c0:m25
def __init__(self, config_builder, height=<NUM_LIT:1000>):
tf.logging.set_verbosity(tf.logging.WARN)<EOL>config = config_builder.build()<EOL>copied_config = dict(config)<EOL>self.estimator_and_spec = (<EOL>dict(config.get('<STR_LIT>'))<EOL>if '<STR_LIT>' in config else {})<EOL>self.compare_estimator_and_spec = (<EOL>dict(config.get('<STR_LIT>'))<EOL>if '<STR_LIT>' in config el...
Constructor for colab notebook WitWidget. Args: config_builder: WitConfigBuilder object containing settings for WIT. height: Optional height in pixels for WIT to occupy. Defaults to 1000.
f8022:c0:m0
def __init__(self, config_builder, height=<NUM_LIT:1000>):
super(WitWidget, self).__init__(layout=Layout(height='<STR_LIT>' % height))<EOL>tf.logging.set_verbosity(tf.logging.WARN)<EOL>config = config_builder.build()<EOL>copied_config = dict(config)<EOL>self.estimator_and_spec = (<EOL>dict(config.get('<STR_LIT>'))<EOL>if '<STR_LIT>' in config else {})<EOL>self.compare_estimato...
Constructor for Jupyter notebook WitWidget. Args: config_builder: WitConfigBuilder object containing settings for WIT. height: Optional height in pixels for WIT to occupy. Defaults to 1000.
f8023:c0:m0
def load(self, context):
try:<EOL><INDENT>import tensorflow<EOL><DEDENT>except ImportError:<EOL><INDENT>return<EOL><DEDENT>from tensorboard.plugins.interactive_inference.interactive_inference_plugin import InteractiveInferencePlugin<EOL>return InteractiveInferencePlugin(context)<EOL>
Returns the plugin, if possible. Args: context: The TBContext flags. Returns: A InteractiveInferencePlugin instance or None if it couldn't be loaded.
f8025:c0:m0
def filepath_to_filepath_list(file_path):
file_path = file_path.strip()<EOL>if '<STR_LIT:*>' in file_path:<EOL><INDENT>return glob(file_path)<EOL><DEDENT>else:<EOL><INDENT>return [file_path]<EOL><DEDENT>
Returns a list of files given by a filepath. Args: file_path: A path, possibly representing a single file, or containing a wildcard or sharded path. Returns: A list of files represented by the provided path.
f8026:m0
def throw_if_file_access_not_allowed(file_path, logdir, has_auth_group):
return<EOL>
Throws an error if a file cannot be loaded for inference. Args: file_path: A file path. logdir: The path to the logdir of the TensorBoard context. has_auth_group: True if TensorBoard was started with an authorized group, in which case we allow access to all visible files. Raises: ...
f8026:m1
def example_protos_from_path(path,<EOL>num_examples=<NUM_LIT:10>,<EOL>start_index=<NUM_LIT:0>,<EOL>parse_examples=True,<EOL>sampling_odds=<NUM_LIT:1>,<EOL>example_class=tf.train.Example):
def append_examples_from_iterable(iterable, examples):<EOL><INDENT>for value in iterable:<EOL><INDENT>if sampling_odds >= <NUM_LIT:1> or random.random() < sampling_odds:<EOL><INDENT>examples.append(<EOL>example_class.FromString(value) if parse_examples else value)<EOL>if len(examples) >= num_examples:<EOL><INDENT>retur...
Returns a number of examples from the provided path. Args: path: A string path to the examples. num_examples: The maximum number of examples to return from the path. parse_examples: If true then parses the serialized proto from the path into proto objects. Defaults to True. sampli...
f8026:m2
def call_servo(examples, serving_bundle):
parsed_url = urlparse('<STR_LIT>' + serving_bundle.inference_address)<EOL>channel = implementations.insecure_channel(parsed_url.hostname,<EOL>parsed_url.port)<EOL>stub = prediction_service_pb2.beta_create_PredictionService_stub(channel)<EOL>if serving_bundle.use_predict:<EOL><INDENT>request = predict_pb2.PredictRequest...
Send an RPC request to the Servomatic prediction service. Args: examples: A list of examples that matches the model spec. serving_bundle: A `ServingBundle` object that contains the information to make the serving request. Returns: A ClassificationResponse or RegressionResponse proto.
f8026:m3
def make_and_write_fake_example(self):
example = test_utils.make_fake_example()<EOL>test_utils.write_out_examples([example], self.examples_path)<EOL>return example<EOL>
Make example and write it to self.examples_path.
f8027:c0:m2
def convert_predict_response(pred, serving_bundle):
output = pred.outputs[serving_bundle.predict_output_tensor]<EOL>raw_output = output.float_val<EOL>if serving_bundle.model_type == '<STR_LIT>':<EOL><INDENT>values = []<EOL>for example_index in range(output.tensor_shape.dim[<NUM_LIT:0>].size):<EOL><INDENT>start = example_index * output.tensor_shape.dim[<NUM_LIT:1>].size<...
Converts a PredictResponse to ClassificationResponse or RegressionResponse. Args: pred: PredictResponse to convert. serving_bundle: A `ServingBundle` object that contains the information about the serving request that the response was generated by. Returns: A ClassificationResponse o...
f8028:m0
def convert_prediction_values(values, serving_bundle, model_spec=None):
if serving_bundle.model_type == '<STR_LIT>':<EOL><INDENT>response = classification_pb2.ClassificationResponse()<EOL>for example_index in range(len(values)):<EOL><INDENT>classification = response.result.classifications.add()<EOL>for class_index in range(len(values[example_index])):<EOL><INDENT>class_score = classificati...
Converts tensor values into ClassificationResponse or RegressionResponse. Args: values: For classification, a 2D list of numbers. The first dimension is for each example being predicted. The second dimension are the probabilities for each class ID in the prediction. For regression, a 1D list ...
f8028:m1
def __init__(self, original_exception):
self.original_exception = original_exception<EOL>Exception.__init__(self)<EOL>
Inits InvalidUserInputError.
f8028:c0:m0
def proto_value_for_feature(example, feature_name):
feature = get_example_features(example)[feature_name]<EOL>if feature is None:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(feature_name))<EOL><DEDENT>feature_type = feature.WhichOneof('<STR_LIT>')<EOL>if feature_type is None:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(<EOL>feature_name))<EOL><DEDENT>return geta...
Get the value of a feature from Example regardless of feature type.
f8029:m0
def parse_original_feature_from_example(example, feature_name):
feature = get_example_features(example)[feature_name]<EOL>feature_type = feature.WhichOneof('<STR_LIT>')<EOL>original_value = proto_value_for_feature(example, feature_name)<EOL>return OriginalFeatureList(feature_name, original_value, feature_type)<EOL>
Returns an `OriginalFeatureList` for the specified feature_name. Args: example: An example. feature_name: A string feature name. Returns: A filled in `OriginalFeatureList` object representing the feature.
f8029:m1
def wrap_inference_results(inference_result_proto):
inference_proto = inference_pb2.InferenceResult()<EOL>if isinstance(inference_result_proto,<EOL>classification_pb2.ClassificationResponse):<EOL><INDENT>inference_proto.classification_result.CopyFrom(<EOL>inference_result_proto.result)<EOL><DEDENT>elif isinstance(inference_result_proto, regression_pb2.RegressionResponse...
Returns packaged inference results from the provided proto. Args: inference_result_proto: The classification or regression response proto. Returns: An InferenceResult proto with the result from the response.
f8029:m2
def get_numeric_feature_names(example):
numeric_features = ('<STR_LIT>', '<STR_LIT>')<EOL>features = get_example_features(example)<EOL>return sorted([<EOL>feature_name for feature_name in features<EOL>if features[feature_name].WhichOneof('<STR_LIT>') in numeric_features<EOL>])<EOL>
Returns a list of feature names for float and int64 type features. Args: example: An example. Returns: A list of strings of the names of numeric features.
f8029:m3
def get_categorical_feature_names(example):
features = get_example_features(example)<EOL>return sorted([<EOL>feature_name for feature_name in features<EOL>if features[feature_name].WhichOneof('<STR_LIT>') == '<STR_LIT>'<EOL>])<EOL>
Returns a list of feature names for byte type features. Args: example: An example. Returns: A list of categorical feature names (e.g. ['education', 'marital_status'] )
f8029:m4
def get_numeric_features_to_observed_range(examples):
observed_features = collections.defaultdict(list) <EOL>for example in examples:<EOL><INDENT>for feature_name in get_numeric_feature_names(example):<EOL><INDENT>original_feature = parse_original_feature_from_example(<EOL>example, feature_name)<EOL>observed_features[feature_name].extend(original_feature.original_value)<...
Returns numerical features and their observed ranges. Args: examples: Examples to read to get ranges. Returns: A dict mapping feature_name -> {'observedMin': 'observedMax': } dicts, with a key for each numerical feature.
f8029:m5
def get_categorical_features_to_sampling(examples, top_k):
observed_features = collections.defaultdict(list) <EOL>for example in examples:<EOL><INDENT>for feature_name in get_categorical_feature_names(example):<EOL><INDENT>original_feature = parse_original_feature_from_example(<EOL>example, feature_name)<EOL>observed_features[feature_name].extend(original_feature.original_val...
Returns categorical features and a sampling of their most-common values. The results of this slow function are used by the visualization repeatedly, so the results are cached. Args: examples: Examples to read to get feature samples. top_k: Max number of samples to return per feature. Retu...
f8029:m6
def make_mutant_features(original_feature, index_to_mutate, viz_params):
lower = viz_params.x_min<EOL>upper = viz_params.x_max<EOL>examples = viz_params.examples<EOL>num_mutants = viz_params.num_mutants<EOL>if original_feature.feature_type == '<STR_LIT>':<EOL><INDENT>return [<EOL>MutantFeatureValue(original_feature, index_to_mutate, value)<EOL>for value in np.linspace(lower, upper, num_muta...
Return a list of `MutantFeatureValue`s that are variants of original.
f8029:m7
def make_mutant_tuples(example_protos, original_feature, index_to_mutate,<EOL>viz_params):
mutant_features = make_mutant_features(original_feature, index_to_mutate,<EOL>viz_params)<EOL>mutant_examples = []<EOL>for example_proto in example_protos:<EOL><INDENT>for mutant_feature in mutant_features:<EOL><INDENT>copied_example = copy.deepcopy(example_proto)<EOL>feature_name = mutant_feature.original_feature.feat...
Return a list of `MutantFeatureValue`s and a list of mutant Examples. Args: example_protos: The examples to mutate. original_feature: A `OriginalFeatureList` that encapsulates the feature to mutate. index_to_mutate: The index of the int64_list or float_list to mutate. viz_params: A ...
f8029:m8
def mutant_charts_for_feature(example_protos, feature_name, serving_bundles,<EOL>viz_params):
def chart_for_index(index_to_mutate):<EOL><INDENT>mutant_features, mutant_examples = make_mutant_tuples(<EOL>example_protos, original_feature, index_to_mutate, viz_params)<EOL>charts = []<EOL>for serving_bundle in serving_bundles:<EOL><INDENT>inference_result_proto = run_inference(mutant_examples, serving_bundle)<EOL>c...
Returns JSON formatted for rendering all charts for a feature. Args: example_proto: The example protos to mutate. feature_name: The string feature name to mutate. serving_bundles: One `ServingBundle` object per model, that contains the information to make the serving request. viz_pa...
f8029:m9
def make_json_formatted_for_single_chart(mutant_features,<EOL>inference_result_proto,<EOL>index_to_mutate):
x_label = '<STR_LIT>'<EOL>y_label = '<STR_LIT>'<EOL>if isinstance(inference_result_proto,<EOL>classification_pb2.ClassificationResponse):<EOL><INDENT>series = {}<EOL>for idx, classification in enumerate(<EOL>inference_result_proto.result.classifications):<EOL><INDENT>mutant_feature = mutant_features[idx % len(mutant_fe...
Returns JSON formatted for a single mutant chart. Args: mutant_features: An iterable of `MutantFeatureValue`s representing the X-axis. inference_result_proto: A ClassificationResponse or RegressionResponse returned by Servo, representing the Y-axis. It contains one 'classificati...
f8029:m10