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 = metadata.parse_session_start_info_plugin_data(<EOL>tag_to_content[metadata.SESSION_START_INFO_TAG])<EOL>end_info = None<EOL>if metadata.SESSION_END_INFO_TAG in tag_to_content:<EOL><INDENT>end_info = metadata.parse_session_end_info_plugin_data(<EOL>tag_to_content[metadata.SESSION_END_INFO_TAG])<EOL><DEDENT>session = self._build_session(run, start_info, end_info)<EOL>if session.status in self._request.allowed_statuses:<EOL><INDENT>self._add_session(session, start_info, groups_by_name)<EOL><DEDENT><DEDENT>groups = groups_by_name.values()<EOL>for group in groups:<EOL><INDENT>group.sessions.sort(key=operator.attrgetter('<STR_LIT:name>'))<EOL>self._aggregate_metrics(group)<EOL><DEDENT>return groups<EOL>
|
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, value) in six.iteritems(start_info.hparams):<EOL><INDENT>group.hparams[key].CopyFrom(value)<EOL><DEDENT>groups_by_name[group_name] = group<EOL><DEDENT>
|
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 encounter it.
Args:
session: api_pb2.Session. The session to add.
start_info: The SessionStartInfo protobuffer associated with the session.
groups_by_name: A str to SessionGroup protobuffer dict. Representing the
session groups and sessions found so far.
|
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_info.status<EOL>result.end_time_secs = end_info.end_time_secs<EOL><DEDENT>return result<EOL>
|
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>continue<EOL><DEDENT>result.append(api_pb2.MetricValue(name=metric_name,<EOL>wall_time_secs=metric_eval[<NUM_LIT:0>],<EOL>training_step=metric_eval[<NUM_LIT:1>],<EOL>value=metric_eval[<NUM_LIT:2>]))<EOL><DEDENT>return result<EOL>
|
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>self._request.aggregation_metric)<EOL><DEDENT>elif self._request.aggregation_type == api_pb2.AGGREGATION_MIN:<EOL><INDENT>_set_extremum_session_metrics(session_group,<EOL>self._request.aggregation_metric,<EOL>min)<EOL><DEDENT>elif self._request.aggregation_type == api_pb2.AGGREGATION_MAX:<EOL><INDENT>_set_extremum_session_metrics(session_group,<EOL>self._request.aggregation_metric,<EOL>max)<EOL><DEDENT>else:<EOL><INDENT>raise error.HParamsError('<STR_LIT>' %<EOL>self._request.aggregation_type)<EOL><DEDENT>
|
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>session_groups.sort(<EOL>key=_create_key_func(<EOL>extractor,<EOL>none_is_largest=not col_param.missing_values_first))<EOL><DEDENT>elif col_param.order == api_pb2.ORDER_DESC:<EOL><INDENT>session_groups.sort(<EOL>key=_create_key_func(<EOL>extractor,<EOL>none_is_largest=col_param.missing_values_first),<EOL>reverse=True)<EOL><DEDENT>else:<EOL><INDENT>raise error.HParamsError('<STR_LIT>' %<EOL>col_param)<EOL><DEDENT><DEDENT>
|
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>plugin_data_pb2.HParamsPluginData(experiment=experiment))<EOL>
|
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 the documentation at the top of this file
for how to populate this.
user: String. An id for the user running the experiment
description: String. A description for the experiment. May contain markdown.
time_created_secs: float. The time the experiment is created in seconds
since the UNIX epoch. If None uses the current time.
Returns:
A summary protobuffer containing the experiment definition.
|
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>if isinstance(hp_val, (float, int)):<EOL><INDENT>session_start_info.hparams[hp_name].number_value = hp_val<EOL><DEDENT>elif isinstance(hp_val, six.string_types):<EOL><INDENT>session_start_info.hparams[hp_name].string_value = hp_val<EOL><DEDENT>elif isinstance(hp_val, bool):<EOL><INDENT>session_start_info.hparams[hp_name].bool_value = hp_val<EOL><DEDENT>elif isinstance(hp_val, (list, tuple)):<EOL><INDENT>session_start_info.hparams[hp_name].string_value = str(hp_val)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>' %<EOL>(hp_name, hp_val, type(hp_val)))<EOL><DEDENT><DEDENT>return _summary(metadata.SESSION_START_INFO_TAG,<EOL>plugin_data_pb2.HParamsPluginData(<EOL>session_start_info=session_start_info))<EOL>
|
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
used in the session, mapping each hyperparameter name to its value.
Supported value types are `bool`, `int`, `float`, `str`, `list`,
`tuple`.
The type of value must correspond to the type of hyperparameter
(defined in the corresponding api_pb2.HParamInfo member of the
Experiment protobuf) as follows:
+-----------------+---------------------------------+
|Hyperparameter | Allowed (Python) value types |
|type | |
+-----------------+---------------------------------+
|DATA_TYPE_BOOL | bool |
|DATA_TYPE_FLOAT64| int, float |
|DATA_TYPE_STRING | six.string_types, tuple, list |
+-----------------+---------------------------------+
Tuple and list instances will be converted to their string
representation.
model_uri: See the comment for the field with the same name of
plugin_data_pb2.SessionStartInfo.
monitor_url: See the comment for the field with the same name of
plugin_data_pb2.SessionStartInfo.
group_name: See the comment for the field with the same name of
plugin_data_pb2.SessionStartInfo.
start_time_secs: float. The time to use as the session start time.
Represented as seconds since the UNIX epoch. If None uses
the current time.
Returns:
The summary protobuffer mentioned above.
|
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 tensorboard.hparams.Status enumeration value denoting the
status of the session.
end_time_secs: float. The time to use as the session end time. Represented
as seconds since the unix epoch. If None uses the current time.
Returns:
The summary protobuffer mentioned above.
|
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.DATA_TYPE_FLOAT64,<EOL>domain_discrete=temperature_list),<EOL>api_pb2.HParamInfo(name='<STR_LIT>',<EOL>display_name='<STR_LIT>',<EOL>type=api_pb2.DATA_TYPE_FLOAT64,<EOL>domain_discrete=temperature_list),<EOL>api_pb2.HParamInfo(name='<STR_LIT>',<EOL>display_name='<STR_LIT>',<EOL>type=api_pb2.DATA_TYPE_STRING,<EOL>domain_discrete=materials)<EOL>],<EOL>metric_infos=[<EOL>api_pb2.MetricInfo(<EOL>name=api_pb2.MetricName(<EOL>tag='<STR_LIT>'),<EOL>display_name='<STR_LIT>'),<EOL>api_pb2.MetricInfo(<EOL>name=api_pb2.MetricName(<EOL>tag='<STR_LIT>'),<EOL>display_name='<STR_LIT>'),<EOL>api_pb2.MetricInfo(<EOL>name=api_pb2.MetricName(<EOL>tag='<STR_LIT>'),<EOL>display_name='<STR_LIT>')<EOL>]<EOL>)<EOL>
|
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>writer.add_summary(summary.session_start_pb(hparams=hparams,<EOL>group_name=group_name))<EOL>writer.flush()<EOL>with tf.name_scope('<STR_LIT>'):<EOL><INDENT>temperature = tf.Variable(<EOL>tf.constant(initial_temperature),<EOL>name='<STR_LIT>')<EOL>scalar_summary.op('<STR_LIT>', temperature,<EOL>display_name='<STR_LIT>',<EOL>description='<STR_LIT>'<EOL>'<STR_LIT>')<EOL>ambient_difference = temperature - ambient_temperature<EOL>scalar_summary.op('<STR_LIT>', ambient_difference,<EOL>display_name='<STR_LIT>',<EOL>description=('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'))<EOL><DEDENT>noise = <NUM_LIT:50> * tf.random.normal([])<EOL>delta = -heat_coefficient * (ambient_difference + noise)<EOL>scalar_summary.op('<STR_LIT>', delta,<EOL>description='<STR_LIT>'<EOL>'<STR_LIT>')<EOL>summ = tf.summary.merge_all()<EOL>with tf.control_dependencies([summ]):<EOL><INDENT>update_step = temperature.assign_add(delta)<EOL><DEDENT>sess = tf.Session()<EOL>sess.run(tf.global_variables_initializer())<EOL>for step in xrange(FLAGS.num_steps):<EOL><INDENT>(s, _) = sess.run([summ, update_step])<EOL>if (step % FLAGS.summary_freq) == <NUM_LIT:0>:<EOL><INDENT>writer.add_summary(s, global_step=step)<EOL><DEDENT><DEDENT>writer.add_summary(summary.session_end_pb(api_pb2.STATUS_SUCCESS))<EOL>writer.close()<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
thermal conductivity, while the thermal conductivity of water is low.
Over time, the object's temperature will adjust to match the
temperature of its environment. We'll track the object's temperature,
how far it is from the room's temperature, and how much it changes at
each time step.
Arguments:
logdir: the top-level directory into which to write summary data
session_id: an id for the session.
hparams: A dictionary mapping a hyperparameter name to its value.
group_name: an id for the session group this session belongs to.
|
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_temperature in TEMPERATURE_LIST:<EOL><INDENT>for material in HEAT_COEFFICIENTS:<EOL><INDENT>hparams = {u'<STR_LIT>': initial_temperature,<EOL>u'<STR_LIT>': ambient_temperature,<EOL>u'<STR_LIT>': material}<EOL>hparam_str = str(hparams)<EOL>group_name = fingerprint(hparam_str)<EOL>for repeat_idx in xrange(<NUM_LIT:2>):<EOL><INDENT>session_id = str(session_num)<EOL>if verbose:<EOL><INDENT>print('<STR_LIT>' % (session_num + <NUM_LIT:1>,<EOL>num_sessions))<EOL>print(hparam_str)<EOL>print('<STR_LIT>' % (repeat_idx+<NUM_LIT:1>))<EOL><DEDENT>run(logdir, session_id, hparams, group_name)<EOL>session_num += <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT><DEDENT>
|
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>return tf.compat.v1.SummaryMetadata(<EOL>plugin_data=tf.compat.v1.SummaryMetadata.PluginData(<EOL>plugin_name=PLUGIN_NAME, content=content.SerializeToString()))<EOL>
|
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 HParamsPluginData protobuffer to use.
|
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.HParamsError(<EOL>'<STR_LIT>' %<EOL>(data_oneof_field, plugin_data))<EOL><DEDENT>return getattr(plugin_data, data_oneof_field)<EOL>
|
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 of the data oneof field to return.
|
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_LIT>'))<EOL><DEDENT><DEDENT>
|
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 hyperparameter names (as strings) and whose
values are the corresponding hyperparameter values.
Raises:
ValueError: If two entries in `hparams` share the same
hyperparameter name.
|
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
experiment.
time_created_secs: The time that this experiment was created, as
seconds since epoch. Defaults to the current time.
|
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.append(info)<EOL><DEDENT>metric_infos = [metric.as_proto() for metric in self._metrics]<EOL>return summary.experiment_pb(<EOL>hparam_infos=hparam_infos,<EOL>metric_infos=metric_infos,<EOL>user=self._user,<EOL>description=self._description,<EOL>time_created_secs=self._time_created_secs,<EOL>)<EOL>
|
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-readable display name (`str`).
description: An optional Markdown string describing this
hyperparameter.
Raises:
ValueError: If `domain` is not a `Domain`.
|
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_value = min_value<EOL>self._max_value = max_value<EOL>
|
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._min_value = min_value<EOL>self._max_value = max_value<EOL>
|
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>self._dtype = dtype<EOL>for value in self._values:<EOL><INDENT>if not isinstance(value, self._dtype):<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>"<EOL>% (value, self._dtype.__name__)<EOL>)<EOL><DEDENT><DEDENT>self._values.sort()<EOL>
|
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 the
type of the first element of `values`.
Raises:
ValueError: If `values` is empty but no `dtype` is specified.
ValueError: If `dtype` or its inferred value is not `int`,
`float`, `bool`, or `str`.
TypeError: If an element of `values` is not an instance of
`dtype`.
|
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_LOGDIR/SESSION_ID/train`, then `group`
should be `"train"`. Defaults to the empty string: i.e.,
summaries are expected to be written to the session logdir.
display_name: An optional human-readable display name.
description: An optional Markdown string with a human-readable
description of this metric, to appear in TensorBoard.
dataset_type: Either `Metric.TRAINING` or `Metric.VALIDATION`, or
`None`.
|
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:<EOL><INDENT>self._writer = writer<EOL><DEDENT>
|
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 logdir (as a `str`) to be passed to
`tf.summary.create_file_writer` to create such a writer.
logdir: The log directory for this session.
hparams: A `dict` mapping hyperparameters to the values used in
this session. Keys should be the names of `HParam` objects used
in an `Experiment`, or the `HParam` objects themselves. Values
should be Python `bool`, `int`, `float`, or `string` values,
depending on the type of the hyperparameter.
group_name: The name of the session group containing this session,
as a string or `None`. If `None` or empty, the group name is
taken to be the session ID.
Raises:
ValueError: If two entries in `hparams` share the same
hyperparameter name.
|
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', 'two', 'three']) == '''
<tr>
<td>one</td>
<td>two</td>
<td>three</td>
</tr>'''
|
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(headers)<EOL><DEDENT>if not isinstance(headers, np.ndarray):<EOL><INDENT>raise ValueError('<STR_LIT>' % headers)<EOL><DEDENT>if headers.ndim != <NUM_LIT:1>:<EOL><INDENT>raise ValueError('<STR_LIT>' % headers.ndim)<EOL><DEDENT>expected_n_columns = contents.shape[<NUM_LIT:1>] if contents.ndim == <NUM_LIT:2> else <NUM_LIT:1><EOL>if headers.shape[<NUM_LIT:0>] != expected_n_columns:<EOL><INDENT>raise ValueError('<STR_LIT>' %<EOL>(headers.shape[<NUM_LIT:0>], expected_n_columns))<EOL><DEDENT>header = '<STR_LIT>' % make_table_row(headers, tag='<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>header = '<STR_LIT>'<EOL><DEDENT>n_rows = contents.shape[<NUM_LIT:0>]<EOL>if contents.ndim == <NUM_LIT:1>:<EOL><INDENT>rows = (make_table_row([contents[i]]) for i in range(n_rows))<EOL><DEDENT>else:<EOL><INDENT>rows = (make_table_row(contents[i, :]) for i in range(n_rows))<EOL><DEDENT>return '<STR_LIT>' % (header, '<STR_LIT>'.join(rows))<EOL>
|
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 containing all of the content strings, organized into a table.
Raises:
ValueError: If contents is not a np.ndarray.
ValueError: If contents is not 1d or 2d.
ValueError: If contents is empty.
ValueError: If headers is present and not a list, tuple, or ndarray.
ValueError: If headers is not 1d.
ValueError: If number of elements in headers does not correspond to number
of columns in contents.
|
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 argument is not a numpy ndarray, or the dimensionality
is too low.
|
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><DEDENT>html_arr = [plugin_util.markdown_to_safe_html(x)<EOL>for x in text_arr.reshape(-<NUM_LIT:1>)]<EOL>html_arr = np.array(html_arr).reshape(text_arr.shape)<EOL>return warning + make_table(html_arr)<EOL>
|
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 make_table. If the array contains dimensionality greater than 2,
all but two of the dimensions are removed, and a warning message is prefixed
to the table.
Args:
text_arr: A numpy.ndarray containing strings.
Returns:
The array converted to html.
|
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_impl_thread()<EOL>return False<EOL>
|
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.string)]):<EOL><INDENT>return tf.summary.tensor_summary(name='<STR_LIT>',<EOL>tensor=data,<EOL>collections=collections,<EOL>summary_metadata=summary_metadata)<EOL><DEDENT><DEDENT>
|
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 is provided, a 2D subarray will be
displayed along with a warning message. (Note that this behavior is not
intrinsic to the text summary API, but rather to the default TensorBoard text
plugin.)
Args:
name: A name for the generated node. Will also serve as a series name in
TensorBoard.
data: A string-type Tensor to summarize. The text must be encoded in UTF-8.
display_name: Optional name for this summary in TensorBoard, as a
constant `str`. Defaults to `name`.
description: Optional long-form description for this summary, as a
constant `str`. Markdown is supported. Defaults to empty.
collections: Optional list of ops.GraphKeys. The collections to which to add
the summary. Defaults to [Graph Keys.SUMMARIES].
Returns:
A TensorSummary op that is configured so that TensorBoard will recognize
that it contains textual data. The TensorSummary is a scalar `Tensor` of
type `string` which contains `Summary` protobufs.
Raises:
ValueError: If tensor has the wrong type.
|
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>display_name=display_name, description=description)<EOL>tf_summary_metadata = tf.SummaryMetadata.FromString(<EOL>summary_metadata.SerializeToString())<EOL>summary = tf.Summary()<EOL>summary.value.add(tag='<STR_LIT>' % name,<EOL>metadata=tf_summary_metadata,<EOL>tensor=tensor)<EOL>return summary<EOL>
|
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 in TensorBoard, as a
`str`. Defaults to `name`.
description: Optional long-form description for this summary, as a
`str`. Markdown is supported. Defaults to empty.
Raises:
ValueError: If the type of the data is unsupported.
Returns:
A `tf.Summary` protobuf object.
|
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_with(thread)<EOL>thread.run()<EOL>self.assertIsNone(plugin._index_impl_thread)<EOL>if expected_finally_is_active:<EOL><INDENT>self.assertTrue(plugin.is_active())<EOL>mock.assert_called_once_with(thread)<EOL><DEDENT>else:<EOL><INDENT>self.assertFalse(plugin.is_active())<EOL>self.assertEqual(<NUM_LIT:2>, mock.call_count)<EOL><DEDENT>
|
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 metadata<EOL>
|
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, PROTO_VERSION)<EOL>return result<EOL><DEDENT>
|
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.assert_type(data, tf.string)<EOL>return tf.summary.write(<EOL>tag=tag, tensor=data, step=step, metadata=summary_metadata)<EOL><DEDENT>
|
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 defaults to `tf.summary.experimental.get_step()`, which must
not be None.
description: Optional long-form description for this summary, as a
constant `str`. Markdown is supported. Defaults to empty.
Returns:
True on success, or false if no summary was emitted because no default
summary writer was available.
Raises:
ValueError: if a default writer exists, but no step was provided and
`tf.summary.experimental.get_step()` is None.
|
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.value.add(tag=tag,<EOL>metadata=summary_metadata,<EOL>tensor=tensor)<EOL>return summary<EOL>
|
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. Defaults to empty.
Raises:
TypeError: If the type of the data is unsupported.
Returns:
A `tf.Summary` protobuf object.
|
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 display the examples for exploration, but no model inference
will be performed by the tool.
|
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.
Returns:
self, in order to enabled method chaining.
|
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, in order to enabled method chaining.
|
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, in order to enabled method chaining.
|
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
"localhost:8888".
Returns:
self, in order to enabled method chaining.
|
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:
name: The name of the model to be queried through TF Serving at the
address provided by set_compare_inference_address.
Returns:
self, in order to enabled method chaining.
|
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. This is optional, as TF Serving will use the latest model version
if none is provided.
Returns:
self, in order to enabled method chaining.
|
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
Serving. This is optional, as TF Serving will use the default model
signature if none is provided.
Returns:
self, in order to enabled method chaining.
|
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. If this is true, then use the
set_predict_input_tensor and set_predict_output_tensor methods to indicate
the names of the tensors that are used as the input and output for the
models provided in order to perform the appropriate inference request.
Args:
predict: True if the model or models use the Predict API.
Returns:
self, in order to enabled method chaining.
|
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 results for any given
example. This method sets that limit.
Args:
max_classes: The maximum number of classes to display for inference
results for multiclass classification models.
Returns:
self, in order to enabled method chaining.
|
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 tensor.
Returns:
self, in order to enabled method chaining.
|
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 name of the output tensor.
Returns:
self, in order to enabled method chaining.
|
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
string labels for each class ID.
Args:
vocab: A list of strings, where the string at each index corresponds to
the label for that class ID. For example ['<=50K', '>50K'] for the UCI
census binary classification task.
Returns:
self, in order to enabled method chaining.
|
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 the estimator.
Args:
estimator: The TF Estimator which will be used for model inference.
feature_spec: The feature_spec object which will be used for example
parsing.
Returns:
self, in order to enabled method chaining.
|
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 to query. In order to
accomplish this, a feature_spec must also be provided to parse the
example protos for input into the estimator.
Args:
estimator: The TF Estimator which will be used for model inference.
feature_spec: The feature_spec object which will be used for example
parsing.
Returns:
self, in order to enabled method chaining.
|
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. 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 of numbers, with a regression score for each
example being predicted.
Args:
predict_fn: The custom python function which will be used for model
inference.
Returns:
self, in order to enabled method chaining.
|
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 this case, the
provided function should accept example protos and return:
- 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 of numbers, with a regression score for each
example being predicted.
Args:
predict_fn: The custom python function which will be used for model
inference.
Returns:
self, in order to enabled method chaining.
|
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 else {})<EOL>if '<STR_LIT>' in copied_config:<EOL><INDENT>del copied_config['<STR_LIT>']<EOL><DEDENT>if '<STR_LIT>' in copied_config:<EOL><INDENT>del copied_config['<STR_LIT>']<EOL><DEDENT>self.custom_predict_fn = (<EOL>config.get('<STR_LIT>')<EOL>if '<STR_LIT>' in config else None)<EOL>self.compare_custom_predict_fn = (<EOL>config.get('<STR_LIT>')<EOL>if '<STR_LIT>' in config else None)<EOL>if '<STR_LIT>' in copied_config:<EOL><INDENT>del copied_config['<STR_LIT>']<EOL><DEDENT>if '<STR_LIT>' in copied_config:<EOL><INDENT>del copied_config['<STR_LIT>']<EOL><DEDENT>self._set_examples(config['<STR_LIT>'])<EOL>del copied_config['<STR_LIT>']<EOL>self.config = copied_config<EOL>WitWidget.widgets.append(self)<EOL>display.display(display.HTML(self._get_element_html()))<EOL>display.display(display.HTML(<EOL>WIT_HTML.format(<EOL>examples=json.dumps(self.examples), height=height, id=WitWidget.index)))<EOL>WitWidget.index += <NUM_LIT:1><EOL>output.eval_js("""<STR_LIT>""".format(<EOL>config=json.dumps(self.config)))<EOL>output.eval_js('<STR_LIT>')<EOL>self._generate_sprite()<EOL>
|
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_estimator_and_spec = (<EOL>dict(config.get('<STR_LIT>'))<EOL>if '<STR_LIT>' in config else {})<EOL>if '<STR_LIT>' in copied_config:<EOL><INDENT>del copied_config['<STR_LIT>']<EOL><DEDENT>if '<STR_LIT>' in copied_config:<EOL><INDENT>del copied_config['<STR_LIT>']<EOL><DEDENT>self.custom_predict_fn = (<EOL>config.get('<STR_LIT>')<EOL>if '<STR_LIT>' in config else None)<EOL>self.compare_custom_predict_fn = (<EOL>config.get('<STR_LIT>')<EOL>if '<STR_LIT>' in config else None)<EOL>if '<STR_LIT>' in copied_config:<EOL><INDENT>del copied_config['<STR_LIT>']<EOL><DEDENT>if '<STR_LIT>' in copied_config:<EOL><INDENT>del copied_config['<STR_LIT>']<EOL><DEDENT>self._set_examples(config['<STR_LIT>'])<EOL>del copied_config['<STR_LIT>']<EOL>self.config = copied_config<EOL>display(HTML("<STR_LIT>"))<EOL>
|
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:
InvalidUserInputError: If the file is not in the logdir and is not globally
readable.
|
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>return<EOL><DEDENT><DEDENT><DEDENT><DEDENT>examples = []<EOL>if path.endswith('<STR_LIT>'):<EOL><INDENT>def are_floats(values):<EOL><INDENT>for value in values:<EOL><INDENT>try:<EOL><INDENT>float(value)<EOL><DEDENT>except ValueError:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<EOL><DEDENT>csv.register_dialect('<STR_LIT>', skipinitialspace=True)<EOL>rows = csv.DictReader(open(path), dialect='<STR_LIT>')<EOL>for row in rows:<EOL><INDENT>if sampling_odds < <NUM_LIT:1> and random.random() > sampling_odds:<EOL><INDENT>continue<EOL><DEDENT>example = tf.train.Example()<EOL>for col in row.keys():<EOL><INDENT>values = [val.strip() for val in row[col].split('<STR_LIT:|>')]<EOL>if are_floats(values):<EOL><INDENT>example.features.feature[col].float_list.value.extend(<EOL>[float(val) for val in values])<EOL><DEDENT>else:<EOL><INDENT>example.features.feature[col].bytes_list.value.extend(<EOL>[val.encode('<STR_LIT:utf-8>') for val in values])<EOL><DEDENT><DEDENT>examples.append(<EOL>example if parse_examples else example.SerializeToString())<EOL>if len(examples) >= num_examples:<EOL><INDENT>break<EOL><DEDENT><DEDENT>return examples<EOL><DEDENT>filenames = filepath_to_filepath_list(path)<EOL>compression_types = [<EOL>'<STR_LIT>', <EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>]<EOL>current_compression_idx = <NUM_LIT:0><EOL>current_file_index = <NUM_LIT:0><EOL>while (current_file_index < len(filenames) and<EOL>current_compression_idx < len(compression_types)):<EOL><INDENT>try:<EOL><INDENT>record_iterator = tf.compat.v1.python_io.tf_record_iterator(<EOL>path=filenames[current_file_index],<EOL>options=tf.io.TFRecordOptions(<EOL>compression_types[current_compression_idx]))<EOL>append_examples_from_iterable(record_iterator, examples)<EOL>current_file_index += <NUM_LIT:1><EOL>if len(examples) >= num_examples:<EOL><INDENT>break<EOL><DEDENT><DEDENT>except tf.errors.DataLossError:<EOL><INDENT>current_compression_idx += <NUM_LIT:1><EOL><DEDENT>except (IOError, tf.errors.NotFoundError) as e:<EOL><INDENT>raise common_utils.InvalidUserInputError(e)<EOL><DEDENT><DEDENT>if examples:<EOL><INDENT>return examples<EOL><DEDENT>else:<EOL><INDENT>raise common_utils.InvalidUserInputError(<EOL>'<STR_LIT>' + path +<EOL>'<STR_LIT>')<EOL><DEDENT>
|
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.
sampling_odds: Odds of loading an example, used for sampling. When >= 1
(the default), then all examples are loaded.
example_class: tf.train.Example or tf.train.SequenceExample class to load.
Defaults to tf.train.Example.
Returns:
A list of Example protos or serialized proto strings at the path.
Raises:
InvalidUserInputError: If examples cannot be procured from the path.
|
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()<EOL><DEDENT>elif serving_bundle.model_type == '<STR_LIT>':<EOL><INDENT>request = classification_pb2.ClassificationRequest()<EOL><DEDENT>else:<EOL><INDENT>request = regression_pb2.RegressionRequest()<EOL><DEDENT>request.model_spec.name = serving_bundle.model_name<EOL>if serving_bundle.model_version is not None:<EOL><INDENT>request.model_spec.version.value = serving_bundle.model_version<EOL><DEDENT>if serving_bundle.signature is not None:<EOL><INDENT>request.model_spec.signature_name = serving_bundle.signature<EOL><DEDENT>if serving_bundle.use_predict:<EOL><INDENT>request.inputs[serving_bundle.predict_input_tensor].CopyFrom(<EOL>tf.compat.v1.make_tensor_proto(<EOL>values=[ex.SerializeToString() for ex in examples],<EOL>dtype=types_pb2.DT_STRING))<EOL><DEDENT>else:<EOL><INDENT>request.input.example_list.examples.extend(examples)<EOL><DEDENT>if serving_bundle.use_predict:<EOL><INDENT>return common_utils.convert_predict_response(<EOL>stub.Predict(request, <NUM_LIT>), serving_bundle) <EOL><DEDENT>elif serving_bundle.model_type == '<STR_LIT>':<EOL><INDENT>return stub.Classify(request, <NUM_LIT>) <EOL><DEDENT>else:<EOL><INDENT>return stub.Regress(request, <NUM_LIT>)<EOL><DEDENT>
|
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<EOL>values.append(raw_output[start:start + output.tensor_shape.dim[<NUM_LIT:1>].size])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>values = raw_output<EOL><DEDENT>return convert_prediction_values(values, serving_bundle, pred.model_spec)<EOL>
|
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 or RegressionResponse.
|
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 = classification.classes.add()<EOL>class_score.score = values[example_index][class_index]<EOL>class_score.label = str(class_index)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>response = regression_pb2.RegressionResponse()<EOL>for example_index in range(len(values)):<EOL><INDENT>regression = response.result.regressions.add()<EOL>regression.value = values[example_index]<EOL><DEDENT><DEDENT>if model_spec:<EOL><INDENT>response.model_spec.CopyFrom(model_spec)<EOL><DEDENT>return response<EOL>
|
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 of numbers,
with a regression score for each example being predicted.
serving_bundle: A `ServingBundle` object that contains the information about
the serving request that the response was generated by.
model_spec: Optional model spec to put into the response.
Returns:
A ClassificationResponse or RegressionResponse.
|
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 getattr(feature, feature_type).value<EOL>
|
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):<EOL><INDENT>inference_proto.regression_result.CopyFrom(inference_result_proto.result)<EOL><DEDENT>return inference_proto<EOL>
|
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)<EOL><DEDENT><DEDENT>return {<EOL>feature_name: {<EOL>'<STR_LIT>': min(feature_values),<EOL>'<STR_LIT>': max(feature_values),<EOL>}<EOL>for feature_name, feature_values in iteritems(observed_features)<EOL>}<EOL>
|
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_value)<EOL><DEDENT><DEDENT>result = {}<EOL>for feature_name, feature_values in sorted(iteritems(observed_features)):<EOL><INDENT>samples = [<EOL>word<EOL>for word, count in collections.Counter(feature_values).most_common(<EOL>top_k) if count > <NUM_LIT:1><EOL>]<EOL>if samples:<EOL><INDENT>result[feature_name] = {'<STR_LIT>': samples}<EOL><DEDENT><DEDENT>return result<EOL>
|
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.
Returns:
A dict of feature_name -> {'samples': ['Married-civ-spouse',
'Never-married', 'Divorced']}.
There is one key for each categorical feature.
Currently, the inner dict just has one key, but this structure leaves room
for further expansion, and mirrors the structure used by
`get_numeric_features_to_observed_range`.
|
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_mutants)<EOL>]<EOL><DEDENT>elif original_feature.feature_type == '<STR_LIT>':<EOL><INDENT>mutant_values = np.linspace(int(lower), int(upper),<EOL>num_mutants).astype(int).tolist()<EOL>mutant_values = sorted(set(mutant_values))<EOL>return [<EOL>MutantFeatureValue(original_feature, index_to_mutate, value)<EOL>for value in mutant_values<EOL>]<EOL><DEDENT>elif original_feature.feature_type == '<STR_LIT>':<EOL><INDENT>feature_to_samples = get_categorical_features_to_sampling(<EOL>examples, num_mutants)<EOL>mutant_values = feature_to_samples[original_feature.feature_name]['<STR_LIT>']<EOL>return [<EOL>MutantFeatureValue(original_feature, None, value)<EOL>for value in mutant_values<EOL>]<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' +<EOL>original_feature.feature_type)<EOL><DEDENT>
|
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.feature_name<EOL>try:<EOL><INDENT>feature_list = proto_value_for_feature(copied_example, feature_name)<EOL>if index_to_mutate is None:<EOL><INDENT>new_values = mutant_feature.mutant_value<EOL><DEDENT>else:<EOL><INDENT>new_values = list(feature_list)<EOL>new_values[index_to_mutate] = mutant_feature.mutant_value<EOL><DEDENT>del feature_list[:]<EOL>feature_list.extend(new_values)<EOL>mutant_examples.append(copied_example)<EOL><DEDENT>except (ValueError, IndexError):<EOL><INDENT>mutant_examples.append(copied_example)<EOL><DEDENT><DEDENT><DEDENT>return mutant_features, mutant_examples<EOL>
|
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 `VizParams` object that contains the UI state of the request.
Returns:
A list of `MutantFeatureValue`s and a list of mutant examples.
|
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>charts.append(make_json_formatted_for_single_chart(<EOL>mutant_features, inference_result_proto, index_to_mutate))<EOL><DEDENT>return charts<EOL><DEDENT>try:<EOL><INDENT>original_feature = parse_original_feature_from_example(<EOL>example_protos[<NUM_LIT:0>], feature_name)<EOL><DEDENT>except ValueError as e:<EOL><INDENT>return {<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT:data>': []<EOL>}<EOL><DEDENT>indices_to_mutate = viz_params.feature_indices or range(<EOL>original_feature.length)<EOL>chart_type = ('<STR_LIT>' if original_feature.feature_type == '<STR_LIT>'<EOL>else '<STR_LIT>')<EOL>try:<EOL><INDENT>return {<EOL>'<STR_LIT>': chart_type,<EOL>'<STR_LIT:data>': [<EOL>chart_for_index(index_to_mutate)<EOL>for index_to_mutate in indices_to_mutate<EOL>]<EOL>}<EOL><DEDENT>except IndexError as e:<EOL><INDENT>raise common_utils.InvalidUserInputError(e)<EOL><DEDENT>
|
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_params: A `VizParams` object that contains the UI state of the request.
Raises:
InvalidUserInputError if `viz_params.feature_index_pattern` requests out of
range indices for `feature_name` within `example_proto`.
Returns:
A JSON-able dict for rendering a single mutant chart. parsed in
`tf-inference-dashboard.html`.
{
'chartType': 'numeric', # oneof('numeric', 'categorical')
'data': [A list of data] # parseable by vz-line-chart or vz-bar-chart
}
|
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_features)]<EOL>for class_index, classification_class in enumerate(<EOL>classification.classes):<EOL><INDENT>if classification_class.label == '<STR_LIT>':<EOL><INDENT>classification_class.label = str(class_index)<EOL><DEDENT>if len(<EOL>classification.classes) == <NUM_LIT:2> and classification_class.label == '<STR_LIT:0>':<EOL><INDENT>continue<EOL><DEDENT>key = classification_class.label<EOL>if index_to_mutate:<EOL><INDENT>key += '<STR_LIT>' % index_to_mutate<EOL><DEDENT>if not key in series:<EOL><INDENT>series[key] = {}<EOL><DEDENT>if not mutant_feature.mutant_value in series[key]:<EOL><INDENT>series[key][mutant_feature.mutant_value] = []<EOL><DEDENT>series[key][mutant_feature.mutant_value].append(<EOL>classification_class.score)<EOL><DEDENT><DEDENT>return_series = collections.defaultdict(list)<EOL>for key, mutant_values in iteritems(series):<EOL><INDENT>for value, y_list in iteritems(mutant_values):<EOL><INDENT>return_series[key].append({<EOL>x_label: value,<EOL>y_label: sum(y_list) / float(len(y_list))<EOL>})<EOL><DEDENT>return_series[key].sort(key=lambda p: p[x_label])<EOL><DEDENT>return return_series<EOL><DEDENT>elif isinstance(inference_result_proto, regression_pb2.RegressionResponse):<EOL><INDENT>points = {}<EOL>for idx, regression in enumerate(inference_result_proto.result.regressions):<EOL><INDENT>mutant_feature = mutant_features[idx % len(mutant_features)]<EOL>if not mutant_feature.mutant_value in points:<EOL><INDENT>points[mutant_feature.mutant_value] = []<EOL><DEDENT>points[mutant_feature.mutant_value].append(regression.value)<EOL><DEDENT>key = '<STR_LIT:value>'<EOL>if (index_to_mutate != <NUM_LIT:0>):<EOL><INDENT>key += '<STR_LIT>' % index_to_mutate<EOL><DEDENT>list_of_points = []<EOL>for value, y_list in iteritems(points):<EOL><INDENT>list_of_points.append({<EOL>x_label: value,<EOL>y_label: sum(y_list) / float(len(y_list))<EOL>})<EOL><DEDENT>list_of_points.sort(key=lambda p: p[x_label])<EOL>return {key: list_of_points}<EOL><DEDENT>else:<EOL><INDENT>raise NotImplementedError('<STR_LIT>')<EOL><DEDENT>
|
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 'classification' or 'regression' for every Example that
was sent for inference. The length of that field should be the same length
of mutant_features.
index_to_mutate: The index of the feature being mutated for this chart.
Returns:
A JSON-able dict for rendering a single mutant chart, parseable by
`vz-line-chart` or `vz-bar-chart`.
|
f8029:m10
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.