repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1 value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
tensorflow/tensorboard | tensorboard/plugins/debugger/debugger_plugin.py | DebuggerPlugin._obtain_health_pills_at_step | def _obtain_health_pills_at_step(self, events_directory, node_names, step):
"""Reads disk to obtain the health pills for a run at a specific step.
This could be much slower than the alternative path of just returning all
health pills sampled by the event multiplexer. It could take tens of minutes
to complete this call for large graphs for big step values (in the
thousands).
Args:
events_directory: The directory containing events for the desired run.
node_names: A list of node names for which to retrieve health pills.
step: The step to obtain health pills for.
Returns:
A dictionary mapping from node name to a list of health pill objects (see
docs for _serve_health_pills_handler for properties of those objects).
Raises:
IOError: If no files with health pill events could be found.
"""
# Obtain all files with debugger-related events.
pattern = os.path.join(events_directory, _DEBUGGER_EVENTS_GLOB_PATTERN)
file_paths = glob.glob(pattern)
if not file_paths:
raise IOError(
'No events files found that matches the pattern %r.' % pattern)
# Sort by name (and thus by timestamp).
file_paths.sort()
mapping = collections.defaultdict(list)
node_name_set = frozenset(node_names)
for file_path in file_paths:
should_stop = self._process_health_pill_event(
node_name_set, mapping, step, file_path)
if should_stop:
break
return mapping | python | def _obtain_health_pills_at_step(self, events_directory, node_names, step):
"""Reads disk to obtain the health pills for a run at a specific step.
This could be much slower than the alternative path of just returning all
health pills sampled by the event multiplexer. It could take tens of minutes
to complete this call for large graphs for big step values (in the
thousands).
Args:
events_directory: The directory containing events for the desired run.
node_names: A list of node names for which to retrieve health pills.
step: The step to obtain health pills for.
Returns:
A dictionary mapping from node name to a list of health pill objects (see
docs for _serve_health_pills_handler for properties of those objects).
Raises:
IOError: If no files with health pill events could be found.
"""
# Obtain all files with debugger-related events.
pattern = os.path.join(events_directory, _DEBUGGER_EVENTS_GLOB_PATTERN)
file_paths = glob.glob(pattern)
if not file_paths:
raise IOError(
'No events files found that matches the pattern %r.' % pattern)
# Sort by name (and thus by timestamp).
file_paths.sort()
mapping = collections.defaultdict(list)
node_name_set = frozenset(node_names)
for file_path in file_paths:
should_stop = self._process_health_pill_event(
node_name_set, mapping, step, file_path)
if should_stop:
break
return mapping | [
"def",
"_obtain_health_pills_at_step",
"(",
"self",
",",
"events_directory",
",",
"node_names",
",",
"step",
")",
":",
"# Obtain all files with debugger-related events.",
"pattern",
"=",
"os",
".",
"path",
".",
"join",
"(",
"events_directory",
",",
"_DEBUGGER_EVENTS_GLOB_PATTERN",
")",
"file_paths",
"=",
"glob",
".",
"glob",
"(",
"pattern",
")",
"if",
"not",
"file_paths",
":",
"raise",
"IOError",
"(",
"'No events files found that matches the pattern %r.'",
"%",
"pattern",
")",
"# Sort by name (and thus by timestamp).",
"file_paths",
".",
"sort",
"(",
")",
"mapping",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"node_name_set",
"=",
"frozenset",
"(",
"node_names",
")",
"for",
"file_path",
"in",
"file_paths",
":",
"should_stop",
"=",
"self",
".",
"_process_health_pill_event",
"(",
"node_name_set",
",",
"mapping",
",",
"step",
",",
"file_path",
")",
"if",
"should_stop",
":",
"break",
"return",
"mapping"
] | Reads disk to obtain the health pills for a run at a specific step.
This could be much slower than the alternative path of just returning all
health pills sampled by the event multiplexer. It could take tens of minutes
to complete this call for large graphs for big step values (in the
thousands).
Args:
events_directory: The directory containing events for the desired run.
node_names: A list of node names for which to retrieve health pills.
step: The step to obtain health pills for.
Returns:
A dictionary mapping from node name to a list of health pill objects (see
docs for _serve_health_pills_handler for properties of those objects).
Raises:
IOError: If no files with health pill events could be found. | [
"Reads",
"disk",
"to",
"obtain",
"the",
"health",
"pills",
"for",
"a",
"run",
"at",
"a",
"specific",
"step",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/debugger/debugger_plugin.py#L325-L365 | train |
tensorflow/tensorboard | tensorboard/plugins/debugger/debugger_plugin.py | DebuggerPlugin._process_health_pill_event | def _process_health_pill_event(self, node_name_set, mapping, target_step,
file_path):
"""Creates health pills out of data in an event.
Creates health pills out of the event and adds them to the mapping.
Args:
node_name_set: A set of node names that are relevant.
mapping: The mapping from node name to HealthPillEvents.
This object may be destructively modified.
target_step: The target step at which to obtain health pills.
file_path: The path to the file with health pill events.
Returns:
Whether we should stop reading events because future events are no longer
relevant.
"""
events_loader = event_file_loader.EventFileLoader(file_path)
for event in events_loader.Load():
if not event.HasField('summary'):
logger.warn(
'An event in a debugger events file lacks a summary.')
continue
if event.step < target_step:
# This event is not of the relevant step. We perform this check
# first because the majority of events will be eliminated from
# consideration by this check.
continue
if event.step > target_step:
# We have passed the relevant step. No need to read more events.
return True
for value in event.summary.value:
# Obtain the device name from the metadata.
summary_metadata = value.metadata
plugin_data = summary_metadata.plugin_data
if plugin_data.plugin_name == constants.DEBUGGER_PLUGIN_NAME:
try:
content = json.loads(
tf.compat.as_text(summary_metadata.plugin_data.content))
except ValueError as err:
logger.warn(
'Could not parse the JSON string containing data for '
'the debugger plugin: %r, %r', content, err)
continue
device_name = content['device']
output_slot = content['outputSlot']
else:
logger.error(
'No debugger plugin data found for event with tag %s and node '
'name %s.', value.tag, value.node_name)
continue
if not value.HasField('tensor'):
logger.warn(
'An event in a debugger events file lacks a tensor value.')
continue
match = re.match(r'^(.*):(\d+):DebugNumericSummary$', value.node_name)
if not match:
logger.warn(
('A event with a health pill has an invalid watch, (i.e., an '
'unexpected debug op): %r'), value.node_name)
return None
health_pill = self._process_health_pill_value(
wall_time=event.wall_time,
step=event.step,
device_name=device_name,
output_slot=output_slot,
node_name=match.group(1),
tensor_proto=value.tensor,
node_name_set=node_name_set)
if not health_pill:
continue
mapping[health_pill.node_name].append(health_pill)
# Keep reading events.
return False | python | def _process_health_pill_event(self, node_name_set, mapping, target_step,
file_path):
"""Creates health pills out of data in an event.
Creates health pills out of the event and adds them to the mapping.
Args:
node_name_set: A set of node names that are relevant.
mapping: The mapping from node name to HealthPillEvents.
This object may be destructively modified.
target_step: The target step at which to obtain health pills.
file_path: The path to the file with health pill events.
Returns:
Whether we should stop reading events because future events are no longer
relevant.
"""
events_loader = event_file_loader.EventFileLoader(file_path)
for event in events_loader.Load():
if not event.HasField('summary'):
logger.warn(
'An event in a debugger events file lacks a summary.')
continue
if event.step < target_step:
# This event is not of the relevant step. We perform this check
# first because the majority of events will be eliminated from
# consideration by this check.
continue
if event.step > target_step:
# We have passed the relevant step. No need to read more events.
return True
for value in event.summary.value:
# Obtain the device name from the metadata.
summary_metadata = value.metadata
plugin_data = summary_metadata.plugin_data
if plugin_data.plugin_name == constants.DEBUGGER_PLUGIN_NAME:
try:
content = json.loads(
tf.compat.as_text(summary_metadata.plugin_data.content))
except ValueError as err:
logger.warn(
'Could not parse the JSON string containing data for '
'the debugger plugin: %r, %r', content, err)
continue
device_name = content['device']
output_slot = content['outputSlot']
else:
logger.error(
'No debugger plugin data found for event with tag %s and node '
'name %s.', value.tag, value.node_name)
continue
if not value.HasField('tensor'):
logger.warn(
'An event in a debugger events file lacks a tensor value.')
continue
match = re.match(r'^(.*):(\d+):DebugNumericSummary$', value.node_name)
if not match:
logger.warn(
('A event with a health pill has an invalid watch, (i.e., an '
'unexpected debug op): %r'), value.node_name)
return None
health_pill = self._process_health_pill_value(
wall_time=event.wall_time,
step=event.step,
device_name=device_name,
output_slot=output_slot,
node_name=match.group(1),
tensor_proto=value.tensor,
node_name_set=node_name_set)
if not health_pill:
continue
mapping[health_pill.node_name].append(health_pill)
# Keep reading events.
return False | [
"def",
"_process_health_pill_event",
"(",
"self",
",",
"node_name_set",
",",
"mapping",
",",
"target_step",
",",
"file_path",
")",
":",
"events_loader",
"=",
"event_file_loader",
".",
"EventFileLoader",
"(",
"file_path",
")",
"for",
"event",
"in",
"events_loader",
".",
"Load",
"(",
")",
":",
"if",
"not",
"event",
".",
"HasField",
"(",
"'summary'",
")",
":",
"logger",
".",
"warn",
"(",
"'An event in a debugger events file lacks a summary.'",
")",
"continue",
"if",
"event",
".",
"step",
"<",
"target_step",
":",
"# This event is not of the relevant step. We perform this check",
"# first because the majority of events will be eliminated from",
"# consideration by this check.",
"continue",
"if",
"event",
".",
"step",
">",
"target_step",
":",
"# We have passed the relevant step. No need to read more events.",
"return",
"True",
"for",
"value",
"in",
"event",
".",
"summary",
".",
"value",
":",
"# Obtain the device name from the metadata.",
"summary_metadata",
"=",
"value",
".",
"metadata",
"plugin_data",
"=",
"summary_metadata",
".",
"plugin_data",
"if",
"plugin_data",
".",
"plugin_name",
"==",
"constants",
".",
"DEBUGGER_PLUGIN_NAME",
":",
"try",
":",
"content",
"=",
"json",
".",
"loads",
"(",
"tf",
".",
"compat",
".",
"as_text",
"(",
"summary_metadata",
".",
"plugin_data",
".",
"content",
")",
")",
"except",
"ValueError",
"as",
"err",
":",
"logger",
".",
"warn",
"(",
"'Could not parse the JSON string containing data for '",
"'the debugger plugin: %r, %r'",
",",
"content",
",",
"err",
")",
"continue",
"device_name",
"=",
"content",
"[",
"'device'",
"]",
"output_slot",
"=",
"content",
"[",
"'outputSlot'",
"]",
"else",
":",
"logger",
".",
"error",
"(",
"'No debugger plugin data found for event with tag %s and node '",
"'name %s.'",
",",
"value",
".",
"tag",
",",
"value",
".",
"node_name",
")",
"continue",
"if",
"not",
"value",
".",
"HasField",
"(",
"'tensor'",
")",
":",
"logger",
".",
"warn",
"(",
"'An event in a debugger events file lacks a tensor value.'",
")",
"continue",
"match",
"=",
"re",
".",
"match",
"(",
"r'^(.*):(\\d+):DebugNumericSummary$'",
",",
"value",
".",
"node_name",
")",
"if",
"not",
"match",
":",
"logger",
".",
"warn",
"(",
"(",
"'A event with a health pill has an invalid watch, (i.e., an '",
"'unexpected debug op): %r'",
")",
",",
"value",
".",
"node_name",
")",
"return",
"None",
"health_pill",
"=",
"self",
".",
"_process_health_pill_value",
"(",
"wall_time",
"=",
"event",
".",
"wall_time",
",",
"step",
"=",
"event",
".",
"step",
",",
"device_name",
"=",
"device_name",
",",
"output_slot",
"=",
"output_slot",
",",
"node_name",
"=",
"match",
".",
"group",
"(",
"1",
")",
",",
"tensor_proto",
"=",
"value",
".",
"tensor",
",",
"node_name_set",
"=",
"node_name_set",
")",
"if",
"not",
"health_pill",
":",
"continue",
"mapping",
"[",
"health_pill",
".",
"node_name",
"]",
".",
"append",
"(",
"health_pill",
")",
"# Keep reading events.",
"return",
"False"
] | Creates health pills out of data in an event.
Creates health pills out of the event and adds them to the mapping.
Args:
node_name_set: A set of node names that are relevant.
mapping: The mapping from node name to HealthPillEvents.
This object may be destructively modified.
target_step: The target step at which to obtain health pills.
file_path: The path to the file with health pill events.
Returns:
Whether we should stop reading events because future events are no longer
relevant. | [
"Creates",
"health",
"pills",
"out",
"of",
"data",
"in",
"an",
"event",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/debugger/debugger_plugin.py#L367-L447 | train |
tensorflow/tensorboard | tensorboard/plugins/debugger/debugger_plugin.py | DebuggerPlugin._process_health_pill_value | def _process_health_pill_value(self,
wall_time,
step,
device_name,
output_slot,
node_name,
tensor_proto,
node_name_set=None):
"""Creates a HealthPillEvent containing various properties of a health pill.
Args:
wall_time: The wall time in seconds.
step: The session run step of the event.
device_name: The name of the node's device.
output_slot: The numeric output slot.
node_name: The name of the node (without the output slot).
tensor_proto: A tensor proto of data.
node_name_set: An optional set of node names that are relevant. If not
provided, no filtering by relevance occurs.
Returns:
An event_accumulator.HealthPillEvent. Or None if one could not be created.
"""
if node_name_set and node_name not in node_name_set:
# This event is not relevant.
return None
# Since we seek health pills for a specific step, this function
# returns 1 health pill per node per step. The wall time is the
# seconds since the epoch.
elements = list(tensor_util.make_ndarray(tensor_proto))
return HealthPillEvent(
wall_time=wall_time,
step=step,
device_name=device_name,
output_slot=output_slot,
node_name=node_name,
dtype=repr(tf.as_dtype(elements[12])),
shape=elements[14:],
value=elements) | python | def _process_health_pill_value(self,
wall_time,
step,
device_name,
output_slot,
node_name,
tensor_proto,
node_name_set=None):
"""Creates a HealthPillEvent containing various properties of a health pill.
Args:
wall_time: The wall time in seconds.
step: The session run step of the event.
device_name: The name of the node's device.
output_slot: The numeric output slot.
node_name: The name of the node (without the output slot).
tensor_proto: A tensor proto of data.
node_name_set: An optional set of node names that are relevant. If not
provided, no filtering by relevance occurs.
Returns:
An event_accumulator.HealthPillEvent. Or None if one could not be created.
"""
if node_name_set and node_name not in node_name_set:
# This event is not relevant.
return None
# Since we seek health pills for a specific step, this function
# returns 1 health pill per node per step. The wall time is the
# seconds since the epoch.
elements = list(tensor_util.make_ndarray(tensor_proto))
return HealthPillEvent(
wall_time=wall_time,
step=step,
device_name=device_name,
output_slot=output_slot,
node_name=node_name,
dtype=repr(tf.as_dtype(elements[12])),
shape=elements[14:],
value=elements) | [
"def",
"_process_health_pill_value",
"(",
"self",
",",
"wall_time",
",",
"step",
",",
"device_name",
",",
"output_slot",
",",
"node_name",
",",
"tensor_proto",
",",
"node_name_set",
"=",
"None",
")",
":",
"if",
"node_name_set",
"and",
"node_name",
"not",
"in",
"node_name_set",
":",
"# This event is not relevant.",
"return",
"None",
"# Since we seek health pills for a specific step, this function",
"# returns 1 health pill per node per step. The wall time is the",
"# seconds since the epoch.",
"elements",
"=",
"list",
"(",
"tensor_util",
".",
"make_ndarray",
"(",
"tensor_proto",
")",
")",
"return",
"HealthPillEvent",
"(",
"wall_time",
"=",
"wall_time",
",",
"step",
"=",
"step",
",",
"device_name",
"=",
"device_name",
",",
"output_slot",
"=",
"output_slot",
",",
"node_name",
"=",
"node_name",
",",
"dtype",
"=",
"repr",
"(",
"tf",
".",
"as_dtype",
"(",
"elements",
"[",
"12",
"]",
")",
")",
",",
"shape",
"=",
"elements",
"[",
"14",
":",
"]",
",",
"value",
"=",
"elements",
")"
] | Creates a HealthPillEvent containing various properties of a health pill.
Args:
wall_time: The wall time in seconds.
step: The session run step of the event.
device_name: The name of the node's device.
output_slot: The numeric output slot.
node_name: The name of the node (without the output slot).
tensor_proto: A tensor proto of data.
node_name_set: An optional set of node names that are relevant. If not
provided, no filtering by relevance occurs.
Returns:
An event_accumulator.HealthPillEvent. Or None if one could not be created. | [
"Creates",
"a",
"HealthPillEvent",
"containing",
"various",
"properties",
"of",
"a",
"health",
"pill",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/debugger/debugger_plugin.py#L449-L488 | train |
tensorflow/tensorboard | tensorboard/plugins/debugger/debugger_plugin.py | DebuggerPlugin._serve_numerics_alert_report_handler | def _serve_numerics_alert_report_handler(self, request):
"""A (wrapped) werkzeug handler for serving numerics alert report.
Accepts GET requests and responds with an array of JSON-ified
NumericsAlertReportRow.
Each JSON-ified NumericsAlertReportRow object has the following format:
{
'device_name': string,
'tensor_name': string,
'first_timestamp': float,
'nan_event_count': int,
'neg_inf_event_count': int,
'pos_inf_event_count': int
}
These objects are sorted by ascending order of first_timestamp in the
response array.
Args:
request: The request, currently assumed to be empty.
Returns:
A werkzeug BaseResponse object.
"""
if request.method != 'GET':
logger.error(
'%s requests are forbidden by the debugger plugin.', request.method)
return wrappers.Response(status=405)
report = self._debugger_data_server.numerics_alert_report()
# Convert the named tuples to dictionaries so we JSON them into objects.
response = [r._asdict() for r in report] # pylint: disable=protected-access
return http_util.Respond(request, response, 'application/json') | python | def _serve_numerics_alert_report_handler(self, request):
"""A (wrapped) werkzeug handler for serving numerics alert report.
Accepts GET requests and responds with an array of JSON-ified
NumericsAlertReportRow.
Each JSON-ified NumericsAlertReportRow object has the following format:
{
'device_name': string,
'tensor_name': string,
'first_timestamp': float,
'nan_event_count': int,
'neg_inf_event_count': int,
'pos_inf_event_count': int
}
These objects are sorted by ascending order of first_timestamp in the
response array.
Args:
request: The request, currently assumed to be empty.
Returns:
A werkzeug BaseResponse object.
"""
if request.method != 'GET':
logger.error(
'%s requests are forbidden by the debugger plugin.', request.method)
return wrappers.Response(status=405)
report = self._debugger_data_server.numerics_alert_report()
# Convert the named tuples to dictionaries so we JSON them into objects.
response = [r._asdict() for r in report] # pylint: disable=protected-access
return http_util.Respond(request, response, 'application/json') | [
"def",
"_serve_numerics_alert_report_handler",
"(",
"self",
",",
"request",
")",
":",
"if",
"request",
".",
"method",
"!=",
"'GET'",
":",
"logger",
".",
"error",
"(",
"'%s requests are forbidden by the debugger plugin.'",
",",
"request",
".",
"method",
")",
"return",
"wrappers",
".",
"Response",
"(",
"status",
"=",
"405",
")",
"report",
"=",
"self",
".",
"_debugger_data_server",
".",
"numerics_alert_report",
"(",
")",
"# Convert the named tuples to dictionaries so we JSON them into objects.",
"response",
"=",
"[",
"r",
".",
"_asdict",
"(",
")",
"for",
"r",
"in",
"report",
"]",
"# pylint: disable=protected-access",
"return",
"http_util",
".",
"Respond",
"(",
"request",
",",
"response",
",",
"'application/json'",
")"
] | A (wrapped) werkzeug handler for serving numerics alert report.
Accepts GET requests and responds with an array of JSON-ified
NumericsAlertReportRow.
Each JSON-ified NumericsAlertReportRow object has the following format:
{
'device_name': string,
'tensor_name': string,
'first_timestamp': float,
'nan_event_count': int,
'neg_inf_event_count': int,
'pos_inf_event_count': int
}
These objects are sorted by ascending order of first_timestamp in the
response array.
Args:
request: The request, currently assumed to be empty.
Returns:
A werkzeug BaseResponse object. | [
"A",
"(",
"wrapped",
")",
"werkzeug",
"handler",
"for",
"serving",
"numerics",
"alert",
"report",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/debugger/debugger_plugin.py#L491-L525 | train |
tensorflow/tensorboard | tensorboard/manager.py | _info_to_string | def _info_to_string(info):
"""Convert a `TensorBoardInfo` to string form to be stored on disk.
The format returned by this function is opaque and should only be
interpreted by `_info_from_string`.
Args:
info: A valid `TensorBoardInfo` object.
Raises:
ValueError: If any field on `info` is not of the correct type.
Returns:
A string representation of the provided `TensorBoardInfo`.
"""
for key in _TENSORBOARD_INFO_FIELDS:
field_type = _TENSORBOARD_INFO_FIELDS[key]
if not isinstance(getattr(info, key), field_type.runtime_type):
raise ValueError(
"expected %r of type %s, but found: %r" %
(key, field_type.runtime_type, getattr(info, key))
)
if info.version != version.VERSION:
raise ValueError(
"expected 'version' to be %r, but found: %r" %
(version.VERSION, info.version)
)
json_value = {
k: _TENSORBOARD_INFO_FIELDS[k].serialize(getattr(info, k))
for k in _TENSORBOARD_INFO_FIELDS
}
return json.dumps(json_value, sort_keys=True, indent=4) | python | def _info_to_string(info):
"""Convert a `TensorBoardInfo` to string form to be stored on disk.
The format returned by this function is opaque and should only be
interpreted by `_info_from_string`.
Args:
info: A valid `TensorBoardInfo` object.
Raises:
ValueError: If any field on `info` is not of the correct type.
Returns:
A string representation of the provided `TensorBoardInfo`.
"""
for key in _TENSORBOARD_INFO_FIELDS:
field_type = _TENSORBOARD_INFO_FIELDS[key]
if not isinstance(getattr(info, key), field_type.runtime_type):
raise ValueError(
"expected %r of type %s, but found: %r" %
(key, field_type.runtime_type, getattr(info, key))
)
if info.version != version.VERSION:
raise ValueError(
"expected 'version' to be %r, but found: %r" %
(version.VERSION, info.version)
)
json_value = {
k: _TENSORBOARD_INFO_FIELDS[k].serialize(getattr(info, k))
for k in _TENSORBOARD_INFO_FIELDS
}
return json.dumps(json_value, sort_keys=True, indent=4) | [
"def",
"_info_to_string",
"(",
"info",
")",
":",
"for",
"key",
"in",
"_TENSORBOARD_INFO_FIELDS",
":",
"field_type",
"=",
"_TENSORBOARD_INFO_FIELDS",
"[",
"key",
"]",
"if",
"not",
"isinstance",
"(",
"getattr",
"(",
"info",
",",
"key",
")",
",",
"field_type",
".",
"runtime_type",
")",
":",
"raise",
"ValueError",
"(",
"\"expected %r of type %s, but found: %r\"",
"%",
"(",
"key",
",",
"field_type",
".",
"runtime_type",
",",
"getattr",
"(",
"info",
",",
"key",
")",
")",
")",
"if",
"info",
".",
"version",
"!=",
"version",
".",
"VERSION",
":",
"raise",
"ValueError",
"(",
"\"expected 'version' to be %r, but found: %r\"",
"%",
"(",
"version",
".",
"VERSION",
",",
"info",
".",
"version",
")",
")",
"json_value",
"=",
"{",
"k",
":",
"_TENSORBOARD_INFO_FIELDS",
"[",
"k",
"]",
".",
"serialize",
"(",
"getattr",
"(",
"info",
",",
"k",
")",
")",
"for",
"k",
"in",
"_TENSORBOARD_INFO_FIELDS",
"}",
"return",
"json",
".",
"dumps",
"(",
"json_value",
",",
"sort_keys",
"=",
"True",
",",
"indent",
"=",
"4",
")"
] | Convert a `TensorBoardInfo` to string form to be stored on disk.
The format returned by this function is opaque and should only be
interpreted by `_info_from_string`.
Args:
info: A valid `TensorBoardInfo` object.
Raises:
ValueError: If any field on `info` is not of the correct type.
Returns:
A string representation of the provided `TensorBoardInfo`. | [
"Convert",
"a",
"TensorBoardInfo",
"to",
"string",
"form",
"to",
"be",
"stored",
"on",
"disk",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/manager.py#L97-L128 | train |
tensorflow/tensorboard | tensorboard/manager.py | _info_from_string | def _info_from_string(info_string):
"""Parse a `TensorBoardInfo` object from its string representation.
Args:
info_string: A string representation of a `TensorBoardInfo`, as
produced by a previous call to `_info_to_string`.
Returns:
A `TensorBoardInfo` value.
Raises:
ValueError: If the provided string is not valid JSON, or if it does
not represent a JSON object with a "version" field whose value is
`tensorboard.version.VERSION`, or if it has the wrong set of
fields, or if at least one field is of invalid type.
"""
try:
json_value = json.loads(info_string)
except ValueError:
raise ValueError("invalid JSON: %r" % (info_string,))
if not isinstance(json_value, dict):
raise ValueError("not a JSON object: %r" % (json_value,))
if json_value.get("version") != version.VERSION:
raise ValueError("incompatible version: %r" % (json_value,))
expected_keys = frozenset(_TENSORBOARD_INFO_FIELDS)
actual_keys = frozenset(json_value)
if expected_keys != actual_keys:
raise ValueError(
"bad keys on TensorBoardInfo (missing: %s; extraneous: %s)"
% (expected_keys - actual_keys, actual_keys - expected_keys)
)
# Validate and deserialize fields.
for key in _TENSORBOARD_INFO_FIELDS:
field_type = _TENSORBOARD_INFO_FIELDS[key]
if not isinstance(json_value[key], field_type.serialized_type):
raise ValueError(
"expected %r of type %s, but found: %r" %
(key, field_type.serialized_type, json_value[key])
)
json_value[key] = field_type.deserialize(json_value[key])
return TensorBoardInfo(**json_value) | python | def _info_from_string(info_string):
"""Parse a `TensorBoardInfo` object from its string representation.
Args:
info_string: A string representation of a `TensorBoardInfo`, as
produced by a previous call to `_info_to_string`.
Returns:
A `TensorBoardInfo` value.
Raises:
ValueError: If the provided string is not valid JSON, or if it does
not represent a JSON object with a "version" field whose value is
`tensorboard.version.VERSION`, or if it has the wrong set of
fields, or if at least one field is of invalid type.
"""
try:
json_value = json.loads(info_string)
except ValueError:
raise ValueError("invalid JSON: %r" % (info_string,))
if not isinstance(json_value, dict):
raise ValueError("not a JSON object: %r" % (json_value,))
if json_value.get("version") != version.VERSION:
raise ValueError("incompatible version: %r" % (json_value,))
expected_keys = frozenset(_TENSORBOARD_INFO_FIELDS)
actual_keys = frozenset(json_value)
if expected_keys != actual_keys:
raise ValueError(
"bad keys on TensorBoardInfo (missing: %s; extraneous: %s)"
% (expected_keys - actual_keys, actual_keys - expected_keys)
)
# Validate and deserialize fields.
for key in _TENSORBOARD_INFO_FIELDS:
field_type = _TENSORBOARD_INFO_FIELDS[key]
if not isinstance(json_value[key], field_type.serialized_type):
raise ValueError(
"expected %r of type %s, but found: %r" %
(key, field_type.serialized_type, json_value[key])
)
json_value[key] = field_type.deserialize(json_value[key])
return TensorBoardInfo(**json_value) | [
"def",
"_info_from_string",
"(",
"info_string",
")",
":",
"try",
":",
"json_value",
"=",
"json",
".",
"loads",
"(",
"info_string",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"\"invalid JSON: %r\"",
"%",
"(",
"info_string",
",",
")",
")",
"if",
"not",
"isinstance",
"(",
"json_value",
",",
"dict",
")",
":",
"raise",
"ValueError",
"(",
"\"not a JSON object: %r\"",
"%",
"(",
"json_value",
",",
")",
")",
"if",
"json_value",
".",
"get",
"(",
"\"version\"",
")",
"!=",
"version",
".",
"VERSION",
":",
"raise",
"ValueError",
"(",
"\"incompatible version: %r\"",
"%",
"(",
"json_value",
",",
")",
")",
"expected_keys",
"=",
"frozenset",
"(",
"_TENSORBOARD_INFO_FIELDS",
")",
"actual_keys",
"=",
"frozenset",
"(",
"json_value",
")",
"if",
"expected_keys",
"!=",
"actual_keys",
":",
"raise",
"ValueError",
"(",
"\"bad keys on TensorBoardInfo (missing: %s; extraneous: %s)\"",
"%",
"(",
"expected_keys",
"-",
"actual_keys",
",",
"actual_keys",
"-",
"expected_keys",
")",
")",
"# Validate and deserialize fields.",
"for",
"key",
"in",
"_TENSORBOARD_INFO_FIELDS",
":",
"field_type",
"=",
"_TENSORBOARD_INFO_FIELDS",
"[",
"key",
"]",
"if",
"not",
"isinstance",
"(",
"json_value",
"[",
"key",
"]",
",",
"field_type",
".",
"serialized_type",
")",
":",
"raise",
"ValueError",
"(",
"\"expected %r of type %s, but found: %r\"",
"%",
"(",
"key",
",",
"field_type",
".",
"serialized_type",
",",
"json_value",
"[",
"key",
"]",
")",
")",
"json_value",
"[",
"key",
"]",
"=",
"field_type",
".",
"deserialize",
"(",
"json_value",
"[",
"key",
"]",
")",
"return",
"TensorBoardInfo",
"(",
"*",
"*",
"json_value",
")"
] | Parse a `TensorBoardInfo` object from its string representation.
Args:
info_string: A string representation of a `TensorBoardInfo`, as
produced by a previous call to `_info_to_string`.
Returns:
A `TensorBoardInfo` value.
Raises:
ValueError: If the provided string is not valid JSON, or if it does
not represent a JSON object with a "version" field whose value is
`tensorboard.version.VERSION`, or if it has the wrong set of
fields, or if at least one field is of invalid type. | [
"Parse",
"a",
"TensorBoardInfo",
"object",
"from",
"its",
"string",
"representation",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/manager.py#L131-L174 | train |
tensorflow/tensorboard | tensorboard/manager.py | cache_key | def cache_key(working_directory, arguments, configure_kwargs):
"""Compute a `TensorBoardInfo.cache_key` field.
The format returned by this function is opaque. Clients may only
inspect it by comparing it for equality with other results from this
function.
Args:
working_directory: The directory from which TensorBoard was launched
and relative to which paths like `--logdir` and `--db` are
resolved.
arguments: The command-line args to TensorBoard, as `sys.argv[1:]`.
Should be a list (or tuple), not an unparsed string. If you have a
raw shell command, use `shlex.split` before passing it to this
function.
configure_kwargs: A dictionary of additional argument values to
override the textual `arguments`, with the same semantics as in
`tensorboard.program.TensorBoard.configure`. May be an empty
dictionary.
Returns:
A string such that if two (prospective or actual) TensorBoard
invocations have the same cache key then it is safe to use one in
place of the other. The converse is not guaranteed: it is often safe
to change the order of TensorBoard arguments, or to explicitly set
them to their default values, or to move them between `arguments`
and `configure_kwargs`, but such invocations may yield distinct
cache keys.
"""
if not isinstance(arguments, (list, tuple)):
raise TypeError(
"'arguments' should be a list of arguments, but found: %r "
"(use `shlex.split` if given a string)"
% (arguments,)
)
datum = {
"working_directory": working_directory,
"arguments": arguments,
"configure_kwargs": configure_kwargs,
}
raw = base64.b64encode(
json.dumps(datum, sort_keys=True, separators=(",", ":")).encode("utf-8")
)
# `raw` is of type `bytes`, even though it only contains ASCII
# characters; we want it to be `str` in both Python 2 and 3.
return str(raw.decode("ascii")) | python | def cache_key(working_directory, arguments, configure_kwargs):
"""Compute a `TensorBoardInfo.cache_key` field.
The format returned by this function is opaque. Clients may only
inspect it by comparing it for equality with other results from this
function.
Args:
working_directory: The directory from which TensorBoard was launched
and relative to which paths like `--logdir` and `--db` are
resolved.
arguments: The command-line args to TensorBoard, as `sys.argv[1:]`.
Should be a list (or tuple), not an unparsed string. If you have a
raw shell command, use `shlex.split` before passing it to this
function.
configure_kwargs: A dictionary of additional argument values to
override the textual `arguments`, with the same semantics as in
`tensorboard.program.TensorBoard.configure`. May be an empty
dictionary.
Returns:
A string such that if two (prospective or actual) TensorBoard
invocations have the same cache key then it is safe to use one in
place of the other. The converse is not guaranteed: it is often safe
to change the order of TensorBoard arguments, or to explicitly set
them to their default values, or to move them between `arguments`
and `configure_kwargs`, but such invocations may yield distinct
cache keys.
"""
if not isinstance(arguments, (list, tuple)):
raise TypeError(
"'arguments' should be a list of arguments, but found: %r "
"(use `shlex.split` if given a string)"
% (arguments,)
)
datum = {
"working_directory": working_directory,
"arguments": arguments,
"configure_kwargs": configure_kwargs,
}
raw = base64.b64encode(
json.dumps(datum, sort_keys=True, separators=(",", ":")).encode("utf-8")
)
# `raw` is of type `bytes`, even though it only contains ASCII
# characters; we want it to be `str` in both Python 2 and 3.
return str(raw.decode("ascii")) | [
"def",
"cache_key",
"(",
"working_directory",
",",
"arguments",
",",
"configure_kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"arguments",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"'arguments' should be a list of arguments, but found: %r \"",
"\"(use `shlex.split` if given a string)\"",
"%",
"(",
"arguments",
",",
")",
")",
"datum",
"=",
"{",
"\"working_directory\"",
":",
"working_directory",
",",
"\"arguments\"",
":",
"arguments",
",",
"\"configure_kwargs\"",
":",
"configure_kwargs",
",",
"}",
"raw",
"=",
"base64",
".",
"b64encode",
"(",
"json",
".",
"dumps",
"(",
"datum",
",",
"sort_keys",
"=",
"True",
",",
"separators",
"=",
"(",
"\",\"",
",",
"\":\"",
")",
")",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"# `raw` is of type `bytes`, even though it only contains ASCII",
"# characters; we want it to be `str` in both Python 2 and 3.",
"return",
"str",
"(",
"raw",
".",
"decode",
"(",
"\"ascii\"",
")",
")"
] | Compute a `TensorBoardInfo.cache_key` field.
The format returned by this function is opaque. Clients may only
inspect it by comparing it for equality with other results from this
function.
Args:
working_directory: The directory from which TensorBoard was launched
and relative to which paths like `--logdir` and `--db` are
resolved.
arguments: The command-line args to TensorBoard, as `sys.argv[1:]`.
Should be a list (or tuple), not an unparsed string. If you have a
raw shell command, use `shlex.split` before passing it to this
function.
configure_kwargs: A dictionary of additional argument values to
override the textual `arguments`, with the same semantics as in
`tensorboard.program.TensorBoard.configure`. May be an empty
dictionary.
Returns:
A string such that if two (prospective or actual) TensorBoard
invocations have the same cache key then it is safe to use one in
place of the other. The converse is not guaranteed: it is often safe
to change the order of TensorBoard arguments, or to explicitly set
them to their default values, or to move them between `arguments`
and `configure_kwargs`, but such invocations may yield distinct
cache keys. | [
"Compute",
"a",
"TensorBoardInfo",
".",
"cache_key",
"field",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/manager.py#L177-L222 | train |
tensorflow/tensorboard | tensorboard/manager.py | _get_info_dir | def _get_info_dir():
"""Get path to directory in which to store info files.
The directory returned by this function is "owned" by this module. If
the contents of the directory are modified other than via the public
functions of this module, subsequent behavior is undefined.
The directory will be created if it does not exist.
"""
path = os.path.join(tempfile.gettempdir(), ".tensorboard-info")
try:
os.makedirs(path)
except OSError as e:
if e.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
else:
os.chmod(path, 0o777)
return path | python | def _get_info_dir():
"""Get path to directory in which to store info files.
The directory returned by this function is "owned" by this module. If
the contents of the directory are modified other than via the public
functions of this module, subsequent behavior is undefined.
The directory will be created if it does not exist.
"""
path = os.path.join(tempfile.gettempdir(), ".tensorboard-info")
try:
os.makedirs(path)
except OSError as e:
if e.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
else:
os.chmod(path, 0o777)
return path | [
"def",
"_get_info_dir",
"(",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tempfile",
".",
"gettempdir",
"(",
")",
",",
"\".tensorboard-info\"",
")",
"try",
":",
"os",
".",
"makedirs",
"(",
"path",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"EEXIST",
"and",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"pass",
"else",
":",
"raise",
"else",
":",
"os",
".",
"chmod",
"(",
"path",
",",
"0o777",
")",
"return",
"path"
] | Get path to directory in which to store info files.
The directory returned by this function is "owned" by this module. If
the contents of the directory are modified other than via the public
functions of this module, subsequent behavior is undefined.
The directory will be created if it does not exist. | [
"Get",
"path",
"to",
"directory",
"in",
"which",
"to",
"store",
"info",
"files",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/manager.py#L225-L244 | train |
tensorflow/tensorboard | tensorboard/manager.py | write_info_file | def write_info_file(tensorboard_info):
"""Write TensorBoardInfo to the current process's info file.
This should be called by `main` once the server is ready. When the
server shuts down, `remove_info_file` should be called.
Args:
tensorboard_info: A valid `TensorBoardInfo` object.
Raises:
ValueError: If any field on `info` is not of the correct type.
"""
payload = "%s\n" % _info_to_string(tensorboard_info)
with open(_get_info_file_path(), "w") as outfile:
outfile.write(payload) | python | def write_info_file(tensorboard_info):
"""Write TensorBoardInfo to the current process's info file.
This should be called by `main` once the server is ready. When the
server shuts down, `remove_info_file` should be called.
Args:
tensorboard_info: A valid `TensorBoardInfo` object.
Raises:
ValueError: If any field on `info` is not of the correct type.
"""
payload = "%s\n" % _info_to_string(tensorboard_info)
with open(_get_info_file_path(), "w") as outfile:
outfile.write(payload) | [
"def",
"write_info_file",
"(",
"tensorboard_info",
")",
":",
"payload",
"=",
"\"%s\\n\"",
"%",
"_info_to_string",
"(",
"tensorboard_info",
")",
"with",
"open",
"(",
"_get_info_file_path",
"(",
")",
",",
"\"w\"",
")",
"as",
"outfile",
":",
"outfile",
".",
"write",
"(",
"payload",
")"
] | Write TensorBoardInfo to the current process's info file.
This should be called by `main` once the server is ready. When the
server shuts down, `remove_info_file` should be called.
Args:
tensorboard_info: A valid `TensorBoardInfo` object.
Raises:
ValueError: If any field on `info` is not of the correct type. | [
"Write",
"TensorBoardInfo",
"to",
"the",
"current",
"process",
"s",
"info",
"file",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/manager.py#L256-L270 | train |
tensorflow/tensorboard | tensorboard/manager.py | remove_info_file | def remove_info_file():
"""Remove the current process's TensorBoardInfo file, if it exists.
If the file does not exist, no action is taken and no error is raised.
"""
try:
os.unlink(_get_info_file_path())
except OSError as e:
if e.errno == errno.ENOENT:
# The user may have wiped their temporary directory or something.
# Not a problem: we're already in the state that we want to be in.
pass
else:
raise | python | def remove_info_file():
"""Remove the current process's TensorBoardInfo file, if it exists.
If the file does not exist, no action is taken and no error is raised.
"""
try:
os.unlink(_get_info_file_path())
except OSError as e:
if e.errno == errno.ENOENT:
# The user may have wiped their temporary directory or something.
# Not a problem: we're already in the state that we want to be in.
pass
else:
raise | [
"def",
"remove_info_file",
"(",
")",
":",
"try",
":",
"os",
".",
"unlink",
"(",
"_get_info_file_path",
"(",
")",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"ENOENT",
":",
"# The user may have wiped their temporary directory or something.",
"# Not a problem: we're already in the state that we want to be in.",
"pass",
"else",
":",
"raise"
] | Remove the current process's TensorBoardInfo file, if it exists.
If the file does not exist, no action is taken and no error is raised. | [
"Remove",
"the",
"current",
"process",
"s",
"TensorBoardInfo",
"file",
"if",
"it",
"exists",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/manager.py#L273-L286 | train |
tensorflow/tensorboard | tensorboard/manager.py | get_all | def get_all():
"""Return TensorBoardInfo values for running TensorBoard processes.
This function may not provide a perfect snapshot of the set of running
processes. Its result set may be incomplete if the user has cleaned
their /tmp/ directory while TensorBoard processes are running. It may
contain extraneous entries if TensorBoard processes exited uncleanly
(e.g., with SIGKILL or SIGQUIT).
Returns:
A fresh list of `TensorBoardInfo` objects.
"""
info_dir = _get_info_dir()
results = []
for filename in os.listdir(info_dir):
filepath = os.path.join(info_dir, filename)
try:
with open(filepath) as infile:
contents = infile.read()
except IOError as e:
if e.errno == errno.EACCES:
# May have been written by this module in a process whose
# `umask` includes some bits of 0o444.
continue
else:
raise
try:
info = _info_from_string(contents)
except ValueError:
tb_logging.get_logger().warning(
"invalid info file: %r",
filepath,
exc_info=True,
)
else:
results.append(info)
return results | python | def get_all():
"""Return TensorBoardInfo values for running TensorBoard processes.
This function may not provide a perfect snapshot of the set of running
processes. Its result set may be incomplete if the user has cleaned
their /tmp/ directory while TensorBoard processes are running. It may
contain extraneous entries if TensorBoard processes exited uncleanly
(e.g., with SIGKILL or SIGQUIT).
Returns:
A fresh list of `TensorBoardInfo` objects.
"""
info_dir = _get_info_dir()
results = []
for filename in os.listdir(info_dir):
filepath = os.path.join(info_dir, filename)
try:
with open(filepath) as infile:
contents = infile.read()
except IOError as e:
if e.errno == errno.EACCES:
# May have been written by this module in a process whose
# `umask` includes some bits of 0o444.
continue
else:
raise
try:
info = _info_from_string(contents)
except ValueError:
tb_logging.get_logger().warning(
"invalid info file: %r",
filepath,
exc_info=True,
)
else:
results.append(info)
return results | [
"def",
"get_all",
"(",
")",
":",
"info_dir",
"=",
"_get_info_dir",
"(",
")",
"results",
"=",
"[",
"]",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"info_dir",
")",
":",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"info_dir",
",",
"filename",
")",
"try",
":",
"with",
"open",
"(",
"filepath",
")",
"as",
"infile",
":",
"contents",
"=",
"infile",
".",
"read",
"(",
")",
"except",
"IOError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"EACCES",
":",
"# May have been written by this module in a process whose",
"# `umask` includes some bits of 0o444.",
"continue",
"else",
":",
"raise",
"try",
":",
"info",
"=",
"_info_from_string",
"(",
"contents",
")",
"except",
"ValueError",
":",
"tb_logging",
".",
"get_logger",
"(",
")",
".",
"warning",
"(",
"\"invalid info file: %r\"",
",",
"filepath",
",",
"exc_info",
"=",
"True",
",",
")",
"else",
":",
"results",
".",
"append",
"(",
"info",
")",
"return",
"results"
] | Return TensorBoardInfo values for running TensorBoard processes.
This function may not provide a perfect snapshot of the set of running
processes. Its result set may be incomplete if the user has cleaned
their /tmp/ directory while TensorBoard processes are running. It may
contain extraneous entries if TensorBoard processes exited uncleanly
(e.g., with SIGKILL or SIGQUIT).
Returns:
A fresh list of `TensorBoardInfo` objects. | [
"Return",
"TensorBoardInfo",
"values",
"for",
"running",
"TensorBoard",
"processes",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/manager.py#L289-L325 | train |
tensorflow/tensorboard | tensorboard/manager.py | start | def start(arguments, timeout=datetime.timedelta(seconds=60)):
"""Start a new TensorBoard instance, or reuse a compatible one.
If the cache key determined by the provided arguments and the current
working directory (see `cache_key`) matches the cache key of a running
TensorBoard process (see `get_all`), that process will be reused.
Otherwise, a new TensorBoard process will be spawned with the provided
arguments, using the `tensorboard` binary from the system path.
Args:
arguments: List of strings to be passed as arguments to
`tensorboard`. (If you have a raw command-line string, see
`shlex.split`.)
timeout: `datetime.timedelta` object describing how long to wait for
the subprocess to initialize a TensorBoard server and write its
`TensorBoardInfo` file. If the info file is not written within
this time period, `start` will assume that the subprocess is stuck
in a bad state, and will give up on waiting for it and return a
`StartTimedOut` result. Note that in such a case the subprocess
will not be killed. Default value is 60 seconds.
Returns:
A `StartReused`, `StartLaunched`, `StartFailed`, or `StartTimedOut`
object.
"""
match = _find_matching_instance(
cache_key(
working_directory=os.getcwd(),
arguments=arguments,
configure_kwargs={},
),
)
if match:
return StartReused(info=match)
(stdout_fd, stdout_path) = tempfile.mkstemp(prefix=".tensorboard-stdout-")
(stderr_fd, stderr_path) = tempfile.mkstemp(prefix=".tensorboard-stderr-")
start_time_seconds = time.time()
try:
p = subprocess.Popen(
["tensorboard"] + arguments,
stdout=stdout_fd,
stderr=stderr_fd,
)
finally:
os.close(stdout_fd)
os.close(stderr_fd)
poll_interval_seconds = 0.5
end_time_seconds = start_time_seconds + timeout.total_seconds()
while time.time() < end_time_seconds:
time.sleep(poll_interval_seconds)
subprocess_result = p.poll()
if subprocess_result is not None:
return StartFailed(
exit_code=subprocess_result,
stdout=_maybe_read_file(stdout_path),
stderr=_maybe_read_file(stderr_path),
)
for info in get_all():
if info.pid == p.pid and info.start_time >= start_time_seconds:
return StartLaunched(info=info)
else:
return StartTimedOut(pid=p.pid) | python | def start(arguments, timeout=datetime.timedelta(seconds=60)):
"""Start a new TensorBoard instance, or reuse a compatible one.
If the cache key determined by the provided arguments and the current
working directory (see `cache_key`) matches the cache key of a running
TensorBoard process (see `get_all`), that process will be reused.
Otherwise, a new TensorBoard process will be spawned with the provided
arguments, using the `tensorboard` binary from the system path.
Args:
arguments: List of strings to be passed as arguments to
`tensorboard`. (If you have a raw command-line string, see
`shlex.split`.)
timeout: `datetime.timedelta` object describing how long to wait for
the subprocess to initialize a TensorBoard server and write its
`TensorBoardInfo` file. If the info file is not written within
this time period, `start` will assume that the subprocess is stuck
in a bad state, and will give up on waiting for it and return a
`StartTimedOut` result. Note that in such a case the subprocess
will not be killed. Default value is 60 seconds.
Returns:
A `StartReused`, `StartLaunched`, `StartFailed`, or `StartTimedOut`
object.
"""
match = _find_matching_instance(
cache_key(
working_directory=os.getcwd(),
arguments=arguments,
configure_kwargs={},
),
)
if match:
return StartReused(info=match)
(stdout_fd, stdout_path) = tempfile.mkstemp(prefix=".tensorboard-stdout-")
(stderr_fd, stderr_path) = tempfile.mkstemp(prefix=".tensorboard-stderr-")
start_time_seconds = time.time()
try:
p = subprocess.Popen(
["tensorboard"] + arguments,
stdout=stdout_fd,
stderr=stderr_fd,
)
finally:
os.close(stdout_fd)
os.close(stderr_fd)
poll_interval_seconds = 0.5
end_time_seconds = start_time_seconds + timeout.total_seconds()
while time.time() < end_time_seconds:
time.sleep(poll_interval_seconds)
subprocess_result = p.poll()
if subprocess_result is not None:
return StartFailed(
exit_code=subprocess_result,
stdout=_maybe_read_file(stdout_path),
stderr=_maybe_read_file(stderr_path),
)
for info in get_all():
if info.pid == p.pid and info.start_time >= start_time_seconds:
return StartLaunched(info=info)
else:
return StartTimedOut(pid=p.pid) | [
"def",
"start",
"(",
"arguments",
",",
"timeout",
"=",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"60",
")",
")",
":",
"match",
"=",
"_find_matching_instance",
"(",
"cache_key",
"(",
"working_directory",
"=",
"os",
".",
"getcwd",
"(",
")",
",",
"arguments",
"=",
"arguments",
",",
"configure_kwargs",
"=",
"{",
"}",
",",
")",
",",
")",
"if",
"match",
":",
"return",
"StartReused",
"(",
"info",
"=",
"match",
")",
"(",
"stdout_fd",
",",
"stdout_path",
")",
"=",
"tempfile",
".",
"mkstemp",
"(",
"prefix",
"=",
"\".tensorboard-stdout-\"",
")",
"(",
"stderr_fd",
",",
"stderr_path",
")",
"=",
"tempfile",
".",
"mkstemp",
"(",
"prefix",
"=",
"\".tensorboard-stderr-\"",
")",
"start_time_seconds",
"=",
"time",
".",
"time",
"(",
")",
"try",
":",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"\"tensorboard\"",
"]",
"+",
"arguments",
",",
"stdout",
"=",
"stdout_fd",
",",
"stderr",
"=",
"stderr_fd",
",",
")",
"finally",
":",
"os",
".",
"close",
"(",
"stdout_fd",
")",
"os",
".",
"close",
"(",
"stderr_fd",
")",
"poll_interval_seconds",
"=",
"0.5",
"end_time_seconds",
"=",
"start_time_seconds",
"+",
"timeout",
".",
"total_seconds",
"(",
")",
"while",
"time",
".",
"time",
"(",
")",
"<",
"end_time_seconds",
":",
"time",
".",
"sleep",
"(",
"poll_interval_seconds",
")",
"subprocess_result",
"=",
"p",
".",
"poll",
"(",
")",
"if",
"subprocess_result",
"is",
"not",
"None",
":",
"return",
"StartFailed",
"(",
"exit_code",
"=",
"subprocess_result",
",",
"stdout",
"=",
"_maybe_read_file",
"(",
"stdout_path",
")",
",",
"stderr",
"=",
"_maybe_read_file",
"(",
"stderr_path",
")",
",",
")",
"for",
"info",
"in",
"get_all",
"(",
")",
":",
"if",
"info",
".",
"pid",
"==",
"p",
".",
"pid",
"and",
"info",
".",
"start_time",
">=",
"start_time_seconds",
":",
"return",
"StartLaunched",
"(",
"info",
"=",
"info",
")",
"else",
":",
"return",
"StartTimedOut",
"(",
"pid",
"=",
"p",
".",
"pid",
")"
] | Start a new TensorBoard instance, or reuse a compatible one.
If the cache key determined by the provided arguments and the current
working directory (see `cache_key`) matches the cache key of a running
TensorBoard process (see `get_all`), that process will be reused.
Otherwise, a new TensorBoard process will be spawned with the provided
arguments, using the `tensorboard` binary from the system path.
Args:
arguments: List of strings to be passed as arguments to
`tensorboard`. (If you have a raw command-line string, see
`shlex.split`.)
timeout: `datetime.timedelta` object describing how long to wait for
the subprocess to initialize a TensorBoard server and write its
`TensorBoardInfo` file. If the info file is not written within
this time period, `start` will assume that the subprocess is stuck
in a bad state, and will give up on waiting for it and return a
`StartTimedOut` result. Note that in such a case the subprocess
will not be killed. Default value is 60 seconds.
Returns:
A `StartReused`, `StartLaunched`, `StartFailed`, or `StartTimedOut`
object. | [
"Start",
"a",
"new",
"TensorBoard",
"instance",
"or",
"reuse",
"a",
"compatible",
"one",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/manager.py#L361-L425 | train |
tensorflow/tensorboard | tensorboard/manager.py | _find_matching_instance | def _find_matching_instance(cache_key):
"""Find a running TensorBoard instance compatible with the cache key.
Returns:
A `TensorBoardInfo` object, or `None` if none matches the cache key.
"""
infos = get_all()
candidates = [info for info in infos if info.cache_key == cache_key]
for candidate in sorted(candidates, key=lambda x: x.port):
# TODO(@wchargin): Check here that the provided port is still live.
return candidate
return None | python | def _find_matching_instance(cache_key):
"""Find a running TensorBoard instance compatible with the cache key.
Returns:
A `TensorBoardInfo` object, or `None` if none matches the cache key.
"""
infos = get_all()
candidates = [info for info in infos if info.cache_key == cache_key]
for candidate in sorted(candidates, key=lambda x: x.port):
# TODO(@wchargin): Check here that the provided port is still live.
return candidate
return None | [
"def",
"_find_matching_instance",
"(",
"cache_key",
")",
":",
"infos",
"=",
"get_all",
"(",
")",
"candidates",
"=",
"[",
"info",
"for",
"info",
"in",
"infos",
"if",
"info",
".",
"cache_key",
"==",
"cache_key",
"]",
"for",
"candidate",
"in",
"sorted",
"(",
"candidates",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"port",
")",
":",
"# TODO(@wchargin): Check here that the provided port is still live.",
"return",
"candidate",
"return",
"None"
] | Find a running TensorBoard instance compatible with the cache key.
Returns:
A `TensorBoardInfo` object, or `None` if none matches the cache key. | [
"Find",
"a",
"running",
"TensorBoard",
"instance",
"compatible",
"with",
"the",
"cache",
"key",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/manager.py#L428-L439 | train |
tensorflow/tensorboard | tensorboard/manager.py | _maybe_read_file | def _maybe_read_file(filename):
"""Read the given file, if it exists.
Args:
filename: A path to a file.
Returns:
A string containing the file contents, or `None` if the file does
not exist.
"""
try:
with open(filename) as infile:
return infile.read()
except IOError as e:
if e.errno == errno.ENOENT:
return None | python | def _maybe_read_file(filename):
"""Read the given file, if it exists.
Args:
filename: A path to a file.
Returns:
A string containing the file contents, or `None` if the file does
not exist.
"""
try:
with open(filename) as infile:
return infile.read()
except IOError as e:
if e.errno == errno.ENOENT:
return None | [
"def",
"_maybe_read_file",
"(",
"filename",
")",
":",
"try",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"infile",
":",
"return",
"infile",
".",
"read",
"(",
")",
"except",
"IOError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"ENOENT",
":",
"return",
"None"
] | Read the given file, if it exists.
Args:
filename: A path to a file.
Returns:
A string containing the file contents, or `None` if the file does
not exist. | [
"Read",
"the",
"given",
"file",
"if",
"it",
"exists",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/manager.py#L442-L457 | train |
tensorflow/tensorboard | tensorboard/plugins/profile/profile_plugin.py | process_raw_trace | def process_raw_trace(raw_trace):
"""Processes raw trace data and returns the UI data."""
trace = trace_events_pb2.Trace()
trace.ParseFromString(raw_trace)
return ''.join(trace_events_json.TraceEventsJsonStream(trace)) | python | def process_raw_trace(raw_trace):
"""Processes raw trace data and returns the UI data."""
trace = trace_events_pb2.Trace()
trace.ParseFromString(raw_trace)
return ''.join(trace_events_json.TraceEventsJsonStream(trace)) | [
"def",
"process_raw_trace",
"(",
"raw_trace",
")",
":",
"trace",
"=",
"trace_events_pb2",
".",
"Trace",
"(",
")",
"trace",
".",
"ParseFromString",
"(",
"raw_trace",
")",
"return",
"''",
".",
"join",
"(",
"trace_events_json",
".",
"TraceEventsJsonStream",
"(",
"trace",
")",
")"
] | Processes raw trace data and returns the UI data. | [
"Processes",
"raw",
"trace",
"data",
"and",
"returns",
"the",
"UI",
"data",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/profile/profile_plugin.py#L70-L74 | train |
tensorflow/tensorboard | tensorboard/plugins/profile/profile_plugin.py | ProfilePlugin.is_active | def is_active(self):
"""Whether this plugin is active and has any profile data to show.
Detecting profile data is expensive, so this process runs asynchronously
and the value reported by this method is the cached value and may be stale.
Returns:
Whether any run has profile data.
"""
# If we are already active, we remain active and don't recompute this.
# Otherwise, try to acquire the lock without blocking; if we get it and
# we're still not active, launch a thread to check if we're active and
# release the lock once the computation is finished. Either way, this
# thread returns the current cached value to avoid blocking.
if not self._is_active and self._is_active_lock.acquire(False):
if self._is_active:
self._is_active_lock.release()
else:
def compute_is_active():
self._is_active = any(self.generate_run_to_tools())
self._is_active_lock.release()
new_thread = threading.Thread(
target=compute_is_active,
name='ProfilePluginIsActiveThread')
new_thread.start()
return self._is_active | python | def is_active(self):
"""Whether this plugin is active and has any profile data to show.
Detecting profile data is expensive, so this process runs asynchronously
and the value reported by this method is the cached value and may be stale.
Returns:
Whether any run has profile data.
"""
# If we are already active, we remain active and don't recompute this.
# Otherwise, try to acquire the lock without blocking; if we get it and
# we're still not active, launch a thread to check if we're active and
# release the lock once the computation is finished. Either way, this
# thread returns the current cached value to avoid blocking.
if not self._is_active and self._is_active_lock.acquire(False):
if self._is_active:
self._is_active_lock.release()
else:
def compute_is_active():
self._is_active = any(self.generate_run_to_tools())
self._is_active_lock.release()
new_thread = threading.Thread(
target=compute_is_active,
name='ProfilePluginIsActiveThread')
new_thread.start()
return self._is_active | [
"def",
"is_active",
"(",
"self",
")",
":",
"# If we are already active, we remain active and don't recompute this.",
"# Otherwise, try to acquire the lock without blocking; if we get it and",
"# we're still not active, launch a thread to check if we're active and",
"# release the lock once the computation is finished. Either way, this",
"# thread returns the current cached value to avoid blocking.",
"if",
"not",
"self",
".",
"_is_active",
"and",
"self",
".",
"_is_active_lock",
".",
"acquire",
"(",
"False",
")",
":",
"if",
"self",
".",
"_is_active",
":",
"self",
".",
"_is_active_lock",
".",
"release",
"(",
")",
"else",
":",
"def",
"compute_is_active",
"(",
")",
":",
"self",
".",
"_is_active",
"=",
"any",
"(",
"self",
".",
"generate_run_to_tools",
"(",
")",
")",
"self",
".",
"_is_active_lock",
".",
"release",
"(",
")",
"new_thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"compute_is_active",
",",
"name",
"=",
"'ProfilePluginIsActiveThread'",
")",
"new_thread",
".",
"start",
"(",
")",
"return",
"self",
".",
"_is_active"
] | Whether this plugin is active and has any profile data to show.
Detecting profile data is expensive, so this process runs asynchronously
and the value reported by this method is the cached value and may be stale.
Returns:
Whether any run has profile data. | [
"Whether",
"this",
"plugin",
"is",
"active",
"and",
"has",
"any",
"profile",
"data",
"to",
"show",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/profile/profile_plugin.py#L103-L128 | train |
tensorflow/tensorboard | tensorboard/plugins/profile/profile_plugin.py | ProfilePlugin._run_dir | def _run_dir(self, run):
"""Helper that maps a frontend run name to a profile "run" directory.
The frontend run name consists of the TensorBoard run name (aka the relative
path from the logdir root to the directory containing the data) path-joined
to the Profile plugin's "run" concept (which is a subdirectory of the
plugins/profile directory representing an individual run of the tool), with
the special case that TensorBoard run is the logdir root (which is the run
named '.') then only the Profile plugin "run" name is used, for backwards
compatibility.
To convert back to the actual run directory, we apply the following
transformation:
- If the run name doesn't contain '/', prepend './'
- Split on the rightmost instance of '/'
- Assume the left side is a TensorBoard run name and map it to a directory
path using EventMultiplexer.RunPaths(), then map that to the profile
plugin directory via PluginDirectory()
- Assume the right side is a Profile plugin "run" and path-join it to
the preceding path to get the final directory
Args:
run: the frontend run name, as described above, e.g. train/run1.
Returns:
The resolved directory path, e.g. /logdir/train/plugins/profile/run1.
"""
run = run.rstrip('/')
if '/' not in run:
run = './' + run
tb_run_name, _, profile_run_name = run.rpartition('/')
tb_run_directory = self.multiplexer.RunPaths().get(tb_run_name)
if tb_run_directory is None:
# Check if logdir is a directory to handle case where it's actually a
# multipart directory spec, which this plugin does not support.
if tb_run_name == '.' and tf.io.gfile.isdir(self.logdir):
tb_run_directory = self.logdir
else:
raise RuntimeError("No matching run directory for run %s" % run)
plugin_directory = plugin_asset_util.PluginDirectory(
tb_run_directory, PLUGIN_NAME)
return os.path.join(plugin_directory, profile_run_name) | python | def _run_dir(self, run):
"""Helper that maps a frontend run name to a profile "run" directory.
The frontend run name consists of the TensorBoard run name (aka the relative
path from the logdir root to the directory containing the data) path-joined
to the Profile plugin's "run" concept (which is a subdirectory of the
plugins/profile directory representing an individual run of the tool), with
the special case that TensorBoard run is the logdir root (which is the run
named '.') then only the Profile plugin "run" name is used, for backwards
compatibility.
To convert back to the actual run directory, we apply the following
transformation:
- If the run name doesn't contain '/', prepend './'
- Split on the rightmost instance of '/'
- Assume the left side is a TensorBoard run name and map it to a directory
path using EventMultiplexer.RunPaths(), then map that to the profile
plugin directory via PluginDirectory()
- Assume the right side is a Profile plugin "run" and path-join it to
the preceding path to get the final directory
Args:
run: the frontend run name, as described above, e.g. train/run1.
Returns:
The resolved directory path, e.g. /logdir/train/plugins/profile/run1.
"""
run = run.rstrip('/')
if '/' not in run:
run = './' + run
tb_run_name, _, profile_run_name = run.rpartition('/')
tb_run_directory = self.multiplexer.RunPaths().get(tb_run_name)
if tb_run_directory is None:
# Check if logdir is a directory to handle case where it's actually a
# multipart directory spec, which this plugin does not support.
if tb_run_name == '.' and tf.io.gfile.isdir(self.logdir):
tb_run_directory = self.logdir
else:
raise RuntimeError("No matching run directory for run %s" % run)
plugin_directory = plugin_asset_util.PluginDirectory(
tb_run_directory, PLUGIN_NAME)
return os.path.join(plugin_directory, profile_run_name) | [
"def",
"_run_dir",
"(",
"self",
",",
"run",
")",
":",
"run",
"=",
"run",
".",
"rstrip",
"(",
"'/'",
")",
"if",
"'/'",
"not",
"in",
"run",
":",
"run",
"=",
"'./'",
"+",
"run",
"tb_run_name",
",",
"_",
",",
"profile_run_name",
"=",
"run",
".",
"rpartition",
"(",
"'/'",
")",
"tb_run_directory",
"=",
"self",
".",
"multiplexer",
".",
"RunPaths",
"(",
")",
".",
"get",
"(",
"tb_run_name",
")",
"if",
"tb_run_directory",
"is",
"None",
":",
"# Check if logdir is a directory to handle case where it's actually a",
"# multipart directory spec, which this plugin does not support.",
"if",
"tb_run_name",
"==",
"'.'",
"and",
"tf",
".",
"io",
".",
"gfile",
".",
"isdir",
"(",
"self",
".",
"logdir",
")",
":",
"tb_run_directory",
"=",
"self",
".",
"logdir",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"No matching run directory for run %s\"",
"%",
"run",
")",
"plugin_directory",
"=",
"plugin_asset_util",
".",
"PluginDirectory",
"(",
"tb_run_directory",
",",
"PLUGIN_NAME",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"plugin_directory",
",",
"profile_run_name",
")"
] | Helper that maps a frontend run name to a profile "run" directory.
The frontend run name consists of the TensorBoard run name (aka the relative
path from the logdir root to the directory containing the data) path-joined
to the Profile plugin's "run" concept (which is a subdirectory of the
plugins/profile directory representing an individual run of the tool), with
the special case that TensorBoard run is the logdir root (which is the run
named '.') then only the Profile plugin "run" name is used, for backwards
compatibility.
To convert back to the actual run directory, we apply the following
transformation:
- If the run name doesn't contain '/', prepend './'
- Split on the rightmost instance of '/'
- Assume the left side is a TensorBoard run name and map it to a directory
path using EventMultiplexer.RunPaths(), then map that to the profile
plugin directory via PluginDirectory()
- Assume the right side is a Profile plugin "run" and path-join it to
the preceding path to get the final directory
Args:
run: the frontend run name, as described above, e.g. train/run1.
Returns:
The resolved directory path, e.g. /logdir/train/plugins/profile/run1. | [
"Helper",
"that",
"maps",
"a",
"frontend",
"run",
"name",
"to",
"a",
"profile",
"run",
"directory",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/profile/profile_plugin.py#L149-L190 | train |
tensorflow/tensorboard | tensorboard/plugins/profile/profile_plugin.py | ProfilePlugin.generate_run_to_tools | def generate_run_to_tools(self):
"""Generator for pairs of "run name" and a list of tools for that run.
The "run name" here is a "frontend run name" - see _run_dir() for the
definition of a "frontend run name" and how it maps to a directory of
profile data for a specific profile "run". The profile plugin concept of
"run" is different from the normal TensorBoard run; each run in this case
represents a single instance of profile data collection, more similar to a
"step" of data in typical TensorBoard semantics. These runs reside in
subdirectories of the plugins/profile directory within any regular
TensorBoard run directory (defined as a subdirectory of the logdir that
contains at least one tfevents file) or within the logdir root directory
itself (even if it contains no tfevents file and would thus not be
considered a normal TensorBoard run, for backwards compatibility).
Within those "profile run directories", there are files in the directory
that correspond to different profiling tools. The file that contains profile
for a specific tool "x" will have a suffix name TOOLS["x"].
Example:
logs/
plugins/
profile/
run1/
hostA.trace
train/
events.out.tfevents.foo
plugins/
profile/
run1/
hostA.trace
hostB.trace
run2/
hostA.trace
validation/
events.out.tfevents.foo
plugins/
profile/
run1/
hostA.trace
Yields:
A sequence of tuples mapping "frontend run names" to lists of tool names
available for those runs. For the above example, this would be:
("run1", ["trace_viewer"])
("train/run1", ["trace_viewer"])
("train/run2", ["trace_viewer"])
("validation/run1", ["trace_viewer"])
"""
self.start_grpc_stub_if_necessary()
plugin_assets = self.multiplexer.PluginAssets(PLUGIN_NAME)
tb_run_names_to_dirs = self.multiplexer.RunPaths()
# Ensure that we also check the root logdir, even if it isn't a recognized
# TensorBoard run (i.e. has no tfevents file directly under it), to remain
# backwards compatible with previously profile plugin behavior. Note that we
# check if logdir is a directory to handle case where it's actually a
# multipart directory spec, which this plugin does not support.
if '.' not in plugin_assets and tf.io.gfile.isdir(self.logdir):
tb_run_names_to_dirs['.'] = self.logdir
plugin_assets['.'] = plugin_asset_util.ListAssets(
self.logdir, PLUGIN_NAME)
for tb_run_name, profile_runs in six.iteritems(plugin_assets):
tb_run_dir = tb_run_names_to_dirs[tb_run_name]
tb_plugin_dir = plugin_asset_util.PluginDirectory(
tb_run_dir, PLUGIN_NAME)
for profile_run in profile_runs:
# Remove trailing slash; some filesystem implementations emit this.
profile_run = profile_run.rstrip('/')
if tb_run_name == '.':
frontend_run = profile_run
else:
frontend_run = '/'.join([tb_run_name, profile_run])
profile_run_dir = os.path.join(tb_plugin_dir, profile_run)
if tf.io.gfile.isdir(profile_run_dir):
yield frontend_run, self._get_active_tools(profile_run_dir) | python | def generate_run_to_tools(self):
"""Generator for pairs of "run name" and a list of tools for that run.
The "run name" here is a "frontend run name" - see _run_dir() for the
definition of a "frontend run name" and how it maps to a directory of
profile data for a specific profile "run". The profile plugin concept of
"run" is different from the normal TensorBoard run; each run in this case
represents a single instance of profile data collection, more similar to a
"step" of data in typical TensorBoard semantics. These runs reside in
subdirectories of the plugins/profile directory within any regular
TensorBoard run directory (defined as a subdirectory of the logdir that
contains at least one tfevents file) or within the logdir root directory
itself (even if it contains no tfevents file and would thus not be
considered a normal TensorBoard run, for backwards compatibility).
Within those "profile run directories", there are files in the directory
that correspond to different profiling tools. The file that contains profile
for a specific tool "x" will have a suffix name TOOLS["x"].
Example:
logs/
plugins/
profile/
run1/
hostA.trace
train/
events.out.tfevents.foo
plugins/
profile/
run1/
hostA.trace
hostB.trace
run2/
hostA.trace
validation/
events.out.tfevents.foo
plugins/
profile/
run1/
hostA.trace
Yields:
A sequence of tuples mapping "frontend run names" to lists of tool names
available for those runs. For the above example, this would be:
("run1", ["trace_viewer"])
("train/run1", ["trace_viewer"])
("train/run2", ["trace_viewer"])
("validation/run1", ["trace_viewer"])
"""
self.start_grpc_stub_if_necessary()
plugin_assets = self.multiplexer.PluginAssets(PLUGIN_NAME)
tb_run_names_to_dirs = self.multiplexer.RunPaths()
# Ensure that we also check the root logdir, even if it isn't a recognized
# TensorBoard run (i.e. has no tfevents file directly under it), to remain
# backwards compatible with previously profile plugin behavior. Note that we
# check if logdir is a directory to handle case where it's actually a
# multipart directory spec, which this plugin does not support.
if '.' not in plugin_assets and tf.io.gfile.isdir(self.logdir):
tb_run_names_to_dirs['.'] = self.logdir
plugin_assets['.'] = plugin_asset_util.ListAssets(
self.logdir, PLUGIN_NAME)
for tb_run_name, profile_runs in six.iteritems(plugin_assets):
tb_run_dir = tb_run_names_to_dirs[tb_run_name]
tb_plugin_dir = plugin_asset_util.PluginDirectory(
tb_run_dir, PLUGIN_NAME)
for profile_run in profile_runs:
# Remove trailing slash; some filesystem implementations emit this.
profile_run = profile_run.rstrip('/')
if tb_run_name == '.':
frontend_run = profile_run
else:
frontend_run = '/'.join([tb_run_name, profile_run])
profile_run_dir = os.path.join(tb_plugin_dir, profile_run)
if tf.io.gfile.isdir(profile_run_dir):
yield frontend_run, self._get_active_tools(profile_run_dir) | [
"def",
"generate_run_to_tools",
"(",
"self",
")",
":",
"self",
".",
"start_grpc_stub_if_necessary",
"(",
")",
"plugin_assets",
"=",
"self",
".",
"multiplexer",
".",
"PluginAssets",
"(",
"PLUGIN_NAME",
")",
"tb_run_names_to_dirs",
"=",
"self",
".",
"multiplexer",
".",
"RunPaths",
"(",
")",
"# Ensure that we also check the root logdir, even if it isn't a recognized",
"# TensorBoard run (i.e. has no tfevents file directly under it), to remain",
"# backwards compatible with previously profile plugin behavior. Note that we",
"# check if logdir is a directory to handle case where it's actually a",
"# multipart directory spec, which this plugin does not support.",
"if",
"'.'",
"not",
"in",
"plugin_assets",
"and",
"tf",
".",
"io",
".",
"gfile",
".",
"isdir",
"(",
"self",
".",
"logdir",
")",
":",
"tb_run_names_to_dirs",
"[",
"'.'",
"]",
"=",
"self",
".",
"logdir",
"plugin_assets",
"[",
"'.'",
"]",
"=",
"plugin_asset_util",
".",
"ListAssets",
"(",
"self",
".",
"logdir",
",",
"PLUGIN_NAME",
")",
"for",
"tb_run_name",
",",
"profile_runs",
"in",
"six",
".",
"iteritems",
"(",
"plugin_assets",
")",
":",
"tb_run_dir",
"=",
"tb_run_names_to_dirs",
"[",
"tb_run_name",
"]",
"tb_plugin_dir",
"=",
"plugin_asset_util",
".",
"PluginDirectory",
"(",
"tb_run_dir",
",",
"PLUGIN_NAME",
")",
"for",
"profile_run",
"in",
"profile_runs",
":",
"# Remove trailing slash; some filesystem implementations emit this.",
"profile_run",
"=",
"profile_run",
".",
"rstrip",
"(",
"'/'",
")",
"if",
"tb_run_name",
"==",
"'.'",
":",
"frontend_run",
"=",
"profile_run",
"else",
":",
"frontend_run",
"=",
"'/'",
".",
"join",
"(",
"[",
"tb_run_name",
",",
"profile_run",
"]",
")",
"profile_run_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tb_plugin_dir",
",",
"profile_run",
")",
"if",
"tf",
".",
"io",
".",
"gfile",
".",
"isdir",
"(",
"profile_run_dir",
")",
":",
"yield",
"frontend_run",
",",
"self",
".",
"_get_active_tools",
"(",
"profile_run_dir",
")"
] | Generator for pairs of "run name" and a list of tools for that run.
The "run name" here is a "frontend run name" - see _run_dir() for the
definition of a "frontend run name" and how it maps to a directory of
profile data for a specific profile "run". The profile plugin concept of
"run" is different from the normal TensorBoard run; each run in this case
represents a single instance of profile data collection, more similar to a
"step" of data in typical TensorBoard semantics. These runs reside in
subdirectories of the plugins/profile directory within any regular
TensorBoard run directory (defined as a subdirectory of the logdir that
contains at least one tfevents file) or within the logdir root directory
itself (even if it contains no tfevents file and would thus not be
considered a normal TensorBoard run, for backwards compatibility).
Within those "profile run directories", there are files in the directory
that correspond to different profiling tools. The file that contains profile
for a specific tool "x" will have a suffix name TOOLS["x"].
Example:
logs/
plugins/
profile/
run1/
hostA.trace
train/
events.out.tfevents.foo
plugins/
profile/
run1/
hostA.trace
hostB.trace
run2/
hostA.trace
validation/
events.out.tfevents.foo
plugins/
profile/
run1/
hostA.trace
Yields:
A sequence of tuples mapping "frontend run names" to lists of tool names
available for those runs. For the above example, this would be:
("run1", ["trace_viewer"])
("train/run1", ["trace_viewer"])
("train/run2", ["trace_viewer"])
("validation/run1", ["trace_viewer"]) | [
"Generator",
"for",
"pairs",
"of",
"run",
"name",
"and",
"a",
"list",
"of",
"tools",
"for",
"that",
"run",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/profile/profile_plugin.py#L192-L270 | train |
tensorflow/tensorboard | tensorboard/plugins/profile/profile_plugin.py | ProfilePlugin.host_impl | def host_impl(self, run, tool):
"""Returns available hosts for the run and tool in the log directory.
In the plugin log directory, each directory contains profile data for a
single run (identified by the directory name), and files in the run
directory contains data for different tools and hosts. The file that
contains profile for a specific tool "x" will have a prefix name TOOLS["x"].
Example:
log/
run1/
plugins/
profile/
host1.trace
host2.trace
run2/
plugins/
profile/
host1.trace
host2.trace
Returns:
A list of host names e.g.
{"host1", "host2", "host3"} for the example.
"""
hosts = {}
run_dir = self._run_dir(run)
if not run_dir:
logger.warn("Cannot find asset directory for: %s", run)
return hosts
tool_pattern = '*' + TOOLS[tool]
try:
files = tf.io.gfile.glob(os.path.join(run_dir, tool_pattern))
hosts = [os.path.basename(f).replace(TOOLS[tool], '') for f in files]
except tf.errors.OpError as e:
logger.warn("Cannot read asset directory: %s, OpError %s",
run_dir, e)
return hosts | python | def host_impl(self, run, tool):
"""Returns available hosts for the run and tool in the log directory.
In the plugin log directory, each directory contains profile data for a
single run (identified by the directory name), and files in the run
directory contains data for different tools and hosts. The file that
contains profile for a specific tool "x" will have a prefix name TOOLS["x"].
Example:
log/
run1/
plugins/
profile/
host1.trace
host2.trace
run2/
plugins/
profile/
host1.trace
host2.trace
Returns:
A list of host names e.g.
{"host1", "host2", "host3"} for the example.
"""
hosts = {}
run_dir = self._run_dir(run)
if not run_dir:
logger.warn("Cannot find asset directory for: %s", run)
return hosts
tool_pattern = '*' + TOOLS[tool]
try:
files = tf.io.gfile.glob(os.path.join(run_dir, tool_pattern))
hosts = [os.path.basename(f).replace(TOOLS[tool], '') for f in files]
except tf.errors.OpError as e:
logger.warn("Cannot read asset directory: %s, OpError %s",
run_dir, e)
return hosts | [
"def",
"host_impl",
"(",
"self",
",",
"run",
",",
"tool",
")",
":",
"hosts",
"=",
"{",
"}",
"run_dir",
"=",
"self",
".",
"_run_dir",
"(",
"run",
")",
"if",
"not",
"run_dir",
":",
"logger",
".",
"warn",
"(",
"\"Cannot find asset directory for: %s\"",
",",
"run",
")",
"return",
"hosts",
"tool_pattern",
"=",
"'*'",
"+",
"TOOLS",
"[",
"tool",
"]",
"try",
":",
"files",
"=",
"tf",
".",
"io",
".",
"gfile",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"run_dir",
",",
"tool_pattern",
")",
")",
"hosts",
"=",
"[",
"os",
".",
"path",
".",
"basename",
"(",
"f",
")",
".",
"replace",
"(",
"TOOLS",
"[",
"tool",
"]",
",",
"''",
")",
"for",
"f",
"in",
"files",
"]",
"except",
"tf",
".",
"errors",
".",
"OpError",
"as",
"e",
":",
"logger",
".",
"warn",
"(",
"\"Cannot read asset directory: %s, OpError %s\"",
",",
"run_dir",
",",
"e",
")",
"return",
"hosts"
] | Returns available hosts for the run and tool in the log directory.
In the plugin log directory, each directory contains profile data for a
single run (identified by the directory name), and files in the run
directory contains data for different tools and hosts. The file that
contains profile for a specific tool "x" will have a prefix name TOOLS["x"].
Example:
log/
run1/
plugins/
profile/
host1.trace
host2.trace
run2/
plugins/
profile/
host1.trace
host2.trace
Returns:
A list of host names e.g.
{"host1", "host2", "host3"} for the example. | [
"Returns",
"available",
"hosts",
"for",
"the",
"run",
"and",
"tool",
"in",
"the",
"log",
"directory",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/profile/profile_plugin.py#L304-L341 | train |
tensorflow/tensorboard | tensorboard/plugins/profile/profile_plugin.py | ProfilePlugin.data_impl | def data_impl(self, request):
"""Retrieves and processes the tool data for a run and a host.
Args:
request: XMLHttpRequest
Returns:
A string that can be served to the frontend tool or None if tool,
run or host is invalid.
"""
run = request.args.get('run')
tool = request.args.get('tag')
host = request.args.get('host')
run_dir = self._run_dir(run)
# Profile plugin "run" is the last component of run dir.
profile_run = os.path.basename(run_dir)
if tool not in TOOLS:
return None
self.start_grpc_stub_if_necessary()
if tool == 'trace_viewer@' and self.stub is not None:
from tensorflow.contrib.tpu.profiler import tpu_profiler_analysis_pb2
grpc_request = tpu_profiler_analysis_pb2.ProfileSessionDataRequest()
grpc_request.repository_root = run_dir
grpc_request.session_id = profile_run[:-1]
grpc_request.tool_name = 'trace_viewer'
# Remove the trailing dot if present
grpc_request.host_name = host.rstrip('.')
grpc_request.parameters['resolution'] = request.args.get('resolution')
if request.args.get('start_time_ms') is not None:
grpc_request.parameters['start_time_ms'] = request.args.get(
'start_time_ms')
if request.args.get('end_time_ms') is not None:
grpc_request.parameters['end_time_ms'] = request.args.get('end_time_ms')
grpc_response = self.stub.GetSessionToolData(grpc_request)
return grpc_response.output
if tool not in TOOLS:
return None
tool_name = str(host) + TOOLS[tool]
asset_path = os.path.join(run_dir, tool_name)
raw_data = None
try:
with tf.io.gfile.GFile(asset_path, 'rb') as f:
raw_data = f.read()
except tf.errors.NotFoundError:
logger.warn('Asset path %s not found', asset_path)
except tf.errors.OpError as e:
logger.warn("Couldn't read asset path: %s, OpError %s", asset_path, e)
if raw_data is None:
return None
if tool == 'trace_viewer':
return process_raw_trace(raw_data)
if tool in _RAW_DATA_TOOLS:
return raw_data
return None | python | def data_impl(self, request):
"""Retrieves and processes the tool data for a run and a host.
Args:
request: XMLHttpRequest
Returns:
A string that can be served to the frontend tool or None if tool,
run or host is invalid.
"""
run = request.args.get('run')
tool = request.args.get('tag')
host = request.args.get('host')
run_dir = self._run_dir(run)
# Profile plugin "run" is the last component of run dir.
profile_run = os.path.basename(run_dir)
if tool not in TOOLS:
return None
self.start_grpc_stub_if_necessary()
if tool == 'trace_viewer@' and self.stub is not None:
from tensorflow.contrib.tpu.profiler import tpu_profiler_analysis_pb2
grpc_request = tpu_profiler_analysis_pb2.ProfileSessionDataRequest()
grpc_request.repository_root = run_dir
grpc_request.session_id = profile_run[:-1]
grpc_request.tool_name = 'trace_viewer'
# Remove the trailing dot if present
grpc_request.host_name = host.rstrip('.')
grpc_request.parameters['resolution'] = request.args.get('resolution')
if request.args.get('start_time_ms') is not None:
grpc_request.parameters['start_time_ms'] = request.args.get(
'start_time_ms')
if request.args.get('end_time_ms') is not None:
grpc_request.parameters['end_time_ms'] = request.args.get('end_time_ms')
grpc_response = self.stub.GetSessionToolData(grpc_request)
return grpc_response.output
if tool not in TOOLS:
return None
tool_name = str(host) + TOOLS[tool]
asset_path = os.path.join(run_dir, tool_name)
raw_data = None
try:
with tf.io.gfile.GFile(asset_path, 'rb') as f:
raw_data = f.read()
except tf.errors.NotFoundError:
logger.warn('Asset path %s not found', asset_path)
except tf.errors.OpError as e:
logger.warn("Couldn't read asset path: %s, OpError %s", asset_path, e)
if raw_data is None:
return None
if tool == 'trace_viewer':
return process_raw_trace(raw_data)
if tool in _RAW_DATA_TOOLS:
return raw_data
return None | [
"def",
"data_impl",
"(",
"self",
",",
"request",
")",
":",
"run",
"=",
"request",
".",
"args",
".",
"get",
"(",
"'run'",
")",
"tool",
"=",
"request",
".",
"args",
".",
"get",
"(",
"'tag'",
")",
"host",
"=",
"request",
".",
"args",
".",
"get",
"(",
"'host'",
")",
"run_dir",
"=",
"self",
".",
"_run_dir",
"(",
"run",
")",
"# Profile plugin \"run\" is the last component of run dir.",
"profile_run",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"run_dir",
")",
"if",
"tool",
"not",
"in",
"TOOLS",
":",
"return",
"None",
"self",
".",
"start_grpc_stub_if_necessary",
"(",
")",
"if",
"tool",
"==",
"'trace_viewer@'",
"and",
"self",
".",
"stub",
"is",
"not",
"None",
":",
"from",
"tensorflow",
".",
"contrib",
".",
"tpu",
".",
"profiler",
"import",
"tpu_profiler_analysis_pb2",
"grpc_request",
"=",
"tpu_profiler_analysis_pb2",
".",
"ProfileSessionDataRequest",
"(",
")",
"grpc_request",
".",
"repository_root",
"=",
"run_dir",
"grpc_request",
".",
"session_id",
"=",
"profile_run",
"[",
":",
"-",
"1",
"]",
"grpc_request",
".",
"tool_name",
"=",
"'trace_viewer'",
"# Remove the trailing dot if present",
"grpc_request",
".",
"host_name",
"=",
"host",
".",
"rstrip",
"(",
"'.'",
")",
"grpc_request",
".",
"parameters",
"[",
"'resolution'",
"]",
"=",
"request",
".",
"args",
".",
"get",
"(",
"'resolution'",
")",
"if",
"request",
".",
"args",
".",
"get",
"(",
"'start_time_ms'",
")",
"is",
"not",
"None",
":",
"grpc_request",
".",
"parameters",
"[",
"'start_time_ms'",
"]",
"=",
"request",
".",
"args",
".",
"get",
"(",
"'start_time_ms'",
")",
"if",
"request",
".",
"args",
".",
"get",
"(",
"'end_time_ms'",
")",
"is",
"not",
"None",
":",
"grpc_request",
".",
"parameters",
"[",
"'end_time_ms'",
"]",
"=",
"request",
".",
"args",
".",
"get",
"(",
"'end_time_ms'",
")",
"grpc_response",
"=",
"self",
".",
"stub",
".",
"GetSessionToolData",
"(",
"grpc_request",
")",
"return",
"grpc_response",
".",
"output",
"if",
"tool",
"not",
"in",
"TOOLS",
":",
"return",
"None",
"tool_name",
"=",
"str",
"(",
"host",
")",
"+",
"TOOLS",
"[",
"tool",
"]",
"asset_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"run_dir",
",",
"tool_name",
")",
"raw_data",
"=",
"None",
"try",
":",
"with",
"tf",
".",
"io",
".",
"gfile",
".",
"GFile",
"(",
"asset_path",
",",
"'rb'",
")",
"as",
"f",
":",
"raw_data",
"=",
"f",
".",
"read",
"(",
")",
"except",
"tf",
".",
"errors",
".",
"NotFoundError",
":",
"logger",
".",
"warn",
"(",
"'Asset path %s not found'",
",",
"asset_path",
")",
"except",
"tf",
".",
"errors",
".",
"OpError",
"as",
"e",
":",
"logger",
".",
"warn",
"(",
"\"Couldn't read asset path: %s, OpError %s\"",
",",
"asset_path",
",",
"e",
")",
"if",
"raw_data",
"is",
"None",
":",
"return",
"None",
"if",
"tool",
"==",
"'trace_viewer'",
":",
"return",
"process_raw_trace",
"(",
"raw_data",
")",
"if",
"tool",
"in",
"_RAW_DATA_TOOLS",
":",
"return",
"raw_data",
"return",
"None"
] | Retrieves and processes the tool data for a run and a host.
Args:
request: XMLHttpRequest
Returns:
A string that can be served to the frontend tool or None if tool,
run or host is invalid. | [
"Retrieves",
"and",
"processes",
"the",
"tool",
"data",
"for",
"a",
"run",
"and",
"a",
"host",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/profile/profile_plugin.py#L351-L409 | train |
tensorflow/tensorboard | tensorboard/plugins/scalar/scalars_demo.py | run | def run(logdir, run_name,
initial_temperature, ambient_temperature, heat_coefficient):
"""Run 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
run_name: the name of this run; will be created as a subdirectory
under logdir
initial_temperature: float; the object's initial temperature
ambient_temperature: float; the temperature of the enclosing room
heat_coefficient: float; a measure of the object's thermal
conductivity
"""
tf.compat.v1.reset_default_graph()
tf.compat.v1.set_random_seed(0)
with tf.name_scope('temperature'):
# Create a mutable variable to hold the object's temperature, and
# create a scalar summary to track its value over time. The name of
# the summary will appear as "temperature/current" due to the
# name-scope above.
temperature = tf.Variable(tf.constant(initial_temperature),
name='temperature')
summary.op('current', temperature,
display_name='Temperature',
description='The temperature of the object under '
'simulation, in Kelvins.')
# Compute how much the object's temperature differs from that of its
# environment, and track this, too: likewise, as
# "temperature/difference_to_ambient".
ambient_difference = temperature - ambient_temperature
summary.op('difference_to_ambient', ambient_difference,
display_name='Difference to ambient temperature',
description='The difference between the ambient '
'temperature and the temperature of the '
'object under simulation, in Kelvins.')
# Newton suggested that the rate of change of the temperature of an
# object is directly proportional to this `ambient_difference` above,
# where the proportionality constant is what we called the heat
# coefficient. But in real life, not everything is quite so clean, so
# we'll add in some noise. (The value of 50 is arbitrary, chosen to
# make the data look somewhat interesting. :-) )
noise = 50 * tf.random.normal([])
delta = -heat_coefficient * (ambient_difference + noise)
summary.op('delta', delta,
description='The change in temperature from the previous '
'step, in Kelvins.')
# Collect all the scalars that we want to keep track of.
summ = tf.compat.v1.summary.merge_all()
# Now, augment the current temperature by this delta that we computed,
# blocking the assignment on summary collection to avoid race conditions
# and ensure that the summary always reports the pre-update value.
with tf.control_dependencies([summ]):
update_step = temperature.assign_add(delta)
sess = tf.compat.v1.Session()
writer = tf.summary.FileWriter(os.path.join(logdir, run_name))
writer.add_graph(sess.graph)
sess.run(tf.compat.v1.global_variables_initializer())
for step in xrange(STEPS):
# By asking TensorFlow to compute the update step, we force it to
# change the value of the temperature variable. We don't actually
# care about this value, so we discard it; instead, we grab the
# summary data computed along the way.
(s, _) = sess.run([summ, update_step])
writer.add_summary(s, global_step=step)
writer.close() | python | def run(logdir, run_name,
initial_temperature, ambient_temperature, heat_coefficient):
"""Run 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
run_name: the name of this run; will be created as a subdirectory
under logdir
initial_temperature: float; the object's initial temperature
ambient_temperature: float; the temperature of the enclosing room
heat_coefficient: float; a measure of the object's thermal
conductivity
"""
tf.compat.v1.reset_default_graph()
tf.compat.v1.set_random_seed(0)
with tf.name_scope('temperature'):
# Create a mutable variable to hold the object's temperature, and
# create a scalar summary to track its value over time. The name of
# the summary will appear as "temperature/current" due to the
# name-scope above.
temperature = tf.Variable(tf.constant(initial_temperature),
name='temperature')
summary.op('current', temperature,
display_name='Temperature',
description='The temperature of the object under '
'simulation, in Kelvins.')
# Compute how much the object's temperature differs from that of its
# environment, and track this, too: likewise, as
# "temperature/difference_to_ambient".
ambient_difference = temperature - ambient_temperature
summary.op('difference_to_ambient', ambient_difference,
display_name='Difference to ambient temperature',
description='The difference between the ambient '
'temperature and the temperature of the '
'object under simulation, in Kelvins.')
# Newton suggested that the rate of change of the temperature of an
# object is directly proportional to this `ambient_difference` above,
# where the proportionality constant is what we called the heat
# coefficient. But in real life, not everything is quite so clean, so
# we'll add in some noise. (The value of 50 is arbitrary, chosen to
# make the data look somewhat interesting. :-) )
noise = 50 * tf.random.normal([])
delta = -heat_coefficient * (ambient_difference + noise)
summary.op('delta', delta,
description='The change in temperature from the previous '
'step, in Kelvins.')
# Collect all the scalars that we want to keep track of.
summ = tf.compat.v1.summary.merge_all()
# Now, augment the current temperature by this delta that we computed,
# blocking the assignment on summary collection to avoid race conditions
# and ensure that the summary always reports the pre-update value.
with tf.control_dependencies([summ]):
update_step = temperature.assign_add(delta)
sess = tf.compat.v1.Session()
writer = tf.summary.FileWriter(os.path.join(logdir, run_name))
writer.add_graph(sess.graph)
sess.run(tf.compat.v1.global_variables_initializer())
for step in xrange(STEPS):
# By asking TensorFlow to compute the update step, we force it to
# change the value of the temperature variable. We don't actually
# care about this value, so we discard it; instead, we grab the
# summary data computed along the way.
(s, _) = sess.run([summ, update_step])
writer.add_summary(s, global_step=step)
writer.close() | [
"def",
"run",
"(",
"logdir",
",",
"run_name",
",",
"initial_temperature",
",",
"ambient_temperature",
",",
"heat_coefficient",
")",
":",
"tf",
".",
"compat",
".",
"v1",
".",
"reset_default_graph",
"(",
")",
"tf",
".",
"compat",
".",
"v1",
".",
"set_random_seed",
"(",
"0",
")",
"with",
"tf",
".",
"name_scope",
"(",
"'temperature'",
")",
":",
"# Create a mutable variable to hold the object's temperature, and",
"# create a scalar summary to track its value over time. The name of",
"# the summary will appear as \"temperature/current\" due to the",
"# name-scope above.",
"temperature",
"=",
"tf",
".",
"Variable",
"(",
"tf",
".",
"constant",
"(",
"initial_temperature",
")",
",",
"name",
"=",
"'temperature'",
")",
"summary",
".",
"op",
"(",
"'current'",
",",
"temperature",
",",
"display_name",
"=",
"'Temperature'",
",",
"description",
"=",
"'The temperature of the object under '",
"'simulation, in Kelvins.'",
")",
"# Compute how much the object's temperature differs from that of its",
"# environment, and track this, too: likewise, as",
"# \"temperature/difference_to_ambient\".",
"ambient_difference",
"=",
"temperature",
"-",
"ambient_temperature",
"summary",
".",
"op",
"(",
"'difference_to_ambient'",
",",
"ambient_difference",
",",
"display_name",
"=",
"'Difference to ambient temperature'",
",",
"description",
"=",
"'The difference between the ambient '",
"'temperature and the temperature of the '",
"'object under simulation, in Kelvins.'",
")",
"# Newton suggested that the rate of change of the temperature of an",
"# object is directly proportional to this `ambient_difference` above,",
"# where the proportionality constant is what we called the heat",
"# coefficient. But in real life, not everything is quite so clean, so",
"# we'll add in some noise. (The value of 50 is arbitrary, chosen to",
"# make the data look somewhat interesting. :-) )",
"noise",
"=",
"50",
"*",
"tf",
".",
"random",
".",
"normal",
"(",
"[",
"]",
")",
"delta",
"=",
"-",
"heat_coefficient",
"*",
"(",
"ambient_difference",
"+",
"noise",
")",
"summary",
".",
"op",
"(",
"'delta'",
",",
"delta",
",",
"description",
"=",
"'The change in temperature from the previous '",
"'step, in Kelvins.'",
")",
"# Collect all the scalars that we want to keep track of.",
"summ",
"=",
"tf",
".",
"compat",
".",
"v1",
".",
"summary",
".",
"merge_all",
"(",
")",
"# Now, augment the current temperature by this delta that we computed,",
"# blocking the assignment on summary collection to avoid race conditions",
"# and ensure that the summary always reports the pre-update value.",
"with",
"tf",
".",
"control_dependencies",
"(",
"[",
"summ",
"]",
")",
":",
"update_step",
"=",
"temperature",
".",
"assign_add",
"(",
"delta",
")",
"sess",
"=",
"tf",
".",
"compat",
".",
"v1",
".",
"Session",
"(",
")",
"writer",
"=",
"tf",
".",
"summary",
".",
"FileWriter",
"(",
"os",
".",
"path",
".",
"join",
"(",
"logdir",
",",
"run_name",
")",
")",
"writer",
".",
"add_graph",
"(",
"sess",
".",
"graph",
")",
"sess",
".",
"run",
"(",
"tf",
".",
"compat",
".",
"v1",
".",
"global_variables_initializer",
"(",
")",
")",
"for",
"step",
"in",
"xrange",
"(",
"STEPS",
")",
":",
"# By asking TensorFlow to compute the update step, we force it to",
"# change the value of the temperature variable. We don't actually",
"# care about this value, so we discard it; instead, we grab the",
"# summary data computed along the way.",
"(",
"s",
",",
"_",
")",
"=",
"sess",
".",
"run",
"(",
"[",
"summ",
",",
"update_step",
"]",
")",
"writer",
".",
"add_summary",
"(",
"s",
",",
"global_step",
"=",
"step",
")",
"writer",
".",
"close",
"(",
")"
] | Run 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
run_name: the name of this run; will be created as a subdirectory
under logdir
initial_temperature: float; the object's initial temperature
ambient_temperature: float; the temperature of the enclosing room
heat_coefficient: float; a measure of the object's thermal
conductivity | [
"Run",
"a",
"temperature",
"simulation",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/scalar/scalars_demo.py#L35-L116 | train |
tensorflow/tensorboard | tensorboard/plugins/scalar/scalars_demo.py | run_all | def run_all(logdir, verbose=False):
"""Run simulations on a reasonable set of parameters.
Arguments:
logdir: the directory into which to store all the runs' data
verbose: if true, print out each run's name as it begins
"""
for initial_temperature in [270.0, 310.0, 350.0]:
for final_temperature in [270.0, 310.0, 350.0]:
for heat_coefficient in [0.001, 0.005]:
run_name = 'temperature:t0=%g,tA=%g,kH=%g' % (
initial_temperature, final_temperature, heat_coefficient)
if verbose:
print('--- Running: %s' % run_name)
run(logdir, run_name,
initial_temperature, final_temperature, heat_coefficient) | python | def run_all(logdir, verbose=False):
"""Run simulations on a reasonable set of parameters.
Arguments:
logdir: the directory into which to store all the runs' data
verbose: if true, print out each run's name as it begins
"""
for initial_temperature in [270.0, 310.0, 350.0]:
for final_temperature in [270.0, 310.0, 350.0]:
for heat_coefficient in [0.001, 0.005]:
run_name = 'temperature:t0=%g,tA=%g,kH=%g' % (
initial_temperature, final_temperature, heat_coefficient)
if verbose:
print('--- Running: %s' % run_name)
run(logdir, run_name,
initial_temperature, final_temperature, heat_coefficient) | [
"def",
"run_all",
"(",
"logdir",
",",
"verbose",
"=",
"False",
")",
":",
"for",
"initial_temperature",
"in",
"[",
"270.0",
",",
"310.0",
",",
"350.0",
"]",
":",
"for",
"final_temperature",
"in",
"[",
"270.0",
",",
"310.0",
",",
"350.0",
"]",
":",
"for",
"heat_coefficient",
"in",
"[",
"0.001",
",",
"0.005",
"]",
":",
"run_name",
"=",
"'temperature:t0=%g,tA=%g,kH=%g'",
"%",
"(",
"initial_temperature",
",",
"final_temperature",
",",
"heat_coefficient",
")",
"if",
"verbose",
":",
"print",
"(",
"'--- Running: %s'",
"%",
"run_name",
")",
"run",
"(",
"logdir",
",",
"run_name",
",",
"initial_temperature",
",",
"final_temperature",
",",
"heat_coefficient",
")"
] | Run simulations on a reasonable set of parameters.
Arguments:
logdir: the directory into which to store all the runs' data
verbose: if true, print out each run's name as it begins | [
"Run",
"simulations",
"on",
"a",
"reasonable",
"set",
"of",
"parameters",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/scalar/scalars_demo.py#L119-L134 | train |
tensorflow/tensorboard | tensorboard/backend/json_util.py | Cleanse | def Cleanse(obj, encoding='utf-8'):
"""Makes Python object appropriate for JSON serialization.
- Replaces instances of Infinity/-Infinity/NaN with strings.
- Turns byte strings into unicode strings.
- Turns sets into sorted lists.
- Turns tuples into lists.
Args:
obj: Python data structure.
encoding: Charset used to decode byte strings.
Returns:
Unicode JSON data structure.
"""
if isinstance(obj, int):
return obj
elif isinstance(obj, float):
if obj == _INFINITY:
return 'Infinity'
elif obj == _NEGATIVE_INFINITY:
return '-Infinity'
elif math.isnan(obj):
return 'NaN'
else:
return obj
elif isinstance(obj, bytes):
return tf.compat.as_text(obj, encoding)
elif isinstance(obj, (list, tuple)):
return [Cleanse(i, encoding) for i in obj]
elif isinstance(obj, set):
return [Cleanse(i, encoding) for i in sorted(obj)]
elif isinstance(obj, dict):
return {Cleanse(k, encoding): Cleanse(v, encoding) for k, v in obj.items()}
else:
return obj | python | def Cleanse(obj, encoding='utf-8'):
"""Makes Python object appropriate for JSON serialization.
- Replaces instances of Infinity/-Infinity/NaN with strings.
- Turns byte strings into unicode strings.
- Turns sets into sorted lists.
- Turns tuples into lists.
Args:
obj: Python data structure.
encoding: Charset used to decode byte strings.
Returns:
Unicode JSON data structure.
"""
if isinstance(obj, int):
return obj
elif isinstance(obj, float):
if obj == _INFINITY:
return 'Infinity'
elif obj == _NEGATIVE_INFINITY:
return '-Infinity'
elif math.isnan(obj):
return 'NaN'
else:
return obj
elif isinstance(obj, bytes):
return tf.compat.as_text(obj, encoding)
elif isinstance(obj, (list, tuple)):
return [Cleanse(i, encoding) for i in obj]
elif isinstance(obj, set):
return [Cleanse(i, encoding) for i in sorted(obj)]
elif isinstance(obj, dict):
return {Cleanse(k, encoding): Cleanse(v, encoding) for k, v in obj.items()}
else:
return obj | [
"def",
"Cleanse",
"(",
"obj",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"int",
")",
":",
"return",
"obj",
"elif",
"isinstance",
"(",
"obj",
",",
"float",
")",
":",
"if",
"obj",
"==",
"_INFINITY",
":",
"return",
"'Infinity'",
"elif",
"obj",
"==",
"_NEGATIVE_INFINITY",
":",
"return",
"'-Infinity'",
"elif",
"math",
".",
"isnan",
"(",
"obj",
")",
":",
"return",
"'NaN'",
"else",
":",
"return",
"obj",
"elif",
"isinstance",
"(",
"obj",
",",
"bytes",
")",
":",
"return",
"tf",
".",
"compat",
".",
"as_text",
"(",
"obj",
",",
"encoding",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"[",
"Cleanse",
"(",
"i",
",",
"encoding",
")",
"for",
"i",
"in",
"obj",
"]",
"elif",
"isinstance",
"(",
"obj",
",",
"set",
")",
":",
"return",
"[",
"Cleanse",
"(",
"i",
",",
"encoding",
")",
"for",
"i",
"in",
"sorted",
"(",
"obj",
")",
"]",
"elif",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"return",
"{",
"Cleanse",
"(",
"k",
",",
"encoding",
")",
":",
"Cleanse",
"(",
"v",
",",
"encoding",
")",
"for",
"k",
",",
"v",
"in",
"obj",
".",
"items",
"(",
")",
"}",
"else",
":",
"return",
"obj"
] | Makes Python object appropriate for JSON serialization.
- Replaces instances of Infinity/-Infinity/NaN with strings.
- Turns byte strings into unicode strings.
- Turns sets into sorted lists.
- Turns tuples into lists.
Args:
obj: Python data structure.
encoding: Charset used to decode byte strings.
Returns:
Unicode JSON data structure. | [
"Makes",
"Python",
"object",
"appropriate",
"for",
"JSON",
"serialization",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/json_util.py#L39-L74 | train |
tensorflow/tensorboard | tensorboard/plugins/text/summary.py | op | def op(name,
data,
display_name=None,
description=None,
collections=None):
"""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.
"""
# TODO(nickfelt): remove on-demand imports once dep situation is fixed.
import tensorflow.compat.v1 as tf
if display_name is None:
display_name = name
summary_metadata = metadata.create_summary_metadata(
display_name=display_name, description=description)
with tf.name_scope(name):
with tf.control_dependencies([tf.assert_type(data, tf.string)]):
return tf.summary.tensor_summary(name='text_summary',
tensor=data,
collections=collections,
summary_metadata=summary_metadata) | python | def op(name,
data,
display_name=None,
description=None,
collections=None):
"""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.
"""
# TODO(nickfelt): remove on-demand imports once dep situation is fixed.
import tensorflow.compat.v1 as tf
if display_name is None:
display_name = name
summary_metadata = metadata.create_summary_metadata(
display_name=display_name, description=description)
with tf.name_scope(name):
with tf.control_dependencies([tf.assert_type(data, tf.string)]):
return tf.summary.tensor_summary(name='text_summary',
tensor=data,
collections=collections,
summary_metadata=summary_metadata) | [
"def",
"op",
"(",
"name",
",",
"data",
",",
"display_name",
"=",
"None",
",",
"description",
"=",
"None",
",",
"collections",
"=",
"None",
")",
":",
"# TODO(nickfelt): remove on-demand imports once dep situation is fixed.",
"import",
"tensorflow",
".",
"compat",
".",
"v1",
"as",
"tf",
"if",
"display_name",
"is",
"None",
":",
"display_name",
"=",
"name",
"summary_metadata",
"=",
"metadata",
".",
"create_summary_metadata",
"(",
"display_name",
"=",
"display_name",
",",
"description",
"=",
"description",
")",
"with",
"tf",
".",
"name_scope",
"(",
"name",
")",
":",
"with",
"tf",
".",
"control_dependencies",
"(",
"[",
"tf",
".",
"assert_type",
"(",
"data",
",",
"tf",
".",
"string",
")",
"]",
")",
":",
"return",
"tf",
".",
"summary",
".",
"tensor_summary",
"(",
"name",
"=",
"'text_summary'",
",",
"tensor",
"=",
"data",
",",
"collections",
"=",
"collections",
",",
"summary_metadata",
"=",
"summary_metadata",
")"
] | 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. | [
"Create",
"a",
"legacy",
"text",
"summary",
"op",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/text/summary.py#L30-L76 | train |
tensorflow/tensorboard | tensorboard/plugins/text/summary.py | pb | def pb(name, data, display_name=None, description=None):
"""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.
"""
# TODO(nickfelt): remove on-demand imports once dep situation is fixed.
import tensorflow.compat.v1 as tf
try:
tensor = tf.make_tensor_proto(data, dtype=tf.string)
except TypeError as e:
raise ValueError(e)
if display_name is None:
display_name = name
summary_metadata = metadata.create_summary_metadata(
display_name=display_name, description=description)
tf_summary_metadata = tf.SummaryMetadata.FromString(
summary_metadata.SerializeToString())
summary = tf.Summary()
summary.value.add(tag='%s/text_summary' % name,
metadata=tf_summary_metadata,
tensor=tensor)
return summary | python | def pb(name, data, display_name=None, description=None):
"""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.
"""
# TODO(nickfelt): remove on-demand imports once dep situation is fixed.
import tensorflow.compat.v1 as tf
try:
tensor = tf.make_tensor_proto(data, dtype=tf.string)
except TypeError as e:
raise ValueError(e)
if display_name is None:
display_name = name
summary_metadata = metadata.create_summary_metadata(
display_name=display_name, description=description)
tf_summary_metadata = tf.SummaryMetadata.FromString(
summary_metadata.SerializeToString())
summary = tf.Summary()
summary.value.add(tag='%s/text_summary' % name,
metadata=tf_summary_metadata,
tensor=tensor)
return summary | [
"def",
"pb",
"(",
"name",
",",
"data",
",",
"display_name",
"=",
"None",
",",
"description",
"=",
"None",
")",
":",
"# TODO(nickfelt): remove on-demand imports once dep situation is fixed.",
"import",
"tensorflow",
".",
"compat",
".",
"v1",
"as",
"tf",
"try",
":",
"tensor",
"=",
"tf",
".",
"make_tensor_proto",
"(",
"data",
",",
"dtype",
"=",
"tf",
".",
"string",
")",
"except",
"TypeError",
"as",
"e",
":",
"raise",
"ValueError",
"(",
"e",
")",
"if",
"display_name",
"is",
"None",
":",
"display_name",
"=",
"name",
"summary_metadata",
"=",
"metadata",
".",
"create_summary_metadata",
"(",
"display_name",
"=",
"display_name",
",",
"description",
"=",
"description",
")",
"tf_summary_metadata",
"=",
"tf",
".",
"SummaryMetadata",
".",
"FromString",
"(",
"summary_metadata",
".",
"SerializeToString",
"(",
")",
")",
"summary",
"=",
"tf",
".",
"Summary",
"(",
")",
"summary",
".",
"value",
".",
"add",
"(",
"tag",
"=",
"'%s/text_summary'",
"%",
"name",
",",
"metadata",
"=",
"tf_summary_metadata",
",",
"tensor",
"=",
"tensor",
")",
"return",
"summary"
] | 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. | [
"Create",
"a",
"legacy",
"text",
"summary",
"protobuf",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/text/summary.py#L79-L116 | train |
tensorflow/tensorboard | tensorboard/backend/event_processing/event_accumulator.py | _GetPurgeMessage | def _GetPurgeMessage(most_recent_step, most_recent_wall_time, event_step,
event_wall_time, num_expired_scalars, num_expired_histos,
num_expired_comp_histos, num_expired_images,
num_expired_audio):
"""Return the string message associated with TensorBoard purges."""
return ('Detected out of order event.step likely caused by '
'a TensorFlow restart. Purging expired events from Tensorboard'
' display between the previous step: {} (timestamp: {}) and '
'current step: {} (timestamp: {}). Removing {} scalars, {} '
'histograms, {} compressed histograms, {} images, '
'and {} audio.').format(most_recent_step, most_recent_wall_time,
event_step, event_wall_time,
num_expired_scalars, num_expired_histos,
num_expired_comp_histos, num_expired_images,
num_expired_audio) | python | def _GetPurgeMessage(most_recent_step, most_recent_wall_time, event_step,
event_wall_time, num_expired_scalars, num_expired_histos,
num_expired_comp_histos, num_expired_images,
num_expired_audio):
"""Return the string message associated with TensorBoard purges."""
return ('Detected out of order event.step likely caused by '
'a TensorFlow restart. Purging expired events from Tensorboard'
' display between the previous step: {} (timestamp: {}) and '
'current step: {} (timestamp: {}). Removing {} scalars, {} '
'histograms, {} compressed histograms, {} images, '
'and {} audio.').format(most_recent_step, most_recent_wall_time,
event_step, event_wall_time,
num_expired_scalars, num_expired_histos,
num_expired_comp_histos, num_expired_images,
num_expired_audio) | [
"def",
"_GetPurgeMessage",
"(",
"most_recent_step",
",",
"most_recent_wall_time",
",",
"event_step",
",",
"event_wall_time",
",",
"num_expired_scalars",
",",
"num_expired_histos",
",",
"num_expired_comp_histos",
",",
"num_expired_images",
",",
"num_expired_audio",
")",
":",
"return",
"(",
"'Detected out of order event.step likely caused by '",
"'a TensorFlow restart. Purging expired events from Tensorboard'",
"' display between the previous step: {} (timestamp: {}) and '",
"'current step: {} (timestamp: {}). Removing {} scalars, {} '",
"'histograms, {} compressed histograms, {} images, '",
"'and {} audio.'",
")",
".",
"format",
"(",
"most_recent_step",
",",
"most_recent_wall_time",
",",
"event_step",
",",
"event_wall_time",
",",
"num_expired_scalars",
",",
"num_expired_histos",
",",
"num_expired_comp_histos",
",",
"num_expired_images",
",",
"num_expired_audio",
")"
] | Return the string message associated with TensorBoard purges. | [
"Return",
"the",
"string",
"message",
"associated",
"with",
"TensorBoard",
"purges",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/event_processing/event_accumulator.py#L719-L733 | train |
tensorflow/tensorboard | tensorboard/backend/event_processing/event_accumulator.py | _GeneratorFromPath | def _GeneratorFromPath(path):
"""Create an event generator for file or directory at given path string."""
if not path:
raise ValueError('path must be a valid string')
if io_wrapper.IsTensorFlowEventsFile(path):
return event_file_loader.EventFileLoader(path)
else:
return directory_watcher.DirectoryWatcher(
path,
event_file_loader.EventFileLoader,
io_wrapper.IsTensorFlowEventsFile) | python | def _GeneratorFromPath(path):
"""Create an event generator for file or directory at given path string."""
if not path:
raise ValueError('path must be a valid string')
if io_wrapper.IsTensorFlowEventsFile(path):
return event_file_loader.EventFileLoader(path)
else:
return directory_watcher.DirectoryWatcher(
path,
event_file_loader.EventFileLoader,
io_wrapper.IsTensorFlowEventsFile) | [
"def",
"_GeneratorFromPath",
"(",
"path",
")",
":",
"if",
"not",
"path",
":",
"raise",
"ValueError",
"(",
"'path must be a valid string'",
")",
"if",
"io_wrapper",
".",
"IsTensorFlowEventsFile",
"(",
"path",
")",
":",
"return",
"event_file_loader",
".",
"EventFileLoader",
"(",
"path",
")",
"else",
":",
"return",
"directory_watcher",
".",
"DirectoryWatcher",
"(",
"path",
",",
"event_file_loader",
".",
"EventFileLoader",
",",
"io_wrapper",
".",
"IsTensorFlowEventsFile",
")"
] | Create an event generator for file or directory at given path string. | [
"Create",
"an",
"event",
"generator",
"for",
"file",
"or",
"directory",
"at",
"given",
"path",
"string",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/event_processing/event_accumulator.py#L736-L746 | train |
tensorflow/tensorboard | tensorboard/backend/event_processing/event_accumulator.py | _ParseFileVersion | def _ParseFileVersion(file_version):
"""Convert the string file_version in event.proto into a float.
Args:
file_version: String file_version from event.proto
Returns:
Version number as a float.
"""
tokens = file_version.split('brain.Event:')
try:
return float(tokens[-1])
except ValueError:
## This should never happen according to the definition of file_version
## specified in event.proto.
logger.warn(
('Invalid event.proto file_version. Defaulting to use of '
'out-of-order event.step logic for purging expired events.'))
return -1 | python | def _ParseFileVersion(file_version):
"""Convert the string file_version in event.proto into a float.
Args:
file_version: String file_version from event.proto
Returns:
Version number as a float.
"""
tokens = file_version.split('brain.Event:')
try:
return float(tokens[-1])
except ValueError:
## This should never happen according to the definition of file_version
## specified in event.proto.
logger.warn(
('Invalid event.proto file_version. Defaulting to use of '
'out-of-order event.step logic for purging expired events.'))
return -1 | [
"def",
"_ParseFileVersion",
"(",
"file_version",
")",
":",
"tokens",
"=",
"file_version",
".",
"split",
"(",
"'brain.Event:'",
")",
"try",
":",
"return",
"float",
"(",
"tokens",
"[",
"-",
"1",
"]",
")",
"except",
"ValueError",
":",
"## This should never happen according to the definition of file_version",
"## specified in event.proto.",
"logger",
".",
"warn",
"(",
"(",
"'Invalid event.proto file_version. Defaulting to use of '",
"'out-of-order event.step logic for purging expired events.'",
")",
")",
"return",
"-",
"1"
] | Convert the string file_version in event.proto into a float.
Args:
file_version: String file_version from event.proto
Returns:
Version number as a float. | [
"Convert",
"the",
"string",
"file_version",
"in",
"event",
".",
"proto",
"into",
"a",
"float",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/event_processing/event_accumulator.py#L749-L767 | train |
tensorflow/tensorboard | tensorboard/backend/event_processing/event_accumulator.py | EventAccumulator.Reload | def Reload(self):
"""Loads all events added since the last call to `Reload`.
If `Reload` was never called, loads all events in the file.
Returns:
The `EventAccumulator`.
"""
with self._generator_mutex:
for event in self._generator.Load():
self._ProcessEvent(event)
return self | python | def Reload(self):
"""Loads all events added since the last call to `Reload`.
If `Reload` was never called, loads all events in the file.
Returns:
The `EventAccumulator`.
"""
with self._generator_mutex:
for event in self._generator.Load():
self._ProcessEvent(event)
return self | [
"def",
"Reload",
"(",
"self",
")",
":",
"with",
"self",
".",
"_generator_mutex",
":",
"for",
"event",
"in",
"self",
".",
"_generator",
".",
"Load",
"(",
")",
":",
"self",
".",
"_ProcessEvent",
"(",
"event",
")",
"return",
"self"
] | Loads all events added since the last call to `Reload`.
If `Reload` was never called, loads all events in the file.
Returns:
The `EventAccumulator`. | [
"Loads",
"all",
"events",
"added",
"since",
"the",
"last",
"call",
"to",
"Reload",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/event_processing/event_accumulator.py#L220-L231 | train |
tensorflow/tensorboard | tensorboard/backend/event_processing/event_accumulator.py | EventAccumulator.RetrievePluginAsset | def RetrievePluginAsset(self, plugin_name, asset_name):
"""Return the contents of a given plugin asset.
Args:
plugin_name: The string name of a plugin.
asset_name: The string name of an asset.
Returns:
The string contents of the plugin asset.
Raises:
KeyError: If the asset is not available.
"""
return plugin_asset_util.RetrieveAsset(self.path, plugin_name, asset_name) | python | def RetrievePluginAsset(self, plugin_name, asset_name):
"""Return the contents of a given plugin asset.
Args:
plugin_name: The string name of a plugin.
asset_name: The string name of an asset.
Returns:
The string contents of the plugin asset.
Raises:
KeyError: If the asset is not available.
"""
return plugin_asset_util.RetrieveAsset(self.path, plugin_name, asset_name) | [
"def",
"RetrievePluginAsset",
"(",
"self",
",",
"plugin_name",
",",
"asset_name",
")",
":",
"return",
"plugin_asset_util",
".",
"RetrieveAsset",
"(",
"self",
".",
"path",
",",
"plugin_name",
",",
"asset_name",
")"
] | Return the contents of a given plugin asset.
Args:
plugin_name: The string name of a plugin.
asset_name: The string name of an asset.
Returns:
The string contents of the plugin asset.
Raises:
KeyError: If the asset is not available. | [
"Return",
"the",
"contents",
"of",
"a",
"given",
"plugin",
"asset",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/event_processing/event_accumulator.py#L245-L258 | train |
tensorflow/tensorboard | tensorboard/backend/event_processing/event_accumulator.py | EventAccumulator.FirstEventTimestamp | def FirstEventTimestamp(self):
"""Returns the timestamp in seconds of the first event.
If the first event has been loaded (either by this method or by `Reload`,
this returns immediately. Otherwise, it will load in the first event. Note
that this means that calling `Reload` will cause this to block until
`Reload` has finished.
Returns:
The timestamp in seconds of the first event that was loaded.
Raises:
ValueError: If no events have been loaded and there were no events found
on disk.
"""
if self._first_event_timestamp is not None:
return self._first_event_timestamp
with self._generator_mutex:
try:
event = next(self._generator.Load())
self._ProcessEvent(event)
return self._first_event_timestamp
except StopIteration:
raise ValueError('No event timestamp could be found') | python | def FirstEventTimestamp(self):
"""Returns the timestamp in seconds of the first event.
If the first event has been loaded (either by this method or by `Reload`,
this returns immediately. Otherwise, it will load in the first event. Note
that this means that calling `Reload` will cause this to block until
`Reload` has finished.
Returns:
The timestamp in seconds of the first event that was loaded.
Raises:
ValueError: If no events have been loaded and there were no events found
on disk.
"""
if self._first_event_timestamp is not None:
return self._first_event_timestamp
with self._generator_mutex:
try:
event = next(self._generator.Load())
self._ProcessEvent(event)
return self._first_event_timestamp
except StopIteration:
raise ValueError('No event timestamp could be found') | [
"def",
"FirstEventTimestamp",
"(",
"self",
")",
":",
"if",
"self",
".",
"_first_event_timestamp",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_first_event_timestamp",
"with",
"self",
".",
"_generator_mutex",
":",
"try",
":",
"event",
"=",
"next",
"(",
"self",
".",
"_generator",
".",
"Load",
"(",
")",
")",
"self",
".",
"_ProcessEvent",
"(",
"event",
")",
"return",
"self",
".",
"_first_event_timestamp",
"except",
"StopIteration",
":",
"raise",
"ValueError",
"(",
"'No event timestamp could be found'",
")"
] | Returns the timestamp in seconds of the first event.
If the first event has been loaded (either by this method or by `Reload`,
this returns immediately. Otherwise, it will load in the first event. Note
that this means that calling `Reload` will cause this to block until
`Reload` has finished.
Returns:
The timestamp in seconds of the first event that was loaded.
Raises:
ValueError: If no events have been loaded and there were no events found
on disk. | [
"Returns",
"the",
"timestamp",
"in",
"seconds",
"of",
"the",
"first",
"event",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/event_processing/event_accumulator.py#L260-L284 | train |
tensorflow/tensorboard | tensorboard/backend/event_processing/event_accumulator.py | EventAccumulator.PluginTagToContent | def PluginTagToContent(self, plugin_name):
"""Returns a dict mapping tags to content specific to that plugin.
Args:
plugin_name: The name of the plugin for which to fetch plugin-specific
content.
Raises:
KeyError: if the plugin name is not found.
Returns:
A dict mapping tags to plugin-specific content (which are always strings).
Those strings are often serialized protos.
"""
if plugin_name not in self._plugin_to_tag_to_content:
raise KeyError('Plugin %r could not be found.' % plugin_name)
return self._plugin_to_tag_to_content[plugin_name] | python | def PluginTagToContent(self, plugin_name):
"""Returns a dict mapping tags to content specific to that plugin.
Args:
plugin_name: The name of the plugin for which to fetch plugin-specific
content.
Raises:
KeyError: if the plugin name is not found.
Returns:
A dict mapping tags to plugin-specific content (which are always strings).
Those strings are often serialized protos.
"""
if plugin_name not in self._plugin_to_tag_to_content:
raise KeyError('Plugin %r could not be found.' % plugin_name)
return self._plugin_to_tag_to_content[plugin_name] | [
"def",
"PluginTagToContent",
"(",
"self",
",",
"plugin_name",
")",
":",
"if",
"plugin_name",
"not",
"in",
"self",
".",
"_plugin_to_tag_to_content",
":",
"raise",
"KeyError",
"(",
"'Plugin %r could not be found.'",
"%",
"plugin_name",
")",
"return",
"self",
".",
"_plugin_to_tag_to_content",
"[",
"plugin_name",
"]"
] | Returns a dict mapping tags to content specific to that plugin.
Args:
plugin_name: The name of the plugin for which to fetch plugin-specific
content.
Raises:
KeyError: if the plugin name is not found.
Returns:
A dict mapping tags to plugin-specific content (which are always strings).
Those strings are often serialized protos. | [
"Returns",
"a",
"dict",
"mapping",
"tags",
"to",
"content",
"specific",
"to",
"that",
"plugin",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/event_processing/event_accumulator.py#L286-L302 | train |
tensorflow/tensorboard | tensorboard/backend/event_processing/event_accumulator.py | EventAccumulator.Tags | def Tags(self):
"""Return all tags found in the value stream.
Returns:
A `{tagType: ['list', 'of', 'tags']}` dictionary.
"""
return {
IMAGES: self.images.Keys(),
AUDIO: self.audios.Keys(),
HISTOGRAMS: self.histograms.Keys(),
SCALARS: self.scalars.Keys(),
COMPRESSED_HISTOGRAMS: self.compressed_histograms.Keys(),
TENSORS: self.tensors.Keys(),
# Use a heuristic: if the metagraph is available, but
# graph is not, then we assume the metagraph contains the graph.
GRAPH: self._graph is not None,
META_GRAPH: self._meta_graph is not None,
RUN_METADATA: list(self._tagged_metadata.keys())
} | python | def Tags(self):
"""Return all tags found in the value stream.
Returns:
A `{tagType: ['list', 'of', 'tags']}` dictionary.
"""
return {
IMAGES: self.images.Keys(),
AUDIO: self.audios.Keys(),
HISTOGRAMS: self.histograms.Keys(),
SCALARS: self.scalars.Keys(),
COMPRESSED_HISTOGRAMS: self.compressed_histograms.Keys(),
TENSORS: self.tensors.Keys(),
# Use a heuristic: if the metagraph is available, but
# graph is not, then we assume the metagraph contains the graph.
GRAPH: self._graph is not None,
META_GRAPH: self._meta_graph is not None,
RUN_METADATA: list(self._tagged_metadata.keys())
} | [
"def",
"Tags",
"(",
"self",
")",
":",
"return",
"{",
"IMAGES",
":",
"self",
".",
"images",
".",
"Keys",
"(",
")",
",",
"AUDIO",
":",
"self",
".",
"audios",
".",
"Keys",
"(",
")",
",",
"HISTOGRAMS",
":",
"self",
".",
"histograms",
".",
"Keys",
"(",
")",
",",
"SCALARS",
":",
"self",
".",
"scalars",
".",
"Keys",
"(",
")",
",",
"COMPRESSED_HISTOGRAMS",
":",
"self",
".",
"compressed_histograms",
".",
"Keys",
"(",
")",
",",
"TENSORS",
":",
"self",
".",
"tensors",
".",
"Keys",
"(",
")",
",",
"# Use a heuristic: if the metagraph is available, but",
"# graph is not, then we assume the metagraph contains the graph.",
"GRAPH",
":",
"self",
".",
"_graph",
"is",
"not",
"None",
",",
"META_GRAPH",
":",
"self",
".",
"_meta_graph",
"is",
"not",
"None",
",",
"RUN_METADATA",
":",
"list",
"(",
"self",
".",
"_tagged_metadata",
".",
"keys",
"(",
")",
")",
"}"
] | Return all tags found in the value stream.
Returns:
A `{tagType: ['list', 'of', 'tags']}` dictionary. | [
"Return",
"all",
"tags",
"found",
"in",
"the",
"value",
"stream",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/event_processing/event_accumulator.py#L406-L424 | train |
tensorflow/tensorboard | tensorboard/backend/event_processing/event_accumulator.py | EventAccumulator.Graph | def Graph(self):
"""Return the graph definition, if there is one.
If the graph is stored directly, return that. If no graph is stored
directly but a metagraph is stored containing a graph, return that.
Raises:
ValueError: If there is no graph for this run.
Returns:
The `graph_def` proto.
"""
graph = graph_pb2.GraphDef()
if self._graph is not None:
graph.ParseFromString(self._graph)
return graph
raise ValueError('There is no graph in this EventAccumulator') | python | def Graph(self):
"""Return the graph definition, if there is one.
If the graph is stored directly, return that. If no graph is stored
directly but a metagraph is stored containing a graph, return that.
Raises:
ValueError: If there is no graph for this run.
Returns:
The `graph_def` proto.
"""
graph = graph_pb2.GraphDef()
if self._graph is not None:
graph.ParseFromString(self._graph)
return graph
raise ValueError('There is no graph in this EventAccumulator') | [
"def",
"Graph",
"(",
"self",
")",
":",
"graph",
"=",
"graph_pb2",
".",
"GraphDef",
"(",
")",
"if",
"self",
".",
"_graph",
"is",
"not",
"None",
":",
"graph",
".",
"ParseFromString",
"(",
"self",
".",
"_graph",
")",
"return",
"graph",
"raise",
"ValueError",
"(",
"'There is no graph in this EventAccumulator'",
")"
] | Return the graph definition, if there is one.
If the graph is stored directly, return that. If no graph is stored
directly but a metagraph is stored containing a graph, return that.
Raises:
ValueError: If there is no graph for this run.
Returns:
The `graph_def` proto. | [
"Return",
"the",
"graph",
"definition",
"if",
"there",
"is",
"one",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/event_processing/event_accumulator.py#L440-L456 | train |
tensorflow/tensorboard | tensorboard/backend/event_processing/event_accumulator.py | EventAccumulator.MetaGraph | def MetaGraph(self):
"""Return the metagraph definition, if there is one.
Raises:
ValueError: If there is no metagraph for this run.
Returns:
The `meta_graph_def` proto.
"""
if self._meta_graph is None:
raise ValueError('There is no metagraph in this EventAccumulator')
meta_graph = meta_graph_pb2.MetaGraphDef()
meta_graph.ParseFromString(self._meta_graph)
return meta_graph | python | def MetaGraph(self):
"""Return the metagraph definition, if there is one.
Raises:
ValueError: If there is no metagraph for this run.
Returns:
The `meta_graph_def` proto.
"""
if self._meta_graph is None:
raise ValueError('There is no metagraph in this EventAccumulator')
meta_graph = meta_graph_pb2.MetaGraphDef()
meta_graph.ParseFromString(self._meta_graph)
return meta_graph | [
"def",
"MetaGraph",
"(",
"self",
")",
":",
"if",
"self",
".",
"_meta_graph",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'There is no metagraph in this EventAccumulator'",
")",
"meta_graph",
"=",
"meta_graph_pb2",
".",
"MetaGraphDef",
"(",
")",
"meta_graph",
".",
"ParseFromString",
"(",
"self",
".",
"_meta_graph",
")",
"return",
"meta_graph"
] | Return the metagraph definition, if there is one.
Raises:
ValueError: If there is no metagraph for this run.
Returns:
The `meta_graph_def` proto. | [
"Return",
"the",
"metagraph",
"definition",
"if",
"there",
"is",
"one",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/event_processing/event_accumulator.py#L458-L471 | train |
tensorflow/tensorboard | tensorboard/backend/event_processing/event_accumulator.py | EventAccumulator.RunMetadata | def RunMetadata(self, tag):
"""Given a tag, return the associated session.run() metadata.
Args:
tag: A string tag associated with the event.
Raises:
ValueError: If the tag is not found.
Returns:
The metadata in form of `RunMetadata` proto.
"""
if tag not in self._tagged_metadata:
raise ValueError('There is no run metadata with this tag name')
run_metadata = config_pb2.RunMetadata()
run_metadata.ParseFromString(self._tagged_metadata[tag])
return run_metadata | python | def RunMetadata(self, tag):
"""Given a tag, return the associated session.run() metadata.
Args:
tag: A string tag associated with the event.
Raises:
ValueError: If the tag is not found.
Returns:
The metadata in form of `RunMetadata` proto.
"""
if tag not in self._tagged_metadata:
raise ValueError('There is no run metadata with this tag name')
run_metadata = config_pb2.RunMetadata()
run_metadata.ParseFromString(self._tagged_metadata[tag])
return run_metadata | [
"def",
"RunMetadata",
"(",
"self",
",",
"tag",
")",
":",
"if",
"tag",
"not",
"in",
"self",
".",
"_tagged_metadata",
":",
"raise",
"ValueError",
"(",
"'There is no run metadata with this tag name'",
")",
"run_metadata",
"=",
"config_pb2",
".",
"RunMetadata",
"(",
")",
"run_metadata",
".",
"ParseFromString",
"(",
"self",
".",
"_tagged_metadata",
"[",
"tag",
"]",
")",
"return",
"run_metadata"
] | Given a tag, return the associated session.run() metadata.
Args:
tag: A string tag associated with the event.
Raises:
ValueError: If the tag is not found.
Returns:
The metadata in form of `RunMetadata` proto. | [
"Given",
"a",
"tag",
"return",
"the",
"associated",
"session",
".",
"run",
"()",
"metadata",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/event_processing/event_accumulator.py#L473-L490 | train |
tensorflow/tensorboard | tensorboard/backend/event_processing/event_accumulator.py | EventAccumulator._MaybePurgeOrphanedData | def _MaybePurgeOrphanedData(self, event):
"""Maybe purge orphaned data due to a TensorFlow crash.
When TensorFlow crashes at step T+O and restarts at step T, any events
written after step T are now "orphaned" and will be at best misleading if
they are included in TensorBoard.
This logic attempts to determine if there is orphaned data, and purge it
if it is found.
Args:
event: The event to use as a reference, to determine if a purge is needed.
"""
if not self.purge_orphaned_data:
return
## Check if the event happened after a crash, and purge expired tags.
if self.file_version and self.file_version >= 2:
## If the file_version is recent enough, use the SessionLog enum
## to check for restarts.
self._CheckForRestartAndMaybePurge(event)
else:
## If there is no file version, default to old logic of checking for
## out of order steps.
self._CheckForOutOfOrderStepAndMaybePurge(event) | python | def _MaybePurgeOrphanedData(self, event):
"""Maybe purge orphaned data due to a TensorFlow crash.
When TensorFlow crashes at step T+O and restarts at step T, any events
written after step T are now "orphaned" and will be at best misleading if
they are included in TensorBoard.
This logic attempts to determine if there is orphaned data, and purge it
if it is found.
Args:
event: The event to use as a reference, to determine if a purge is needed.
"""
if not self.purge_orphaned_data:
return
## Check if the event happened after a crash, and purge expired tags.
if self.file_version and self.file_version >= 2:
## If the file_version is recent enough, use the SessionLog enum
## to check for restarts.
self._CheckForRestartAndMaybePurge(event)
else:
## If there is no file version, default to old logic of checking for
## out of order steps.
self._CheckForOutOfOrderStepAndMaybePurge(event) | [
"def",
"_MaybePurgeOrphanedData",
"(",
"self",
",",
"event",
")",
":",
"if",
"not",
"self",
".",
"purge_orphaned_data",
":",
"return",
"## Check if the event happened after a crash, and purge expired tags.",
"if",
"self",
".",
"file_version",
"and",
"self",
".",
"file_version",
">=",
"2",
":",
"## If the file_version is recent enough, use the SessionLog enum",
"## to check for restarts.",
"self",
".",
"_CheckForRestartAndMaybePurge",
"(",
"event",
")",
"else",
":",
"## If there is no file version, default to old logic of checking for",
"## out of order steps.",
"self",
".",
"_CheckForOutOfOrderStepAndMaybePurge",
"(",
"event",
")"
] | Maybe purge orphaned data due to a TensorFlow crash.
When TensorFlow crashes at step T+O and restarts at step T, any events
written after step T are now "orphaned" and will be at best misleading if
they are included in TensorBoard.
This logic attempts to determine if there is orphaned data, and purge it
if it is found.
Args:
event: The event to use as a reference, to determine if a purge is needed. | [
"Maybe",
"purge",
"orphaned",
"data",
"due",
"to",
"a",
"TensorFlow",
"crash",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/event_processing/event_accumulator.py#L562-L585 | train |
tensorflow/tensorboard | tensorboard/backend/event_processing/event_accumulator.py | EventAccumulator._CheckForRestartAndMaybePurge | def _CheckForRestartAndMaybePurge(self, event):
"""Check and discard expired events using SessionLog.START.
Check for a SessionLog.START event and purge all previously seen events
with larger steps, because they are out of date. Because of supervisor
threading, it is possible that this logic will cause the first few event
messages to be discarded since supervisor threading does not guarantee
that the START message is deterministically written first.
This method is preferred over _CheckForOutOfOrderStepAndMaybePurge which
can inadvertently discard events due to supervisor threading.
Args:
event: The event to use as reference. If the event is a START event, all
previously seen events with a greater event.step will be purged.
"""
if event.HasField(
'session_log') and event.session_log.status == event_pb2.SessionLog.START:
self._Purge(event, by_tags=False) | python | def _CheckForRestartAndMaybePurge(self, event):
"""Check and discard expired events using SessionLog.START.
Check for a SessionLog.START event and purge all previously seen events
with larger steps, because they are out of date. Because of supervisor
threading, it is possible that this logic will cause the first few event
messages to be discarded since supervisor threading does not guarantee
that the START message is deterministically written first.
This method is preferred over _CheckForOutOfOrderStepAndMaybePurge which
can inadvertently discard events due to supervisor threading.
Args:
event: The event to use as reference. If the event is a START event, all
previously seen events with a greater event.step will be purged.
"""
if event.HasField(
'session_log') and event.session_log.status == event_pb2.SessionLog.START:
self._Purge(event, by_tags=False) | [
"def",
"_CheckForRestartAndMaybePurge",
"(",
"self",
",",
"event",
")",
":",
"if",
"event",
".",
"HasField",
"(",
"'session_log'",
")",
"and",
"event",
".",
"session_log",
".",
"status",
"==",
"event_pb2",
".",
"SessionLog",
".",
"START",
":",
"self",
".",
"_Purge",
"(",
"event",
",",
"by_tags",
"=",
"False",
")"
] | Check and discard expired events using SessionLog.START.
Check for a SessionLog.START event and purge all previously seen events
with larger steps, because they are out of date. Because of supervisor
threading, it is possible that this logic will cause the first few event
messages to be discarded since supervisor threading does not guarantee
that the START message is deterministically written first.
This method is preferred over _CheckForOutOfOrderStepAndMaybePurge which
can inadvertently discard events due to supervisor threading.
Args:
event: The event to use as reference. If the event is a START event, all
previously seen events with a greater event.step will be purged. | [
"Check",
"and",
"discard",
"expired",
"events",
"using",
"SessionLog",
".",
"START",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/event_processing/event_accumulator.py#L587-L605 | train |
tensorflow/tensorboard | tensorboard/backend/event_processing/event_accumulator.py | EventAccumulator._CheckForOutOfOrderStepAndMaybePurge | def _CheckForOutOfOrderStepAndMaybePurge(self, event):
"""Check for out-of-order event.step and discard expired events for tags.
Check if the event is out of order relative to the global most recent step.
If it is, purge outdated summaries for tags that the event contains.
Args:
event: The event to use as reference. If the event is out-of-order, all
events with the same tags, but with a greater event.step will be purged.
"""
if event.step < self.most_recent_step and event.HasField('summary'):
self._Purge(event, by_tags=True)
else:
self.most_recent_step = event.step
self.most_recent_wall_time = event.wall_time | python | def _CheckForOutOfOrderStepAndMaybePurge(self, event):
"""Check for out-of-order event.step and discard expired events for tags.
Check if the event is out of order relative to the global most recent step.
If it is, purge outdated summaries for tags that the event contains.
Args:
event: The event to use as reference. If the event is out-of-order, all
events with the same tags, but with a greater event.step will be purged.
"""
if event.step < self.most_recent_step and event.HasField('summary'):
self._Purge(event, by_tags=True)
else:
self.most_recent_step = event.step
self.most_recent_wall_time = event.wall_time | [
"def",
"_CheckForOutOfOrderStepAndMaybePurge",
"(",
"self",
",",
"event",
")",
":",
"if",
"event",
".",
"step",
"<",
"self",
".",
"most_recent_step",
"and",
"event",
".",
"HasField",
"(",
"'summary'",
")",
":",
"self",
".",
"_Purge",
"(",
"event",
",",
"by_tags",
"=",
"True",
")",
"else",
":",
"self",
".",
"most_recent_step",
"=",
"event",
".",
"step",
"self",
".",
"most_recent_wall_time",
"=",
"event",
".",
"wall_time"
] | Check for out-of-order event.step and discard expired events for tags.
Check if the event is out of order relative to the global most recent step.
If it is, purge outdated summaries for tags that the event contains.
Args:
event: The event to use as reference. If the event is out-of-order, all
events with the same tags, but with a greater event.step will be purged. | [
"Check",
"for",
"out",
"-",
"of",
"-",
"order",
"event",
".",
"step",
"and",
"discard",
"expired",
"events",
"for",
"tags",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/event_processing/event_accumulator.py#L607-L621 | train |
tensorflow/tensorboard | tensorboard/backend/event_processing/event_accumulator.py | EventAccumulator._ProcessHistogram | def _ProcessHistogram(self, tag, wall_time, step, histo):
"""Processes a proto histogram by adding it to accumulated state."""
histo = self._ConvertHistogramProtoToTuple(histo)
histo_ev = HistogramEvent(wall_time, step, histo)
self.histograms.AddItem(tag, histo_ev)
self.compressed_histograms.AddItem(tag, histo_ev, self._CompressHistogram) | python | def _ProcessHistogram(self, tag, wall_time, step, histo):
"""Processes a proto histogram by adding it to accumulated state."""
histo = self._ConvertHistogramProtoToTuple(histo)
histo_ev = HistogramEvent(wall_time, step, histo)
self.histograms.AddItem(tag, histo_ev)
self.compressed_histograms.AddItem(tag, histo_ev, self._CompressHistogram) | [
"def",
"_ProcessHistogram",
"(",
"self",
",",
"tag",
",",
"wall_time",
",",
"step",
",",
"histo",
")",
":",
"histo",
"=",
"self",
".",
"_ConvertHistogramProtoToTuple",
"(",
"histo",
")",
"histo_ev",
"=",
"HistogramEvent",
"(",
"wall_time",
",",
"step",
",",
"histo",
")",
"self",
".",
"histograms",
".",
"AddItem",
"(",
"tag",
",",
"histo_ev",
")",
"self",
".",
"compressed_histograms",
".",
"AddItem",
"(",
"tag",
",",
"histo_ev",
",",
"self",
".",
"_CompressHistogram",
")"
] | Processes a proto histogram by adding it to accumulated state. | [
"Processes",
"a",
"proto",
"histogram",
"by",
"adding",
"it",
"to",
"accumulated",
"state",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/event_processing/event_accumulator.py#L632-L637 | train |
tensorflow/tensorboard | tensorboard/backend/event_processing/event_accumulator.py | EventAccumulator._CompressHistogram | def _CompressHistogram(self, histo_ev):
"""Callback for _ProcessHistogram."""
return CompressedHistogramEvent(
histo_ev.wall_time,
histo_ev.step,
compressor.compress_histogram_proto(
histo_ev.histogram_value, self._compression_bps)) | python | def _CompressHistogram(self, histo_ev):
"""Callback for _ProcessHistogram."""
return CompressedHistogramEvent(
histo_ev.wall_time,
histo_ev.step,
compressor.compress_histogram_proto(
histo_ev.histogram_value, self._compression_bps)) | [
"def",
"_CompressHistogram",
"(",
"self",
",",
"histo_ev",
")",
":",
"return",
"CompressedHistogramEvent",
"(",
"histo_ev",
".",
"wall_time",
",",
"histo_ev",
".",
"step",
",",
"compressor",
".",
"compress_histogram_proto",
"(",
"histo_ev",
".",
"histogram_value",
",",
"self",
".",
"_compression_bps",
")",
")"
] | Callback for _ProcessHistogram. | [
"Callback",
"for",
"_ProcessHistogram",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/event_processing/event_accumulator.py#L639-L645 | train |
tensorflow/tensorboard | tensorboard/backend/event_processing/event_accumulator.py | EventAccumulator._ProcessImage | def _ProcessImage(self, tag, wall_time, step, image):
"""Processes an image by adding it to accumulated state."""
event = ImageEvent(wall_time=wall_time,
step=step,
encoded_image_string=image.encoded_image_string,
width=image.width,
height=image.height)
self.images.AddItem(tag, event) | python | def _ProcessImage(self, tag, wall_time, step, image):
"""Processes an image by adding it to accumulated state."""
event = ImageEvent(wall_time=wall_time,
step=step,
encoded_image_string=image.encoded_image_string,
width=image.width,
height=image.height)
self.images.AddItem(tag, event) | [
"def",
"_ProcessImage",
"(",
"self",
",",
"tag",
",",
"wall_time",
",",
"step",
",",
"image",
")",
":",
"event",
"=",
"ImageEvent",
"(",
"wall_time",
"=",
"wall_time",
",",
"step",
"=",
"step",
",",
"encoded_image_string",
"=",
"image",
".",
"encoded_image_string",
",",
"width",
"=",
"image",
".",
"width",
",",
"height",
"=",
"image",
".",
"height",
")",
"self",
".",
"images",
".",
"AddItem",
"(",
"tag",
",",
"event",
")"
] | Processes an image by adding it to accumulated state. | [
"Processes",
"an",
"image",
"by",
"adding",
"it",
"to",
"accumulated",
"state",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/event_processing/event_accumulator.py#L647-L654 | train |
tensorflow/tensorboard | tensorboard/backend/event_processing/event_accumulator.py | EventAccumulator._ProcessAudio | def _ProcessAudio(self, tag, wall_time, step, audio):
"""Processes a audio by adding it to accumulated state."""
event = AudioEvent(wall_time=wall_time,
step=step,
encoded_audio_string=audio.encoded_audio_string,
content_type=audio.content_type,
sample_rate=audio.sample_rate,
length_frames=audio.length_frames)
self.audios.AddItem(tag, event) | python | def _ProcessAudio(self, tag, wall_time, step, audio):
"""Processes a audio by adding it to accumulated state."""
event = AudioEvent(wall_time=wall_time,
step=step,
encoded_audio_string=audio.encoded_audio_string,
content_type=audio.content_type,
sample_rate=audio.sample_rate,
length_frames=audio.length_frames)
self.audios.AddItem(tag, event) | [
"def",
"_ProcessAudio",
"(",
"self",
",",
"tag",
",",
"wall_time",
",",
"step",
",",
"audio",
")",
":",
"event",
"=",
"AudioEvent",
"(",
"wall_time",
"=",
"wall_time",
",",
"step",
"=",
"step",
",",
"encoded_audio_string",
"=",
"audio",
".",
"encoded_audio_string",
",",
"content_type",
"=",
"audio",
".",
"content_type",
",",
"sample_rate",
"=",
"audio",
".",
"sample_rate",
",",
"length_frames",
"=",
"audio",
".",
"length_frames",
")",
"self",
".",
"audios",
".",
"AddItem",
"(",
"tag",
",",
"event",
")"
] | Processes a audio by adding it to accumulated state. | [
"Processes",
"a",
"audio",
"by",
"adding",
"it",
"to",
"accumulated",
"state",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/event_processing/event_accumulator.py#L656-L664 | train |
tensorflow/tensorboard | tensorboard/backend/event_processing/event_accumulator.py | EventAccumulator._ProcessScalar | def _ProcessScalar(self, tag, wall_time, step, scalar):
"""Processes a simple value by adding it to accumulated state."""
sv = ScalarEvent(wall_time=wall_time, step=step, value=scalar)
self.scalars.AddItem(tag, sv) | python | def _ProcessScalar(self, tag, wall_time, step, scalar):
"""Processes a simple value by adding it to accumulated state."""
sv = ScalarEvent(wall_time=wall_time, step=step, value=scalar)
self.scalars.AddItem(tag, sv) | [
"def",
"_ProcessScalar",
"(",
"self",
",",
"tag",
",",
"wall_time",
",",
"step",
",",
"scalar",
")",
":",
"sv",
"=",
"ScalarEvent",
"(",
"wall_time",
"=",
"wall_time",
",",
"step",
"=",
"step",
",",
"value",
"=",
"scalar",
")",
"self",
".",
"scalars",
".",
"AddItem",
"(",
"tag",
",",
"sv",
")"
] | Processes a simple value by adding it to accumulated state. | [
"Processes",
"a",
"simple",
"value",
"by",
"adding",
"it",
"to",
"accumulated",
"state",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/event_processing/event_accumulator.py#L666-L669 | train |
tensorflow/tensorboard | tensorboard/backend/event_processing/event_accumulator.py | EventAccumulator._Purge | def _Purge(self, event, by_tags):
"""Purge all events that have occurred after the given event.step.
If by_tags is True, purge all events that occurred after the given
event.step, but only for the tags that the event has. Non-sequential
event.steps suggest that a TensorFlow restart occurred, and we discard
the out-of-order events to display a consistent view in TensorBoard.
Discarding by tags is the safer method, when we are unsure whether a restart
has occurred, given that threading in supervisor can cause events of
different tags to arrive with unsynchronized step values.
If by_tags is False, then purge all events with event.step greater than the
given event.step. This can be used when we are certain that a TensorFlow
restart has occurred and these events can be discarded.
Args:
event: The event to use as reference for the purge. All events with
the same tags, but with a greater event.step will be purged.
by_tags: Bool to dictate whether to discard all out-of-order events or
only those that are associated with the given reference event.
"""
## Keep data in reservoirs that has a step less than event.step
_NotExpired = lambda x: x.step < event.step
if by_tags:
def _ExpiredPerTag(value):
return [getattr(self, x).FilterItems(_NotExpired, value.tag)
for x in self.accumulated_attrs]
expired_per_tags = [_ExpiredPerTag(value)
for value in event.summary.value]
expired_per_type = [sum(x) for x in zip(*expired_per_tags)]
else:
expired_per_type = [getattr(self, x).FilterItems(_NotExpired)
for x in self.accumulated_attrs]
if sum(expired_per_type) > 0:
purge_msg = _GetPurgeMessage(self.most_recent_step,
self.most_recent_wall_time, event.step,
event.wall_time, *expired_per_type)
logger.warn(purge_msg) | python | def _Purge(self, event, by_tags):
"""Purge all events that have occurred after the given event.step.
If by_tags is True, purge all events that occurred after the given
event.step, but only for the tags that the event has. Non-sequential
event.steps suggest that a TensorFlow restart occurred, and we discard
the out-of-order events to display a consistent view in TensorBoard.
Discarding by tags is the safer method, when we are unsure whether a restart
has occurred, given that threading in supervisor can cause events of
different tags to arrive with unsynchronized step values.
If by_tags is False, then purge all events with event.step greater than the
given event.step. This can be used when we are certain that a TensorFlow
restart has occurred and these events can be discarded.
Args:
event: The event to use as reference for the purge. All events with
the same tags, but with a greater event.step will be purged.
by_tags: Bool to dictate whether to discard all out-of-order events or
only those that are associated with the given reference event.
"""
## Keep data in reservoirs that has a step less than event.step
_NotExpired = lambda x: x.step < event.step
if by_tags:
def _ExpiredPerTag(value):
return [getattr(self, x).FilterItems(_NotExpired, value.tag)
for x in self.accumulated_attrs]
expired_per_tags = [_ExpiredPerTag(value)
for value in event.summary.value]
expired_per_type = [sum(x) for x in zip(*expired_per_tags)]
else:
expired_per_type = [getattr(self, x).FilterItems(_NotExpired)
for x in self.accumulated_attrs]
if sum(expired_per_type) > 0:
purge_msg = _GetPurgeMessage(self.most_recent_step,
self.most_recent_wall_time, event.step,
event.wall_time, *expired_per_type)
logger.warn(purge_msg) | [
"def",
"_Purge",
"(",
"self",
",",
"event",
",",
"by_tags",
")",
":",
"## Keep data in reservoirs that has a step less than event.step",
"_NotExpired",
"=",
"lambda",
"x",
":",
"x",
".",
"step",
"<",
"event",
".",
"step",
"if",
"by_tags",
":",
"def",
"_ExpiredPerTag",
"(",
"value",
")",
":",
"return",
"[",
"getattr",
"(",
"self",
",",
"x",
")",
".",
"FilterItems",
"(",
"_NotExpired",
",",
"value",
".",
"tag",
")",
"for",
"x",
"in",
"self",
".",
"accumulated_attrs",
"]",
"expired_per_tags",
"=",
"[",
"_ExpiredPerTag",
"(",
"value",
")",
"for",
"value",
"in",
"event",
".",
"summary",
".",
"value",
"]",
"expired_per_type",
"=",
"[",
"sum",
"(",
"x",
")",
"for",
"x",
"in",
"zip",
"(",
"*",
"expired_per_tags",
")",
"]",
"else",
":",
"expired_per_type",
"=",
"[",
"getattr",
"(",
"self",
",",
"x",
")",
".",
"FilterItems",
"(",
"_NotExpired",
")",
"for",
"x",
"in",
"self",
".",
"accumulated_attrs",
"]",
"if",
"sum",
"(",
"expired_per_type",
")",
">",
"0",
":",
"purge_msg",
"=",
"_GetPurgeMessage",
"(",
"self",
".",
"most_recent_step",
",",
"self",
".",
"most_recent_wall_time",
",",
"event",
".",
"step",
",",
"event",
".",
"wall_time",
",",
"*",
"expired_per_type",
")",
"logger",
".",
"warn",
"(",
"purge_msg",
")"
] | Purge all events that have occurred after the given event.step.
If by_tags is True, purge all events that occurred after the given
event.step, but only for the tags that the event has. Non-sequential
event.steps suggest that a TensorFlow restart occurred, and we discard
the out-of-order events to display a consistent view in TensorBoard.
Discarding by tags is the safer method, when we are unsure whether a restart
has occurred, given that threading in supervisor can cause events of
different tags to arrive with unsynchronized step values.
If by_tags is False, then purge all events with event.step greater than the
given event.step. This can be used when we are certain that a TensorFlow
restart has occurred and these events can be discarded.
Args:
event: The event to use as reference for the purge. All events with
the same tags, but with a greater event.step will be purged.
by_tags: Bool to dictate whether to discard all out-of-order events or
only those that are associated with the given reference event. | [
"Purge",
"all",
"events",
"that",
"have",
"occurred",
"after",
"the",
"given",
"event",
".",
"step",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/event_processing/event_accumulator.py#L675-L716 | train |
tensorflow/tensorboard | tensorboard/backend/event_processing/event_file_loader.py | RawEventFileLoader.Load | def Load(self):
"""Loads all new events from disk as raw serialized proto bytestrings.
Calling Load multiple times in a row will not 'drop' events as long as the
return value is not iterated over.
Yields:
All event proto bytestrings in the file that have not been yielded yet.
"""
logger.debug('Loading events from %s', self._file_path)
# GetNext() expects a status argument on TF <= 1.7.
get_next_args = inspect.getargspec(self._reader.GetNext).args # pylint: disable=deprecated-method
# First argument is self
legacy_get_next = (len(get_next_args) > 1)
while True:
try:
if legacy_get_next:
with tf.compat.v1.errors.raise_exception_on_not_ok_status() as status:
self._reader.GetNext(status)
else:
self._reader.GetNext()
except (tf.errors.DataLossError, tf.errors.OutOfRangeError) as e:
logger.debug('Cannot read more events: %s', e)
# We ignore partial read exceptions, because a record may be truncated.
# PyRecordReader holds the offset prior to the failed read, so retrying
# will succeed.
break
yield self._reader.record()
logger.debug('No more events in %s', self._file_path) | python | def Load(self):
"""Loads all new events from disk as raw serialized proto bytestrings.
Calling Load multiple times in a row will not 'drop' events as long as the
return value is not iterated over.
Yields:
All event proto bytestrings in the file that have not been yielded yet.
"""
logger.debug('Loading events from %s', self._file_path)
# GetNext() expects a status argument on TF <= 1.7.
get_next_args = inspect.getargspec(self._reader.GetNext).args # pylint: disable=deprecated-method
# First argument is self
legacy_get_next = (len(get_next_args) > 1)
while True:
try:
if legacy_get_next:
with tf.compat.v1.errors.raise_exception_on_not_ok_status() as status:
self._reader.GetNext(status)
else:
self._reader.GetNext()
except (tf.errors.DataLossError, tf.errors.OutOfRangeError) as e:
logger.debug('Cannot read more events: %s', e)
# We ignore partial read exceptions, because a record may be truncated.
# PyRecordReader holds the offset prior to the failed read, so retrying
# will succeed.
break
yield self._reader.record()
logger.debug('No more events in %s', self._file_path) | [
"def",
"Load",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'Loading events from %s'",
",",
"self",
".",
"_file_path",
")",
"# GetNext() expects a status argument on TF <= 1.7.",
"get_next_args",
"=",
"inspect",
".",
"getargspec",
"(",
"self",
".",
"_reader",
".",
"GetNext",
")",
".",
"args",
"# pylint: disable=deprecated-method",
"# First argument is self",
"legacy_get_next",
"=",
"(",
"len",
"(",
"get_next_args",
")",
">",
"1",
")",
"while",
"True",
":",
"try",
":",
"if",
"legacy_get_next",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"errors",
".",
"raise_exception_on_not_ok_status",
"(",
")",
"as",
"status",
":",
"self",
".",
"_reader",
".",
"GetNext",
"(",
"status",
")",
"else",
":",
"self",
".",
"_reader",
".",
"GetNext",
"(",
")",
"except",
"(",
"tf",
".",
"errors",
".",
"DataLossError",
",",
"tf",
".",
"errors",
".",
"OutOfRangeError",
")",
"as",
"e",
":",
"logger",
".",
"debug",
"(",
"'Cannot read more events: %s'",
",",
"e",
")",
"# We ignore partial read exceptions, because a record may be truncated.",
"# PyRecordReader holds the offset prior to the failed read, so retrying",
"# will succeed.",
"break",
"yield",
"self",
".",
"_reader",
".",
"record",
"(",
")",
"logger",
".",
"debug",
"(",
"'No more events in %s'",
",",
"self",
".",
"_file_path",
")"
] | Loads all new events from disk as raw serialized proto bytestrings.
Calling Load multiple times in a row will not 'drop' events as long as the
return value is not iterated over.
Yields:
All event proto bytestrings in the file that have not been yielded yet. | [
"Loads",
"all",
"new",
"events",
"from",
"disk",
"as",
"raw",
"serialized",
"proto",
"bytestrings",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/event_processing/event_file_loader.py#L49-L79 | train |
tensorflow/tensorboard | tensorboard/backend/event_processing/event_file_loader.py | EventFileLoader.Load | def Load(self):
"""Loads all new events from disk.
Calling Load multiple times in a row will not 'drop' events as long as the
return value is not iterated over.
Yields:
All events in the file that have not been yielded yet.
"""
for record in super(EventFileLoader, self).Load():
yield event_pb2.Event.FromString(record) | python | def Load(self):
"""Loads all new events from disk.
Calling Load multiple times in a row will not 'drop' events as long as the
return value is not iterated over.
Yields:
All events in the file that have not been yielded yet.
"""
for record in super(EventFileLoader, self).Load():
yield event_pb2.Event.FromString(record) | [
"def",
"Load",
"(",
"self",
")",
":",
"for",
"record",
"in",
"super",
"(",
"EventFileLoader",
",",
"self",
")",
".",
"Load",
"(",
")",
":",
"yield",
"event_pb2",
".",
"Event",
".",
"FromString",
"(",
"record",
")"
] | Loads all new events from disk.
Calling Load multiple times in a row will not 'drop' events as long as the
return value is not iterated over.
Yields:
All events in the file that have not been yielded yet. | [
"Loads",
"all",
"new",
"events",
"from",
"disk",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/event_processing/event_file_loader.py#L85-L95 | train |
tensorflow/tensorboard | tensorboard/plugins/beholder/im_util.py | scale_sections | def scale_sections(sections, scaling_scope):
'''
input: unscaled sections.
returns: sections scaled to [0, 255]
'''
new_sections = []
if scaling_scope == 'layer':
for section in sections:
new_sections.append(scale_image_for_display(section))
elif scaling_scope == 'network':
global_min, global_max = global_extrema(sections)
for section in sections:
new_sections.append(scale_image_for_display(section,
global_min,
global_max))
return new_sections | python | def scale_sections(sections, scaling_scope):
'''
input: unscaled sections.
returns: sections scaled to [0, 255]
'''
new_sections = []
if scaling_scope == 'layer':
for section in sections:
new_sections.append(scale_image_for_display(section))
elif scaling_scope == 'network':
global_min, global_max = global_extrema(sections)
for section in sections:
new_sections.append(scale_image_for_display(section,
global_min,
global_max))
return new_sections | [
"def",
"scale_sections",
"(",
"sections",
",",
"scaling_scope",
")",
":",
"new_sections",
"=",
"[",
"]",
"if",
"scaling_scope",
"==",
"'layer'",
":",
"for",
"section",
"in",
"sections",
":",
"new_sections",
".",
"append",
"(",
"scale_image_for_display",
"(",
"section",
")",
")",
"elif",
"scaling_scope",
"==",
"'network'",
":",
"global_min",
",",
"global_max",
"=",
"global_extrema",
"(",
"sections",
")",
"for",
"section",
"in",
"sections",
":",
"new_sections",
".",
"append",
"(",
"scale_image_for_display",
"(",
"section",
",",
"global_min",
",",
"global_max",
")",
")",
"return",
"new_sections"
] | input: unscaled sections.
returns: sections scaled to [0, 255] | [
"input",
":",
"unscaled",
"sections",
".",
"returns",
":",
"sections",
"scaled",
"to",
"[",
"0",
"255",
"]"
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/beholder/im_util.py#L35-L53 | train |
tensorflow/tensorboard | tensorboard/plugins/debugger/debugger_server_lib.py | DebuggerDataStreamHandler.on_value_event | def on_value_event(self, event):
"""Records the summary values based on an updated message from the debugger.
Logs an error message if writing the event to disk fails.
Args:
event: The Event proto to be processed.
"""
if not event.summary.value:
logger.warn("The summary of the event lacks a value.")
return
# The node name property is actually a watch key, which is a concatenation
# of several pieces of data.
watch_key = event.summary.value[0].node_name
if not watch_key.endswith(constants.DEBUG_NUMERIC_SUMMARY_SUFFIX):
# Ignore events that lack a DebugNumericSummary.
# NOTE(@chihuahua): We may later handle other types of debug ops.
return
# We remove the constants.DEBUG_NUMERIC_SUMMARY_SUFFIX from the end of the
# watch name because it is not distinguishing: every health pill entry ends
# with it.
node_name_and_output_slot = watch_key[
:-len(constants.DEBUG_NUMERIC_SUMMARY_SUFFIX)]
shape = tensor_util.make_ndarray(event.summary.value[0].tensor).shape
if (len(shape) != 1 or
shape[0] < constants.MIN_DEBUG_NUMERIC_SUMMARY_TENSOR_LENGTH):
logger.warn("Health-pill tensor either lacks a dimension or is "
"shaped incorrectly: %s" % shape)
return
match = re.match(r"^(.*):(\d+)$", node_name_and_output_slot)
if not match:
logger.warn(
("A event with a health pill has an invalid node name and output "
"slot combination, (i.e., an unexpected debug op): %r"),
node_name_and_output_slot)
return
if self._session_run_index >= 0:
event.step = self._session_run_index
else:
# Data from parameter servers (or any graphs without a master) do not
# contain core metadata. So the session run count is missing. Set its
# value to a microsecond epoch timestamp.
event.step = int(time.time() * 1e6)
# Write this event to the events file designated for data from the
# debugger.
self._events_writer_manager.write_event(event)
alert = numerics_alert.extract_numerics_alert(event)
if self._numerics_alert_callback and alert:
self._numerics_alert_callback(alert) | python | def on_value_event(self, event):
"""Records the summary values based on an updated message from the debugger.
Logs an error message if writing the event to disk fails.
Args:
event: The Event proto to be processed.
"""
if not event.summary.value:
logger.warn("The summary of the event lacks a value.")
return
# The node name property is actually a watch key, which is a concatenation
# of several pieces of data.
watch_key = event.summary.value[0].node_name
if not watch_key.endswith(constants.DEBUG_NUMERIC_SUMMARY_SUFFIX):
# Ignore events that lack a DebugNumericSummary.
# NOTE(@chihuahua): We may later handle other types of debug ops.
return
# We remove the constants.DEBUG_NUMERIC_SUMMARY_SUFFIX from the end of the
# watch name because it is not distinguishing: every health pill entry ends
# with it.
node_name_and_output_slot = watch_key[
:-len(constants.DEBUG_NUMERIC_SUMMARY_SUFFIX)]
shape = tensor_util.make_ndarray(event.summary.value[0].tensor).shape
if (len(shape) != 1 or
shape[0] < constants.MIN_DEBUG_NUMERIC_SUMMARY_TENSOR_LENGTH):
logger.warn("Health-pill tensor either lacks a dimension or is "
"shaped incorrectly: %s" % shape)
return
match = re.match(r"^(.*):(\d+)$", node_name_and_output_slot)
if not match:
logger.warn(
("A event with a health pill has an invalid node name and output "
"slot combination, (i.e., an unexpected debug op): %r"),
node_name_and_output_slot)
return
if self._session_run_index >= 0:
event.step = self._session_run_index
else:
# Data from parameter servers (or any graphs without a master) do not
# contain core metadata. So the session run count is missing. Set its
# value to a microsecond epoch timestamp.
event.step = int(time.time() * 1e6)
# Write this event to the events file designated for data from the
# debugger.
self._events_writer_manager.write_event(event)
alert = numerics_alert.extract_numerics_alert(event)
if self._numerics_alert_callback and alert:
self._numerics_alert_callback(alert) | [
"def",
"on_value_event",
"(",
"self",
",",
"event",
")",
":",
"if",
"not",
"event",
".",
"summary",
".",
"value",
":",
"logger",
".",
"warn",
"(",
"\"The summary of the event lacks a value.\"",
")",
"return",
"# The node name property is actually a watch key, which is a concatenation",
"# of several pieces of data.",
"watch_key",
"=",
"event",
".",
"summary",
".",
"value",
"[",
"0",
"]",
".",
"node_name",
"if",
"not",
"watch_key",
".",
"endswith",
"(",
"constants",
".",
"DEBUG_NUMERIC_SUMMARY_SUFFIX",
")",
":",
"# Ignore events that lack a DebugNumericSummary.",
"# NOTE(@chihuahua): We may later handle other types of debug ops.",
"return",
"# We remove the constants.DEBUG_NUMERIC_SUMMARY_SUFFIX from the end of the",
"# watch name because it is not distinguishing: every health pill entry ends",
"# with it.",
"node_name_and_output_slot",
"=",
"watch_key",
"[",
":",
"-",
"len",
"(",
"constants",
".",
"DEBUG_NUMERIC_SUMMARY_SUFFIX",
")",
"]",
"shape",
"=",
"tensor_util",
".",
"make_ndarray",
"(",
"event",
".",
"summary",
".",
"value",
"[",
"0",
"]",
".",
"tensor",
")",
".",
"shape",
"if",
"(",
"len",
"(",
"shape",
")",
"!=",
"1",
"or",
"shape",
"[",
"0",
"]",
"<",
"constants",
".",
"MIN_DEBUG_NUMERIC_SUMMARY_TENSOR_LENGTH",
")",
":",
"logger",
".",
"warn",
"(",
"\"Health-pill tensor either lacks a dimension or is \"",
"\"shaped incorrectly: %s\"",
"%",
"shape",
")",
"return",
"match",
"=",
"re",
".",
"match",
"(",
"r\"^(.*):(\\d+)$\"",
",",
"node_name_and_output_slot",
")",
"if",
"not",
"match",
":",
"logger",
".",
"warn",
"(",
"(",
"\"A event with a health pill has an invalid node name and output \"",
"\"slot combination, (i.e., an unexpected debug op): %r\"",
")",
",",
"node_name_and_output_slot",
")",
"return",
"if",
"self",
".",
"_session_run_index",
">=",
"0",
":",
"event",
".",
"step",
"=",
"self",
".",
"_session_run_index",
"else",
":",
"# Data from parameter servers (or any graphs without a master) do not",
"# contain core metadata. So the session run count is missing. Set its",
"# value to a microsecond epoch timestamp.",
"event",
".",
"step",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
"*",
"1e6",
")",
"# Write this event to the events file designated for data from the",
"# debugger.",
"self",
".",
"_events_writer_manager",
".",
"write_event",
"(",
"event",
")",
"alert",
"=",
"numerics_alert",
".",
"extract_numerics_alert",
"(",
"event",
")",
"if",
"self",
".",
"_numerics_alert_callback",
"and",
"alert",
":",
"self",
".",
"_numerics_alert_callback",
"(",
"alert",
")"
] | Records the summary values based on an updated message from the debugger.
Logs an error message if writing the event to disk fails.
Args:
event: The Event proto to be processed. | [
"Records",
"the",
"summary",
"values",
"based",
"on",
"an",
"updated",
"message",
"from",
"the",
"debugger",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/debugger/debugger_server_lib.py#L112-L167 | train |
tensorflow/tensorboard | tensorboard/plugins/debugger/debugger_server_lib.py | DebuggerDataStreamHandler._parse_session_run_index | def _parse_session_run_index(self, event):
"""Parses the session_run_index value from the event proto.
Args:
event: The event with metadata that contains the session_run_index.
Returns:
The int session_run_index value. Or
constants.SENTINEL_FOR_UNDETERMINED_STEP if it could not be determined.
"""
metadata_string = event.log_message.message
try:
metadata = json.loads(metadata_string)
except ValueError as e:
logger.error(
"Could not decode metadata string '%s' for step value: %s",
metadata_string, e)
return constants.SENTINEL_FOR_UNDETERMINED_STEP
try:
return metadata["session_run_index"]
except KeyError:
logger.error(
"The session_run_index is missing from the metadata: %s",
metadata_string)
return constants.SENTINEL_FOR_UNDETERMINED_STEP | python | def _parse_session_run_index(self, event):
"""Parses the session_run_index value from the event proto.
Args:
event: The event with metadata that contains the session_run_index.
Returns:
The int session_run_index value. Or
constants.SENTINEL_FOR_UNDETERMINED_STEP if it could not be determined.
"""
metadata_string = event.log_message.message
try:
metadata = json.loads(metadata_string)
except ValueError as e:
logger.error(
"Could not decode metadata string '%s' for step value: %s",
metadata_string, e)
return constants.SENTINEL_FOR_UNDETERMINED_STEP
try:
return metadata["session_run_index"]
except KeyError:
logger.error(
"The session_run_index is missing from the metadata: %s",
metadata_string)
return constants.SENTINEL_FOR_UNDETERMINED_STEP | [
"def",
"_parse_session_run_index",
"(",
"self",
",",
"event",
")",
":",
"metadata_string",
"=",
"event",
".",
"log_message",
".",
"message",
"try",
":",
"metadata",
"=",
"json",
".",
"loads",
"(",
"metadata_string",
")",
"except",
"ValueError",
"as",
"e",
":",
"logger",
".",
"error",
"(",
"\"Could not decode metadata string '%s' for step value: %s\"",
",",
"metadata_string",
",",
"e",
")",
"return",
"constants",
".",
"SENTINEL_FOR_UNDETERMINED_STEP",
"try",
":",
"return",
"metadata",
"[",
"\"session_run_index\"",
"]",
"except",
"KeyError",
":",
"logger",
".",
"error",
"(",
"\"The session_run_index is missing from the metadata: %s\"",
",",
"metadata_string",
")",
"return",
"constants",
".",
"SENTINEL_FOR_UNDETERMINED_STEP"
] | Parses the session_run_index value from the event proto.
Args:
event: The event with metadata that contains the session_run_index.
Returns:
The int session_run_index value. Or
constants.SENTINEL_FOR_UNDETERMINED_STEP if it could not be determined. | [
"Parses",
"the",
"session_run_index",
"value",
"from",
"the",
"event",
"proto",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/debugger/debugger_server_lib.py#L169-L194 | train |
tensorflow/tensorboard | tensorboard/plugins/distribution/compressor.py | compress_histogram_proto | def compress_histogram_proto(histo, bps=NORMAL_HISTOGRAM_BPS):
"""Creates fixed size histogram by adding compression to accumulated state.
This routine transforms a histogram at a particular step by interpolating its
variable number of buckets to represent their cumulative weight at a constant
number of compression points. This significantly reduces the size of the
histogram and makes it suitable for a two-dimensional area plot where the
output of this routine constitutes the ranges for a single x coordinate.
Args:
histo: A HistogramProto object.
bps: Compression points represented in basis points, 1/100ths of a percent.
Defaults to normal distribution.
Returns:
List of values for each basis point.
"""
# See also: Histogram::Percentile() in core/lib/histogram/histogram.cc
if not histo.num:
return [CompressedHistogramValue(b, 0.0) for b in bps]
bucket = np.array(histo.bucket)
bucket_limit = list(histo.bucket_limit)
weights = (bucket * bps[-1] / (bucket.sum() or 1.0)).cumsum()
values = []
j = 0
while j < len(bps):
i = np.searchsorted(weights, bps[j], side='right')
while i < len(weights):
cumsum = weights[i]
cumsum_prev = weights[i - 1] if i > 0 else 0.0
if cumsum == cumsum_prev: # prevent lerp divide by zero
i += 1
continue
if not i or not cumsum_prev:
lhs = histo.min
else:
lhs = max(bucket_limit[i - 1], histo.min)
rhs = min(bucket_limit[i], histo.max)
weight = _lerp(bps[j], cumsum_prev, cumsum, lhs, rhs)
values.append(CompressedHistogramValue(bps[j], weight))
j += 1
break
else:
break
while j < len(bps):
values.append(CompressedHistogramValue(bps[j], histo.max))
j += 1
return values | python | def compress_histogram_proto(histo, bps=NORMAL_HISTOGRAM_BPS):
"""Creates fixed size histogram by adding compression to accumulated state.
This routine transforms a histogram at a particular step by interpolating its
variable number of buckets to represent their cumulative weight at a constant
number of compression points. This significantly reduces the size of the
histogram and makes it suitable for a two-dimensional area plot where the
output of this routine constitutes the ranges for a single x coordinate.
Args:
histo: A HistogramProto object.
bps: Compression points represented in basis points, 1/100ths of a percent.
Defaults to normal distribution.
Returns:
List of values for each basis point.
"""
# See also: Histogram::Percentile() in core/lib/histogram/histogram.cc
if not histo.num:
return [CompressedHistogramValue(b, 0.0) for b in bps]
bucket = np.array(histo.bucket)
bucket_limit = list(histo.bucket_limit)
weights = (bucket * bps[-1] / (bucket.sum() or 1.0)).cumsum()
values = []
j = 0
while j < len(bps):
i = np.searchsorted(weights, bps[j], side='right')
while i < len(weights):
cumsum = weights[i]
cumsum_prev = weights[i - 1] if i > 0 else 0.0
if cumsum == cumsum_prev: # prevent lerp divide by zero
i += 1
continue
if not i or not cumsum_prev:
lhs = histo.min
else:
lhs = max(bucket_limit[i - 1], histo.min)
rhs = min(bucket_limit[i], histo.max)
weight = _lerp(bps[j], cumsum_prev, cumsum, lhs, rhs)
values.append(CompressedHistogramValue(bps[j], weight))
j += 1
break
else:
break
while j < len(bps):
values.append(CompressedHistogramValue(bps[j], histo.max))
j += 1
return values | [
"def",
"compress_histogram_proto",
"(",
"histo",
",",
"bps",
"=",
"NORMAL_HISTOGRAM_BPS",
")",
":",
"# See also: Histogram::Percentile() in core/lib/histogram/histogram.cc",
"if",
"not",
"histo",
".",
"num",
":",
"return",
"[",
"CompressedHistogramValue",
"(",
"b",
",",
"0.0",
")",
"for",
"b",
"in",
"bps",
"]",
"bucket",
"=",
"np",
".",
"array",
"(",
"histo",
".",
"bucket",
")",
"bucket_limit",
"=",
"list",
"(",
"histo",
".",
"bucket_limit",
")",
"weights",
"=",
"(",
"bucket",
"*",
"bps",
"[",
"-",
"1",
"]",
"/",
"(",
"bucket",
".",
"sum",
"(",
")",
"or",
"1.0",
")",
")",
".",
"cumsum",
"(",
")",
"values",
"=",
"[",
"]",
"j",
"=",
"0",
"while",
"j",
"<",
"len",
"(",
"bps",
")",
":",
"i",
"=",
"np",
".",
"searchsorted",
"(",
"weights",
",",
"bps",
"[",
"j",
"]",
",",
"side",
"=",
"'right'",
")",
"while",
"i",
"<",
"len",
"(",
"weights",
")",
":",
"cumsum",
"=",
"weights",
"[",
"i",
"]",
"cumsum_prev",
"=",
"weights",
"[",
"i",
"-",
"1",
"]",
"if",
"i",
">",
"0",
"else",
"0.0",
"if",
"cumsum",
"==",
"cumsum_prev",
":",
"# prevent lerp divide by zero",
"i",
"+=",
"1",
"continue",
"if",
"not",
"i",
"or",
"not",
"cumsum_prev",
":",
"lhs",
"=",
"histo",
".",
"min",
"else",
":",
"lhs",
"=",
"max",
"(",
"bucket_limit",
"[",
"i",
"-",
"1",
"]",
",",
"histo",
".",
"min",
")",
"rhs",
"=",
"min",
"(",
"bucket_limit",
"[",
"i",
"]",
",",
"histo",
".",
"max",
")",
"weight",
"=",
"_lerp",
"(",
"bps",
"[",
"j",
"]",
",",
"cumsum_prev",
",",
"cumsum",
",",
"lhs",
",",
"rhs",
")",
"values",
".",
"append",
"(",
"CompressedHistogramValue",
"(",
"bps",
"[",
"j",
"]",
",",
"weight",
")",
")",
"j",
"+=",
"1",
"break",
"else",
":",
"break",
"while",
"j",
"<",
"len",
"(",
"bps",
")",
":",
"values",
".",
"append",
"(",
"CompressedHistogramValue",
"(",
"bps",
"[",
"j",
"]",
",",
"histo",
".",
"max",
")",
")",
"j",
"+=",
"1",
"return",
"values"
] | Creates fixed size histogram by adding compression to accumulated state.
This routine transforms a histogram at a particular step by interpolating its
variable number of buckets to represent their cumulative weight at a constant
number of compression points. This significantly reduces the size of the
histogram and makes it suitable for a two-dimensional area plot where the
output of this routine constitutes the ranges for a single x coordinate.
Args:
histo: A HistogramProto object.
bps: Compression points represented in basis points, 1/100ths of a percent.
Defaults to normal distribution.
Returns:
List of values for each basis point. | [
"Creates",
"fixed",
"size",
"histogram",
"by",
"adding",
"compression",
"to",
"accumulated",
"state",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/distribution/compressor.py#L36-L83 | train |
tensorflow/tensorboard | tensorboard/plugins/distribution/compressor.py | compress_histogram | def compress_histogram(buckets, bps=NORMAL_HISTOGRAM_BPS):
"""Creates fixed size histogram by adding compression to accumulated state.
This routine transforms a histogram at a particular step by linearly
interpolating its variable number of buckets to represent their cumulative
weight at a constant number of compression points. This significantly reduces
the size of the histogram and makes it suitable for a two-dimensional area
plot where the output of this routine constitutes the ranges for a single x
coordinate.
Args:
buckets: A list of buckets, each of which is a 3-tuple of the form
`(min, max, count)`.
bps: Compression points represented in basis points, 1/100ths of a percent.
Defaults to normal distribution.
Returns:
List of values for each basis point.
"""
# See also: Histogram::Percentile() in core/lib/histogram/histogram.cc
buckets = np.array(buckets)
if not buckets.size:
return [CompressedHistogramValue(b, 0.0) for b in bps]
(minmin, maxmax) = (buckets[0][0], buckets[-1][1])
counts = buckets[:, 2]
right_edges = list(buckets[:, 1])
weights = (counts * bps[-1] / (counts.sum() or 1.0)).cumsum()
result = []
bp_index = 0
while bp_index < len(bps):
i = np.searchsorted(weights, bps[bp_index], side='right')
while i < len(weights):
cumsum = weights[i]
cumsum_prev = weights[i - 1] if i > 0 else 0.0
if cumsum == cumsum_prev: # prevent division-by-zero in `_lerp`
i += 1
continue
if not i or not cumsum_prev:
lhs = minmin
else:
lhs = max(right_edges[i - 1], minmin)
rhs = min(right_edges[i], maxmax)
weight = _lerp(bps[bp_index], cumsum_prev, cumsum, lhs, rhs)
result.append(CompressedHistogramValue(bps[bp_index], weight))
bp_index += 1
break
else:
break
while bp_index < len(bps):
result.append(CompressedHistogramValue(bps[bp_index], maxmax))
bp_index += 1
return result | python | def compress_histogram(buckets, bps=NORMAL_HISTOGRAM_BPS):
"""Creates fixed size histogram by adding compression to accumulated state.
This routine transforms a histogram at a particular step by linearly
interpolating its variable number of buckets to represent their cumulative
weight at a constant number of compression points. This significantly reduces
the size of the histogram and makes it suitable for a two-dimensional area
plot where the output of this routine constitutes the ranges for a single x
coordinate.
Args:
buckets: A list of buckets, each of which is a 3-tuple of the form
`(min, max, count)`.
bps: Compression points represented in basis points, 1/100ths of a percent.
Defaults to normal distribution.
Returns:
List of values for each basis point.
"""
# See also: Histogram::Percentile() in core/lib/histogram/histogram.cc
buckets = np.array(buckets)
if not buckets.size:
return [CompressedHistogramValue(b, 0.0) for b in bps]
(minmin, maxmax) = (buckets[0][0], buckets[-1][1])
counts = buckets[:, 2]
right_edges = list(buckets[:, 1])
weights = (counts * bps[-1] / (counts.sum() or 1.0)).cumsum()
result = []
bp_index = 0
while bp_index < len(bps):
i = np.searchsorted(weights, bps[bp_index], side='right')
while i < len(weights):
cumsum = weights[i]
cumsum_prev = weights[i - 1] if i > 0 else 0.0
if cumsum == cumsum_prev: # prevent division-by-zero in `_lerp`
i += 1
continue
if not i or not cumsum_prev:
lhs = minmin
else:
lhs = max(right_edges[i - 1], minmin)
rhs = min(right_edges[i], maxmax)
weight = _lerp(bps[bp_index], cumsum_prev, cumsum, lhs, rhs)
result.append(CompressedHistogramValue(bps[bp_index], weight))
bp_index += 1
break
else:
break
while bp_index < len(bps):
result.append(CompressedHistogramValue(bps[bp_index], maxmax))
bp_index += 1
return result | [
"def",
"compress_histogram",
"(",
"buckets",
",",
"bps",
"=",
"NORMAL_HISTOGRAM_BPS",
")",
":",
"# See also: Histogram::Percentile() in core/lib/histogram/histogram.cc",
"buckets",
"=",
"np",
".",
"array",
"(",
"buckets",
")",
"if",
"not",
"buckets",
".",
"size",
":",
"return",
"[",
"CompressedHistogramValue",
"(",
"b",
",",
"0.0",
")",
"for",
"b",
"in",
"bps",
"]",
"(",
"minmin",
",",
"maxmax",
")",
"=",
"(",
"buckets",
"[",
"0",
"]",
"[",
"0",
"]",
",",
"buckets",
"[",
"-",
"1",
"]",
"[",
"1",
"]",
")",
"counts",
"=",
"buckets",
"[",
":",
",",
"2",
"]",
"right_edges",
"=",
"list",
"(",
"buckets",
"[",
":",
",",
"1",
"]",
")",
"weights",
"=",
"(",
"counts",
"*",
"bps",
"[",
"-",
"1",
"]",
"/",
"(",
"counts",
".",
"sum",
"(",
")",
"or",
"1.0",
")",
")",
".",
"cumsum",
"(",
")",
"result",
"=",
"[",
"]",
"bp_index",
"=",
"0",
"while",
"bp_index",
"<",
"len",
"(",
"bps",
")",
":",
"i",
"=",
"np",
".",
"searchsorted",
"(",
"weights",
",",
"bps",
"[",
"bp_index",
"]",
",",
"side",
"=",
"'right'",
")",
"while",
"i",
"<",
"len",
"(",
"weights",
")",
":",
"cumsum",
"=",
"weights",
"[",
"i",
"]",
"cumsum_prev",
"=",
"weights",
"[",
"i",
"-",
"1",
"]",
"if",
"i",
">",
"0",
"else",
"0.0",
"if",
"cumsum",
"==",
"cumsum_prev",
":",
"# prevent division-by-zero in `_lerp`",
"i",
"+=",
"1",
"continue",
"if",
"not",
"i",
"or",
"not",
"cumsum_prev",
":",
"lhs",
"=",
"minmin",
"else",
":",
"lhs",
"=",
"max",
"(",
"right_edges",
"[",
"i",
"-",
"1",
"]",
",",
"minmin",
")",
"rhs",
"=",
"min",
"(",
"right_edges",
"[",
"i",
"]",
",",
"maxmax",
")",
"weight",
"=",
"_lerp",
"(",
"bps",
"[",
"bp_index",
"]",
",",
"cumsum_prev",
",",
"cumsum",
",",
"lhs",
",",
"rhs",
")",
"result",
".",
"append",
"(",
"CompressedHistogramValue",
"(",
"bps",
"[",
"bp_index",
"]",
",",
"weight",
")",
")",
"bp_index",
"+=",
"1",
"break",
"else",
":",
"break",
"while",
"bp_index",
"<",
"len",
"(",
"bps",
")",
":",
"result",
".",
"append",
"(",
"CompressedHistogramValue",
"(",
"bps",
"[",
"bp_index",
"]",
",",
"maxmax",
")",
")",
"bp_index",
"+=",
"1",
"return",
"result"
] | Creates fixed size histogram by adding compression to accumulated state.
This routine transforms a histogram at a particular step by linearly
interpolating its variable number of buckets to represent their cumulative
weight at a constant number of compression points. This significantly reduces
the size of the histogram and makes it suitable for a two-dimensional area
plot where the output of this routine constitutes the ranges for a single x
coordinate.
Args:
buckets: A list of buckets, each of which is a 3-tuple of the form
`(min, max, count)`.
bps: Compression points represented in basis points, 1/100ths of a percent.
Defaults to normal distribution.
Returns:
List of values for each basis point. | [
"Creates",
"fixed",
"size",
"histogram",
"by",
"adding",
"compression",
"to",
"accumulated",
"state",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/distribution/compressor.py#L86-L138 | train |
tensorflow/tensorboard | tensorboard/plugins/distribution/compressor.py | _lerp | def _lerp(x, x0, x1, y0, y1):
"""Affinely map from [x0, x1] onto [y0, y1]."""
return y0 + (x - x0) * float(y1 - y0) / (x1 - x0) | python | def _lerp(x, x0, x1, y0, y1):
"""Affinely map from [x0, x1] onto [y0, y1]."""
return y0 + (x - x0) * float(y1 - y0) / (x1 - x0) | [
"def",
"_lerp",
"(",
"x",
",",
"x0",
",",
"x1",
",",
"y0",
",",
"y1",
")",
":",
"return",
"y0",
"+",
"(",
"x",
"-",
"x0",
")",
"*",
"float",
"(",
"y1",
"-",
"y0",
")",
"/",
"(",
"x1",
"-",
"x0",
")"
] | Affinely map from [x0, x1] onto [y0, y1]. | [
"Affinely",
"map",
"from",
"[",
"x0",
"x1",
"]",
"onto",
"[",
"y0",
"y1",
"]",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/distribution/compressor.py#L141-L143 | train |
tensorflow/tensorboard | tensorboard/plugins/image/images_plugin.py | ImagesPlugin.is_active | def is_active(self):
"""The images plugin is active iff any run has at least one relevant tag."""
if self._db_connection_provider:
# The plugin is active if one relevant tag can be found in the database.
db = self._db_connection_provider()
cursor = db.execute(
'''
SELECT 1
FROM Tags
WHERE Tags.plugin_name = ?
LIMIT 1
''',
(metadata.PLUGIN_NAME,))
return bool(list(cursor))
if not self._multiplexer:
return False
return bool(self._multiplexer.PluginRunToTagToContent(metadata.PLUGIN_NAME)) | python | def is_active(self):
"""The images plugin is active iff any run has at least one relevant tag."""
if self._db_connection_provider:
# The plugin is active if one relevant tag can be found in the database.
db = self._db_connection_provider()
cursor = db.execute(
'''
SELECT 1
FROM Tags
WHERE Tags.plugin_name = ?
LIMIT 1
''',
(metadata.PLUGIN_NAME,))
return bool(list(cursor))
if not self._multiplexer:
return False
return bool(self._multiplexer.PluginRunToTagToContent(metadata.PLUGIN_NAME)) | [
"def",
"is_active",
"(",
"self",
")",
":",
"if",
"self",
".",
"_db_connection_provider",
":",
"# The plugin is active if one relevant tag can be found in the database.",
"db",
"=",
"self",
".",
"_db_connection_provider",
"(",
")",
"cursor",
"=",
"db",
".",
"execute",
"(",
"'''\n SELECT 1\n FROM Tags\n WHERE Tags.plugin_name = ?\n LIMIT 1\n '''",
",",
"(",
"metadata",
".",
"PLUGIN_NAME",
",",
")",
")",
"return",
"bool",
"(",
"list",
"(",
"cursor",
")",
")",
"if",
"not",
"self",
".",
"_multiplexer",
":",
"return",
"False",
"return",
"bool",
"(",
"self",
".",
"_multiplexer",
".",
"PluginRunToTagToContent",
"(",
"metadata",
".",
"PLUGIN_NAME",
")",
")"
] | The images plugin is active iff any run has at least one relevant tag. | [
"The",
"images",
"plugin",
"is",
"active",
"iff",
"any",
"run",
"has",
"at",
"least",
"one",
"relevant",
"tag",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/image/images_plugin.py#L77-L93 | train |
tensorflow/tensorboard | tensorboard/plugins/image/images_plugin.py | ImagesPlugin._serve_image_metadata | def _serve_image_metadata(self, request):
"""Given a tag and list of runs, serve a list of metadata for images.
Note that the images themselves are not sent; instead, we respond with URLs
to the images. The frontend should treat these URLs as opaque and should not
try to parse information about them or generate them itself, as the format
may change.
Args:
request: A werkzeug.wrappers.Request object.
Returns:
A werkzeug.Response application.
"""
tag = request.args.get('tag')
run = request.args.get('run')
sample = int(request.args.get('sample', 0))
response = self._image_response_for_run(run, tag, sample)
return http_util.Respond(request, response, 'application/json') | python | def _serve_image_metadata(self, request):
"""Given a tag and list of runs, serve a list of metadata for images.
Note that the images themselves are not sent; instead, we respond with URLs
to the images. The frontend should treat these URLs as opaque and should not
try to parse information about them or generate them itself, as the format
may change.
Args:
request: A werkzeug.wrappers.Request object.
Returns:
A werkzeug.Response application.
"""
tag = request.args.get('tag')
run = request.args.get('run')
sample = int(request.args.get('sample', 0))
response = self._image_response_for_run(run, tag, sample)
return http_util.Respond(request, response, 'application/json') | [
"def",
"_serve_image_metadata",
"(",
"self",
",",
"request",
")",
":",
"tag",
"=",
"request",
".",
"args",
".",
"get",
"(",
"'tag'",
")",
"run",
"=",
"request",
".",
"args",
".",
"get",
"(",
"'run'",
")",
"sample",
"=",
"int",
"(",
"request",
".",
"args",
".",
"get",
"(",
"'sample'",
",",
"0",
")",
")",
"response",
"=",
"self",
".",
"_image_response_for_run",
"(",
"run",
",",
"tag",
",",
"sample",
")",
"return",
"http_util",
".",
"Respond",
"(",
"request",
",",
"response",
",",
"'application/json'",
")"
] | Given a tag and list of runs, serve a list of metadata for images.
Note that the images themselves are not sent; instead, we respond with URLs
to the images. The frontend should treat these URLs as opaque and should not
try to parse information about them or generate them itself, as the format
may change.
Args:
request: A werkzeug.wrappers.Request object.
Returns:
A werkzeug.Response application. | [
"Given",
"a",
"tag",
"and",
"list",
"of",
"runs",
"serve",
"a",
"list",
"of",
"metadata",
"for",
"images",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/image/images_plugin.py#L147-L165 | train |
tensorflow/tensorboard | tensorboard/plugins/image/images_plugin.py | ImagesPlugin._image_response_for_run | def _image_response_for_run(self, run, tag, sample):
"""Builds a JSON-serializable object with information about images.
Args:
run: The name of the run.
tag: The name of the tag the images all belong to.
sample: The zero-indexed sample of the image for which to retrieve
information. For instance, setting `sample` to `2` will fetch
information about only the third image of each batch. Steps with
fewer than three images will be omitted from the results.
Returns:
A list of dictionaries containing the wall time, step, URL, width, and
height for each image.
"""
if self._db_connection_provider:
db = self._db_connection_provider()
cursor = db.execute(
'''
SELECT
computed_time,
step,
CAST (T0.data AS INT) AS width,
CAST (T1.data AS INT) AS height
FROM Tensors
JOIN TensorStrings AS T0
ON Tensors.rowid = T0.tensor_rowid
JOIN TensorStrings AS T1
ON Tensors.rowid = T1.tensor_rowid
WHERE
series = (
SELECT tag_id
FROM Runs
CROSS JOIN Tags USING (run_id)
WHERE Runs.run_name = :run AND Tags.tag_name = :tag)
AND step IS NOT NULL
AND dtype = :dtype
/* Should be n-vector, n >= 3: [width, height, samples...] */
AND (NOT INSTR(shape, ',') AND CAST (shape AS INT) >= 3)
AND T0.idx = 0
AND T1.idx = 1
ORDER BY step
''',
{'run': run, 'tag': tag, 'dtype': tf.string.as_datatype_enum})
return [{
'wall_time': computed_time,
'step': step,
'width': width,
'height': height,
'query': self._query_for_individual_image(run, tag, sample, index)
} for index, (computed_time, step, width, height) in enumerate(cursor)]
response = []
index = 0
tensor_events = self._multiplexer.Tensors(run, tag)
filtered_events = self._filter_by_sample(tensor_events, sample)
for (index, tensor_event) in enumerate(filtered_events):
(width, height) = tensor_event.tensor_proto.string_val[:2]
response.append({
'wall_time': tensor_event.wall_time,
'step': tensor_event.step,
# We include the size so that the frontend can add that to the <img>
# tag so that the page layout doesn't change when the image loads.
'width': int(width),
'height': int(height),
'query': self._query_for_individual_image(run, tag, sample, index)
})
return response | python | def _image_response_for_run(self, run, tag, sample):
"""Builds a JSON-serializable object with information about images.
Args:
run: The name of the run.
tag: The name of the tag the images all belong to.
sample: The zero-indexed sample of the image for which to retrieve
information. For instance, setting `sample` to `2` will fetch
information about only the third image of each batch. Steps with
fewer than three images will be omitted from the results.
Returns:
A list of dictionaries containing the wall time, step, URL, width, and
height for each image.
"""
if self._db_connection_provider:
db = self._db_connection_provider()
cursor = db.execute(
'''
SELECT
computed_time,
step,
CAST (T0.data AS INT) AS width,
CAST (T1.data AS INT) AS height
FROM Tensors
JOIN TensorStrings AS T0
ON Tensors.rowid = T0.tensor_rowid
JOIN TensorStrings AS T1
ON Tensors.rowid = T1.tensor_rowid
WHERE
series = (
SELECT tag_id
FROM Runs
CROSS JOIN Tags USING (run_id)
WHERE Runs.run_name = :run AND Tags.tag_name = :tag)
AND step IS NOT NULL
AND dtype = :dtype
/* Should be n-vector, n >= 3: [width, height, samples...] */
AND (NOT INSTR(shape, ',') AND CAST (shape AS INT) >= 3)
AND T0.idx = 0
AND T1.idx = 1
ORDER BY step
''',
{'run': run, 'tag': tag, 'dtype': tf.string.as_datatype_enum})
return [{
'wall_time': computed_time,
'step': step,
'width': width,
'height': height,
'query': self._query_for_individual_image(run, tag, sample, index)
} for index, (computed_time, step, width, height) in enumerate(cursor)]
response = []
index = 0
tensor_events = self._multiplexer.Tensors(run, tag)
filtered_events = self._filter_by_sample(tensor_events, sample)
for (index, tensor_event) in enumerate(filtered_events):
(width, height) = tensor_event.tensor_proto.string_val[:2]
response.append({
'wall_time': tensor_event.wall_time,
'step': tensor_event.step,
# We include the size so that the frontend can add that to the <img>
# tag so that the page layout doesn't change when the image loads.
'width': int(width),
'height': int(height),
'query': self._query_for_individual_image(run, tag, sample, index)
})
return response | [
"def",
"_image_response_for_run",
"(",
"self",
",",
"run",
",",
"tag",
",",
"sample",
")",
":",
"if",
"self",
".",
"_db_connection_provider",
":",
"db",
"=",
"self",
".",
"_db_connection_provider",
"(",
")",
"cursor",
"=",
"db",
".",
"execute",
"(",
"'''\n SELECT\n computed_time,\n step,\n CAST (T0.data AS INT) AS width,\n CAST (T1.data AS INT) AS height\n FROM Tensors\n JOIN TensorStrings AS T0\n ON Tensors.rowid = T0.tensor_rowid\n JOIN TensorStrings AS T1\n ON Tensors.rowid = T1.tensor_rowid\n WHERE\n series = (\n SELECT tag_id\n FROM Runs\n CROSS JOIN Tags USING (run_id)\n WHERE Runs.run_name = :run AND Tags.tag_name = :tag)\n AND step IS NOT NULL\n AND dtype = :dtype\n /* Should be n-vector, n >= 3: [width, height, samples...] */\n AND (NOT INSTR(shape, ',') AND CAST (shape AS INT) >= 3)\n AND T0.idx = 0\n AND T1.idx = 1\n ORDER BY step\n '''",
",",
"{",
"'run'",
":",
"run",
",",
"'tag'",
":",
"tag",
",",
"'dtype'",
":",
"tf",
".",
"string",
".",
"as_datatype_enum",
"}",
")",
"return",
"[",
"{",
"'wall_time'",
":",
"computed_time",
",",
"'step'",
":",
"step",
",",
"'width'",
":",
"width",
",",
"'height'",
":",
"height",
",",
"'query'",
":",
"self",
".",
"_query_for_individual_image",
"(",
"run",
",",
"tag",
",",
"sample",
",",
"index",
")",
"}",
"for",
"index",
",",
"(",
"computed_time",
",",
"step",
",",
"width",
",",
"height",
")",
"in",
"enumerate",
"(",
"cursor",
")",
"]",
"response",
"=",
"[",
"]",
"index",
"=",
"0",
"tensor_events",
"=",
"self",
".",
"_multiplexer",
".",
"Tensors",
"(",
"run",
",",
"tag",
")",
"filtered_events",
"=",
"self",
".",
"_filter_by_sample",
"(",
"tensor_events",
",",
"sample",
")",
"for",
"(",
"index",
",",
"tensor_event",
")",
"in",
"enumerate",
"(",
"filtered_events",
")",
":",
"(",
"width",
",",
"height",
")",
"=",
"tensor_event",
".",
"tensor_proto",
".",
"string_val",
"[",
":",
"2",
"]",
"response",
".",
"append",
"(",
"{",
"'wall_time'",
":",
"tensor_event",
".",
"wall_time",
",",
"'step'",
":",
"tensor_event",
".",
"step",
",",
"# We include the size so that the frontend can add that to the <img>",
"# tag so that the page layout doesn't change when the image loads.",
"'width'",
":",
"int",
"(",
"width",
")",
",",
"'height'",
":",
"int",
"(",
"height",
")",
",",
"'query'",
":",
"self",
".",
"_query_for_individual_image",
"(",
"run",
",",
"tag",
",",
"sample",
",",
"index",
")",
"}",
")",
"return",
"response"
] | Builds a JSON-serializable object with information about images.
Args:
run: The name of the run.
tag: The name of the tag the images all belong to.
sample: The zero-indexed sample of the image for which to retrieve
information. For instance, setting `sample` to `2` will fetch
information about only the third image of each batch. Steps with
fewer than three images will be omitted from the results.
Returns:
A list of dictionaries containing the wall time, step, URL, width, and
height for each image. | [
"Builds",
"a",
"JSON",
"-",
"serializable",
"object",
"with",
"information",
"about",
"images",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/image/images_plugin.py#L167-L233 | train |
tensorflow/tensorboard | tensorboard/plugins/image/images_plugin.py | ImagesPlugin._get_individual_image | def _get_individual_image(self, run, tag, index, sample):
"""
Returns the actual image bytes for a given image.
Args:
run: The name of the run the image belongs to.
tag: The name of the tag the images belongs to.
index: The index of the image in the current reservoir.
sample: The zero-indexed sample of the image to retrieve (for example,
setting `sample` to `2` will fetch the third image sample at `step`).
Returns:
A bytestring of the raw image bytes.
"""
if self._db_connection_provider:
db = self._db_connection_provider()
cursor = db.execute(
'''
SELECT data
FROM TensorStrings
WHERE
/* Skip first 2 elements which are width and height. */
idx = 2 + :sample
AND tensor_rowid = (
SELECT rowid
FROM Tensors
WHERE
series = (
SELECT tag_id
FROM Runs
CROSS JOIN Tags USING (run_id)
WHERE
Runs.run_name = :run
AND Tags.tag_name = :tag)
AND step IS NOT NULL
AND dtype = :dtype
/* Should be n-vector, n >= 3: [width, height, samples...] */
AND (NOT INSTR(shape, ',') AND CAST (shape AS INT) >= 3)
ORDER BY step
LIMIT 1
OFFSET :index)
''',
{'run': run,
'tag': tag,
'sample': sample,
'index': index,
'dtype': tf.string.as_datatype_enum})
(data,) = cursor.fetchone()
return six.binary_type(data)
events = self._filter_by_sample(self._multiplexer.Tensors(run, tag), sample)
images = events[index].tensor_proto.string_val[2:] # skip width, height
return images[sample] | python | def _get_individual_image(self, run, tag, index, sample):
"""
Returns the actual image bytes for a given image.
Args:
run: The name of the run the image belongs to.
tag: The name of the tag the images belongs to.
index: The index of the image in the current reservoir.
sample: The zero-indexed sample of the image to retrieve (for example,
setting `sample` to `2` will fetch the third image sample at `step`).
Returns:
A bytestring of the raw image bytes.
"""
if self._db_connection_provider:
db = self._db_connection_provider()
cursor = db.execute(
'''
SELECT data
FROM TensorStrings
WHERE
/* Skip first 2 elements which are width and height. */
idx = 2 + :sample
AND tensor_rowid = (
SELECT rowid
FROM Tensors
WHERE
series = (
SELECT tag_id
FROM Runs
CROSS JOIN Tags USING (run_id)
WHERE
Runs.run_name = :run
AND Tags.tag_name = :tag)
AND step IS NOT NULL
AND dtype = :dtype
/* Should be n-vector, n >= 3: [width, height, samples...] */
AND (NOT INSTR(shape, ',') AND CAST (shape AS INT) >= 3)
ORDER BY step
LIMIT 1
OFFSET :index)
''',
{'run': run,
'tag': tag,
'sample': sample,
'index': index,
'dtype': tf.string.as_datatype_enum})
(data,) = cursor.fetchone()
return six.binary_type(data)
events = self._filter_by_sample(self._multiplexer.Tensors(run, tag), sample)
images = events[index].tensor_proto.string_val[2:] # skip width, height
return images[sample] | [
"def",
"_get_individual_image",
"(",
"self",
",",
"run",
",",
"tag",
",",
"index",
",",
"sample",
")",
":",
"if",
"self",
".",
"_db_connection_provider",
":",
"db",
"=",
"self",
".",
"_db_connection_provider",
"(",
")",
"cursor",
"=",
"db",
".",
"execute",
"(",
"'''\n SELECT data\n FROM TensorStrings\n WHERE\n /* Skip first 2 elements which are width and height. */\n idx = 2 + :sample\n AND tensor_rowid = (\n SELECT rowid\n FROM Tensors\n WHERE\n series = (\n SELECT tag_id\n FROM Runs\n CROSS JOIN Tags USING (run_id)\n WHERE\n Runs.run_name = :run\n AND Tags.tag_name = :tag)\n AND step IS NOT NULL\n AND dtype = :dtype\n /* Should be n-vector, n >= 3: [width, height, samples...] */\n AND (NOT INSTR(shape, ',') AND CAST (shape AS INT) >= 3)\n ORDER BY step\n LIMIT 1\n OFFSET :index)\n '''",
",",
"{",
"'run'",
":",
"run",
",",
"'tag'",
":",
"tag",
",",
"'sample'",
":",
"sample",
",",
"'index'",
":",
"index",
",",
"'dtype'",
":",
"tf",
".",
"string",
".",
"as_datatype_enum",
"}",
")",
"(",
"data",
",",
")",
"=",
"cursor",
".",
"fetchone",
"(",
")",
"return",
"six",
".",
"binary_type",
"(",
"data",
")",
"events",
"=",
"self",
".",
"_filter_by_sample",
"(",
"self",
".",
"_multiplexer",
".",
"Tensors",
"(",
"run",
",",
"tag",
")",
",",
"sample",
")",
"images",
"=",
"events",
"[",
"index",
"]",
".",
"tensor_proto",
".",
"string_val",
"[",
"2",
":",
"]",
"# skip width, height",
"return",
"images",
"[",
"sample",
"]"
] | Returns the actual image bytes for a given image.
Args:
run: The name of the run the image belongs to.
tag: The name of the tag the images belongs to.
index: The index of the image in the current reservoir.
sample: The zero-indexed sample of the image to retrieve (for example,
setting `sample` to `2` will fetch the third image sample at `step`).
Returns:
A bytestring of the raw image bytes. | [
"Returns",
"the",
"actual",
"image",
"bytes",
"for",
"a",
"given",
"image",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/image/images_plugin.py#L266-L318 | train |
tensorflow/tensorboard | tensorboard/plugins/image/images_plugin.py | ImagesPlugin._serve_individual_image | def _serve_individual_image(self, request):
"""Serves an individual image."""
run = request.args.get('run')
tag = request.args.get('tag')
index = int(request.args.get('index'))
sample = int(request.args.get('sample', 0))
data = self._get_individual_image(run, tag, index, sample)
image_type = imghdr.what(None, data)
content_type = _IMGHDR_TO_MIMETYPE.get(image_type, _DEFAULT_IMAGE_MIMETYPE)
return http_util.Respond(request, data, content_type) | python | def _serve_individual_image(self, request):
"""Serves an individual image."""
run = request.args.get('run')
tag = request.args.get('tag')
index = int(request.args.get('index'))
sample = int(request.args.get('sample', 0))
data = self._get_individual_image(run, tag, index, sample)
image_type = imghdr.what(None, data)
content_type = _IMGHDR_TO_MIMETYPE.get(image_type, _DEFAULT_IMAGE_MIMETYPE)
return http_util.Respond(request, data, content_type) | [
"def",
"_serve_individual_image",
"(",
"self",
",",
"request",
")",
":",
"run",
"=",
"request",
".",
"args",
".",
"get",
"(",
"'run'",
")",
"tag",
"=",
"request",
".",
"args",
".",
"get",
"(",
"'tag'",
")",
"index",
"=",
"int",
"(",
"request",
".",
"args",
".",
"get",
"(",
"'index'",
")",
")",
"sample",
"=",
"int",
"(",
"request",
".",
"args",
".",
"get",
"(",
"'sample'",
",",
"0",
")",
")",
"data",
"=",
"self",
".",
"_get_individual_image",
"(",
"run",
",",
"tag",
",",
"index",
",",
"sample",
")",
"image_type",
"=",
"imghdr",
".",
"what",
"(",
"None",
",",
"data",
")",
"content_type",
"=",
"_IMGHDR_TO_MIMETYPE",
".",
"get",
"(",
"image_type",
",",
"_DEFAULT_IMAGE_MIMETYPE",
")",
"return",
"http_util",
".",
"Respond",
"(",
"request",
",",
"data",
",",
"content_type",
")"
] | Serves an individual image. | [
"Serves",
"an",
"individual",
"image",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/image/images_plugin.py#L321-L330 | train |
tensorflow/tensorboard | tensorboard/plugins/pr_curve/pr_curve_demo.py | start_runs | def start_runs(
logdir,
steps,
run_name,
thresholds,
mask_every_other_prediction=False):
"""Generate a PR curve with precision and recall evenly weighted.
Arguments:
logdir: The directory into which to store all the runs' data.
steps: The number of steps to run for.
run_name: The name of the run.
thresholds: The number of thresholds to use for PR curves.
mask_every_other_prediction: Whether to mask every other prediction by
alternating weights between 0 and 1.
"""
tf.compat.v1.reset_default_graph()
tf.compat.v1.set_random_seed(42)
# Create a normal distribution layer used to generate true color labels.
distribution = tf.compat.v1.distributions.Normal(loc=0., scale=142.)
# Sample the distribution to generate colors. Lets generate different numbers
# of each color. The first dimension is the count of examples.
# The calls to sample() are given fixed random seed values that are "magic"
# in that they correspond to the default seeds for those ops when the PR
# curve test (which depends on this code) was written. We've pinned these
# instead of continuing to use the defaults since the defaults are based on
# node IDs from the sequence of nodes added to the graph, which can silently
# change when this code or any TF op implementations it uses are modified.
# TODO(nickfelt): redo the PR curve test to avoid reliance on random seeds.
# Generate reds.
number_of_reds = 100
true_reds = tf.clip_by_value(
tf.concat([
255 - tf.abs(distribution.sample([number_of_reds, 1], seed=11)),
tf.abs(distribution.sample([number_of_reds, 2], seed=34))
], axis=1),
0, 255)
# Generate greens.
number_of_greens = 200
true_greens = tf.clip_by_value(
tf.concat([
tf.abs(distribution.sample([number_of_greens, 1], seed=61)),
255 - tf.abs(distribution.sample([number_of_greens, 1], seed=82)),
tf.abs(distribution.sample([number_of_greens, 1], seed=105))
], axis=1),
0, 255)
# Generate blues.
number_of_blues = 150
true_blues = tf.clip_by_value(
tf.concat([
tf.abs(distribution.sample([number_of_blues, 2], seed=132)),
255 - tf.abs(distribution.sample([number_of_blues, 1], seed=153))
], axis=1),
0, 255)
# Assign each color a vector of 3 booleans based on its true label.
labels = tf.concat([
tf.tile(tf.constant([[True, False, False]]), (number_of_reds, 1)),
tf.tile(tf.constant([[False, True, False]]), (number_of_greens, 1)),
tf.tile(tf.constant([[False, False, True]]), (number_of_blues, 1)),
], axis=0)
# We introduce 3 normal distributions. They are used to predict whether a
# color falls under a certain class (based on distances from corners of the
# color triangle). The distributions vary per color. We have the distributions
# narrow over time.
initial_standard_deviations = [v + FLAGS.steps for v in (158, 200, 242)]
iteration = tf.compat.v1.placeholder(tf.int32, shape=[])
red_predictor = tf.compat.v1.distributions.Normal(
loc=0.,
scale=tf.cast(
initial_standard_deviations[0] - iteration,
dtype=tf.float32))
green_predictor = tf.compat.v1.distributions.Normal(
loc=0.,
scale=tf.cast(
initial_standard_deviations[1] - iteration,
dtype=tf.float32))
blue_predictor = tf.compat.v1.distributions.Normal(
loc=0.,
scale=tf.cast(
initial_standard_deviations[2] - iteration,
dtype=tf.float32))
# Make predictions (assign 3 probabilities to each color based on each color's
# distance to each of the 3 corners). We seek double the area in the right
# tail of the normal distribution.
examples = tf.concat([true_reds, true_greens, true_blues], axis=0)
probabilities_colors_are_red = (1 - red_predictor.cdf(
tf.norm(tensor=examples - tf.constant([255., 0, 0]), axis=1))) * 2
probabilities_colors_are_green = (1 - green_predictor.cdf(
tf.norm(tensor=examples - tf.constant([0, 255., 0]), axis=1))) * 2
probabilities_colors_are_blue = (1 - blue_predictor.cdf(
tf.norm(tensor=examples - tf.constant([0, 0, 255.]), axis=1))) * 2
predictions = (
probabilities_colors_are_red,
probabilities_colors_are_green,
probabilities_colors_are_blue
)
# This is the crucial piece. We write data required for generating PR curves.
# We create 1 summary per class because we create 1 PR curve per class.
for i, color in enumerate(('red', 'green', 'blue')):
description = ('The probabilities used to create this PR curve are '
'generated from a normal distribution. Its standard '
'deviation is initially %0.0f and decreases over time.' %
initial_standard_deviations[i])
weights = None
if mask_every_other_prediction:
# Assign a weight of 0 to every even-indexed prediction. Odd-indexed
# predictions are assigned a default weight of 1.
consecutive_indices = tf.reshape(
tf.range(tf.size(input=predictions[i])), tf.shape(input=predictions[i]))
weights = tf.cast(consecutive_indices % 2, dtype=tf.float32)
summary.op(
name=color,
labels=labels[:, i],
predictions=predictions[i],
num_thresholds=thresholds,
weights=weights,
display_name='classifying %s' % color,
description=description)
merged_summary_op = tf.compat.v1.summary.merge_all()
events_directory = os.path.join(logdir, run_name)
sess = tf.compat.v1.Session()
writer = tf.compat.v1.summary.FileWriter(events_directory, sess.graph)
for step in xrange(steps):
feed_dict = {
iteration: step,
}
merged_summary = sess.run(merged_summary_op, feed_dict=feed_dict)
writer.add_summary(merged_summary, step)
writer.close() | python | def start_runs(
logdir,
steps,
run_name,
thresholds,
mask_every_other_prediction=False):
"""Generate a PR curve with precision and recall evenly weighted.
Arguments:
logdir: The directory into which to store all the runs' data.
steps: The number of steps to run for.
run_name: The name of the run.
thresholds: The number of thresholds to use for PR curves.
mask_every_other_prediction: Whether to mask every other prediction by
alternating weights between 0 and 1.
"""
tf.compat.v1.reset_default_graph()
tf.compat.v1.set_random_seed(42)
# Create a normal distribution layer used to generate true color labels.
distribution = tf.compat.v1.distributions.Normal(loc=0., scale=142.)
# Sample the distribution to generate colors. Lets generate different numbers
# of each color. The first dimension is the count of examples.
# The calls to sample() are given fixed random seed values that are "magic"
# in that they correspond to the default seeds for those ops when the PR
# curve test (which depends on this code) was written. We've pinned these
# instead of continuing to use the defaults since the defaults are based on
# node IDs from the sequence of nodes added to the graph, which can silently
# change when this code or any TF op implementations it uses are modified.
# TODO(nickfelt): redo the PR curve test to avoid reliance on random seeds.
# Generate reds.
number_of_reds = 100
true_reds = tf.clip_by_value(
tf.concat([
255 - tf.abs(distribution.sample([number_of_reds, 1], seed=11)),
tf.abs(distribution.sample([number_of_reds, 2], seed=34))
], axis=1),
0, 255)
# Generate greens.
number_of_greens = 200
true_greens = tf.clip_by_value(
tf.concat([
tf.abs(distribution.sample([number_of_greens, 1], seed=61)),
255 - tf.abs(distribution.sample([number_of_greens, 1], seed=82)),
tf.abs(distribution.sample([number_of_greens, 1], seed=105))
], axis=1),
0, 255)
# Generate blues.
number_of_blues = 150
true_blues = tf.clip_by_value(
tf.concat([
tf.abs(distribution.sample([number_of_blues, 2], seed=132)),
255 - tf.abs(distribution.sample([number_of_blues, 1], seed=153))
], axis=1),
0, 255)
# Assign each color a vector of 3 booleans based on its true label.
labels = tf.concat([
tf.tile(tf.constant([[True, False, False]]), (number_of_reds, 1)),
tf.tile(tf.constant([[False, True, False]]), (number_of_greens, 1)),
tf.tile(tf.constant([[False, False, True]]), (number_of_blues, 1)),
], axis=0)
# We introduce 3 normal distributions. They are used to predict whether a
# color falls under a certain class (based on distances from corners of the
# color triangle). The distributions vary per color. We have the distributions
# narrow over time.
initial_standard_deviations = [v + FLAGS.steps for v in (158, 200, 242)]
iteration = tf.compat.v1.placeholder(tf.int32, shape=[])
red_predictor = tf.compat.v1.distributions.Normal(
loc=0.,
scale=tf.cast(
initial_standard_deviations[0] - iteration,
dtype=tf.float32))
green_predictor = tf.compat.v1.distributions.Normal(
loc=0.,
scale=tf.cast(
initial_standard_deviations[1] - iteration,
dtype=tf.float32))
blue_predictor = tf.compat.v1.distributions.Normal(
loc=0.,
scale=tf.cast(
initial_standard_deviations[2] - iteration,
dtype=tf.float32))
# Make predictions (assign 3 probabilities to each color based on each color's
# distance to each of the 3 corners). We seek double the area in the right
# tail of the normal distribution.
examples = tf.concat([true_reds, true_greens, true_blues], axis=0)
probabilities_colors_are_red = (1 - red_predictor.cdf(
tf.norm(tensor=examples - tf.constant([255., 0, 0]), axis=1))) * 2
probabilities_colors_are_green = (1 - green_predictor.cdf(
tf.norm(tensor=examples - tf.constant([0, 255., 0]), axis=1))) * 2
probabilities_colors_are_blue = (1 - blue_predictor.cdf(
tf.norm(tensor=examples - tf.constant([0, 0, 255.]), axis=1))) * 2
predictions = (
probabilities_colors_are_red,
probabilities_colors_are_green,
probabilities_colors_are_blue
)
# This is the crucial piece. We write data required for generating PR curves.
# We create 1 summary per class because we create 1 PR curve per class.
for i, color in enumerate(('red', 'green', 'blue')):
description = ('The probabilities used to create this PR curve are '
'generated from a normal distribution. Its standard '
'deviation is initially %0.0f and decreases over time.' %
initial_standard_deviations[i])
weights = None
if mask_every_other_prediction:
# Assign a weight of 0 to every even-indexed prediction. Odd-indexed
# predictions are assigned a default weight of 1.
consecutive_indices = tf.reshape(
tf.range(tf.size(input=predictions[i])), tf.shape(input=predictions[i]))
weights = tf.cast(consecutive_indices % 2, dtype=tf.float32)
summary.op(
name=color,
labels=labels[:, i],
predictions=predictions[i],
num_thresholds=thresholds,
weights=weights,
display_name='classifying %s' % color,
description=description)
merged_summary_op = tf.compat.v1.summary.merge_all()
events_directory = os.path.join(logdir, run_name)
sess = tf.compat.v1.Session()
writer = tf.compat.v1.summary.FileWriter(events_directory, sess.graph)
for step in xrange(steps):
feed_dict = {
iteration: step,
}
merged_summary = sess.run(merged_summary_op, feed_dict=feed_dict)
writer.add_summary(merged_summary, step)
writer.close() | [
"def",
"start_runs",
"(",
"logdir",
",",
"steps",
",",
"run_name",
",",
"thresholds",
",",
"mask_every_other_prediction",
"=",
"False",
")",
":",
"tf",
".",
"compat",
".",
"v1",
".",
"reset_default_graph",
"(",
")",
"tf",
".",
"compat",
".",
"v1",
".",
"set_random_seed",
"(",
"42",
")",
"# Create a normal distribution layer used to generate true color labels.",
"distribution",
"=",
"tf",
".",
"compat",
".",
"v1",
".",
"distributions",
".",
"Normal",
"(",
"loc",
"=",
"0.",
",",
"scale",
"=",
"142.",
")",
"# Sample the distribution to generate colors. Lets generate different numbers",
"# of each color. The first dimension is the count of examples.",
"# The calls to sample() are given fixed random seed values that are \"magic\"",
"# in that they correspond to the default seeds for those ops when the PR",
"# curve test (which depends on this code) was written. We've pinned these",
"# instead of continuing to use the defaults since the defaults are based on",
"# node IDs from the sequence of nodes added to the graph, which can silently",
"# change when this code or any TF op implementations it uses are modified.",
"# TODO(nickfelt): redo the PR curve test to avoid reliance on random seeds.",
"# Generate reds.",
"number_of_reds",
"=",
"100",
"true_reds",
"=",
"tf",
".",
"clip_by_value",
"(",
"tf",
".",
"concat",
"(",
"[",
"255",
"-",
"tf",
".",
"abs",
"(",
"distribution",
".",
"sample",
"(",
"[",
"number_of_reds",
",",
"1",
"]",
",",
"seed",
"=",
"11",
")",
")",
",",
"tf",
".",
"abs",
"(",
"distribution",
".",
"sample",
"(",
"[",
"number_of_reds",
",",
"2",
"]",
",",
"seed",
"=",
"34",
")",
")",
"]",
",",
"axis",
"=",
"1",
")",
",",
"0",
",",
"255",
")",
"# Generate greens.",
"number_of_greens",
"=",
"200",
"true_greens",
"=",
"tf",
".",
"clip_by_value",
"(",
"tf",
".",
"concat",
"(",
"[",
"tf",
".",
"abs",
"(",
"distribution",
".",
"sample",
"(",
"[",
"number_of_greens",
",",
"1",
"]",
",",
"seed",
"=",
"61",
")",
")",
",",
"255",
"-",
"tf",
".",
"abs",
"(",
"distribution",
".",
"sample",
"(",
"[",
"number_of_greens",
",",
"1",
"]",
",",
"seed",
"=",
"82",
")",
")",
",",
"tf",
".",
"abs",
"(",
"distribution",
".",
"sample",
"(",
"[",
"number_of_greens",
",",
"1",
"]",
",",
"seed",
"=",
"105",
")",
")",
"]",
",",
"axis",
"=",
"1",
")",
",",
"0",
",",
"255",
")",
"# Generate blues.",
"number_of_blues",
"=",
"150",
"true_blues",
"=",
"tf",
".",
"clip_by_value",
"(",
"tf",
".",
"concat",
"(",
"[",
"tf",
".",
"abs",
"(",
"distribution",
".",
"sample",
"(",
"[",
"number_of_blues",
",",
"2",
"]",
",",
"seed",
"=",
"132",
")",
")",
",",
"255",
"-",
"tf",
".",
"abs",
"(",
"distribution",
".",
"sample",
"(",
"[",
"number_of_blues",
",",
"1",
"]",
",",
"seed",
"=",
"153",
")",
")",
"]",
",",
"axis",
"=",
"1",
")",
",",
"0",
",",
"255",
")",
"# Assign each color a vector of 3 booleans based on its true label.",
"labels",
"=",
"tf",
".",
"concat",
"(",
"[",
"tf",
".",
"tile",
"(",
"tf",
".",
"constant",
"(",
"[",
"[",
"True",
",",
"False",
",",
"False",
"]",
"]",
")",
",",
"(",
"number_of_reds",
",",
"1",
")",
")",
",",
"tf",
".",
"tile",
"(",
"tf",
".",
"constant",
"(",
"[",
"[",
"False",
",",
"True",
",",
"False",
"]",
"]",
")",
",",
"(",
"number_of_greens",
",",
"1",
")",
")",
",",
"tf",
".",
"tile",
"(",
"tf",
".",
"constant",
"(",
"[",
"[",
"False",
",",
"False",
",",
"True",
"]",
"]",
")",
",",
"(",
"number_of_blues",
",",
"1",
")",
")",
",",
"]",
",",
"axis",
"=",
"0",
")",
"# We introduce 3 normal distributions. They are used to predict whether a",
"# color falls under a certain class (based on distances from corners of the",
"# color triangle). The distributions vary per color. We have the distributions",
"# narrow over time.",
"initial_standard_deviations",
"=",
"[",
"v",
"+",
"FLAGS",
".",
"steps",
"for",
"v",
"in",
"(",
"158",
",",
"200",
",",
"242",
")",
"]",
"iteration",
"=",
"tf",
".",
"compat",
".",
"v1",
".",
"placeholder",
"(",
"tf",
".",
"int32",
",",
"shape",
"=",
"[",
"]",
")",
"red_predictor",
"=",
"tf",
".",
"compat",
".",
"v1",
".",
"distributions",
".",
"Normal",
"(",
"loc",
"=",
"0.",
",",
"scale",
"=",
"tf",
".",
"cast",
"(",
"initial_standard_deviations",
"[",
"0",
"]",
"-",
"iteration",
",",
"dtype",
"=",
"tf",
".",
"float32",
")",
")",
"green_predictor",
"=",
"tf",
".",
"compat",
".",
"v1",
".",
"distributions",
".",
"Normal",
"(",
"loc",
"=",
"0.",
",",
"scale",
"=",
"tf",
".",
"cast",
"(",
"initial_standard_deviations",
"[",
"1",
"]",
"-",
"iteration",
",",
"dtype",
"=",
"tf",
".",
"float32",
")",
")",
"blue_predictor",
"=",
"tf",
".",
"compat",
".",
"v1",
".",
"distributions",
".",
"Normal",
"(",
"loc",
"=",
"0.",
",",
"scale",
"=",
"tf",
".",
"cast",
"(",
"initial_standard_deviations",
"[",
"2",
"]",
"-",
"iteration",
",",
"dtype",
"=",
"tf",
".",
"float32",
")",
")",
"# Make predictions (assign 3 probabilities to each color based on each color's",
"# distance to each of the 3 corners). We seek double the area in the right",
"# tail of the normal distribution.",
"examples",
"=",
"tf",
".",
"concat",
"(",
"[",
"true_reds",
",",
"true_greens",
",",
"true_blues",
"]",
",",
"axis",
"=",
"0",
")",
"probabilities_colors_are_red",
"=",
"(",
"1",
"-",
"red_predictor",
".",
"cdf",
"(",
"tf",
".",
"norm",
"(",
"tensor",
"=",
"examples",
"-",
"tf",
".",
"constant",
"(",
"[",
"255.",
",",
"0",
",",
"0",
"]",
")",
",",
"axis",
"=",
"1",
")",
")",
")",
"*",
"2",
"probabilities_colors_are_green",
"=",
"(",
"1",
"-",
"green_predictor",
".",
"cdf",
"(",
"tf",
".",
"norm",
"(",
"tensor",
"=",
"examples",
"-",
"tf",
".",
"constant",
"(",
"[",
"0",
",",
"255.",
",",
"0",
"]",
")",
",",
"axis",
"=",
"1",
")",
")",
")",
"*",
"2",
"probabilities_colors_are_blue",
"=",
"(",
"1",
"-",
"blue_predictor",
".",
"cdf",
"(",
"tf",
".",
"norm",
"(",
"tensor",
"=",
"examples",
"-",
"tf",
".",
"constant",
"(",
"[",
"0",
",",
"0",
",",
"255.",
"]",
")",
",",
"axis",
"=",
"1",
")",
")",
")",
"*",
"2",
"predictions",
"=",
"(",
"probabilities_colors_are_red",
",",
"probabilities_colors_are_green",
",",
"probabilities_colors_are_blue",
")",
"# This is the crucial piece. We write data required for generating PR curves.",
"# We create 1 summary per class because we create 1 PR curve per class.",
"for",
"i",
",",
"color",
"in",
"enumerate",
"(",
"(",
"'red'",
",",
"'green'",
",",
"'blue'",
")",
")",
":",
"description",
"=",
"(",
"'The probabilities used to create this PR curve are '",
"'generated from a normal distribution. Its standard '",
"'deviation is initially %0.0f and decreases over time.'",
"%",
"initial_standard_deviations",
"[",
"i",
"]",
")",
"weights",
"=",
"None",
"if",
"mask_every_other_prediction",
":",
"# Assign a weight of 0 to every even-indexed prediction. Odd-indexed",
"# predictions are assigned a default weight of 1.",
"consecutive_indices",
"=",
"tf",
".",
"reshape",
"(",
"tf",
".",
"range",
"(",
"tf",
".",
"size",
"(",
"input",
"=",
"predictions",
"[",
"i",
"]",
")",
")",
",",
"tf",
".",
"shape",
"(",
"input",
"=",
"predictions",
"[",
"i",
"]",
")",
")",
"weights",
"=",
"tf",
".",
"cast",
"(",
"consecutive_indices",
"%",
"2",
",",
"dtype",
"=",
"tf",
".",
"float32",
")",
"summary",
".",
"op",
"(",
"name",
"=",
"color",
",",
"labels",
"=",
"labels",
"[",
":",
",",
"i",
"]",
",",
"predictions",
"=",
"predictions",
"[",
"i",
"]",
",",
"num_thresholds",
"=",
"thresholds",
",",
"weights",
"=",
"weights",
",",
"display_name",
"=",
"'classifying %s'",
"%",
"color",
",",
"description",
"=",
"description",
")",
"merged_summary_op",
"=",
"tf",
".",
"compat",
".",
"v1",
".",
"summary",
".",
"merge_all",
"(",
")",
"events_directory",
"=",
"os",
".",
"path",
".",
"join",
"(",
"logdir",
",",
"run_name",
")",
"sess",
"=",
"tf",
".",
"compat",
".",
"v1",
".",
"Session",
"(",
")",
"writer",
"=",
"tf",
".",
"compat",
".",
"v1",
".",
"summary",
".",
"FileWriter",
"(",
"events_directory",
",",
"sess",
".",
"graph",
")",
"for",
"step",
"in",
"xrange",
"(",
"steps",
")",
":",
"feed_dict",
"=",
"{",
"iteration",
":",
"step",
",",
"}",
"merged_summary",
"=",
"sess",
".",
"run",
"(",
"merged_summary_op",
",",
"feed_dict",
"=",
"feed_dict",
")",
"writer",
".",
"add_summary",
"(",
"merged_summary",
",",
"step",
")",
"writer",
".",
"close",
"(",
")"
] | Generate a PR curve with precision and recall evenly weighted.
Arguments:
logdir: The directory into which to store all the runs' data.
steps: The number of steps to run for.
run_name: The name of the run.
thresholds: The number of thresholds to use for PR curves.
mask_every_other_prediction: Whether to mask every other prediction by
alternating weights between 0 and 1. | [
"Generate",
"a",
"PR",
"curve",
"with",
"precision",
"and",
"recall",
"evenly",
"weighted",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/pr_curve/pr_curve_demo.py#L51-L195 | train |
tensorflow/tensorboard | tensorboard/plugins/pr_curve/pr_curve_demo.py | run_all | def run_all(logdir, steps, thresholds, verbose=False):
"""Generate PR curve summaries.
Arguments:
logdir: The directory into which to store all the runs' data.
steps: The number of steps to run for.
verbose: Whether to print the names of runs into stdout during execution.
thresholds: The number of thresholds to use for PR curves.
"""
# First, we generate data for a PR curve that assigns even weights for
# predictions of all classes.
run_name = 'colors'
if verbose:
print('--- Running: %s' % run_name)
start_runs(
logdir=logdir,
steps=steps,
run_name=run_name,
thresholds=thresholds)
# Next, we generate data for a PR curve that assigns arbitrary weights to
# predictions.
run_name = 'mask_every_other_prediction'
if verbose:
print('--- Running: %s' % run_name)
start_runs(
logdir=logdir,
steps=steps,
run_name=run_name,
thresholds=thresholds,
mask_every_other_prediction=True) | python | def run_all(logdir, steps, thresholds, verbose=False):
"""Generate PR curve summaries.
Arguments:
logdir: The directory into which to store all the runs' data.
steps: The number of steps to run for.
verbose: Whether to print the names of runs into stdout during execution.
thresholds: The number of thresholds to use for PR curves.
"""
# First, we generate data for a PR curve that assigns even weights for
# predictions of all classes.
run_name = 'colors'
if verbose:
print('--- Running: %s' % run_name)
start_runs(
logdir=logdir,
steps=steps,
run_name=run_name,
thresholds=thresholds)
# Next, we generate data for a PR curve that assigns arbitrary weights to
# predictions.
run_name = 'mask_every_other_prediction'
if verbose:
print('--- Running: %s' % run_name)
start_runs(
logdir=logdir,
steps=steps,
run_name=run_name,
thresholds=thresholds,
mask_every_other_prediction=True) | [
"def",
"run_all",
"(",
"logdir",
",",
"steps",
",",
"thresholds",
",",
"verbose",
"=",
"False",
")",
":",
"# First, we generate data for a PR curve that assigns even weights for",
"# predictions of all classes.",
"run_name",
"=",
"'colors'",
"if",
"verbose",
":",
"print",
"(",
"'--- Running: %s'",
"%",
"run_name",
")",
"start_runs",
"(",
"logdir",
"=",
"logdir",
",",
"steps",
"=",
"steps",
",",
"run_name",
"=",
"run_name",
",",
"thresholds",
"=",
"thresholds",
")",
"# Next, we generate data for a PR curve that assigns arbitrary weights to",
"# predictions.",
"run_name",
"=",
"'mask_every_other_prediction'",
"if",
"verbose",
":",
"print",
"(",
"'--- Running: %s'",
"%",
"run_name",
")",
"start_runs",
"(",
"logdir",
"=",
"logdir",
",",
"steps",
"=",
"steps",
",",
"run_name",
"=",
"run_name",
",",
"thresholds",
"=",
"thresholds",
",",
"mask_every_other_prediction",
"=",
"True",
")"
] | Generate PR curve summaries.
Arguments:
logdir: The directory into which to store all the runs' data.
steps: The number of steps to run for.
verbose: Whether to print the names of runs into stdout during execution.
thresholds: The number of thresholds to use for PR curves. | [
"Generate",
"PR",
"curve",
"summaries",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/pr_curve/pr_curve_demo.py#L197-L227 | train |
tensorflow/tensorboard | tensorboard/plugins/image/summary_v2.py | image | def image(name,
data,
step=None,
max_outputs=3,
description=None):
"""Write an image summary.
Arguments:
name: A name for this summary. The summary tag used for TensorBoard will
be this name prefixed by any active name scopes.
data: A `Tensor` representing pixel data with shape `[k, h, w, c]`,
where `k` is the number of images, `h` and `w` are the height and
width of the images, and `c` is the number of channels, which
should be 1, 2, 3, or 4 (grayscale, grayscale with alpha, RGB, RGBA).
Any of the dimensions may be statically unknown (i.e., `None`).
Floating point data will be clipped to the range [0,1).
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.
max_outputs: Optional `int` or rank-0 integer `Tensor`. At most this
many images will be emitted at each step. When more than
`max_outputs` many images are provided, the first `max_outputs` many
images will be used and the rest silently discarded.
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.
"""
summary_metadata = metadata.create_summary_metadata(
display_name=None, description=description)
# TODO(https://github.com/tensorflow/tensorboard/issues/2109): remove fallback
summary_scope = (
getattr(tf.summary.experimental, 'summary_scope', None) or
tf.summary.summary_scope)
with summary_scope(
name, 'image_summary', values=[data, max_outputs, step]) as (tag, _):
tf.debugging.assert_rank(data, 4)
tf.debugging.assert_non_negative(max_outputs)
images = tf.image.convert_image_dtype(data, tf.uint8, saturate=True)
limited_images = images[:max_outputs]
encoded_images = tf.map_fn(tf.image.encode_png, limited_images,
dtype=tf.string,
name='encode_each_image')
# Workaround for map_fn returning float dtype for an empty elems input.
encoded_images = tf.cond(
tf.shape(input=encoded_images)[0] > 0,
lambda: encoded_images, lambda: tf.constant([], tf.string))
image_shape = tf.shape(input=images)
dimensions = tf.stack([tf.as_string(image_shape[2], name='width'),
tf.as_string(image_shape[1], name='height')],
name='dimensions')
tensor = tf.concat([dimensions, encoded_images], axis=0)
return tf.summary.write(
tag=tag, tensor=tensor, step=step, metadata=summary_metadata) | python | def image(name,
data,
step=None,
max_outputs=3,
description=None):
"""Write an image summary.
Arguments:
name: A name for this summary. The summary tag used for TensorBoard will
be this name prefixed by any active name scopes.
data: A `Tensor` representing pixel data with shape `[k, h, w, c]`,
where `k` is the number of images, `h` and `w` are the height and
width of the images, and `c` is the number of channels, which
should be 1, 2, 3, or 4 (grayscale, grayscale with alpha, RGB, RGBA).
Any of the dimensions may be statically unknown (i.e., `None`).
Floating point data will be clipped to the range [0,1).
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.
max_outputs: Optional `int` or rank-0 integer `Tensor`. At most this
many images will be emitted at each step. When more than
`max_outputs` many images are provided, the first `max_outputs` many
images will be used and the rest silently discarded.
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.
"""
summary_metadata = metadata.create_summary_metadata(
display_name=None, description=description)
# TODO(https://github.com/tensorflow/tensorboard/issues/2109): remove fallback
summary_scope = (
getattr(tf.summary.experimental, 'summary_scope', None) or
tf.summary.summary_scope)
with summary_scope(
name, 'image_summary', values=[data, max_outputs, step]) as (tag, _):
tf.debugging.assert_rank(data, 4)
tf.debugging.assert_non_negative(max_outputs)
images = tf.image.convert_image_dtype(data, tf.uint8, saturate=True)
limited_images = images[:max_outputs]
encoded_images = tf.map_fn(tf.image.encode_png, limited_images,
dtype=tf.string,
name='encode_each_image')
# Workaround for map_fn returning float dtype for an empty elems input.
encoded_images = tf.cond(
tf.shape(input=encoded_images)[0] > 0,
lambda: encoded_images, lambda: tf.constant([], tf.string))
image_shape = tf.shape(input=images)
dimensions = tf.stack([tf.as_string(image_shape[2], name='width'),
tf.as_string(image_shape[1], name='height')],
name='dimensions')
tensor = tf.concat([dimensions, encoded_images], axis=0)
return tf.summary.write(
tag=tag, tensor=tensor, step=step, metadata=summary_metadata) | [
"def",
"image",
"(",
"name",
",",
"data",
",",
"step",
"=",
"None",
",",
"max_outputs",
"=",
"3",
",",
"description",
"=",
"None",
")",
":",
"summary_metadata",
"=",
"metadata",
".",
"create_summary_metadata",
"(",
"display_name",
"=",
"None",
",",
"description",
"=",
"description",
")",
"# TODO(https://github.com/tensorflow/tensorboard/issues/2109): remove fallback",
"summary_scope",
"=",
"(",
"getattr",
"(",
"tf",
".",
"summary",
".",
"experimental",
",",
"'summary_scope'",
",",
"None",
")",
"or",
"tf",
".",
"summary",
".",
"summary_scope",
")",
"with",
"summary_scope",
"(",
"name",
",",
"'image_summary'",
",",
"values",
"=",
"[",
"data",
",",
"max_outputs",
",",
"step",
"]",
")",
"as",
"(",
"tag",
",",
"_",
")",
":",
"tf",
".",
"debugging",
".",
"assert_rank",
"(",
"data",
",",
"4",
")",
"tf",
".",
"debugging",
".",
"assert_non_negative",
"(",
"max_outputs",
")",
"images",
"=",
"tf",
".",
"image",
".",
"convert_image_dtype",
"(",
"data",
",",
"tf",
".",
"uint8",
",",
"saturate",
"=",
"True",
")",
"limited_images",
"=",
"images",
"[",
":",
"max_outputs",
"]",
"encoded_images",
"=",
"tf",
".",
"map_fn",
"(",
"tf",
".",
"image",
".",
"encode_png",
",",
"limited_images",
",",
"dtype",
"=",
"tf",
".",
"string",
",",
"name",
"=",
"'encode_each_image'",
")",
"# Workaround for map_fn returning float dtype for an empty elems input.",
"encoded_images",
"=",
"tf",
".",
"cond",
"(",
"tf",
".",
"shape",
"(",
"input",
"=",
"encoded_images",
")",
"[",
"0",
"]",
">",
"0",
",",
"lambda",
":",
"encoded_images",
",",
"lambda",
":",
"tf",
".",
"constant",
"(",
"[",
"]",
",",
"tf",
".",
"string",
")",
")",
"image_shape",
"=",
"tf",
".",
"shape",
"(",
"input",
"=",
"images",
")",
"dimensions",
"=",
"tf",
".",
"stack",
"(",
"[",
"tf",
".",
"as_string",
"(",
"image_shape",
"[",
"2",
"]",
",",
"name",
"=",
"'width'",
")",
",",
"tf",
".",
"as_string",
"(",
"image_shape",
"[",
"1",
"]",
",",
"name",
"=",
"'height'",
")",
"]",
",",
"name",
"=",
"'dimensions'",
")",
"tensor",
"=",
"tf",
".",
"concat",
"(",
"[",
"dimensions",
",",
"encoded_images",
"]",
",",
"axis",
"=",
"0",
")",
"return",
"tf",
".",
"summary",
".",
"write",
"(",
"tag",
"=",
"tag",
",",
"tensor",
"=",
"tensor",
",",
"step",
"=",
"step",
",",
"metadata",
"=",
"summary_metadata",
")"
] | Write an image summary.
Arguments:
name: A name for this summary. The summary tag used for TensorBoard will
be this name prefixed by any active name scopes.
data: A `Tensor` representing pixel data with shape `[k, h, w, c]`,
where `k` is the number of images, `h` and `w` are the height and
width of the images, and `c` is the number of channels, which
should be 1, 2, 3, or 4 (grayscale, grayscale with alpha, RGB, RGBA).
Any of the dimensions may be statically unknown (i.e., `None`).
Floating point data will be clipped to the range [0,1).
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.
max_outputs: Optional `int` or rank-0 integer `Tensor`. At most this
many images will be emitted at each step. When more than
`max_outputs` many images are provided, the first `max_outputs` many
images will be used and the rest silently discarded.
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. | [
"Write",
"an",
"image",
"summary",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/image/summary_v2.py#L29-L88 | train |
tensorflow/tensorboard | tensorboard/plugins/interactive_inference/witwidget/notebook/visualization.py | WitConfigBuilder.set_examples | def set_examples(self, examples):
"""Sets the examples to be displayed in WIT.
Args:
examples: List of example protos.
Returns:
self, in order to enabled method chaining.
"""
self.store('examples', examples)
if len(examples) > 0:
self.store('are_sequence_examples',
isinstance(examples[0], tf.train.SequenceExample))
return self | python | def set_examples(self, examples):
"""Sets the examples to be displayed in WIT.
Args:
examples: List of example protos.
Returns:
self, in order to enabled method chaining.
"""
self.store('examples', examples)
if len(examples) > 0:
self.store('are_sequence_examples',
isinstance(examples[0], tf.train.SequenceExample))
return self | [
"def",
"set_examples",
"(",
"self",
",",
"examples",
")",
":",
"self",
".",
"store",
"(",
"'examples'",
",",
"examples",
")",
"if",
"len",
"(",
"examples",
")",
">",
"0",
":",
"self",
".",
"store",
"(",
"'are_sequence_examples'",
",",
"isinstance",
"(",
"examples",
"[",
"0",
"]",
",",
"tf",
".",
"train",
".",
"SequenceExample",
")",
")",
"return",
"self"
] | Sets the examples to be displayed in WIT.
Args:
examples: List of example protos.
Returns:
self, in order to enabled method chaining. | [
"Sets",
"the",
"examples",
"to",
"be",
"displayed",
"in",
"WIT",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/interactive_inference/witwidget/notebook/visualization.py#L62-L75 | train |
tensorflow/tensorboard | tensorboard/plugins/interactive_inference/witwidget/notebook/visualization.py | WitConfigBuilder.set_estimator_and_feature_spec | def set_estimator_and_feature_spec(self, estimator, feature_spec):
"""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.
"""
# If custom function is set, remove it before setting estimator
self.delete('custom_predict_fn')
self.store('estimator_and_spec', {
'estimator': estimator, 'feature_spec': feature_spec})
self.set_inference_address('estimator')
# If no model name has been set, give a default
if not self.has_model_name():
self.set_model_name('1')
return self | python | def set_estimator_and_feature_spec(self, estimator, feature_spec):
"""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.
"""
# If custom function is set, remove it before setting estimator
self.delete('custom_predict_fn')
self.store('estimator_and_spec', {
'estimator': estimator, 'feature_spec': feature_spec})
self.set_inference_address('estimator')
# If no model name has been set, give a default
if not self.has_model_name():
self.set_model_name('1')
return self | [
"def",
"set_estimator_and_feature_spec",
"(",
"self",
",",
"estimator",
",",
"feature_spec",
")",
":",
"# If custom function is set, remove it before setting estimator",
"self",
".",
"delete",
"(",
"'custom_predict_fn'",
")",
"self",
".",
"store",
"(",
"'estimator_and_spec'",
",",
"{",
"'estimator'",
":",
"estimator",
",",
"'feature_spec'",
":",
"feature_spec",
"}",
")",
"self",
".",
"set_inference_address",
"(",
"'estimator'",
")",
"# If no model name has been set, give a default",
"if",
"not",
"self",
".",
"has_model_name",
"(",
")",
":",
"self",
".",
"set_model_name",
"(",
"'1'",
")",
"return",
"self"
] | 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. | [
"Sets",
"the",
"model",
"for",
"inference",
"as",
"a",
"TF",
"Estimator",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/interactive_inference/witwidget/notebook/visualization.py#L327-L352 | train |
tensorflow/tensorboard | tensorboard/plugins/interactive_inference/witwidget/notebook/visualization.py | WitConfigBuilder.set_compare_estimator_and_feature_spec | def set_compare_estimator_and_feature_spec(self, estimator, feature_spec):
"""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.
"""
# If custom function is set, remove it before setting estimator
self.delete('compare_custom_predict_fn')
self.store('compare_estimator_and_spec', {
'estimator': estimator, 'feature_spec': feature_spec})
self.set_compare_inference_address('estimator')
# If no model name has been set, give a default
if not self.has_compare_model_name():
self.set_compare_model_name('2')
return self | python | def set_compare_estimator_and_feature_spec(self, estimator, feature_spec):
"""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.
"""
# If custom function is set, remove it before setting estimator
self.delete('compare_custom_predict_fn')
self.store('compare_estimator_and_spec', {
'estimator': estimator, 'feature_spec': feature_spec})
self.set_compare_inference_address('estimator')
# If no model name has been set, give a default
if not self.has_compare_model_name():
self.set_compare_model_name('2')
return self | [
"def",
"set_compare_estimator_and_feature_spec",
"(",
"self",
",",
"estimator",
",",
"feature_spec",
")",
":",
"# If custom function is set, remove it before setting estimator",
"self",
".",
"delete",
"(",
"'compare_custom_predict_fn'",
")",
"self",
".",
"store",
"(",
"'compare_estimator_and_spec'",
",",
"{",
"'estimator'",
":",
"estimator",
",",
"'feature_spec'",
":",
"feature_spec",
"}",
")",
"self",
".",
"set_compare_inference_address",
"(",
"'estimator'",
")",
"# If no model name has been set, give a default",
"if",
"not",
"self",
".",
"has_compare_model_name",
"(",
")",
":",
"self",
".",
"set_compare_model_name",
"(",
"'2'",
")",
"return",
"self"
] | 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. | [
"Sets",
"a",
"second",
"model",
"for",
"inference",
"as",
"a",
"TF",
"Estimator",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/interactive_inference/witwidget/notebook/visualization.py#L354-L382 | train |
tensorflow/tensorboard | tensorboard/plugins/interactive_inference/witwidget/notebook/visualization.py | WitConfigBuilder.set_custom_predict_fn | def set_custom_predict_fn(self, predict_fn):
"""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.
"""
# If estimator is set, remove it before setting predict_fn
self.delete('estimator_and_spec')
self.store('custom_predict_fn', predict_fn)
self.set_inference_address('custom_predict_fn')
# If no model name has been set, give a default
if not self.has_model_name():
self.set_model_name('1')
return self | python | def set_custom_predict_fn(self, predict_fn):
"""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.
"""
# If estimator is set, remove it before setting predict_fn
self.delete('estimator_and_spec')
self.store('custom_predict_fn', predict_fn)
self.set_inference_address('custom_predict_fn')
# If no model name has been set, give a default
if not self.has_model_name():
self.set_model_name('1')
return self | [
"def",
"set_custom_predict_fn",
"(",
"self",
",",
"predict_fn",
")",
":",
"# If estimator is set, remove it before setting predict_fn",
"self",
".",
"delete",
"(",
"'estimator_and_spec'",
")",
"self",
".",
"store",
"(",
"'custom_predict_fn'",
",",
"predict_fn",
")",
"self",
".",
"set_inference_address",
"(",
"'custom_predict_fn'",
")",
"# If no model name has been set, give a default",
"if",
"not",
"self",
".",
"has_model_name",
"(",
")",
":",
"self",
".",
"set_model_name",
"(",
"'1'",
")",
"return",
"self"
] | 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. | [
"Sets",
"a",
"custom",
"function",
"for",
"inference",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/interactive_inference/witwidget/notebook/visualization.py#L384-L411 | train |
tensorflow/tensorboard | tensorboard/plugins/interactive_inference/witwidget/notebook/visualization.py | WitConfigBuilder.set_compare_custom_predict_fn | def set_compare_custom_predict_fn(self, predict_fn):
"""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.
"""
# If estimator is set, remove it before setting predict_fn
self.delete('compare_estimator_and_spec')
self.store('compare_custom_predict_fn', predict_fn)
self.set_compare_inference_address('custom_predict_fn')
# If no model name has been set, give a default
if not self.has_compare_model_name():
self.set_compare_model_name('2')
return self | python | def set_compare_custom_predict_fn(self, predict_fn):
"""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.
"""
# If estimator is set, remove it before setting predict_fn
self.delete('compare_estimator_and_spec')
self.store('compare_custom_predict_fn', predict_fn)
self.set_compare_inference_address('custom_predict_fn')
# If no model name has been set, give a default
if not self.has_compare_model_name():
self.set_compare_model_name('2')
return self | [
"def",
"set_compare_custom_predict_fn",
"(",
"self",
",",
"predict_fn",
")",
":",
"# If estimator is set, remove it before setting predict_fn",
"self",
".",
"delete",
"(",
"'compare_estimator_and_spec'",
")",
"self",
".",
"store",
"(",
"'compare_custom_predict_fn'",
",",
"predict_fn",
")",
"self",
".",
"set_compare_inference_address",
"(",
"'custom_predict_fn'",
")",
"# If no model name has been set, give a default",
"if",
"not",
"self",
".",
"has_compare_model_name",
"(",
")",
":",
"self",
".",
"set_compare_model_name",
"(",
"'2'",
")",
"return",
"self"
] | 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. | [
"Sets",
"a",
"second",
"custom",
"function",
"for",
"inference",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/interactive_inference/witwidget/notebook/visualization.py#L413-L443 | train |
tensorflow/tensorboard | tensorboard/plugins/beholder/visualizer.py | Visualizer._reshape_conv_array | def _reshape_conv_array(self, array, section_height, image_width):
'''Reshape a rank 4 array to be rank 2, where each column of block_width is
a filter, and each row of block height is an input channel. For example:
[[[[ 11, 21, 31, 41],
[ 51, 61, 71, 81],
[ 91, 101, 111, 121]],
[[ 12, 22, 32, 42],
[ 52, 62, 72, 82],
[ 92, 102, 112, 122]],
[[ 13, 23, 33, 43],
[ 53, 63, 73, 83],
[ 93, 103, 113, 123]]],
[[[ 14, 24, 34, 44],
[ 54, 64, 74, 84],
[ 94, 104, 114, 124]],
[[ 15, 25, 35, 45],
[ 55, 65, 75, 85],
[ 95, 105, 115, 125]],
[[ 16, 26, 36, 46],
[ 56, 66, 76, 86],
[ 96, 106, 116, 126]]],
[[[ 17, 27, 37, 47],
[ 57, 67, 77, 87],
[ 97, 107, 117, 127]],
[[ 18, 28, 38, 48],
[ 58, 68, 78, 88],
[ 98, 108, 118, 128]],
[[ 19, 29, 39, 49],
[ 59, 69, 79, 89],
[ 99, 109, 119, 129]]]]
should be reshaped to:
[[ 11, 12, 13, 21, 22, 23, 31, 32, 33, 41, 42, 43],
[ 14, 15, 16, 24, 25, 26, 34, 35, 36, 44, 45, 46],
[ 17, 18, 19, 27, 28, 29, 37, 38, 39, 47, 48, 49],
[ 51, 52, 53, 61, 62, 63, 71, 72, 73, 81, 82, 83],
[ 54, 55, 56, 64, 65, 66, 74, 75, 76, 84, 85, 86],
[ 57, 58, 59, 67, 68, 69, 77, 78, 79, 87, 88, 89],
[ 91, 92, 93, 101, 102, 103, 111, 112, 113, 121, 122, 123],
[ 94, 95, 96, 104, 105, 106, 114, 115, 116, 124, 125, 126],
[ 97, 98, 99, 107, 108, 109, 117, 118, 119, 127, 128, 129]]
'''
# E.g. [100, 24, 24, 10]: this shouldn't be reshaped like normal.
if array.shape[1] == array.shape[2] and array.shape[0] != array.shape[1]:
array = np.rollaxis(np.rollaxis(array, 2), 2)
block_height, block_width, in_channels = array.shape[:3]
rows = []
max_element_count = section_height * int(image_width / MIN_SQUARE_SIZE)
element_count = 0
for i in range(in_channels):
rows.append(array[:, :, i, :].reshape(block_height, -1, order='F'))
# This line should be left in this position. Gives it one extra row.
if element_count >= max_element_count and not self.config['show_all']:
break
element_count += block_height * in_channels * block_width
return np.vstack(rows) | python | def _reshape_conv_array(self, array, section_height, image_width):
'''Reshape a rank 4 array to be rank 2, where each column of block_width is
a filter, and each row of block height is an input channel. For example:
[[[[ 11, 21, 31, 41],
[ 51, 61, 71, 81],
[ 91, 101, 111, 121]],
[[ 12, 22, 32, 42],
[ 52, 62, 72, 82],
[ 92, 102, 112, 122]],
[[ 13, 23, 33, 43],
[ 53, 63, 73, 83],
[ 93, 103, 113, 123]]],
[[[ 14, 24, 34, 44],
[ 54, 64, 74, 84],
[ 94, 104, 114, 124]],
[[ 15, 25, 35, 45],
[ 55, 65, 75, 85],
[ 95, 105, 115, 125]],
[[ 16, 26, 36, 46],
[ 56, 66, 76, 86],
[ 96, 106, 116, 126]]],
[[[ 17, 27, 37, 47],
[ 57, 67, 77, 87],
[ 97, 107, 117, 127]],
[[ 18, 28, 38, 48],
[ 58, 68, 78, 88],
[ 98, 108, 118, 128]],
[[ 19, 29, 39, 49],
[ 59, 69, 79, 89],
[ 99, 109, 119, 129]]]]
should be reshaped to:
[[ 11, 12, 13, 21, 22, 23, 31, 32, 33, 41, 42, 43],
[ 14, 15, 16, 24, 25, 26, 34, 35, 36, 44, 45, 46],
[ 17, 18, 19, 27, 28, 29, 37, 38, 39, 47, 48, 49],
[ 51, 52, 53, 61, 62, 63, 71, 72, 73, 81, 82, 83],
[ 54, 55, 56, 64, 65, 66, 74, 75, 76, 84, 85, 86],
[ 57, 58, 59, 67, 68, 69, 77, 78, 79, 87, 88, 89],
[ 91, 92, 93, 101, 102, 103, 111, 112, 113, 121, 122, 123],
[ 94, 95, 96, 104, 105, 106, 114, 115, 116, 124, 125, 126],
[ 97, 98, 99, 107, 108, 109, 117, 118, 119, 127, 128, 129]]
'''
# E.g. [100, 24, 24, 10]: this shouldn't be reshaped like normal.
if array.shape[1] == array.shape[2] and array.shape[0] != array.shape[1]:
array = np.rollaxis(np.rollaxis(array, 2), 2)
block_height, block_width, in_channels = array.shape[:3]
rows = []
max_element_count = section_height * int(image_width / MIN_SQUARE_SIZE)
element_count = 0
for i in range(in_channels):
rows.append(array[:, :, i, :].reshape(block_height, -1, order='F'))
# This line should be left in this position. Gives it one extra row.
if element_count >= max_element_count and not self.config['show_all']:
break
element_count += block_height * in_channels * block_width
return np.vstack(rows) | [
"def",
"_reshape_conv_array",
"(",
"self",
",",
"array",
",",
"section_height",
",",
"image_width",
")",
":",
"# E.g. [100, 24, 24, 10]: this shouldn't be reshaped like normal.",
"if",
"array",
".",
"shape",
"[",
"1",
"]",
"==",
"array",
".",
"shape",
"[",
"2",
"]",
"and",
"array",
".",
"shape",
"[",
"0",
"]",
"!=",
"array",
".",
"shape",
"[",
"1",
"]",
":",
"array",
"=",
"np",
".",
"rollaxis",
"(",
"np",
".",
"rollaxis",
"(",
"array",
",",
"2",
")",
",",
"2",
")",
"block_height",
",",
"block_width",
",",
"in_channels",
"=",
"array",
".",
"shape",
"[",
":",
"3",
"]",
"rows",
"=",
"[",
"]",
"max_element_count",
"=",
"section_height",
"*",
"int",
"(",
"image_width",
"/",
"MIN_SQUARE_SIZE",
")",
"element_count",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"in_channels",
")",
":",
"rows",
".",
"append",
"(",
"array",
"[",
":",
",",
":",
",",
"i",
",",
":",
"]",
".",
"reshape",
"(",
"block_height",
",",
"-",
"1",
",",
"order",
"=",
"'F'",
")",
")",
"# This line should be left in this position. Gives it one extra row.",
"if",
"element_count",
">=",
"max_element_count",
"and",
"not",
"self",
".",
"config",
"[",
"'show_all'",
"]",
":",
"break",
"element_count",
"+=",
"block_height",
"*",
"in_channels",
"*",
"block_width",
"return",
"np",
".",
"vstack",
"(",
"rows",
")"
] | Reshape a rank 4 array to be rank 2, where each column of block_width is
a filter, and each row of block height is an input channel. For example:
[[[[ 11, 21, 31, 41],
[ 51, 61, 71, 81],
[ 91, 101, 111, 121]],
[[ 12, 22, 32, 42],
[ 52, 62, 72, 82],
[ 92, 102, 112, 122]],
[[ 13, 23, 33, 43],
[ 53, 63, 73, 83],
[ 93, 103, 113, 123]]],
[[[ 14, 24, 34, 44],
[ 54, 64, 74, 84],
[ 94, 104, 114, 124]],
[[ 15, 25, 35, 45],
[ 55, 65, 75, 85],
[ 95, 105, 115, 125]],
[[ 16, 26, 36, 46],
[ 56, 66, 76, 86],
[ 96, 106, 116, 126]]],
[[[ 17, 27, 37, 47],
[ 57, 67, 77, 87],
[ 97, 107, 117, 127]],
[[ 18, 28, 38, 48],
[ 58, 68, 78, 88],
[ 98, 108, 118, 128]],
[[ 19, 29, 39, 49],
[ 59, 69, 79, 89],
[ 99, 109, 119, 129]]]]
should be reshaped to:
[[ 11, 12, 13, 21, 22, 23, 31, 32, 33, 41, 42, 43],
[ 14, 15, 16, 24, 25, 26, 34, 35, 36, 44, 45, 46],
[ 17, 18, 19, 27, 28, 29, 37, 38, 39, 47, 48, 49],
[ 51, 52, 53, 61, 62, 63, 71, 72, 73, 81, 82, 83],
[ 54, 55, 56, 64, 65, 66, 74, 75, 76, 84, 85, 86],
[ 57, 58, 59, 67, 68, 69, 77, 78, 79, 87, 88, 89],
[ 91, 92, 93, 101, 102, 103, 111, 112, 113, 121, 122, 123],
[ 94, 95, 96, 104, 105, 106, 114, 115, 116, 124, 125, 126],
[ 97, 98, 99, 107, 108, 109, 117, 118, 119, 127, 128, 129]] | [
"Reshape",
"a",
"rank",
"4",
"array",
"to",
"be",
"rank",
"2",
"where",
"each",
"column",
"of",
"block_width",
"is",
"a",
"filter",
"and",
"each",
"row",
"of",
"block",
"height",
"is",
"an",
"input",
"channel",
".",
"For",
"example",
":"
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/beholder/visualizer.py#L42-L106 | train |
tensorflow/tensorboard | tensorboard/plugins/beholder/visualizer.py | Visualizer._reshape_irregular_array | def _reshape_irregular_array(self, array, section_height, image_width):
'''Reshapes arrays of ranks not in {1, 2, 4}
'''
section_area = section_height * image_width
flattened_array = np.ravel(array)
if not self.config['show_all']:
flattened_array = flattened_array[:int(section_area/MIN_SQUARE_SIZE)]
cell_count = np.prod(flattened_array.shape)
cell_area = section_area / cell_count
cell_side_length = max(1, floor(sqrt(cell_area)))
row_count = max(1, int(section_height / cell_side_length))
col_count = int(cell_count / row_count)
# Reshape the truncated array so that it has the same aspect ratio as
# the section.
# Truncate whatever remaining values there are that don't fit. Hopefully
# it doesn't matter that the last few (< section count) aren't there.
section = np.reshape(flattened_array[:row_count * col_count],
(row_count, col_count))
return section | python | def _reshape_irregular_array(self, array, section_height, image_width):
'''Reshapes arrays of ranks not in {1, 2, 4}
'''
section_area = section_height * image_width
flattened_array = np.ravel(array)
if not self.config['show_all']:
flattened_array = flattened_array[:int(section_area/MIN_SQUARE_SIZE)]
cell_count = np.prod(flattened_array.shape)
cell_area = section_area / cell_count
cell_side_length = max(1, floor(sqrt(cell_area)))
row_count = max(1, int(section_height / cell_side_length))
col_count = int(cell_count / row_count)
# Reshape the truncated array so that it has the same aspect ratio as
# the section.
# Truncate whatever remaining values there are that don't fit. Hopefully
# it doesn't matter that the last few (< section count) aren't there.
section = np.reshape(flattened_array[:row_count * col_count],
(row_count, col_count))
return section | [
"def",
"_reshape_irregular_array",
"(",
"self",
",",
"array",
",",
"section_height",
",",
"image_width",
")",
":",
"section_area",
"=",
"section_height",
"*",
"image_width",
"flattened_array",
"=",
"np",
".",
"ravel",
"(",
"array",
")",
"if",
"not",
"self",
".",
"config",
"[",
"'show_all'",
"]",
":",
"flattened_array",
"=",
"flattened_array",
"[",
":",
"int",
"(",
"section_area",
"/",
"MIN_SQUARE_SIZE",
")",
"]",
"cell_count",
"=",
"np",
".",
"prod",
"(",
"flattened_array",
".",
"shape",
")",
"cell_area",
"=",
"section_area",
"/",
"cell_count",
"cell_side_length",
"=",
"max",
"(",
"1",
",",
"floor",
"(",
"sqrt",
"(",
"cell_area",
")",
")",
")",
"row_count",
"=",
"max",
"(",
"1",
",",
"int",
"(",
"section_height",
"/",
"cell_side_length",
")",
")",
"col_count",
"=",
"int",
"(",
"cell_count",
"/",
"row_count",
")",
"# Reshape the truncated array so that it has the same aspect ratio as",
"# the section.",
"# Truncate whatever remaining values there are that don't fit. Hopefully",
"# it doesn't matter that the last few (< section count) aren't there.",
"section",
"=",
"np",
".",
"reshape",
"(",
"flattened_array",
"[",
":",
"row_count",
"*",
"col_count",
"]",
",",
"(",
"row_count",
",",
"col_count",
")",
")",
"return",
"section"
] | Reshapes arrays of ranks not in {1, 2, 4} | [
"Reshapes",
"arrays",
"of",
"ranks",
"not",
"in",
"{",
"1",
"2",
"4",
"}"
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/beholder/visualizer.py#L109-L133 | train |
tensorflow/tensorboard | tensorboard/plugins/beholder/visualizer.py | Visualizer._arrays_to_sections | def _arrays_to_sections(self, arrays):
'''
input: unprocessed numpy arrays.
returns: columns of the size that they will appear in the image, not scaled
for display. That needs to wait until after variance is computed.
'''
sections = []
sections_to_resize_later = {}
show_all = self.config['show_all']
image_width = self._determine_image_width(arrays, show_all)
for array_number, array in enumerate(arrays):
rank = len(array.shape)
section_height = self._determine_section_height(array, show_all)
if rank == 1:
section = np.atleast_2d(array)
elif rank == 2:
section = array
elif rank == 4:
section = self._reshape_conv_array(array, section_height, image_width)
else:
section = self._reshape_irregular_array(array,
section_height,
image_width)
# Only calculate variance for what we have to. In some cases (biases),
# the section is larger than the array, so we don't want to calculate
# variance for the same value over and over - better to resize later.
# About a 6-7x speedup for a big network with a big variance window.
section_size = section_height * image_width
array_size = np.prod(array.shape)
if section_size > array_size:
sections.append(section)
sections_to_resize_later[array_number] = section_height
else:
sections.append(im_util.resize(section, section_height, image_width))
self.sections_over_time.append(sections)
if self.config['mode'] == 'variance':
sections = self._sections_to_variance_sections(self.sections_over_time)
for array_number, height in sections_to_resize_later.items():
sections[array_number] = im_util.resize(sections[array_number],
height,
image_width)
return sections | python | def _arrays_to_sections(self, arrays):
'''
input: unprocessed numpy arrays.
returns: columns of the size that they will appear in the image, not scaled
for display. That needs to wait until after variance is computed.
'''
sections = []
sections_to_resize_later = {}
show_all = self.config['show_all']
image_width = self._determine_image_width(arrays, show_all)
for array_number, array in enumerate(arrays):
rank = len(array.shape)
section_height = self._determine_section_height(array, show_all)
if rank == 1:
section = np.atleast_2d(array)
elif rank == 2:
section = array
elif rank == 4:
section = self._reshape_conv_array(array, section_height, image_width)
else:
section = self._reshape_irregular_array(array,
section_height,
image_width)
# Only calculate variance for what we have to. In some cases (biases),
# the section is larger than the array, so we don't want to calculate
# variance for the same value over and over - better to resize later.
# About a 6-7x speedup for a big network with a big variance window.
section_size = section_height * image_width
array_size = np.prod(array.shape)
if section_size > array_size:
sections.append(section)
sections_to_resize_later[array_number] = section_height
else:
sections.append(im_util.resize(section, section_height, image_width))
self.sections_over_time.append(sections)
if self.config['mode'] == 'variance':
sections = self._sections_to_variance_sections(self.sections_over_time)
for array_number, height in sections_to_resize_later.items():
sections[array_number] = im_util.resize(sections[array_number],
height,
image_width)
return sections | [
"def",
"_arrays_to_sections",
"(",
"self",
",",
"arrays",
")",
":",
"sections",
"=",
"[",
"]",
"sections_to_resize_later",
"=",
"{",
"}",
"show_all",
"=",
"self",
".",
"config",
"[",
"'show_all'",
"]",
"image_width",
"=",
"self",
".",
"_determine_image_width",
"(",
"arrays",
",",
"show_all",
")",
"for",
"array_number",
",",
"array",
"in",
"enumerate",
"(",
"arrays",
")",
":",
"rank",
"=",
"len",
"(",
"array",
".",
"shape",
")",
"section_height",
"=",
"self",
".",
"_determine_section_height",
"(",
"array",
",",
"show_all",
")",
"if",
"rank",
"==",
"1",
":",
"section",
"=",
"np",
".",
"atleast_2d",
"(",
"array",
")",
"elif",
"rank",
"==",
"2",
":",
"section",
"=",
"array",
"elif",
"rank",
"==",
"4",
":",
"section",
"=",
"self",
".",
"_reshape_conv_array",
"(",
"array",
",",
"section_height",
",",
"image_width",
")",
"else",
":",
"section",
"=",
"self",
".",
"_reshape_irregular_array",
"(",
"array",
",",
"section_height",
",",
"image_width",
")",
"# Only calculate variance for what we have to. In some cases (biases),",
"# the section is larger than the array, so we don't want to calculate",
"# variance for the same value over and over - better to resize later.",
"# About a 6-7x speedup for a big network with a big variance window.",
"section_size",
"=",
"section_height",
"*",
"image_width",
"array_size",
"=",
"np",
".",
"prod",
"(",
"array",
".",
"shape",
")",
"if",
"section_size",
">",
"array_size",
":",
"sections",
".",
"append",
"(",
"section",
")",
"sections_to_resize_later",
"[",
"array_number",
"]",
"=",
"section_height",
"else",
":",
"sections",
".",
"append",
"(",
"im_util",
".",
"resize",
"(",
"section",
",",
"section_height",
",",
"image_width",
")",
")",
"self",
".",
"sections_over_time",
".",
"append",
"(",
"sections",
")",
"if",
"self",
".",
"config",
"[",
"'mode'",
"]",
"==",
"'variance'",
":",
"sections",
"=",
"self",
".",
"_sections_to_variance_sections",
"(",
"self",
".",
"sections_over_time",
")",
"for",
"array_number",
",",
"height",
"in",
"sections_to_resize_later",
".",
"items",
"(",
")",
":",
"sections",
"[",
"array_number",
"]",
"=",
"im_util",
".",
"resize",
"(",
"sections",
"[",
"array_number",
"]",
",",
"height",
",",
"image_width",
")",
"return",
"sections"
] | input: unprocessed numpy arrays.
returns: columns of the size that they will appear in the image, not scaled
for display. That needs to wait until after variance is computed. | [
"input",
":",
"unprocessed",
"numpy",
"arrays",
".",
"returns",
":",
"columns",
"of",
"the",
"size",
"that",
"they",
"will",
"appear",
"in",
"the",
"image",
"not",
"scaled",
"for",
"display",
".",
"That",
"needs",
"to",
"wait",
"until",
"after",
"variance",
"is",
"computed",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/beholder/visualizer.py#L175-L222 | train |
tensorflow/tensorboard | tensorboard/plugins/beholder/visualizer.py | Visualizer._sections_to_variance_sections | def _sections_to_variance_sections(self, sections_over_time):
'''Computes the variance of corresponding sections over time.
Returns:
a list of np arrays.
'''
variance_sections = []
for i in range(len(sections_over_time[0])):
time_sections = [sections[i] for sections in sections_over_time]
variance = np.var(time_sections, axis=0)
variance_sections.append(variance)
return variance_sections | python | def _sections_to_variance_sections(self, sections_over_time):
'''Computes the variance of corresponding sections over time.
Returns:
a list of np arrays.
'''
variance_sections = []
for i in range(len(sections_over_time[0])):
time_sections = [sections[i] for sections in sections_over_time]
variance = np.var(time_sections, axis=0)
variance_sections.append(variance)
return variance_sections | [
"def",
"_sections_to_variance_sections",
"(",
"self",
",",
"sections_over_time",
")",
":",
"variance_sections",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"sections_over_time",
"[",
"0",
"]",
")",
")",
":",
"time_sections",
"=",
"[",
"sections",
"[",
"i",
"]",
"for",
"sections",
"in",
"sections_over_time",
"]",
"variance",
"=",
"np",
".",
"var",
"(",
"time_sections",
",",
"axis",
"=",
"0",
")",
"variance_sections",
".",
"append",
"(",
"variance",
")",
"return",
"variance_sections"
] | Computes the variance of corresponding sections over time.
Returns:
a list of np arrays. | [
"Computes",
"the",
"variance",
"of",
"corresponding",
"sections",
"over",
"time",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/beholder/visualizer.py#L225-L238 | train |
tensorflow/tensorboard | tensorboard/plugins/beholder/visualizer.py | Visualizer._maybe_clear_deque | def _maybe_clear_deque(self):
'''Clears the deque if certain parts of the config have changed.'''
for config_item in ['values', 'mode', 'show_all']:
if self.config[config_item] != self.old_config[config_item]:
self.sections_over_time.clear()
break
self.old_config = self.config
window_size = self.config['window_size']
if window_size != self.sections_over_time.maxlen:
self.sections_over_time = deque(self.sections_over_time, window_size) | python | def _maybe_clear_deque(self):
'''Clears the deque if certain parts of the config have changed.'''
for config_item in ['values', 'mode', 'show_all']:
if self.config[config_item] != self.old_config[config_item]:
self.sections_over_time.clear()
break
self.old_config = self.config
window_size = self.config['window_size']
if window_size != self.sections_over_time.maxlen:
self.sections_over_time = deque(self.sections_over_time, window_size) | [
"def",
"_maybe_clear_deque",
"(",
"self",
")",
":",
"for",
"config_item",
"in",
"[",
"'values'",
",",
"'mode'",
",",
"'show_all'",
"]",
":",
"if",
"self",
".",
"config",
"[",
"config_item",
"]",
"!=",
"self",
".",
"old_config",
"[",
"config_item",
"]",
":",
"self",
".",
"sections_over_time",
".",
"clear",
"(",
")",
"break",
"self",
".",
"old_config",
"=",
"self",
".",
"config",
"window_size",
"=",
"self",
".",
"config",
"[",
"'window_size'",
"]",
"if",
"window_size",
"!=",
"self",
".",
"sections_over_time",
".",
"maxlen",
":",
"self",
".",
"sections_over_time",
"=",
"deque",
"(",
"self",
".",
"sections_over_time",
",",
"window_size",
")"
] | Clears the deque if certain parts of the config have changed. | [
"Clears",
"the",
"deque",
"if",
"certain",
"parts",
"of",
"the",
"config",
"have",
"changed",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/beholder/visualizer.py#L256-L268 | train |
tensorflow/tensorboard | tensorboard/lazy.py | lazy_load | def lazy_load(name):
"""Decorator to define a function that lazily loads the module 'name'.
This can be used to defer importing troublesome dependencies - e.g. ones that
are large and infrequently used, or that cause a dependency cycle -
until they are actually used.
Args:
name: the fully-qualified name of the module; typically the last segment
of 'name' matches the name of the decorated function
Returns:
Decorator function that produces a lazy-loading module 'name' backed by the
underlying decorated function.
"""
def wrapper(load_fn):
# Wrap load_fn to call it exactly once and update __dict__ afterwards to
# make future lookups efficient (only failed lookups call __getattr__).
@_memoize
def load_once(self):
if load_once.loading:
raise ImportError("Circular import when resolving LazyModule %r" % name)
load_once.loading = True
try:
module = load_fn()
finally:
load_once.loading = False
self.__dict__.update(module.__dict__)
load_once.loaded = True
return module
load_once.loading = False
load_once.loaded = False
# Define a module that proxies getattr() and dir() to the result of calling
# load_once() the first time it's needed. The class is nested so we can close
# over load_once() and avoid polluting the module's attrs with our own state.
class LazyModule(types.ModuleType):
def __getattr__(self, attr_name):
return getattr(load_once(self), attr_name)
def __dir__(self):
return dir(load_once(self))
def __repr__(self):
if load_once.loaded:
return '<%r via LazyModule (loaded)>' % load_once(self)
return '<module %r via LazyModule (not yet loaded)>' % self.__name__
return LazyModule(name)
return wrapper | python | def lazy_load(name):
"""Decorator to define a function that lazily loads the module 'name'.
This can be used to defer importing troublesome dependencies - e.g. ones that
are large and infrequently used, or that cause a dependency cycle -
until they are actually used.
Args:
name: the fully-qualified name of the module; typically the last segment
of 'name' matches the name of the decorated function
Returns:
Decorator function that produces a lazy-loading module 'name' backed by the
underlying decorated function.
"""
def wrapper(load_fn):
# Wrap load_fn to call it exactly once and update __dict__ afterwards to
# make future lookups efficient (only failed lookups call __getattr__).
@_memoize
def load_once(self):
if load_once.loading:
raise ImportError("Circular import when resolving LazyModule %r" % name)
load_once.loading = True
try:
module = load_fn()
finally:
load_once.loading = False
self.__dict__.update(module.__dict__)
load_once.loaded = True
return module
load_once.loading = False
load_once.loaded = False
# Define a module that proxies getattr() and dir() to the result of calling
# load_once() the first time it's needed. The class is nested so we can close
# over load_once() and avoid polluting the module's attrs with our own state.
class LazyModule(types.ModuleType):
def __getattr__(self, attr_name):
return getattr(load_once(self), attr_name)
def __dir__(self):
return dir(load_once(self))
def __repr__(self):
if load_once.loaded:
return '<%r via LazyModule (loaded)>' % load_once(self)
return '<module %r via LazyModule (not yet loaded)>' % self.__name__
return LazyModule(name)
return wrapper | [
"def",
"lazy_load",
"(",
"name",
")",
":",
"def",
"wrapper",
"(",
"load_fn",
")",
":",
"# Wrap load_fn to call it exactly once and update __dict__ afterwards to",
"# make future lookups efficient (only failed lookups call __getattr__).",
"@",
"_memoize",
"def",
"load_once",
"(",
"self",
")",
":",
"if",
"load_once",
".",
"loading",
":",
"raise",
"ImportError",
"(",
"\"Circular import when resolving LazyModule %r\"",
"%",
"name",
")",
"load_once",
".",
"loading",
"=",
"True",
"try",
":",
"module",
"=",
"load_fn",
"(",
")",
"finally",
":",
"load_once",
".",
"loading",
"=",
"False",
"self",
".",
"__dict__",
".",
"update",
"(",
"module",
".",
"__dict__",
")",
"load_once",
".",
"loaded",
"=",
"True",
"return",
"module",
"load_once",
".",
"loading",
"=",
"False",
"load_once",
".",
"loaded",
"=",
"False",
"# Define a module that proxies getattr() and dir() to the result of calling",
"# load_once() the first time it's needed. The class is nested so we can close",
"# over load_once() and avoid polluting the module's attrs with our own state.",
"class",
"LazyModule",
"(",
"types",
".",
"ModuleType",
")",
":",
"def",
"__getattr__",
"(",
"self",
",",
"attr_name",
")",
":",
"return",
"getattr",
"(",
"load_once",
"(",
"self",
")",
",",
"attr_name",
")",
"def",
"__dir__",
"(",
"self",
")",
":",
"return",
"dir",
"(",
"load_once",
"(",
"self",
")",
")",
"def",
"__repr__",
"(",
"self",
")",
":",
"if",
"load_once",
".",
"loaded",
":",
"return",
"'<%r via LazyModule (loaded)>'",
"%",
"load_once",
"(",
"self",
")",
"return",
"'<module %r via LazyModule (not yet loaded)>'",
"%",
"self",
".",
"__name__",
"return",
"LazyModule",
"(",
"name",
")",
"return",
"wrapper"
] | Decorator to define a function that lazily loads the module 'name'.
This can be used to defer importing troublesome dependencies - e.g. ones that
are large and infrequently used, or that cause a dependency cycle -
until they are actually used.
Args:
name: the fully-qualified name of the module; typically the last segment
of 'name' matches the name of the decorated function
Returns:
Decorator function that produces a lazy-loading module 'name' backed by the
underlying decorated function. | [
"Decorator",
"to",
"define",
"a",
"function",
"that",
"lazily",
"loads",
"the",
"module",
"name",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/lazy.py#L27-L76 | train |
tensorflow/tensorboard | tensorboard/lazy.py | _memoize | def _memoize(f):
"""Memoizing decorator for f, which must have exactly 1 hashable argument."""
nothing = object() # Unique "no value" sentinel object.
cache = {}
# Use a reentrant lock so that if f references the resulting wrapper we die
# with recursion depth exceeded instead of deadlocking.
lock = threading.RLock()
@functools.wraps(f)
def wrapper(arg):
if cache.get(arg, nothing) is nothing:
with lock:
if cache.get(arg, nothing) is nothing:
cache[arg] = f(arg)
return cache[arg]
return wrapper | python | def _memoize(f):
"""Memoizing decorator for f, which must have exactly 1 hashable argument."""
nothing = object() # Unique "no value" sentinel object.
cache = {}
# Use a reentrant lock so that if f references the resulting wrapper we die
# with recursion depth exceeded instead of deadlocking.
lock = threading.RLock()
@functools.wraps(f)
def wrapper(arg):
if cache.get(arg, nothing) is nothing:
with lock:
if cache.get(arg, nothing) is nothing:
cache[arg] = f(arg)
return cache[arg]
return wrapper | [
"def",
"_memoize",
"(",
"f",
")",
":",
"nothing",
"=",
"object",
"(",
")",
"# Unique \"no value\" sentinel object.",
"cache",
"=",
"{",
"}",
"# Use a reentrant lock so that if f references the resulting wrapper we die",
"# with recursion depth exceeded instead of deadlocking.",
"lock",
"=",
"threading",
".",
"RLock",
"(",
")",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"arg",
")",
":",
"if",
"cache",
".",
"get",
"(",
"arg",
",",
"nothing",
")",
"is",
"nothing",
":",
"with",
"lock",
":",
"if",
"cache",
".",
"get",
"(",
"arg",
",",
"nothing",
")",
"is",
"nothing",
":",
"cache",
"[",
"arg",
"]",
"=",
"f",
"(",
"arg",
")",
"return",
"cache",
"[",
"arg",
"]",
"return",
"wrapper"
] | Memoizing decorator for f, which must have exactly 1 hashable argument. | [
"Memoizing",
"decorator",
"for",
"f",
"which",
"must",
"have",
"exactly",
"1",
"hashable",
"argument",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/lazy.py#L79-L93 | train |
tensorflow/tensorboard | tensorboard/compat/__init__.py | tf | def tf():
"""Provide the root module of a TF-like API for use within TensorBoard.
By default this is equivalent to `import tensorflow as tf`, but it can be used
in combination with //tensorboard/compat:tensorflow (to fall back to a stub TF
API implementation if the real one is not available) or with
//tensorboard/compat:no_tensorflow (to force unconditional use of the stub).
Returns:
The root module of a TF-like API, if available.
Raises:
ImportError: if a TF-like API is not available.
"""
try:
from tensorboard.compat import notf # pylint: disable=g-import-not-at-top
except ImportError:
try:
import tensorflow # pylint: disable=g-import-not-at-top
return tensorflow
except ImportError:
pass
from tensorboard.compat import tensorflow_stub # pylint: disable=g-import-not-at-top
return tensorflow_stub | python | def tf():
"""Provide the root module of a TF-like API for use within TensorBoard.
By default this is equivalent to `import tensorflow as tf`, but it can be used
in combination with //tensorboard/compat:tensorflow (to fall back to a stub TF
API implementation if the real one is not available) or with
//tensorboard/compat:no_tensorflow (to force unconditional use of the stub).
Returns:
The root module of a TF-like API, if available.
Raises:
ImportError: if a TF-like API is not available.
"""
try:
from tensorboard.compat import notf # pylint: disable=g-import-not-at-top
except ImportError:
try:
import tensorflow # pylint: disable=g-import-not-at-top
return tensorflow
except ImportError:
pass
from tensorboard.compat import tensorflow_stub # pylint: disable=g-import-not-at-top
return tensorflow_stub | [
"def",
"tf",
"(",
")",
":",
"try",
":",
"from",
"tensorboard",
".",
"compat",
"import",
"notf",
"# pylint: disable=g-import-not-at-top",
"except",
"ImportError",
":",
"try",
":",
"import",
"tensorflow",
"# pylint: disable=g-import-not-at-top",
"return",
"tensorflow",
"except",
"ImportError",
":",
"pass",
"from",
"tensorboard",
".",
"compat",
"import",
"tensorflow_stub",
"# pylint: disable=g-import-not-at-top",
"return",
"tensorflow_stub"
] | Provide the root module of a TF-like API for use within TensorBoard.
By default this is equivalent to `import tensorflow as tf`, but it can be used
in combination with //tensorboard/compat:tensorflow (to fall back to a stub TF
API implementation if the real one is not available) or with
//tensorboard/compat:no_tensorflow (to force unconditional use of the stub).
Returns:
The root module of a TF-like API, if available.
Raises:
ImportError: if a TF-like API is not available. | [
"Provide",
"the",
"root",
"module",
"of",
"a",
"TF",
"-",
"like",
"API",
"for",
"use",
"within",
"TensorBoard",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/compat/__init__.py#L32-L55 | train |
tensorflow/tensorboard | tensorboard/compat/__init__.py | tf2 | def tf2():
"""Provide the root module of a TF-2.0 API for use within TensorBoard.
Returns:
The root module of a TF-2.0 API, if available.
Raises:
ImportError: if a TF-2.0 API is not available.
"""
# Import the `tf` compat API from this file and check if it's already TF 2.0.
if tf.__version__.startswith('2.'):
return tf
elif hasattr(tf, 'compat') and hasattr(tf.compat, 'v2'):
# As a fallback, try `tensorflow.compat.v2` if it's defined.
return tf.compat.v2
raise ImportError('cannot import tensorflow 2.0 API') | python | def tf2():
"""Provide the root module of a TF-2.0 API for use within TensorBoard.
Returns:
The root module of a TF-2.0 API, if available.
Raises:
ImportError: if a TF-2.0 API is not available.
"""
# Import the `tf` compat API from this file and check if it's already TF 2.0.
if tf.__version__.startswith('2.'):
return tf
elif hasattr(tf, 'compat') and hasattr(tf.compat, 'v2'):
# As a fallback, try `tensorflow.compat.v2` if it's defined.
return tf.compat.v2
raise ImportError('cannot import tensorflow 2.0 API') | [
"def",
"tf2",
"(",
")",
":",
"# Import the `tf` compat API from this file and check if it's already TF 2.0.",
"if",
"tf",
".",
"__version__",
".",
"startswith",
"(",
"'2.'",
")",
":",
"return",
"tf",
"elif",
"hasattr",
"(",
"tf",
",",
"'compat'",
")",
"and",
"hasattr",
"(",
"tf",
".",
"compat",
",",
"'v2'",
")",
":",
"# As a fallback, try `tensorflow.compat.v2` if it's defined.",
"return",
"tf",
".",
"compat",
".",
"v2",
"raise",
"ImportError",
"(",
"'cannot import tensorflow 2.0 API'",
")"
] | Provide the root module of a TF-2.0 API for use within TensorBoard.
Returns:
The root module of a TF-2.0 API, if available.
Raises:
ImportError: if a TF-2.0 API is not available. | [
"Provide",
"the",
"root",
"module",
"of",
"a",
"TF",
"-",
"2",
".",
"0",
"API",
"for",
"use",
"within",
"TensorBoard",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/compat/__init__.py#L59-L74 | train |
tensorflow/tensorboard | tensorboard/compat/__init__.py | _pywrap_tensorflow | def _pywrap_tensorflow():
"""Provide pywrap_tensorflow access in TensorBoard.
pywrap_tensorflow cannot be accessed from tf.python.pywrap_tensorflow
and needs to be imported using
`from tensorflow.python import pywrap_tensorflow`. Therefore, we provide
a separate accessor function for it here.
NOTE: pywrap_tensorflow is not part of TensorFlow API and this
dependency will go away soon.
Returns:
pywrap_tensorflow import, if available.
Raises:
ImportError: if we couldn't import pywrap_tensorflow.
"""
try:
from tensorboard.compat import notf # pylint: disable=g-import-not-at-top
except ImportError:
try:
from tensorflow.python import pywrap_tensorflow # pylint: disable=g-import-not-at-top
return pywrap_tensorflow
except ImportError:
pass
from tensorboard.compat.tensorflow_stub import pywrap_tensorflow # pylint: disable=g-import-not-at-top
return pywrap_tensorflow | python | def _pywrap_tensorflow():
"""Provide pywrap_tensorflow access in TensorBoard.
pywrap_tensorflow cannot be accessed from tf.python.pywrap_tensorflow
and needs to be imported using
`from tensorflow.python import pywrap_tensorflow`. Therefore, we provide
a separate accessor function for it here.
NOTE: pywrap_tensorflow is not part of TensorFlow API and this
dependency will go away soon.
Returns:
pywrap_tensorflow import, if available.
Raises:
ImportError: if we couldn't import pywrap_tensorflow.
"""
try:
from tensorboard.compat import notf # pylint: disable=g-import-not-at-top
except ImportError:
try:
from tensorflow.python import pywrap_tensorflow # pylint: disable=g-import-not-at-top
return pywrap_tensorflow
except ImportError:
pass
from tensorboard.compat.tensorflow_stub import pywrap_tensorflow # pylint: disable=g-import-not-at-top
return pywrap_tensorflow | [
"def",
"_pywrap_tensorflow",
"(",
")",
":",
"try",
":",
"from",
"tensorboard",
".",
"compat",
"import",
"notf",
"# pylint: disable=g-import-not-at-top",
"except",
"ImportError",
":",
"try",
":",
"from",
"tensorflow",
".",
"python",
"import",
"pywrap_tensorflow",
"# pylint: disable=g-import-not-at-top",
"return",
"pywrap_tensorflow",
"except",
"ImportError",
":",
"pass",
"from",
"tensorboard",
".",
"compat",
".",
"tensorflow_stub",
"import",
"pywrap_tensorflow",
"# pylint: disable=g-import-not-at-top",
"return",
"pywrap_tensorflow"
] | Provide pywrap_tensorflow access in TensorBoard.
pywrap_tensorflow cannot be accessed from tf.python.pywrap_tensorflow
and needs to be imported using
`from tensorflow.python import pywrap_tensorflow`. Therefore, we provide
a separate accessor function for it here.
NOTE: pywrap_tensorflow is not part of TensorFlow API and this
dependency will go away soon.
Returns:
pywrap_tensorflow import, if available.
Raises:
ImportError: if we couldn't import pywrap_tensorflow. | [
"Provide",
"pywrap_tensorflow",
"access",
"in",
"TensorBoard",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/compat/__init__.py#L79-L105 | train |
tensorflow/tensorboard | tensorboard/plugins/hparams/hparams_minimal_demo.py | create_experiment_summary | def create_experiment_summary():
"""Returns a summary proto buffer holding this experiment."""
# Convert TEMPERATURE_LIST to google.protobuf.ListValue
temperature_list = struct_pb2.ListValue()
temperature_list.extend(TEMPERATURE_LIST)
materials = struct_pb2.ListValue()
materials.extend(HEAT_COEFFICIENTS.keys())
return summary.experiment_pb(
hparam_infos=[
api_pb2.HParamInfo(name='initial_temperature',
display_name='Initial temperature',
type=api_pb2.DATA_TYPE_FLOAT64,
domain_discrete=temperature_list),
api_pb2.HParamInfo(name='ambient_temperature',
display_name='Ambient temperature',
type=api_pb2.DATA_TYPE_FLOAT64,
domain_discrete=temperature_list),
api_pb2.HParamInfo(name='material',
display_name='Material',
type=api_pb2.DATA_TYPE_STRING,
domain_discrete=materials)
],
metric_infos=[
api_pb2.MetricInfo(
name=api_pb2.MetricName(
tag='temperature/current/scalar_summary'),
display_name='Current Temp.'),
api_pb2.MetricInfo(
name=api_pb2.MetricName(
tag='temperature/difference_to_ambient/scalar_summary'),
display_name='Difference To Ambient Temp.'),
api_pb2.MetricInfo(
name=api_pb2.MetricName(
tag='delta/scalar_summary'),
display_name='Delta T')
]
) | python | def create_experiment_summary():
"""Returns a summary proto buffer holding this experiment."""
# Convert TEMPERATURE_LIST to google.protobuf.ListValue
temperature_list = struct_pb2.ListValue()
temperature_list.extend(TEMPERATURE_LIST)
materials = struct_pb2.ListValue()
materials.extend(HEAT_COEFFICIENTS.keys())
return summary.experiment_pb(
hparam_infos=[
api_pb2.HParamInfo(name='initial_temperature',
display_name='Initial temperature',
type=api_pb2.DATA_TYPE_FLOAT64,
domain_discrete=temperature_list),
api_pb2.HParamInfo(name='ambient_temperature',
display_name='Ambient temperature',
type=api_pb2.DATA_TYPE_FLOAT64,
domain_discrete=temperature_list),
api_pb2.HParamInfo(name='material',
display_name='Material',
type=api_pb2.DATA_TYPE_STRING,
domain_discrete=materials)
],
metric_infos=[
api_pb2.MetricInfo(
name=api_pb2.MetricName(
tag='temperature/current/scalar_summary'),
display_name='Current Temp.'),
api_pb2.MetricInfo(
name=api_pb2.MetricName(
tag='temperature/difference_to_ambient/scalar_summary'),
display_name='Difference To Ambient Temp.'),
api_pb2.MetricInfo(
name=api_pb2.MetricName(
tag='delta/scalar_summary'),
display_name='Delta T')
]
) | [
"def",
"create_experiment_summary",
"(",
")",
":",
"# Convert TEMPERATURE_LIST to google.protobuf.ListValue",
"temperature_list",
"=",
"struct_pb2",
".",
"ListValue",
"(",
")",
"temperature_list",
".",
"extend",
"(",
"TEMPERATURE_LIST",
")",
"materials",
"=",
"struct_pb2",
".",
"ListValue",
"(",
")",
"materials",
".",
"extend",
"(",
"HEAT_COEFFICIENTS",
".",
"keys",
"(",
")",
")",
"return",
"summary",
".",
"experiment_pb",
"(",
"hparam_infos",
"=",
"[",
"api_pb2",
".",
"HParamInfo",
"(",
"name",
"=",
"'initial_temperature'",
",",
"display_name",
"=",
"'Initial temperature'",
",",
"type",
"=",
"api_pb2",
".",
"DATA_TYPE_FLOAT64",
",",
"domain_discrete",
"=",
"temperature_list",
")",
",",
"api_pb2",
".",
"HParamInfo",
"(",
"name",
"=",
"'ambient_temperature'",
",",
"display_name",
"=",
"'Ambient temperature'",
",",
"type",
"=",
"api_pb2",
".",
"DATA_TYPE_FLOAT64",
",",
"domain_discrete",
"=",
"temperature_list",
")",
",",
"api_pb2",
".",
"HParamInfo",
"(",
"name",
"=",
"'material'",
",",
"display_name",
"=",
"'Material'",
",",
"type",
"=",
"api_pb2",
".",
"DATA_TYPE_STRING",
",",
"domain_discrete",
"=",
"materials",
")",
"]",
",",
"metric_infos",
"=",
"[",
"api_pb2",
".",
"MetricInfo",
"(",
"name",
"=",
"api_pb2",
".",
"MetricName",
"(",
"tag",
"=",
"'temperature/current/scalar_summary'",
")",
",",
"display_name",
"=",
"'Current Temp.'",
")",
",",
"api_pb2",
".",
"MetricInfo",
"(",
"name",
"=",
"api_pb2",
".",
"MetricName",
"(",
"tag",
"=",
"'temperature/difference_to_ambient/scalar_summary'",
")",
",",
"display_name",
"=",
"'Difference To Ambient Temp.'",
")",
",",
"api_pb2",
".",
"MetricInfo",
"(",
"name",
"=",
"api_pb2",
".",
"MetricName",
"(",
"tag",
"=",
"'delta/scalar_summary'",
")",
",",
"display_name",
"=",
"'Delta T'",
")",
"]",
")"
] | Returns a summary proto buffer holding this experiment. | [
"Returns",
"a",
"summary",
"proto",
"buffer",
"holding",
"this",
"experiment",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/hparams/hparams_minimal_demo.py#L95-L132 | train |
tensorflow/tensorboard | tensorboard/plugins/hparams/hparams_minimal_demo.py | run | def run(logdir, session_id, hparams, group_name):
"""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.
"""
tf.reset_default_graph()
tf.set_random_seed(0)
initial_temperature = hparams['initial_temperature']
ambient_temperature = hparams['ambient_temperature']
heat_coefficient = HEAT_COEFFICIENTS[hparams['material']]
session_dir = os.path.join(logdir, session_id)
writer = tf.summary.FileWriter(session_dir)
writer.add_summary(summary.session_start_pb(hparams=hparams,
group_name=group_name))
writer.flush()
with tf.name_scope('temperature'):
# Create a mutable variable to hold the object's temperature, and
# create a scalar summary to track its value over time. The name of
# the summary will appear as 'temperature/current' due to the
# name-scope above.
temperature = tf.Variable(
tf.constant(initial_temperature),
name='temperature')
scalar_summary.op('current', temperature,
display_name='Temperature',
description='The temperature of the object under '
'simulation, in Kelvins.')
# Compute how much the object's temperature differs from that of its
# environment, and track this, too: likewise, as
# 'temperature/difference_to_ambient'.
ambient_difference = temperature - ambient_temperature
scalar_summary.op('difference_to_ambient', ambient_difference,
display_name='Difference to ambient temperature',
description=('The difference between the ambient '
'temperature and the temperature of the '
'object under simulation, in Kelvins.'))
# Newton suggested that the rate of change of the temperature of an
# object is directly proportional to this `ambient_difference` above,
# where the proportionality constant is what we called the heat
# coefficient. But in real life, not everything is quite so clean, so
# we'll add in some noise. (The value of 50 is arbitrary, chosen to
# make the data look somewhat interesting. :-) )
noise = 50 * tf.random.normal([])
delta = -heat_coefficient * (ambient_difference + noise)
scalar_summary.op('delta', delta,
description='The change in temperature from the previous '
'step, in Kelvins.')
# Collect all the scalars that we want to keep track of.
summ = tf.summary.merge_all()
# Now, augment the current temperature by this delta that we computed,
# blocking the assignment on summary collection to avoid race conditions
# and ensure that the summary always reports the pre-update value.
with tf.control_dependencies([summ]):
update_step = temperature.assign_add(delta)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
for step in xrange(FLAGS.num_steps):
# By asking TensorFlow to compute the update step, we force it to
# change the value of the temperature variable. We don't actually
# care about this value, so we discard it; instead, we grab the
# summary data computed along the way.
(s, _) = sess.run([summ, update_step])
if (step % FLAGS.summary_freq) == 0:
writer.add_summary(s, global_step=step)
writer.add_summary(summary.session_end_pb(api_pb2.STATUS_SUCCESS))
writer.close() | python | def run(logdir, session_id, hparams, group_name):
"""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.
"""
tf.reset_default_graph()
tf.set_random_seed(0)
initial_temperature = hparams['initial_temperature']
ambient_temperature = hparams['ambient_temperature']
heat_coefficient = HEAT_COEFFICIENTS[hparams['material']]
session_dir = os.path.join(logdir, session_id)
writer = tf.summary.FileWriter(session_dir)
writer.add_summary(summary.session_start_pb(hparams=hparams,
group_name=group_name))
writer.flush()
with tf.name_scope('temperature'):
# Create a mutable variable to hold the object's temperature, and
# create a scalar summary to track its value over time. The name of
# the summary will appear as 'temperature/current' due to the
# name-scope above.
temperature = tf.Variable(
tf.constant(initial_temperature),
name='temperature')
scalar_summary.op('current', temperature,
display_name='Temperature',
description='The temperature of the object under '
'simulation, in Kelvins.')
# Compute how much the object's temperature differs from that of its
# environment, and track this, too: likewise, as
# 'temperature/difference_to_ambient'.
ambient_difference = temperature - ambient_temperature
scalar_summary.op('difference_to_ambient', ambient_difference,
display_name='Difference to ambient temperature',
description=('The difference between the ambient '
'temperature and the temperature of the '
'object under simulation, in Kelvins.'))
# Newton suggested that the rate of change of the temperature of an
# object is directly proportional to this `ambient_difference` above,
# where the proportionality constant is what we called the heat
# coefficient. But in real life, not everything is quite so clean, so
# we'll add in some noise. (The value of 50 is arbitrary, chosen to
# make the data look somewhat interesting. :-) )
noise = 50 * tf.random.normal([])
delta = -heat_coefficient * (ambient_difference + noise)
scalar_summary.op('delta', delta,
description='The change in temperature from the previous '
'step, in Kelvins.')
# Collect all the scalars that we want to keep track of.
summ = tf.summary.merge_all()
# Now, augment the current temperature by this delta that we computed,
# blocking the assignment on summary collection to avoid race conditions
# and ensure that the summary always reports the pre-update value.
with tf.control_dependencies([summ]):
update_step = temperature.assign_add(delta)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
for step in xrange(FLAGS.num_steps):
# By asking TensorFlow to compute the update step, we force it to
# change the value of the temperature variable. We don't actually
# care about this value, so we discard it; instead, we grab the
# summary data computed along the way.
(s, _) = sess.run([summ, update_step])
if (step % FLAGS.summary_freq) == 0:
writer.add_summary(s, global_step=step)
writer.add_summary(summary.session_end_pb(api_pb2.STATUS_SUCCESS))
writer.close() | [
"def",
"run",
"(",
"logdir",
",",
"session_id",
",",
"hparams",
",",
"group_name",
")",
":",
"tf",
".",
"reset_default_graph",
"(",
")",
"tf",
".",
"set_random_seed",
"(",
"0",
")",
"initial_temperature",
"=",
"hparams",
"[",
"'initial_temperature'",
"]",
"ambient_temperature",
"=",
"hparams",
"[",
"'ambient_temperature'",
"]",
"heat_coefficient",
"=",
"HEAT_COEFFICIENTS",
"[",
"hparams",
"[",
"'material'",
"]",
"]",
"session_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"logdir",
",",
"session_id",
")",
"writer",
"=",
"tf",
".",
"summary",
".",
"FileWriter",
"(",
"session_dir",
")",
"writer",
".",
"add_summary",
"(",
"summary",
".",
"session_start_pb",
"(",
"hparams",
"=",
"hparams",
",",
"group_name",
"=",
"group_name",
")",
")",
"writer",
".",
"flush",
"(",
")",
"with",
"tf",
".",
"name_scope",
"(",
"'temperature'",
")",
":",
"# Create a mutable variable to hold the object's temperature, and",
"# create a scalar summary to track its value over time. The name of",
"# the summary will appear as 'temperature/current' due to the",
"# name-scope above.",
"temperature",
"=",
"tf",
".",
"Variable",
"(",
"tf",
".",
"constant",
"(",
"initial_temperature",
")",
",",
"name",
"=",
"'temperature'",
")",
"scalar_summary",
".",
"op",
"(",
"'current'",
",",
"temperature",
",",
"display_name",
"=",
"'Temperature'",
",",
"description",
"=",
"'The temperature of the object under '",
"'simulation, in Kelvins.'",
")",
"# Compute how much the object's temperature differs from that of its",
"# environment, and track this, too: likewise, as",
"# 'temperature/difference_to_ambient'.",
"ambient_difference",
"=",
"temperature",
"-",
"ambient_temperature",
"scalar_summary",
".",
"op",
"(",
"'difference_to_ambient'",
",",
"ambient_difference",
",",
"display_name",
"=",
"'Difference to ambient temperature'",
",",
"description",
"=",
"(",
"'The difference between the ambient '",
"'temperature and the temperature of the '",
"'object under simulation, in Kelvins.'",
")",
")",
"# Newton suggested that the rate of change of the temperature of an",
"# object is directly proportional to this `ambient_difference` above,",
"# where the proportionality constant is what we called the heat",
"# coefficient. But in real life, not everything is quite so clean, so",
"# we'll add in some noise. (The value of 50 is arbitrary, chosen to",
"# make the data look somewhat interesting. :-) )",
"noise",
"=",
"50",
"*",
"tf",
".",
"random",
".",
"normal",
"(",
"[",
"]",
")",
"delta",
"=",
"-",
"heat_coefficient",
"*",
"(",
"ambient_difference",
"+",
"noise",
")",
"scalar_summary",
".",
"op",
"(",
"'delta'",
",",
"delta",
",",
"description",
"=",
"'The change in temperature from the previous '",
"'step, in Kelvins.'",
")",
"# Collect all the scalars that we want to keep track of.",
"summ",
"=",
"tf",
".",
"summary",
".",
"merge_all",
"(",
")",
"# Now, augment the current temperature by this delta that we computed,",
"# blocking the assignment on summary collection to avoid race conditions",
"# and ensure that the summary always reports the pre-update value.",
"with",
"tf",
".",
"control_dependencies",
"(",
"[",
"summ",
"]",
")",
":",
"update_step",
"=",
"temperature",
".",
"assign_add",
"(",
"delta",
")",
"sess",
"=",
"tf",
".",
"Session",
"(",
")",
"sess",
".",
"run",
"(",
"tf",
".",
"global_variables_initializer",
"(",
")",
")",
"for",
"step",
"in",
"xrange",
"(",
"FLAGS",
".",
"num_steps",
")",
":",
"# By asking TensorFlow to compute the update step, we force it to",
"# change the value of the temperature variable. We don't actually",
"# care about this value, so we discard it; instead, we grab the",
"# summary data computed along the way.",
"(",
"s",
",",
"_",
")",
"=",
"sess",
".",
"run",
"(",
"[",
"summ",
",",
"update_step",
"]",
")",
"if",
"(",
"step",
"%",
"FLAGS",
".",
"summary_freq",
")",
"==",
"0",
":",
"writer",
".",
"add_summary",
"(",
"s",
",",
"global_step",
"=",
"step",
")",
"writer",
".",
"add_summary",
"(",
"summary",
".",
"session_end_pb",
"(",
"api_pb2",
".",
"STATUS_SUCCESS",
")",
")",
"writer",
".",
"close",
"(",
")"
] | 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. | [
"Runs",
"a",
"temperature",
"simulation",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/hparams/hparams_minimal_demo.py#L135-L221 | train |
tensorflow/tensorboard | tensorboard/plugins/hparams/hparams_minimal_demo.py | run_all | def run_all(logdir, verbose=False):
"""Run simulations on a reasonable set of parameters.
Arguments:
logdir: the directory into which to store all the runs' data
verbose: if true, print out each run's name as it begins.
"""
writer = tf.summary.FileWriter(logdir)
writer.add_summary(create_experiment_summary())
writer.close()
session_num = 0
num_sessions = (len(TEMPERATURE_LIST)*len(TEMPERATURE_LIST)*
len(HEAT_COEFFICIENTS)*2)
for initial_temperature in TEMPERATURE_LIST:
for ambient_temperature in TEMPERATURE_LIST:
for material in HEAT_COEFFICIENTS:
hparams = {u'initial_temperature': initial_temperature,
u'ambient_temperature': ambient_temperature,
u'material': material}
hparam_str = str(hparams)
group_name = fingerprint(hparam_str)
for repeat_idx in xrange(2):
session_id = str(session_num)
if verbose:
print('--- Running training session %d/%d' % (session_num + 1,
num_sessions))
print(hparam_str)
print('--- repeat #: %d' % (repeat_idx+1))
run(logdir, session_id, hparams, group_name)
session_num += 1 | python | def run_all(logdir, verbose=False):
"""Run simulations on a reasonable set of parameters.
Arguments:
logdir: the directory into which to store all the runs' data
verbose: if true, print out each run's name as it begins.
"""
writer = tf.summary.FileWriter(logdir)
writer.add_summary(create_experiment_summary())
writer.close()
session_num = 0
num_sessions = (len(TEMPERATURE_LIST)*len(TEMPERATURE_LIST)*
len(HEAT_COEFFICIENTS)*2)
for initial_temperature in TEMPERATURE_LIST:
for ambient_temperature in TEMPERATURE_LIST:
for material in HEAT_COEFFICIENTS:
hparams = {u'initial_temperature': initial_temperature,
u'ambient_temperature': ambient_temperature,
u'material': material}
hparam_str = str(hparams)
group_name = fingerprint(hparam_str)
for repeat_idx in xrange(2):
session_id = str(session_num)
if verbose:
print('--- Running training session %d/%d' % (session_num + 1,
num_sessions))
print(hparam_str)
print('--- repeat #: %d' % (repeat_idx+1))
run(logdir, session_id, hparams, group_name)
session_num += 1 | [
"def",
"run_all",
"(",
"logdir",
",",
"verbose",
"=",
"False",
")",
":",
"writer",
"=",
"tf",
".",
"summary",
".",
"FileWriter",
"(",
"logdir",
")",
"writer",
".",
"add_summary",
"(",
"create_experiment_summary",
"(",
")",
")",
"writer",
".",
"close",
"(",
")",
"session_num",
"=",
"0",
"num_sessions",
"=",
"(",
"len",
"(",
"TEMPERATURE_LIST",
")",
"*",
"len",
"(",
"TEMPERATURE_LIST",
")",
"*",
"len",
"(",
"HEAT_COEFFICIENTS",
")",
"*",
"2",
")",
"for",
"initial_temperature",
"in",
"TEMPERATURE_LIST",
":",
"for",
"ambient_temperature",
"in",
"TEMPERATURE_LIST",
":",
"for",
"material",
"in",
"HEAT_COEFFICIENTS",
":",
"hparams",
"=",
"{",
"u'initial_temperature'",
":",
"initial_temperature",
",",
"u'ambient_temperature'",
":",
"ambient_temperature",
",",
"u'material'",
":",
"material",
"}",
"hparam_str",
"=",
"str",
"(",
"hparams",
")",
"group_name",
"=",
"fingerprint",
"(",
"hparam_str",
")",
"for",
"repeat_idx",
"in",
"xrange",
"(",
"2",
")",
":",
"session_id",
"=",
"str",
"(",
"session_num",
")",
"if",
"verbose",
":",
"print",
"(",
"'--- Running training session %d/%d'",
"%",
"(",
"session_num",
"+",
"1",
",",
"num_sessions",
")",
")",
"print",
"(",
"hparam_str",
")",
"print",
"(",
"'--- repeat #: %d'",
"%",
"(",
"repeat_idx",
"+",
"1",
")",
")",
"run",
"(",
"logdir",
",",
"session_id",
",",
"hparams",
",",
"group_name",
")",
"session_num",
"+=",
"1"
] | Run simulations on a reasonable set of parameters.
Arguments:
logdir: the directory into which to store all the runs' data
verbose: if true, print out each run's name as it begins. | [
"Run",
"simulations",
"on",
"a",
"reasonable",
"set",
"of",
"parameters",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/hparams/hparams_minimal_demo.py#L224-L253 | train |
tensorflow/tensorboard | tensorboard/compat/tensorflow_stub/io/gfile.py | get_filesystem | def get_filesystem(filename):
"""Return the registered filesystem for the given file."""
filename = compat.as_str_any(filename)
prefix = ""
index = filename.find("://")
if index >= 0:
prefix = filename[:index]
fs = _REGISTERED_FILESYSTEMS.get(prefix, None)
if fs is None:
raise ValueError("No recognized filesystem for prefix %s" % prefix)
return fs | python | def get_filesystem(filename):
"""Return the registered filesystem for the given file."""
filename = compat.as_str_any(filename)
prefix = ""
index = filename.find("://")
if index >= 0:
prefix = filename[:index]
fs = _REGISTERED_FILESYSTEMS.get(prefix, None)
if fs is None:
raise ValueError("No recognized filesystem for prefix %s" % prefix)
return fs | [
"def",
"get_filesystem",
"(",
"filename",
")",
":",
"filename",
"=",
"compat",
".",
"as_str_any",
"(",
"filename",
")",
"prefix",
"=",
"\"\"",
"index",
"=",
"filename",
".",
"find",
"(",
"\"://\"",
")",
"if",
"index",
">=",
"0",
":",
"prefix",
"=",
"filename",
"[",
":",
"index",
"]",
"fs",
"=",
"_REGISTERED_FILESYSTEMS",
".",
"get",
"(",
"prefix",
",",
"None",
")",
"if",
"fs",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"No recognized filesystem for prefix %s\"",
"%",
"prefix",
")",
"return",
"fs"
] | Return the registered filesystem for the given file. | [
"Return",
"the",
"registered",
"filesystem",
"for",
"the",
"given",
"file",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/compat/tensorflow_stub/io/gfile.py#L61-L71 | train |
tensorflow/tensorboard | tensorboard/compat/tensorflow_stub/io/gfile.py | walk | def walk(top, topdown=True, onerror=None):
"""Recursive directory tree generator for directories.
Args:
top: string, a Directory name
topdown: bool, Traverse pre order if True, post order if False.
onerror: optional handler for errors. Should be a function, it will be
called with the error as argument. Rethrowing the error aborts the walk.
Errors that happen while listing directories are ignored.
Yields:
Each yield is a 3-tuple: the pathname of a directory, followed by lists of
all its subdirectories and leaf files.
(dirname, [subdirname, subdirname, ...], [filename, filename, ...])
as strings
"""
top = compat.as_str_any(top)
fs = get_filesystem(top)
try:
listing = listdir(top)
except errors.NotFoundError as err:
if onerror:
onerror(err)
else:
return
files = []
subdirs = []
for item in listing:
full_path = fs.join(top, compat.as_str_any(item))
if isdir(full_path):
subdirs.append(item)
else:
files.append(item)
here = (top, subdirs, files)
if topdown:
yield here
for subdir in subdirs:
joined_subdir = fs.join(top, compat.as_str_any(subdir))
for subitem in walk(joined_subdir, topdown, onerror=onerror):
yield subitem
if not topdown:
yield here | python | def walk(top, topdown=True, onerror=None):
"""Recursive directory tree generator for directories.
Args:
top: string, a Directory name
topdown: bool, Traverse pre order if True, post order if False.
onerror: optional handler for errors. Should be a function, it will be
called with the error as argument. Rethrowing the error aborts the walk.
Errors that happen while listing directories are ignored.
Yields:
Each yield is a 3-tuple: the pathname of a directory, followed by lists of
all its subdirectories and leaf files.
(dirname, [subdirname, subdirname, ...], [filename, filename, ...])
as strings
"""
top = compat.as_str_any(top)
fs = get_filesystem(top)
try:
listing = listdir(top)
except errors.NotFoundError as err:
if onerror:
onerror(err)
else:
return
files = []
subdirs = []
for item in listing:
full_path = fs.join(top, compat.as_str_any(item))
if isdir(full_path):
subdirs.append(item)
else:
files.append(item)
here = (top, subdirs, files)
if topdown:
yield here
for subdir in subdirs:
joined_subdir = fs.join(top, compat.as_str_any(subdir))
for subitem in walk(joined_subdir, topdown, onerror=onerror):
yield subitem
if not topdown:
yield here | [
"def",
"walk",
"(",
"top",
",",
"topdown",
"=",
"True",
",",
"onerror",
"=",
"None",
")",
":",
"top",
"=",
"compat",
".",
"as_str_any",
"(",
"top",
")",
"fs",
"=",
"get_filesystem",
"(",
"top",
")",
"try",
":",
"listing",
"=",
"listdir",
"(",
"top",
")",
"except",
"errors",
".",
"NotFoundError",
"as",
"err",
":",
"if",
"onerror",
":",
"onerror",
"(",
"err",
")",
"else",
":",
"return",
"files",
"=",
"[",
"]",
"subdirs",
"=",
"[",
"]",
"for",
"item",
"in",
"listing",
":",
"full_path",
"=",
"fs",
".",
"join",
"(",
"top",
",",
"compat",
".",
"as_str_any",
"(",
"item",
")",
")",
"if",
"isdir",
"(",
"full_path",
")",
":",
"subdirs",
".",
"append",
"(",
"item",
")",
"else",
":",
"files",
".",
"append",
"(",
"item",
")",
"here",
"=",
"(",
"top",
",",
"subdirs",
",",
"files",
")",
"if",
"topdown",
":",
"yield",
"here",
"for",
"subdir",
"in",
"subdirs",
":",
"joined_subdir",
"=",
"fs",
".",
"join",
"(",
"top",
",",
"compat",
".",
"as_str_any",
"(",
"subdir",
")",
")",
"for",
"subitem",
"in",
"walk",
"(",
"joined_subdir",
",",
"topdown",
",",
"onerror",
"=",
"onerror",
")",
":",
"yield",
"subitem",
"if",
"not",
"topdown",
":",
"yield",
"here"
] | Recursive directory tree generator for directories.
Args:
top: string, a Directory name
topdown: bool, Traverse pre order if True, post order if False.
onerror: optional handler for errors. Should be a function, it will be
called with the error as argument. Rethrowing the error aborts the walk.
Errors that happen while listing directories are ignored.
Yields:
Each yield is a 3-tuple: the pathname of a directory, followed by lists of
all its subdirectories and leaf files.
(dirname, [subdirname, subdirname, ...], [filename, filename, ...])
as strings | [
"Recursive",
"directory",
"tree",
"generator",
"for",
"directories",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/compat/tensorflow_stub/io/gfile.py#L463-L510 | train |
tensorflow/tensorboard | tensorboard/compat/tensorflow_stub/io/gfile.py | LocalFileSystem.read | def read(self, filename, binary_mode=False, size=None, offset=None):
"""Reads contents of a file to a string.
Args:
filename: string, a path
binary_mode: bool, read as binary if True, otherwise text
size: int, number of bytes or characters to read, otherwise
read all the contents of the file from the offset
offset: int, offset into file to read from, otherwise read
from the very beginning
Returns:
Subset of the contents of the file as a string or bytes.
"""
mode = "rb" if binary_mode else "r"
with io.open(filename, mode) as f:
if offset is not None:
f.seek(offset)
if size is not None:
return f.read(size)
else:
return f.read() | python | def read(self, filename, binary_mode=False, size=None, offset=None):
"""Reads contents of a file to a string.
Args:
filename: string, a path
binary_mode: bool, read as binary if True, otherwise text
size: int, number of bytes or characters to read, otherwise
read all the contents of the file from the offset
offset: int, offset into file to read from, otherwise read
from the very beginning
Returns:
Subset of the contents of the file as a string or bytes.
"""
mode = "rb" if binary_mode else "r"
with io.open(filename, mode) as f:
if offset is not None:
f.seek(offset)
if size is not None:
return f.read(size)
else:
return f.read() | [
"def",
"read",
"(",
"self",
",",
"filename",
",",
"binary_mode",
"=",
"False",
",",
"size",
"=",
"None",
",",
"offset",
"=",
"None",
")",
":",
"mode",
"=",
"\"rb\"",
"if",
"binary_mode",
"else",
"\"r\"",
"with",
"io",
".",
"open",
"(",
"filename",
",",
"mode",
")",
"as",
"f",
":",
"if",
"offset",
"is",
"not",
"None",
":",
"f",
".",
"seek",
"(",
"offset",
")",
"if",
"size",
"is",
"not",
"None",
":",
"return",
"f",
".",
"read",
"(",
"size",
")",
"else",
":",
"return",
"f",
".",
"read",
"(",
")"
] | Reads contents of a file to a string.
Args:
filename: string, a path
binary_mode: bool, read as binary if True, otherwise text
size: int, number of bytes or characters to read, otherwise
read all the contents of the file from the offset
offset: int, offset into file to read from, otherwise read
from the very beginning
Returns:
Subset of the contents of the file as a string or bytes. | [
"Reads",
"contents",
"of",
"a",
"file",
"to",
"a",
"string",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/compat/tensorflow_stub/io/gfile.py#L89-L110 | train |
tensorflow/tensorboard | tensorboard/compat/tensorflow_stub/io/gfile.py | LocalFileSystem.glob | def glob(self, filename):
"""Returns a list of files that match the given pattern(s)."""
if isinstance(filename, six.string_types):
return [
# Convert the filenames to string from bytes.
compat.as_str_any(matching_filename)
for matching_filename in py_glob.glob(
compat.as_bytes(filename))
]
else:
return [
# Convert the filenames to string from bytes.
compat.as_str_any(matching_filename)
for single_filename in filename
for matching_filename in py_glob.glob(
compat.as_bytes(single_filename))
] | python | def glob(self, filename):
"""Returns a list of files that match the given pattern(s)."""
if isinstance(filename, six.string_types):
return [
# Convert the filenames to string from bytes.
compat.as_str_any(matching_filename)
for matching_filename in py_glob.glob(
compat.as_bytes(filename))
]
else:
return [
# Convert the filenames to string from bytes.
compat.as_str_any(matching_filename)
for single_filename in filename
for matching_filename in py_glob.glob(
compat.as_bytes(single_filename))
] | [
"def",
"glob",
"(",
"self",
",",
"filename",
")",
":",
"if",
"isinstance",
"(",
"filename",
",",
"six",
".",
"string_types",
")",
":",
"return",
"[",
"# Convert the filenames to string from bytes.",
"compat",
".",
"as_str_any",
"(",
"matching_filename",
")",
"for",
"matching_filename",
"in",
"py_glob",
".",
"glob",
"(",
"compat",
".",
"as_bytes",
"(",
"filename",
")",
")",
"]",
"else",
":",
"return",
"[",
"# Convert the filenames to string from bytes.",
"compat",
".",
"as_str_any",
"(",
"matching_filename",
")",
"for",
"single_filename",
"in",
"filename",
"for",
"matching_filename",
"in",
"py_glob",
".",
"glob",
"(",
"compat",
".",
"as_bytes",
"(",
"single_filename",
")",
")",
"]"
] | Returns a list of files that match the given pattern(s). | [
"Returns",
"a",
"list",
"of",
"files",
"that",
"match",
"the",
"given",
"pattern",
"(",
"s",
")",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/compat/tensorflow_stub/io/gfile.py#L112-L128 | train |
tensorflow/tensorboard | tensorboard/compat/tensorflow_stub/io/gfile.py | LocalFileSystem.listdir | def listdir(self, dirname):
"""Returns a list of entries contained within a directory."""
if not self.isdir(dirname):
raise errors.NotFoundError(None, None, "Could not find directory")
entries = os.listdir(compat.as_str_any(dirname))
entries = [compat.as_str_any(item) for item in entries]
return entries | python | def listdir(self, dirname):
"""Returns a list of entries contained within a directory."""
if not self.isdir(dirname):
raise errors.NotFoundError(None, None, "Could not find directory")
entries = os.listdir(compat.as_str_any(dirname))
entries = [compat.as_str_any(item) for item in entries]
return entries | [
"def",
"listdir",
"(",
"self",
",",
"dirname",
")",
":",
"if",
"not",
"self",
".",
"isdir",
"(",
"dirname",
")",
":",
"raise",
"errors",
".",
"NotFoundError",
"(",
"None",
",",
"None",
",",
"\"Could not find directory\"",
")",
"entries",
"=",
"os",
".",
"listdir",
"(",
"compat",
".",
"as_str_any",
"(",
"dirname",
")",
")",
"entries",
"=",
"[",
"compat",
".",
"as_str_any",
"(",
"item",
")",
"for",
"item",
"in",
"entries",
"]",
"return",
"entries"
] | Returns a list of entries contained within a directory. | [
"Returns",
"a",
"list",
"of",
"entries",
"contained",
"within",
"a",
"directory",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/compat/tensorflow_stub/io/gfile.py#L134-L141 | train |
tensorflow/tensorboard | tensorboard/compat/tensorflow_stub/io/gfile.py | LocalFileSystem.stat | def stat(self, filename):
"""Returns file statistics for a given path."""
# NOTE: Size of the file is given by .st_size as returned from
# os.stat(), but we convert to .length
try:
len = os.stat(compat.as_bytes(filename)).st_size
except OSError:
raise errors.NotFoundError(None, None, "Could not find file")
return StatData(len) | python | def stat(self, filename):
"""Returns file statistics for a given path."""
# NOTE: Size of the file is given by .st_size as returned from
# os.stat(), but we convert to .length
try:
len = os.stat(compat.as_bytes(filename)).st_size
except OSError:
raise errors.NotFoundError(None, None, "Could not find file")
return StatData(len) | [
"def",
"stat",
"(",
"self",
",",
"filename",
")",
":",
"# NOTE: Size of the file is given by .st_size as returned from",
"# os.stat(), but we convert to .length",
"try",
":",
"len",
"=",
"os",
".",
"stat",
"(",
"compat",
".",
"as_bytes",
"(",
"filename",
")",
")",
".",
"st_size",
"except",
"OSError",
":",
"raise",
"errors",
".",
"NotFoundError",
"(",
"None",
",",
"None",
",",
"\"Could not find file\"",
")",
"return",
"StatData",
"(",
"len",
")"
] | Returns file statistics for a given path. | [
"Returns",
"file",
"statistics",
"for",
"a",
"given",
"path",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/compat/tensorflow_stub/io/gfile.py#L143-L151 | train |
tensorflow/tensorboard | tensorboard/compat/tensorflow_stub/io/gfile.py | S3FileSystem.bucket_and_path | def bucket_and_path(self, url):
"""Split an S3-prefixed URL into bucket and path."""
url = compat.as_str_any(url)
if url.startswith("s3://"):
url = url[len("s3://"):]
idx = url.index("/")
bucket = url[:idx]
path = url[(idx + 1):]
return bucket, path | python | def bucket_and_path(self, url):
"""Split an S3-prefixed URL into bucket and path."""
url = compat.as_str_any(url)
if url.startswith("s3://"):
url = url[len("s3://"):]
idx = url.index("/")
bucket = url[:idx]
path = url[(idx + 1):]
return bucket, path | [
"def",
"bucket_and_path",
"(",
"self",
",",
"url",
")",
":",
"url",
"=",
"compat",
".",
"as_str_any",
"(",
"url",
")",
"if",
"url",
".",
"startswith",
"(",
"\"s3://\"",
")",
":",
"url",
"=",
"url",
"[",
"len",
"(",
"\"s3://\"",
")",
":",
"]",
"idx",
"=",
"url",
".",
"index",
"(",
"\"/\"",
")",
"bucket",
"=",
"url",
"[",
":",
"idx",
"]",
"path",
"=",
"url",
"[",
"(",
"idx",
"+",
"1",
")",
":",
"]",
"return",
"bucket",
",",
"path"
] | Split an S3-prefixed URL into bucket and path. | [
"Split",
"an",
"S3",
"-",
"prefixed",
"URL",
"into",
"bucket",
"and",
"path",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/compat/tensorflow_stub/io/gfile.py#L161-L169 | train |
tensorflow/tensorboard | tensorboard/compat/tensorflow_stub/io/gfile.py | S3FileSystem.exists | def exists(self, filename):
"""Determines whether a path exists or not."""
client = boto3.client("s3")
bucket, path = self.bucket_and_path(filename)
r = client.list_objects(Bucket=bucket, Prefix=path, Delimiter="/")
if r.get("Contents") or r.get("CommonPrefixes"):
return True
return False | python | def exists(self, filename):
"""Determines whether a path exists or not."""
client = boto3.client("s3")
bucket, path = self.bucket_and_path(filename)
r = client.list_objects(Bucket=bucket, Prefix=path, Delimiter="/")
if r.get("Contents") or r.get("CommonPrefixes"):
return True
return False | [
"def",
"exists",
"(",
"self",
",",
"filename",
")",
":",
"client",
"=",
"boto3",
".",
"client",
"(",
"\"s3\"",
")",
"bucket",
",",
"path",
"=",
"self",
".",
"bucket_and_path",
"(",
"filename",
")",
"r",
"=",
"client",
".",
"list_objects",
"(",
"Bucket",
"=",
"bucket",
",",
"Prefix",
"=",
"path",
",",
"Delimiter",
"=",
"\"/\"",
")",
"if",
"r",
".",
"get",
"(",
"\"Contents\"",
")",
"or",
"r",
".",
"get",
"(",
"\"CommonPrefixes\"",
")",
":",
"return",
"True",
"return",
"False"
] | Determines whether a path exists or not. | [
"Determines",
"whether",
"a",
"path",
"exists",
"or",
"not",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/compat/tensorflow_stub/io/gfile.py#L171-L178 | train |
tensorflow/tensorboard | tensorboard/compat/tensorflow_stub/io/gfile.py | S3FileSystem.read | def read(self, filename, binary_mode=False, size=None, offset=None):
"""Reads contents of a file to a string.
Args:
filename: string, a path
binary_mode: bool, read as binary if True, otherwise text
size: int, number of bytes or characters to read, otherwise
read all the contents of the file from the offset
offset: int, offset into file to read from, otherwise read
from the very beginning
Returns:
Subset of the contents of the file as a string or bytes.
"""
s3 = boto3.resource("s3")
bucket, path = self.bucket_and_path(filename)
args = {}
endpoint = 0
if size is not None or offset is not None:
if offset is None:
offset = 0
endpoint = '' if size is None else (offset + size)
args['Range'] = 'bytes={}-{}'.format(offset, endpoint)
try:
stream = s3.Object(bucket, path).get(**args)['Body'].read()
except botocore.exceptions.ClientError as exc:
if exc.response['Error']['Code'] == '416':
if size is not None:
# Asked for too much, so request just to the end. Do this
# in a second request so we don't check length in all cases.
client = boto3.client("s3")
obj = client.head_object(Bucket=bucket, Key=path)
len = obj['ContentLength']
endpoint = min(len, offset + size)
if offset == endpoint:
# Asked for no bytes, so just return empty
stream = b''
else:
args['Range'] = 'bytes={}-{}'.format(offset, endpoint)
stream = s3.Object(bucket, path).get(**args)['Body'].read()
else:
raise
if binary_mode:
return bytes(stream)
else:
return stream.decode('utf-8') | python | def read(self, filename, binary_mode=False, size=None, offset=None):
"""Reads contents of a file to a string.
Args:
filename: string, a path
binary_mode: bool, read as binary if True, otherwise text
size: int, number of bytes or characters to read, otherwise
read all the contents of the file from the offset
offset: int, offset into file to read from, otherwise read
from the very beginning
Returns:
Subset of the contents of the file as a string or bytes.
"""
s3 = boto3.resource("s3")
bucket, path = self.bucket_and_path(filename)
args = {}
endpoint = 0
if size is not None or offset is not None:
if offset is None:
offset = 0
endpoint = '' if size is None else (offset + size)
args['Range'] = 'bytes={}-{}'.format(offset, endpoint)
try:
stream = s3.Object(bucket, path).get(**args)['Body'].read()
except botocore.exceptions.ClientError as exc:
if exc.response['Error']['Code'] == '416':
if size is not None:
# Asked for too much, so request just to the end. Do this
# in a second request so we don't check length in all cases.
client = boto3.client("s3")
obj = client.head_object(Bucket=bucket, Key=path)
len = obj['ContentLength']
endpoint = min(len, offset + size)
if offset == endpoint:
# Asked for no bytes, so just return empty
stream = b''
else:
args['Range'] = 'bytes={}-{}'.format(offset, endpoint)
stream = s3.Object(bucket, path).get(**args)['Body'].read()
else:
raise
if binary_mode:
return bytes(stream)
else:
return stream.decode('utf-8') | [
"def",
"read",
"(",
"self",
",",
"filename",
",",
"binary_mode",
"=",
"False",
",",
"size",
"=",
"None",
",",
"offset",
"=",
"None",
")",
":",
"s3",
"=",
"boto3",
".",
"resource",
"(",
"\"s3\"",
")",
"bucket",
",",
"path",
"=",
"self",
".",
"bucket_and_path",
"(",
"filename",
")",
"args",
"=",
"{",
"}",
"endpoint",
"=",
"0",
"if",
"size",
"is",
"not",
"None",
"or",
"offset",
"is",
"not",
"None",
":",
"if",
"offset",
"is",
"None",
":",
"offset",
"=",
"0",
"endpoint",
"=",
"''",
"if",
"size",
"is",
"None",
"else",
"(",
"offset",
"+",
"size",
")",
"args",
"[",
"'Range'",
"]",
"=",
"'bytes={}-{}'",
".",
"format",
"(",
"offset",
",",
"endpoint",
")",
"try",
":",
"stream",
"=",
"s3",
".",
"Object",
"(",
"bucket",
",",
"path",
")",
".",
"get",
"(",
"*",
"*",
"args",
")",
"[",
"'Body'",
"]",
".",
"read",
"(",
")",
"except",
"botocore",
".",
"exceptions",
".",
"ClientError",
"as",
"exc",
":",
"if",
"exc",
".",
"response",
"[",
"'Error'",
"]",
"[",
"'Code'",
"]",
"==",
"'416'",
":",
"if",
"size",
"is",
"not",
"None",
":",
"# Asked for too much, so request just to the end. Do this",
"# in a second request so we don't check length in all cases.",
"client",
"=",
"boto3",
".",
"client",
"(",
"\"s3\"",
")",
"obj",
"=",
"client",
".",
"head_object",
"(",
"Bucket",
"=",
"bucket",
",",
"Key",
"=",
"path",
")",
"len",
"=",
"obj",
"[",
"'ContentLength'",
"]",
"endpoint",
"=",
"min",
"(",
"len",
",",
"offset",
"+",
"size",
")",
"if",
"offset",
"==",
"endpoint",
":",
"# Asked for no bytes, so just return empty",
"stream",
"=",
"b''",
"else",
":",
"args",
"[",
"'Range'",
"]",
"=",
"'bytes={}-{}'",
".",
"format",
"(",
"offset",
",",
"endpoint",
")",
"stream",
"=",
"s3",
".",
"Object",
"(",
"bucket",
",",
"path",
")",
".",
"get",
"(",
"*",
"*",
"args",
")",
"[",
"'Body'",
"]",
".",
"read",
"(",
")",
"else",
":",
"raise",
"if",
"binary_mode",
":",
"return",
"bytes",
"(",
"stream",
")",
"else",
":",
"return",
"stream",
".",
"decode",
"(",
"'utf-8'",
")"
] | Reads contents of a file to a string.
Args:
filename: string, a path
binary_mode: bool, read as binary if True, otherwise text
size: int, number of bytes or characters to read, otherwise
read all the contents of the file from the offset
offset: int, offset into file to read from, otherwise read
from the very beginning
Returns:
Subset of the contents of the file as a string or bytes. | [
"Reads",
"contents",
"of",
"a",
"file",
"to",
"a",
"string",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/compat/tensorflow_stub/io/gfile.py#L184-L229 | train |
tensorflow/tensorboard | tensorboard/compat/tensorflow_stub/io/gfile.py | S3FileSystem.glob | def glob(self, filename):
"""Returns a list of files that match the given pattern(s)."""
# Only support prefix with * at the end and no ? in the string
star_i = filename.find('*')
quest_i = filename.find('?')
if quest_i >= 0:
raise NotImplementedError(
"{} not supported by compat glob".format(filename))
if star_i != len(filename) - 1:
# Just return empty so we can use glob from directory watcher
#
# TODO: Remove and instead handle in GetLogdirSubdirectories.
# However, we would need to handle it for all non-local registered
# filesystems in some way.
return []
filename = filename[:-1]
client = boto3.client("s3")
bucket, path = self.bucket_and_path(filename)
p = client.get_paginator("list_objects")
keys = []
for r in p.paginate(Bucket=bucket, Prefix=path):
for o in r.get("Contents", []):
key = o["Key"][len(path):]
if key: # Skip the base dir, which would add an empty string
keys.append(filename + key)
return keys | python | def glob(self, filename):
"""Returns a list of files that match the given pattern(s)."""
# Only support prefix with * at the end and no ? in the string
star_i = filename.find('*')
quest_i = filename.find('?')
if quest_i >= 0:
raise NotImplementedError(
"{} not supported by compat glob".format(filename))
if star_i != len(filename) - 1:
# Just return empty so we can use glob from directory watcher
#
# TODO: Remove and instead handle in GetLogdirSubdirectories.
# However, we would need to handle it for all non-local registered
# filesystems in some way.
return []
filename = filename[:-1]
client = boto3.client("s3")
bucket, path = self.bucket_and_path(filename)
p = client.get_paginator("list_objects")
keys = []
for r in p.paginate(Bucket=bucket, Prefix=path):
for o in r.get("Contents", []):
key = o["Key"][len(path):]
if key: # Skip the base dir, which would add an empty string
keys.append(filename + key)
return keys | [
"def",
"glob",
"(",
"self",
",",
"filename",
")",
":",
"# Only support prefix with * at the end and no ? in the string",
"star_i",
"=",
"filename",
".",
"find",
"(",
"'*'",
")",
"quest_i",
"=",
"filename",
".",
"find",
"(",
"'?'",
")",
"if",
"quest_i",
">=",
"0",
":",
"raise",
"NotImplementedError",
"(",
"\"{} not supported by compat glob\"",
".",
"format",
"(",
"filename",
")",
")",
"if",
"star_i",
"!=",
"len",
"(",
"filename",
")",
"-",
"1",
":",
"# Just return empty so we can use glob from directory watcher",
"#",
"# TODO: Remove and instead handle in GetLogdirSubdirectories.",
"# However, we would need to handle it for all non-local registered",
"# filesystems in some way.",
"return",
"[",
"]",
"filename",
"=",
"filename",
"[",
":",
"-",
"1",
"]",
"client",
"=",
"boto3",
".",
"client",
"(",
"\"s3\"",
")",
"bucket",
",",
"path",
"=",
"self",
".",
"bucket_and_path",
"(",
"filename",
")",
"p",
"=",
"client",
".",
"get_paginator",
"(",
"\"list_objects\"",
")",
"keys",
"=",
"[",
"]",
"for",
"r",
"in",
"p",
".",
"paginate",
"(",
"Bucket",
"=",
"bucket",
",",
"Prefix",
"=",
"path",
")",
":",
"for",
"o",
"in",
"r",
".",
"get",
"(",
"\"Contents\"",
",",
"[",
"]",
")",
":",
"key",
"=",
"o",
"[",
"\"Key\"",
"]",
"[",
"len",
"(",
"path",
")",
":",
"]",
"if",
"key",
":",
"# Skip the base dir, which would add an empty string",
"keys",
".",
"append",
"(",
"filename",
"+",
"key",
")",
"return",
"keys"
] | Returns a list of files that match the given pattern(s). | [
"Returns",
"a",
"list",
"of",
"files",
"that",
"match",
"the",
"given",
"pattern",
"(",
"s",
")",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/compat/tensorflow_stub/io/gfile.py#L231-L256 | train |
tensorflow/tensorboard | tensorboard/compat/tensorflow_stub/io/gfile.py | S3FileSystem.isdir | def isdir(self, dirname):
"""Returns whether the path is a directory or not."""
client = boto3.client("s3")
bucket, path = self.bucket_and_path(dirname)
if not path.endswith("/"):
path += "/" # This will now only retrieve subdir content
r = client.list_objects(Bucket=bucket, Prefix=path, Delimiter="/")
if r.get("Contents") or r.get("CommonPrefixes"):
return True
return False | python | def isdir(self, dirname):
"""Returns whether the path is a directory or not."""
client = boto3.client("s3")
bucket, path = self.bucket_and_path(dirname)
if not path.endswith("/"):
path += "/" # This will now only retrieve subdir content
r = client.list_objects(Bucket=bucket, Prefix=path, Delimiter="/")
if r.get("Contents") or r.get("CommonPrefixes"):
return True
return False | [
"def",
"isdir",
"(",
"self",
",",
"dirname",
")",
":",
"client",
"=",
"boto3",
".",
"client",
"(",
"\"s3\"",
")",
"bucket",
",",
"path",
"=",
"self",
".",
"bucket_and_path",
"(",
"dirname",
")",
"if",
"not",
"path",
".",
"endswith",
"(",
"\"/\"",
")",
":",
"path",
"+=",
"\"/\"",
"# This will now only retrieve subdir content",
"r",
"=",
"client",
".",
"list_objects",
"(",
"Bucket",
"=",
"bucket",
",",
"Prefix",
"=",
"path",
",",
"Delimiter",
"=",
"\"/\"",
")",
"if",
"r",
".",
"get",
"(",
"\"Contents\"",
")",
"or",
"r",
".",
"get",
"(",
"\"CommonPrefixes\"",
")",
":",
"return",
"True",
"return",
"False"
] | Returns whether the path is a directory or not. | [
"Returns",
"whether",
"the",
"path",
"is",
"a",
"directory",
"or",
"not",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/compat/tensorflow_stub/io/gfile.py#L258-L267 | train |
tensorflow/tensorboard | tensorboard/compat/tensorflow_stub/io/gfile.py | S3FileSystem.listdir | def listdir(self, dirname):
"""Returns a list of entries contained within a directory."""
client = boto3.client("s3")
bucket, path = self.bucket_and_path(dirname)
p = client.get_paginator("list_objects")
if not path.endswith("/"):
path += "/" # This will now only retrieve subdir content
keys = []
for r in p.paginate(Bucket=bucket, Prefix=path, Delimiter="/"):
keys.extend(o["Prefix"][len(path):-1] for o in r.get("CommonPrefixes", []))
for o in r.get("Contents", []):
key = o["Key"][len(path):]
if key: # Skip the base dir, which would add an empty string
keys.append(key)
return keys | python | def listdir(self, dirname):
"""Returns a list of entries contained within a directory."""
client = boto3.client("s3")
bucket, path = self.bucket_and_path(dirname)
p = client.get_paginator("list_objects")
if not path.endswith("/"):
path += "/" # This will now only retrieve subdir content
keys = []
for r in p.paginate(Bucket=bucket, Prefix=path, Delimiter="/"):
keys.extend(o["Prefix"][len(path):-1] for o in r.get("CommonPrefixes", []))
for o in r.get("Contents", []):
key = o["Key"][len(path):]
if key: # Skip the base dir, which would add an empty string
keys.append(key)
return keys | [
"def",
"listdir",
"(",
"self",
",",
"dirname",
")",
":",
"client",
"=",
"boto3",
".",
"client",
"(",
"\"s3\"",
")",
"bucket",
",",
"path",
"=",
"self",
".",
"bucket_and_path",
"(",
"dirname",
")",
"p",
"=",
"client",
".",
"get_paginator",
"(",
"\"list_objects\"",
")",
"if",
"not",
"path",
".",
"endswith",
"(",
"\"/\"",
")",
":",
"path",
"+=",
"\"/\"",
"# This will now only retrieve subdir content",
"keys",
"=",
"[",
"]",
"for",
"r",
"in",
"p",
".",
"paginate",
"(",
"Bucket",
"=",
"bucket",
",",
"Prefix",
"=",
"path",
",",
"Delimiter",
"=",
"\"/\"",
")",
":",
"keys",
".",
"extend",
"(",
"o",
"[",
"\"Prefix\"",
"]",
"[",
"len",
"(",
"path",
")",
":",
"-",
"1",
"]",
"for",
"o",
"in",
"r",
".",
"get",
"(",
"\"CommonPrefixes\"",
",",
"[",
"]",
")",
")",
"for",
"o",
"in",
"r",
".",
"get",
"(",
"\"Contents\"",
",",
"[",
"]",
")",
":",
"key",
"=",
"o",
"[",
"\"Key\"",
"]",
"[",
"len",
"(",
"path",
")",
":",
"]",
"if",
"key",
":",
"# Skip the base dir, which would add an empty string",
"keys",
".",
"append",
"(",
"key",
")",
"return",
"keys"
] | Returns a list of entries contained within a directory. | [
"Returns",
"a",
"list",
"of",
"entries",
"contained",
"within",
"a",
"directory",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/compat/tensorflow_stub/io/gfile.py#L269-L283 | train |
tensorflow/tensorboard | tensorboard/compat/tensorflow_stub/io/gfile.py | S3FileSystem.stat | def stat(self, filename):
"""Returns file statistics for a given path."""
# NOTE: Size of the file is given by ContentLength from S3,
# but we convert to .length
client = boto3.client("s3")
bucket, path = self.bucket_and_path(filename)
try:
obj = client.head_object(Bucket=bucket, Key=path)
return StatData(obj['ContentLength'])
except botocore.exceptions.ClientError as exc:
if exc.response['Error']['Code'] == '404':
raise errors.NotFoundError(None, None, "Could not find file")
else:
raise | python | def stat(self, filename):
"""Returns file statistics for a given path."""
# NOTE: Size of the file is given by ContentLength from S3,
# but we convert to .length
client = boto3.client("s3")
bucket, path = self.bucket_and_path(filename)
try:
obj = client.head_object(Bucket=bucket, Key=path)
return StatData(obj['ContentLength'])
except botocore.exceptions.ClientError as exc:
if exc.response['Error']['Code'] == '404':
raise errors.NotFoundError(None, None, "Could not find file")
else:
raise | [
"def",
"stat",
"(",
"self",
",",
"filename",
")",
":",
"# NOTE: Size of the file is given by ContentLength from S3,",
"# but we convert to .length",
"client",
"=",
"boto3",
".",
"client",
"(",
"\"s3\"",
")",
"bucket",
",",
"path",
"=",
"self",
".",
"bucket_and_path",
"(",
"filename",
")",
"try",
":",
"obj",
"=",
"client",
".",
"head_object",
"(",
"Bucket",
"=",
"bucket",
",",
"Key",
"=",
"path",
")",
"return",
"StatData",
"(",
"obj",
"[",
"'ContentLength'",
"]",
")",
"except",
"botocore",
".",
"exceptions",
".",
"ClientError",
"as",
"exc",
":",
"if",
"exc",
".",
"response",
"[",
"'Error'",
"]",
"[",
"'Code'",
"]",
"==",
"'404'",
":",
"raise",
"errors",
".",
"NotFoundError",
"(",
"None",
",",
"None",
",",
"\"Could not find file\"",
")",
"else",
":",
"raise"
] | Returns file statistics for a given path. | [
"Returns",
"file",
"statistics",
"for",
"a",
"given",
"path",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/compat/tensorflow_stub/io/gfile.py#L285-L298 | train |
tensorflow/tensorboard | tensorboard/notebook.py | _get_context | def _get_context():
"""Determine the most specific context that we're in.
Returns:
_CONTEXT_COLAB: If in Colab with an IPython notebook context.
_CONTEXT_IPYTHON: If not in Colab, but we are in an IPython notebook
context (e.g., from running `jupyter notebook` at the command
line).
_CONTEXT_NONE: Otherwise (e.g., by running a Python script at the
command-line or using the `ipython` interactive shell).
"""
# In Colab, the `google.colab` module is available, but the shell
# returned by `IPython.get_ipython` does not have a `get_trait`
# method.
try:
import google.colab
import IPython
except ImportError:
pass
else:
if IPython.get_ipython() is not None:
# We'll assume that we're in a Colab notebook context.
return _CONTEXT_COLAB
# In an IPython command line shell or Jupyter notebook, we can
# directly query whether we're in a notebook context.
try:
import IPython
except ImportError:
pass
else:
ipython = IPython.get_ipython()
if ipython is not None and ipython.has_trait("kernel"):
return _CONTEXT_IPYTHON
# Otherwise, we're not in a known notebook context.
return _CONTEXT_NONE | python | def _get_context():
"""Determine the most specific context that we're in.
Returns:
_CONTEXT_COLAB: If in Colab with an IPython notebook context.
_CONTEXT_IPYTHON: If not in Colab, but we are in an IPython notebook
context (e.g., from running `jupyter notebook` at the command
line).
_CONTEXT_NONE: Otherwise (e.g., by running a Python script at the
command-line or using the `ipython` interactive shell).
"""
# In Colab, the `google.colab` module is available, but the shell
# returned by `IPython.get_ipython` does not have a `get_trait`
# method.
try:
import google.colab
import IPython
except ImportError:
pass
else:
if IPython.get_ipython() is not None:
# We'll assume that we're in a Colab notebook context.
return _CONTEXT_COLAB
# In an IPython command line shell or Jupyter notebook, we can
# directly query whether we're in a notebook context.
try:
import IPython
except ImportError:
pass
else:
ipython = IPython.get_ipython()
if ipython is not None and ipython.has_trait("kernel"):
return _CONTEXT_IPYTHON
# Otherwise, we're not in a known notebook context.
return _CONTEXT_NONE | [
"def",
"_get_context",
"(",
")",
":",
"# In Colab, the `google.colab` module is available, but the shell",
"# returned by `IPython.get_ipython` does not have a `get_trait`",
"# method.",
"try",
":",
"import",
"google",
".",
"colab",
"import",
"IPython",
"except",
"ImportError",
":",
"pass",
"else",
":",
"if",
"IPython",
".",
"get_ipython",
"(",
")",
"is",
"not",
"None",
":",
"# We'll assume that we're in a Colab notebook context.",
"return",
"_CONTEXT_COLAB",
"# In an IPython command line shell or Jupyter notebook, we can",
"# directly query whether we're in a notebook context.",
"try",
":",
"import",
"IPython",
"except",
"ImportError",
":",
"pass",
"else",
":",
"ipython",
"=",
"IPython",
".",
"get_ipython",
"(",
")",
"if",
"ipython",
"is",
"not",
"None",
"and",
"ipython",
".",
"has_trait",
"(",
"\"kernel\"",
")",
":",
"return",
"_CONTEXT_IPYTHON",
"# Otherwise, we're not in a known notebook context.",
"return",
"_CONTEXT_NONE"
] | Determine the most specific context that we're in.
Returns:
_CONTEXT_COLAB: If in Colab with an IPython notebook context.
_CONTEXT_IPYTHON: If not in Colab, but we are in an IPython notebook
context (e.g., from running `jupyter notebook` at the command
line).
_CONTEXT_NONE: Otherwise (e.g., by running a Python script at the
command-line or using the `ipython` interactive shell). | [
"Determine",
"the",
"most",
"specific",
"context",
"that",
"we",
"re",
"in",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/notebook.py#L38-L74 | train |
tensorflow/tensorboard | tensorboard/notebook.py | start | def start(args_string):
"""Launch and display a TensorBoard instance as if at the command line.
Args:
args_string: Command-line arguments to TensorBoard, to be
interpreted by `shlex.split`: e.g., "--logdir ./logs --port 0".
Shell metacharacters are not supported: e.g., "--logdir 2>&1" will
point the logdir at the literal directory named "2>&1".
"""
context = _get_context()
try:
import IPython
import IPython.display
except ImportError:
IPython = None
if context == _CONTEXT_NONE:
handle = None
print("Launching TensorBoard...")
else:
handle = IPython.display.display(
IPython.display.Pretty("Launching TensorBoard..."),
display_id=True,
)
def print_or_update(message):
if handle is None:
print(message)
else:
handle.update(IPython.display.Pretty(message))
parsed_args = shlex.split(args_string, comments=True, posix=True)
start_result = manager.start(parsed_args)
if isinstance(start_result, manager.StartLaunched):
_display(
port=start_result.info.port,
print_message=False,
display_handle=handle,
)
elif isinstance(start_result, manager.StartReused):
template = (
"Reusing TensorBoard on port {port} (pid {pid}), started {delta} ago. "
"(Use '!kill {pid}' to kill it.)"
)
message = template.format(
port=start_result.info.port,
pid=start_result.info.pid,
delta=_time_delta_from_info(start_result.info),
)
print_or_update(message)
_display(
port=start_result.info.port,
print_message=False,
display_handle=None,
)
elif isinstance(start_result, manager.StartFailed):
def format_stream(name, value):
if value == "":
return ""
elif value is None:
return "\n<could not read %s>" % name
else:
return "\nContents of %s:\n%s" % (name, value.strip())
message = (
"ERROR: Failed to launch TensorBoard (exited with %d).%s%s" %
(
start_result.exit_code,
format_stream("stderr", start_result.stderr),
format_stream("stdout", start_result.stdout),
)
)
print_or_update(message)
elif isinstance(start_result, manager.StartTimedOut):
message = (
"ERROR: Timed out waiting for TensorBoard to start. "
"It may still be running as pid %d."
% start_result.pid
)
print_or_update(message)
else:
raise TypeError(
"Unexpected result from `manager.start`: %r.\n"
"This is a TensorBoard bug; please report it."
% start_result
) | python | def start(args_string):
"""Launch and display a TensorBoard instance as if at the command line.
Args:
args_string: Command-line arguments to TensorBoard, to be
interpreted by `shlex.split`: e.g., "--logdir ./logs --port 0".
Shell metacharacters are not supported: e.g., "--logdir 2>&1" will
point the logdir at the literal directory named "2>&1".
"""
context = _get_context()
try:
import IPython
import IPython.display
except ImportError:
IPython = None
if context == _CONTEXT_NONE:
handle = None
print("Launching TensorBoard...")
else:
handle = IPython.display.display(
IPython.display.Pretty("Launching TensorBoard..."),
display_id=True,
)
def print_or_update(message):
if handle is None:
print(message)
else:
handle.update(IPython.display.Pretty(message))
parsed_args = shlex.split(args_string, comments=True, posix=True)
start_result = manager.start(parsed_args)
if isinstance(start_result, manager.StartLaunched):
_display(
port=start_result.info.port,
print_message=False,
display_handle=handle,
)
elif isinstance(start_result, manager.StartReused):
template = (
"Reusing TensorBoard on port {port} (pid {pid}), started {delta} ago. "
"(Use '!kill {pid}' to kill it.)"
)
message = template.format(
port=start_result.info.port,
pid=start_result.info.pid,
delta=_time_delta_from_info(start_result.info),
)
print_or_update(message)
_display(
port=start_result.info.port,
print_message=False,
display_handle=None,
)
elif isinstance(start_result, manager.StartFailed):
def format_stream(name, value):
if value == "":
return ""
elif value is None:
return "\n<could not read %s>" % name
else:
return "\nContents of %s:\n%s" % (name, value.strip())
message = (
"ERROR: Failed to launch TensorBoard (exited with %d).%s%s" %
(
start_result.exit_code,
format_stream("stderr", start_result.stderr),
format_stream("stdout", start_result.stdout),
)
)
print_or_update(message)
elif isinstance(start_result, manager.StartTimedOut):
message = (
"ERROR: Timed out waiting for TensorBoard to start. "
"It may still be running as pid %d."
% start_result.pid
)
print_or_update(message)
else:
raise TypeError(
"Unexpected result from `manager.start`: %r.\n"
"This is a TensorBoard bug; please report it."
% start_result
) | [
"def",
"start",
"(",
"args_string",
")",
":",
"context",
"=",
"_get_context",
"(",
")",
"try",
":",
"import",
"IPython",
"import",
"IPython",
".",
"display",
"except",
"ImportError",
":",
"IPython",
"=",
"None",
"if",
"context",
"==",
"_CONTEXT_NONE",
":",
"handle",
"=",
"None",
"print",
"(",
"\"Launching TensorBoard...\"",
")",
"else",
":",
"handle",
"=",
"IPython",
".",
"display",
".",
"display",
"(",
"IPython",
".",
"display",
".",
"Pretty",
"(",
"\"Launching TensorBoard...\"",
")",
",",
"display_id",
"=",
"True",
",",
")",
"def",
"print_or_update",
"(",
"message",
")",
":",
"if",
"handle",
"is",
"None",
":",
"print",
"(",
"message",
")",
"else",
":",
"handle",
".",
"update",
"(",
"IPython",
".",
"display",
".",
"Pretty",
"(",
"message",
")",
")",
"parsed_args",
"=",
"shlex",
".",
"split",
"(",
"args_string",
",",
"comments",
"=",
"True",
",",
"posix",
"=",
"True",
")",
"start_result",
"=",
"manager",
".",
"start",
"(",
"parsed_args",
")",
"if",
"isinstance",
"(",
"start_result",
",",
"manager",
".",
"StartLaunched",
")",
":",
"_display",
"(",
"port",
"=",
"start_result",
".",
"info",
".",
"port",
",",
"print_message",
"=",
"False",
",",
"display_handle",
"=",
"handle",
",",
")",
"elif",
"isinstance",
"(",
"start_result",
",",
"manager",
".",
"StartReused",
")",
":",
"template",
"=",
"(",
"\"Reusing TensorBoard on port {port} (pid {pid}), started {delta} ago. \"",
"\"(Use '!kill {pid}' to kill it.)\"",
")",
"message",
"=",
"template",
".",
"format",
"(",
"port",
"=",
"start_result",
".",
"info",
".",
"port",
",",
"pid",
"=",
"start_result",
".",
"info",
".",
"pid",
",",
"delta",
"=",
"_time_delta_from_info",
"(",
"start_result",
".",
"info",
")",
",",
")",
"print_or_update",
"(",
"message",
")",
"_display",
"(",
"port",
"=",
"start_result",
".",
"info",
".",
"port",
",",
"print_message",
"=",
"False",
",",
"display_handle",
"=",
"None",
",",
")",
"elif",
"isinstance",
"(",
"start_result",
",",
"manager",
".",
"StartFailed",
")",
":",
"def",
"format_stream",
"(",
"name",
",",
"value",
")",
":",
"if",
"value",
"==",
"\"\"",
":",
"return",
"\"\"",
"elif",
"value",
"is",
"None",
":",
"return",
"\"\\n<could not read %s>\"",
"%",
"name",
"else",
":",
"return",
"\"\\nContents of %s:\\n%s\"",
"%",
"(",
"name",
",",
"value",
".",
"strip",
"(",
")",
")",
"message",
"=",
"(",
"\"ERROR: Failed to launch TensorBoard (exited with %d).%s%s\"",
"%",
"(",
"start_result",
".",
"exit_code",
",",
"format_stream",
"(",
"\"stderr\"",
",",
"start_result",
".",
"stderr",
")",
",",
"format_stream",
"(",
"\"stdout\"",
",",
"start_result",
".",
"stdout",
")",
",",
")",
")",
"print_or_update",
"(",
"message",
")",
"elif",
"isinstance",
"(",
"start_result",
",",
"manager",
".",
"StartTimedOut",
")",
":",
"message",
"=",
"(",
"\"ERROR: Timed out waiting for TensorBoard to start. \"",
"\"It may still be running as pid %d.\"",
"%",
"start_result",
".",
"pid",
")",
"print_or_update",
"(",
"message",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"Unexpected result from `manager.start`: %r.\\n\"",
"\"This is a TensorBoard bug; please report it.\"",
"%",
"start_result",
")"
] | Launch and display a TensorBoard instance as if at the command line.
Args:
args_string: Command-line arguments to TensorBoard, to be
interpreted by `shlex.split`: e.g., "--logdir ./logs --port 0".
Shell metacharacters are not supported: e.g., "--logdir 2>&1" will
point the logdir at the literal directory named "2>&1". | [
"Launch",
"and",
"display",
"a",
"TensorBoard",
"instance",
"as",
"if",
"at",
"the",
"command",
"line",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/notebook.py#L118-L207 | train |
tensorflow/tensorboard | tensorboard/notebook.py | _time_delta_from_info | def _time_delta_from_info(info):
"""Format the elapsed time for the given TensorBoardInfo.
Args:
info: A TensorBoardInfo value.
Returns:
A human-readable string describing the time since the server
described by `info` started: e.g., "2 days, 0:48:58".
"""
delta_seconds = int(time.time()) - info.start_time
return str(datetime.timedelta(seconds=delta_seconds)) | python | def _time_delta_from_info(info):
"""Format the elapsed time for the given TensorBoardInfo.
Args:
info: A TensorBoardInfo value.
Returns:
A human-readable string describing the time since the server
described by `info` started: e.g., "2 days, 0:48:58".
"""
delta_seconds = int(time.time()) - info.start_time
return str(datetime.timedelta(seconds=delta_seconds)) | [
"def",
"_time_delta_from_info",
"(",
"info",
")",
":",
"delta_seconds",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
"-",
"info",
".",
"start_time",
"return",
"str",
"(",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"delta_seconds",
")",
")"
] | Format the elapsed time for the given TensorBoardInfo.
Args:
info: A TensorBoardInfo value.
Returns:
A human-readable string describing the time since the server
described by `info` started: e.g., "2 days, 0:48:58". | [
"Format",
"the",
"elapsed",
"time",
"for",
"the",
"given",
"TensorBoardInfo",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/notebook.py#L210-L221 | train |
tensorflow/tensorboard | tensorboard/notebook.py | display | def display(port=None, height=None):
"""Display a TensorBoard instance already running on this machine.
Args:
port: The port on which the TensorBoard server is listening, as an
`int`, or `None` to automatically select the most recently
launched TensorBoard.
height: The height of the frame into which to render the TensorBoard
UI, as an `int` number of pixels, or `None` to use a default value
(currently 800).
"""
_display(port=port, height=height, print_message=True, display_handle=None) | python | def display(port=None, height=None):
"""Display a TensorBoard instance already running on this machine.
Args:
port: The port on which the TensorBoard server is listening, as an
`int`, or `None` to automatically select the most recently
launched TensorBoard.
height: The height of the frame into which to render the TensorBoard
UI, as an `int` number of pixels, or `None` to use a default value
(currently 800).
"""
_display(port=port, height=height, print_message=True, display_handle=None) | [
"def",
"display",
"(",
"port",
"=",
"None",
",",
"height",
"=",
"None",
")",
":",
"_display",
"(",
"port",
"=",
"port",
",",
"height",
"=",
"height",
",",
"print_message",
"=",
"True",
",",
"display_handle",
"=",
"None",
")"
] | Display a TensorBoard instance already running on this machine.
Args:
port: The port on which the TensorBoard server is listening, as an
`int`, or `None` to automatically select the most recently
launched TensorBoard.
height: The height of the frame into which to render the TensorBoard
UI, as an `int` number of pixels, or `None` to use a default value
(currently 800). | [
"Display",
"a",
"TensorBoard",
"instance",
"already",
"running",
"on",
"this",
"machine",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/notebook.py#L224-L235 | train |
tensorflow/tensorboard | tensorboard/notebook.py | _display | def _display(port=None, height=None, print_message=False, display_handle=None):
"""Internal version of `display`.
Args:
port: As with `display`.
height: As with `display`.
print_message: True to print which TensorBoard instance was selected
for display (if applicable), or False otherwise.
display_handle: If not None, an IPython display handle into which to
render TensorBoard.
"""
if height is None:
height = 800
if port is None:
infos = manager.get_all()
if not infos:
raise ValueError("Can't display TensorBoard: no known instances running.")
else:
info = max(manager.get_all(), key=lambda x: x.start_time)
port = info.port
else:
infos = [i for i in manager.get_all() if i.port == port]
info = (
max(infos, key=lambda x: x.start_time)
if infos
else None
)
if print_message:
if info is not None:
message = (
"Selecting TensorBoard with {data_source} "
"(started {delta} ago; port {port}, pid {pid})."
).format(
data_source=manager.data_source_from_info(info),
delta=_time_delta_from_info(info),
port=info.port,
pid=info.pid,
)
print(message)
else:
# The user explicitly provided a port, and we don't have any
# additional information. There's nothing useful to say.
pass
fn = {
_CONTEXT_COLAB: _display_colab,
_CONTEXT_IPYTHON: _display_ipython,
_CONTEXT_NONE: _display_cli,
}[_get_context()]
return fn(port=port, height=height, display_handle=display_handle) | python | def _display(port=None, height=None, print_message=False, display_handle=None):
"""Internal version of `display`.
Args:
port: As with `display`.
height: As with `display`.
print_message: True to print which TensorBoard instance was selected
for display (if applicable), or False otherwise.
display_handle: If not None, an IPython display handle into which to
render TensorBoard.
"""
if height is None:
height = 800
if port is None:
infos = manager.get_all()
if not infos:
raise ValueError("Can't display TensorBoard: no known instances running.")
else:
info = max(manager.get_all(), key=lambda x: x.start_time)
port = info.port
else:
infos = [i for i in manager.get_all() if i.port == port]
info = (
max(infos, key=lambda x: x.start_time)
if infos
else None
)
if print_message:
if info is not None:
message = (
"Selecting TensorBoard with {data_source} "
"(started {delta} ago; port {port}, pid {pid})."
).format(
data_source=manager.data_source_from_info(info),
delta=_time_delta_from_info(info),
port=info.port,
pid=info.pid,
)
print(message)
else:
# The user explicitly provided a port, and we don't have any
# additional information. There's nothing useful to say.
pass
fn = {
_CONTEXT_COLAB: _display_colab,
_CONTEXT_IPYTHON: _display_ipython,
_CONTEXT_NONE: _display_cli,
}[_get_context()]
return fn(port=port, height=height, display_handle=display_handle) | [
"def",
"_display",
"(",
"port",
"=",
"None",
",",
"height",
"=",
"None",
",",
"print_message",
"=",
"False",
",",
"display_handle",
"=",
"None",
")",
":",
"if",
"height",
"is",
"None",
":",
"height",
"=",
"800",
"if",
"port",
"is",
"None",
":",
"infos",
"=",
"manager",
".",
"get_all",
"(",
")",
"if",
"not",
"infos",
":",
"raise",
"ValueError",
"(",
"\"Can't display TensorBoard: no known instances running.\"",
")",
"else",
":",
"info",
"=",
"max",
"(",
"manager",
".",
"get_all",
"(",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"start_time",
")",
"port",
"=",
"info",
".",
"port",
"else",
":",
"infos",
"=",
"[",
"i",
"for",
"i",
"in",
"manager",
".",
"get_all",
"(",
")",
"if",
"i",
".",
"port",
"==",
"port",
"]",
"info",
"=",
"(",
"max",
"(",
"infos",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"start_time",
")",
"if",
"infos",
"else",
"None",
")",
"if",
"print_message",
":",
"if",
"info",
"is",
"not",
"None",
":",
"message",
"=",
"(",
"\"Selecting TensorBoard with {data_source} \"",
"\"(started {delta} ago; port {port}, pid {pid}).\"",
")",
".",
"format",
"(",
"data_source",
"=",
"manager",
".",
"data_source_from_info",
"(",
"info",
")",
",",
"delta",
"=",
"_time_delta_from_info",
"(",
"info",
")",
",",
"port",
"=",
"info",
".",
"port",
",",
"pid",
"=",
"info",
".",
"pid",
",",
")",
"print",
"(",
"message",
")",
"else",
":",
"# The user explicitly provided a port, and we don't have any",
"# additional information. There's nothing useful to say.",
"pass",
"fn",
"=",
"{",
"_CONTEXT_COLAB",
":",
"_display_colab",
",",
"_CONTEXT_IPYTHON",
":",
"_display_ipython",
",",
"_CONTEXT_NONE",
":",
"_display_cli",
",",
"}",
"[",
"_get_context",
"(",
")",
"]",
"return",
"fn",
"(",
"port",
"=",
"port",
",",
"height",
"=",
"height",
",",
"display_handle",
"=",
"display_handle",
")"
] | Internal version of `display`.
Args:
port: As with `display`.
height: As with `display`.
print_message: True to print which TensorBoard instance was selected
for display (if applicable), or False otherwise.
display_handle: If not None, an IPython display handle into which to
render TensorBoard. | [
"Internal",
"version",
"of",
"display",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/notebook.py#L238-L289 | train |
tensorflow/tensorboard | tensorboard/notebook.py | _display_colab | def _display_colab(port, height, display_handle):
"""Display a TensorBoard instance in a Colab output frame.
The Colab VM is not directly exposed to the network, so the Colab
runtime provides a service worker tunnel to proxy requests from the
end user's browser through to servers running on the Colab VM: the
output frame may issue requests to https://localhost:<port> (HTTPS
only), which will be forwarded to the specified port on the VM.
It does not suffice to create an `iframe` and let the service worker
redirect its traffic (`<iframe src="https://localhost:6006">`),
because for security reasons service workers cannot intercept iframe
traffic. Instead, we manually fetch the TensorBoard index page with an
XHR in the output frame, and inject the raw HTML into `document.body`.
By default, the TensorBoard web app requests resources against
relative paths, like `./data/logdir`. Within the output frame, these
requests must instead hit `https://localhost:<port>/data/logdir`. To
redirect them, we change the document base URI, which transparently
affects all requests (XHRs and resources alike).
"""
import IPython.display
shell = """
<div id="root"></div>
<script>
(function() {
window.TENSORBOARD_ENV = window.TENSORBOARD_ENV || {};
window.TENSORBOARD_ENV["IN_COLAB"] = true;
document.querySelector("base").href = "https://localhost:%PORT%";
function fixUpTensorboard(root) {
const tftb = root.querySelector("tf-tensorboard");
// Disable the fragment manipulation behavior in Colab. Not
// only is the behavior not useful (as the iframe's location
// is not visible to the user), it causes TensorBoard's usage
// of `window.replace` to navigate away from the page and to
// the `localhost:<port>` URL specified by the base URI, which
// in turn causes the frame to (likely) crash.
tftb.removeAttribute("use-hash");
}
function executeAllScripts(root) {
// When `script` elements are inserted into the DOM by
// assigning to an element's `innerHTML`, the scripts are not
// executed. Thus, we manually re-insert these scripts so that
// TensorBoard can initialize itself.
for (const script of root.querySelectorAll("script")) {
const newScript = document.createElement("script");
newScript.type = script.type;
newScript.textContent = script.textContent;
root.appendChild(newScript);
script.remove();
}
}
function setHeight(root, height) {
// We set the height dynamically after the TensorBoard UI has
// been initialized. This avoids an intermediate state in
// which the container plus the UI become taller than the
// final width and cause the Colab output frame to be
// permanently resized, eventually leading to an empty
// vertical gap below the TensorBoard UI. It's not clear
// exactly what causes this problematic intermediate state,
// but setting the height late seems to fix it.
root.style.height = `${height}px`;
}
const root = document.getElementById("root");
fetch(".")
.then((x) => x.text())
.then((html) => void (root.innerHTML = html))
.then(() => fixUpTensorboard(root))
.then(() => executeAllScripts(root))
.then(() => setHeight(root, %HEIGHT%));
})();
</script>
""".replace("%PORT%", "%d" % port).replace("%HEIGHT%", "%d" % height)
html = IPython.display.HTML(shell)
if display_handle:
display_handle.update(html)
else:
IPython.display.display(html) | python | def _display_colab(port, height, display_handle):
"""Display a TensorBoard instance in a Colab output frame.
The Colab VM is not directly exposed to the network, so the Colab
runtime provides a service worker tunnel to proxy requests from the
end user's browser through to servers running on the Colab VM: the
output frame may issue requests to https://localhost:<port> (HTTPS
only), which will be forwarded to the specified port on the VM.
It does not suffice to create an `iframe` and let the service worker
redirect its traffic (`<iframe src="https://localhost:6006">`),
because for security reasons service workers cannot intercept iframe
traffic. Instead, we manually fetch the TensorBoard index page with an
XHR in the output frame, and inject the raw HTML into `document.body`.
By default, the TensorBoard web app requests resources against
relative paths, like `./data/logdir`. Within the output frame, these
requests must instead hit `https://localhost:<port>/data/logdir`. To
redirect them, we change the document base URI, which transparently
affects all requests (XHRs and resources alike).
"""
import IPython.display
shell = """
<div id="root"></div>
<script>
(function() {
window.TENSORBOARD_ENV = window.TENSORBOARD_ENV || {};
window.TENSORBOARD_ENV["IN_COLAB"] = true;
document.querySelector("base").href = "https://localhost:%PORT%";
function fixUpTensorboard(root) {
const tftb = root.querySelector("tf-tensorboard");
// Disable the fragment manipulation behavior in Colab. Not
// only is the behavior not useful (as the iframe's location
// is not visible to the user), it causes TensorBoard's usage
// of `window.replace` to navigate away from the page and to
// the `localhost:<port>` URL specified by the base URI, which
// in turn causes the frame to (likely) crash.
tftb.removeAttribute("use-hash");
}
function executeAllScripts(root) {
// When `script` elements are inserted into the DOM by
// assigning to an element's `innerHTML`, the scripts are not
// executed. Thus, we manually re-insert these scripts so that
// TensorBoard can initialize itself.
for (const script of root.querySelectorAll("script")) {
const newScript = document.createElement("script");
newScript.type = script.type;
newScript.textContent = script.textContent;
root.appendChild(newScript);
script.remove();
}
}
function setHeight(root, height) {
// We set the height dynamically after the TensorBoard UI has
// been initialized. This avoids an intermediate state in
// which the container plus the UI become taller than the
// final width and cause the Colab output frame to be
// permanently resized, eventually leading to an empty
// vertical gap below the TensorBoard UI. It's not clear
// exactly what causes this problematic intermediate state,
// but setting the height late seems to fix it.
root.style.height = `${height}px`;
}
const root = document.getElementById("root");
fetch(".")
.then((x) => x.text())
.then((html) => void (root.innerHTML = html))
.then(() => fixUpTensorboard(root))
.then(() => executeAllScripts(root))
.then(() => setHeight(root, %HEIGHT%));
})();
</script>
""".replace("%PORT%", "%d" % port).replace("%HEIGHT%", "%d" % height)
html = IPython.display.HTML(shell)
if display_handle:
display_handle.update(html)
else:
IPython.display.display(html) | [
"def",
"_display_colab",
"(",
"port",
",",
"height",
",",
"display_handle",
")",
":",
"import",
"IPython",
".",
"display",
"shell",
"=",
"\"\"\"\n <div id=\"root\"></div>\n <script>\n (function() {\n window.TENSORBOARD_ENV = window.TENSORBOARD_ENV || {};\n window.TENSORBOARD_ENV[\"IN_COLAB\"] = true;\n document.querySelector(\"base\").href = \"https://localhost:%PORT%\";\n function fixUpTensorboard(root) {\n const tftb = root.querySelector(\"tf-tensorboard\");\n // Disable the fragment manipulation behavior in Colab. Not\n // only is the behavior not useful (as the iframe's location\n // is not visible to the user), it causes TensorBoard's usage\n // of `window.replace` to navigate away from the page and to\n // the `localhost:<port>` URL specified by the base URI, which\n // in turn causes the frame to (likely) crash.\n tftb.removeAttribute(\"use-hash\");\n }\n function executeAllScripts(root) {\n // When `script` elements are inserted into the DOM by\n // assigning to an element's `innerHTML`, the scripts are not\n // executed. Thus, we manually re-insert these scripts so that\n // TensorBoard can initialize itself.\n for (const script of root.querySelectorAll(\"script\")) {\n const newScript = document.createElement(\"script\");\n newScript.type = script.type;\n newScript.textContent = script.textContent;\n root.appendChild(newScript);\n script.remove();\n }\n }\n function setHeight(root, height) {\n // We set the height dynamically after the TensorBoard UI has\n // been initialized. This avoids an intermediate state in\n // which the container plus the UI become taller than the\n // final width and cause the Colab output frame to be\n // permanently resized, eventually leading to an empty\n // vertical gap below the TensorBoard UI. It's not clear\n // exactly what causes this problematic intermediate state,\n // but setting the height late seems to fix it.\n root.style.height = `${height}px`;\n }\n const root = document.getElementById(\"root\");\n fetch(\".\")\n .then((x) => x.text())\n .then((html) => void (root.innerHTML = html))\n .then(() => fixUpTensorboard(root))\n .then(() => executeAllScripts(root))\n .then(() => setHeight(root, %HEIGHT%));\n })();\n </script>\n \"\"\"",
".",
"replace",
"(",
"\"%PORT%\"",
",",
"\"%d\"",
"%",
"port",
")",
".",
"replace",
"(",
"\"%HEIGHT%\"",
",",
"\"%d\"",
"%",
"height",
")",
"html",
"=",
"IPython",
".",
"display",
".",
"HTML",
"(",
"shell",
")",
"if",
"display_handle",
":",
"display_handle",
".",
"update",
"(",
"html",
")",
"else",
":",
"IPython",
".",
"display",
".",
"display",
"(",
"html",
")"
] | Display a TensorBoard instance in a Colab output frame.
The Colab VM is not directly exposed to the network, so the Colab
runtime provides a service worker tunnel to proxy requests from the
end user's browser through to servers running on the Colab VM: the
output frame may issue requests to https://localhost:<port> (HTTPS
only), which will be forwarded to the specified port on the VM.
It does not suffice to create an `iframe` and let the service worker
redirect its traffic (`<iframe src="https://localhost:6006">`),
because for security reasons service workers cannot intercept iframe
traffic. Instead, we manually fetch the TensorBoard index page with an
XHR in the output frame, and inject the raw HTML into `document.body`.
By default, the TensorBoard web app requests resources against
relative paths, like `./data/logdir`. Within the output frame, these
requests must instead hit `https://localhost:<port>/data/logdir`. To
redirect them, we change the document base URI, which transparently
affects all requests (XHRs and resources alike). | [
"Display",
"a",
"TensorBoard",
"instance",
"in",
"a",
"Colab",
"output",
"frame",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/notebook.py#L292-L369 | train |
tensorflow/tensorboard | tensorboard/notebook.py | list | def list():
"""Print a listing of known running TensorBoard instances.
TensorBoard instances that were killed uncleanly (e.g., with SIGKILL
or SIGQUIT) may appear in this list even if they are no longer
running. Conversely, this list may be missing some entries if your
operating system's temporary directory has been cleared since a
still-running TensorBoard instance started.
"""
infos = manager.get_all()
if not infos:
print("No known TensorBoard instances running.")
return
print("Known TensorBoard instances:")
for info in infos:
template = " - port {port}: {data_source} (started {delta} ago; pid {pid})"
print(template.format(
port=info.port,
data_source=manager.data_source_from_info(info),
delta=_time_delta_from_info(info),
pid=info.pid,
)) | python | def list():
"""Print a listing of known running TensorBoard instances.
TensorBoard instances that were killed uncleanly (e.g., with SIGKILL
or SIGQUIT) may appear in this list even if they are no longer
running. Conversely, this list may be missing some entries if your
operating system's temporary directory has been cleared since a
still-running TensorBoard instance started.
"""
infos = manager.get_all()
if not infos:
print("No known TensorBoard instances running.")
return
print("Known TensorBoard instances:")
for info in infos:
template = " - port {port}: {data_source} (started {delta} ago; pid {pid})"
print(template.format(
port=info.port,
data_source=manager.data_source_from_info(info),
delta=_time_delta_from_info(info),
pid=info.pid,
)) | [
"def",
"list",
"(",
")",
":",
"infos",
"=",
"manager",
".",
"get_all",
"(",
")",
"if",
"not",
"infos",
":",
"print",
"(",
"\"No known TensorBoard instances running.\"",
")",
"return",
"print",
"(",
"\"Known TensorBoard instances:\"",
")",
"for",
"info",
"in",
"infos",
":",
"template",
"=",
"\" - port {port}: {data_source} (started {delta} ago; pid {pid})\"",
"print",
"(",
"template",
".",
"format",
"(",
"port",
"=",
"info",
".",
"port",
",",
"data_source",
"=",
"manager",
".",
"data_source_from_info",
"(",
"info",
")",
",",
"delta",
"=",
"_time_delta_from_info",
"(",
"info",
")",
",",
"pid",
"=",
"info",
".",
"pid",
",",
")",
")"
] | Print a listing of known running TensorBoard instances.
TensorBoard instances that were killed uncleanly (e.g., with SIGKILL
or SIGQUIT) may appear in this list even if they are no longer
running. Conversely, this list may be missing some entries if your
operating system's temporary directory has been cleared since a
still-running TensorBoard instance started. | [
"Print",
"a",
"listing",
"of",
"known",
"running",
"TensorBoard",
"instances",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/notebook.py#L392-L414 | train |
tensorflow/tensorboard | tensorboard/backend/event_processing/io_wrapper.py | IsTensorFlowEventsFile | def IsTensorFlowEventsFile(path):
"""Check the path name to see if it is probably a TF Events file.
Args:
path: A file path to check if it is an event file.
Raises:
ValueError: If the path is an empty string.
Returns:
If path is formatted like a TensorFlowEventsFile.
"""
if not path:
raise ValueError('Path must be a nonempty string')
return 'tfevents' in tf.compat.as_str_any(os.path.basename(path)) | python | def IsTensorFlowEventsFile(path):
"""Check the path name to see if it is probably a TF Events file.
Args:
path: A file path to check if it is an event file.
Raises:
ValueError: If the path is an empty string.
Returns:
If path is formatted like a TensorFlowEventsFile.
"""
if not path:
raise ValueError('Path must be a nonempty string')
return 'tfevents' in tf.compat.as_str_any(os.path.basename(path)) | [
"def",
"IsTensorFlowEventsFile",
"(",
"path",
")",
":",
"if",
"not",
"path",
":",
"raise",
"ValueError",
"(",
"'Path must be a nonempty string'",
")",
"return",
"'tfevents'",
"in",
"tf",
".",
"compat",
".",
"as_str_any",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
")"
] | Check the path name to see if it is probably a TF Events file.
Args:
path: A file path to check if it is an event file.
Raises:
ValueError: If the path is an empty string.
Returns:
If path is formatted like a TensorFlowEventsFile. | [
"Check",
"the",
"path",
"name",
"to",
"see",
"if",
"it",
"is",
"probably",
"a",
"TF",
"Events",
"file",
"."
] | 8e5f497b48e40f2a774f85416b8a35ac0693c35e | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/event_processing/io_wrapper.py#L45-L59 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.