本文整理汇总了Python中tensorflow.python.util.compat.as_text方法的典型用法代码示例。如果您正苦于以下问题:Python compat.as_text方法的具体用法?Python compat.as_text怎么用?Python compat.as_text使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tensorflow.python.util.compat
的用法示例。
在下文中一共展示了compat.as_text方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _do_call
# 需要导入模块: from tensorflow.python.util import compat [as 别名]
# 或者: from tensorflow.python.util.compat import as_text [as 别名]
def _do_call(self, fn, *args):
try:
return fn(*args)
except errors.OpError as e:
message = compat.as_text(e.message)
m = BaseSession._NODEDEF_NAME_RE.search(message)
node_def = None
op = None
if m is not None:
node_name = m.group(1)
try:
op = self._graph.get_operation_by_name(node_name)
node_def = op.node_def
except KeyError:
pass
raise type(e)(node_def, op, message)
示例2: _validate_asset_collection
# 需要导入模块: from tensorflow.python.util import compat [as 别名]
# 或者: from tensorflow.python.util.compat import as_text [as 别名]
def _validate_asset_collection(self, export_dir, graph_collection_def,
expected_asset_file_name,
expected_asset_file_contents,
expected_asset_tensor_name):
assets_any = graph_collection_def[constants.ASSETS_KEY].any_list.value
asset = meta_graph_pb2.AssetFileDef()
assets_any[0].Unpack(asset)
assets_path = os.path.join(
compat.as_bytes(export_dir),
compat.as_bytes(constants.ASSETS_DIRECTORY),
compat.as_bytes(expected_asset_file_name))
actual_asset_contents = file_io.read_file_to_string(assets_path)
self.assertEqual(expected_asset_file_contents,
compat.as_text(actual_asset_contents))
self.assertEqual(expected_asset_file_name, asset.filename)
self.assertEqual(expected_asset_tensor_name, asset.tensor_info.name)
示例3: testNoOverwrite
# 需要导入模块: from tensorflow.python.util import compat [as 别名]
# 或者: from tensorflow.python.util.compat import as_text [as 别名]
def testNoOverwrite(self):
export_dir = os.path.join(test.get_temp_dir(), "test_no_overwrite")
builder = saved_model_builder.SavedModelBuilder(export_dir)
# Graph with a single variable. SavedModel invoked to:
# - add with weights.
with self.test_session(graph=ops.Graph()) as sess:
self._init_and_validate_variable(sess, "v", 42)
builder.add_meta_graph_and_variables(sess, ["foo"])
# Save the SavedModel to disk in text format.
builder.save(as_text=True)
# Restore the graph with tag "foo", whose variables were saved.
with self.test_session(graph=ops.Graph()) as sess:
loader.load(sess, ["foo"], export_dir)
self.assertEqual(
42, ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)[0].eval())
# An attempt to create another builder with the same export directory should
# result in an assertion error.
self.assertRaises(AssertionError, saved_model_builder.SavedModelBuilder,
export_dir)
示例4: testNoOverwrite
# 需要导入模块: from tensorflow.python.util import compat [as 别名]
# 或者: from tensorflow.python.util.compat import as_text [as 别名]
def testNoOverwrite(self):
export_dir = os.path.join(tf.test.get_temp_dir(), "test_no_overwrite")
builder = saved_model_builder.SavedModelBuilder(export_dir)
# Graph with a single variable. SavedModel invoked to:
# - add with weights.
with self.test_session(graph=tf.Graph()) as sess:
self._init_and_validate_variable(sess, "v", 42)
builder.add_meta_graph_and_variables(sess, ["foo"])
# Save the SavedModel to disk in text format.
builder.save(as_text=True)
# Restore the graph with tag "foo", whose variables were saved.
with self.test_session(graph=tf.Graph()) as sess:
loader.load(sess, ["foo"], export_dir)
self.assertEqual(
42, tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)[0].eval())
# An attempt to create another builder with the same export directory should
# result in an assertion error.
self.assertRaises(AssertionError, saved_model_builder.SavedModelBuilder,
export_dir)
示例5: _write_value_event
# 需要导入模块: from tensorflow.python.util import compat [as 别名]
# 或者: from tensorflow.python.util.compat import as_text [as 别名]
def _write_value_event(self, event):
value = event.summary.value[0]
# Obtain the device name from the metadata.
summary_metadata = event.summary.value[0].metadata
if not summary_metadata.plugin_data:
raise ValueError("The value lacks plugin data.")
try:
content = json.loads(compat.as_text(summary_metadata.plugin_data.content))
except ValueError as err:
raise ValueError("Could not parse content into JSON: %r, %r" % (content,
err))
device_name = content["device"]
dump_full_path = _get_dump_file_path(
self._dump_dir, device_name, value.node_name)
self._try_makedirs(os.path.dirname(dump_full_path))
with open(dump_full_path, "wb") as f:
f.write(event.SerializeToString())
开发者ID:PacktPublishing,项目名称:Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda,代码行数:21,代码来源:grpc_debug_test_server.py
示例6: save
# 需要导入模块: from tensorflow.python.util import compat [as 别名]
# 或者: from tensorflow.python.util.compat import as_text [as 别名]
def save(self, as_text=False):
"""Writes a `SavedModel` protocol buffer to disk.
The function writes the SavedModel protocol buffer to the export directory
in serialized format.
Args:
as_text: Writes the SavedModel protocol buffer in text format to disk.
Returns:
The path to which the SavedModel protocol buffer was written.
"""
if not file_io.file_exists(self._export_dir):
file_io.recursive_create_dir(self._export_dir)
if as_text:
path = os.path.join(
compat.as_bytes(self._export_dir),
compat.as_bytes(constants.SAVED_MODEL_FILENAME_PBTXT))
file_io.write_string_to_file(path, str(self._saved_model))
else:
path = os.path.join(
compat.as_bytes(self._export_dir),
compat.as_bytes(constants.SAVED_MODEL_FILENAME_PB))
file_io.write_string_to_file(path, self._saved_model.SerializeToString())
tf_logging.info("SavedModel written to: %s", path)
return path
示例7: raise_exception_on_not_ok_status
# 需要导入模块: from tensorflow.python.util import compat [as 别名]
# 或者: from tensorflow.python.util.compat import as_text [as 别名]
def raise_exception_on_not_ok_status():
status = pywrap_tensorflow.TF_NewStatus()
try:
yield status
if pywrap_tensorflow.TF_GetCode(status) != 0:
raise _make_specific_exception(
None, None,
compat.as_text(pywrap_tensorflow.TF_Message(status)),
pywrap_tensorflow.TF_GetCode(status))
finally:
pywrap_tensorflow.TF_DeleteStatus(status)
示例8: load_file_system_library
# 需要导入模块: from tensorflow.python.util import compat [as 别名]
# 或者: from tensorflow.python.util.compat import as_text [as 别名]
def load_file_system_library(library_filename):
"""Loads a TensorFlow plugin, containing file system implementation.
Pass `library_filename` to a platform-specific mechanism for dynamically
loading a library. The rules for determining the exact location of the
library are platform-specific and are not documented here.
Args:
library_filename: Path to the plugin.
Relative or absolute filesystem path to a dynamic library file.
Returns:
None.
Raises:
RuntimeError: when unable to load the library.
"""
status = py_tf.TF_NewStatus()
lib_handle = py_tf.TF_LoadLibrary(library_filename, status)
try:
error_code = py_tf.TF_GetCode(status)
if error_code != 0:
error_msg = compat.as_text(py_tf.TF_Message(status))
# pylint: disable=protected-access
raise errors_impl._make_specific_exception(
None, None, error_msg, error_code)
# pylint: enable=protected-access
finally:
py_tf.TF_DeleteStatus(status)
示例9: testSaveAsText
# 需要导入模块: from tensorflow.python.util import compat [as 别名]
# 或者: from tensorflow.python.util.compat import as_text [as 别名]
def testSaveAsText(self):
export_dir = os.path.join(test.get_temp_dir(), "test_astext")
builder = saved_model_builder.SavedModelBuilder(export_dir)
# Graph with a single variable. SavedModel invoked to:
# - add with weights.
with self.test_session(graph=ops.Graph()) as sess:
self._init_and_validate_variable(sess, "v", 42)
builder.add_meta_graph_and_variables(sess, ["foo"])
# Graph with the same single variable. SavedModel invoked to:
# - simply add the model (weights are not updated).
with self.test_session(graph=ops.Graph()) as sess:
self._init_and_validate_variable(sess, "v", 43)
builder.add_meta_graph(["bar"])
# Save the SavedModel to disk in text format.
builder.save(as_text=True)
# Restore the graph with tag "foo", whose variables were saved.
with self.test_session(graph=ops.Graph()) as sess:
loader.load(sess, ["foo"], export_dir)
self.assertEqual(
42, ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)[0].eval())
# Restore the graph with tag "bar", whose variables were not saved.
with self.test_session(graph=ops.Graph()) as sess:
loader.load(sess, ["bar"], export_dir)
self.assertEqual(
42, ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)[0].eval())
示例10: Cleanse
# 需要导入模块: from tensorflow.python.util import compat [as 别名]
# 或者: from tensorflow.python.util.compat import as_text [as 别名]
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 compat.as_text(obj, encoding)
elif isinstance(obj, list) or isinstance(obj, 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
示例11: testSaveAsText
# 需要导入模块: from tensorflow.python.util import compat [as 别名]
# 或者: from tensorflow.python.util.compat import as_text [as 别名]
def testSaveAsText(self):
export_dir = os.path.join(tf.test.get_temp_dir(), "test_astext")
builder = saved_model_builder.SavedModelBuilder(export_dir)
# Graph with a single variable. SavedModel invoked to:
# - add with weights.
with self.test_session(graph=tf.Graph()) as sess:
self._init_and_validate_variable(sess, "v", 42)
builder.add_meta_graph_and_variables(sess, ["foo"])
# Graph with the same single variable. SavedModel invoked to:
# - simply add the model (weights are not updated).
with self.test_session(graph=tf.Graph()) as sess:
self._init_and_validate_variable(sess, "v", 43)
builder.add_meta_graph(["bar"])
# Save the SavedModel to disk in text format.
builder.save(as_text=True)
# Restore the graph with tag "foo", whose variables were saved.
with self.test_session(graph=tf.Graph()) as sess:
loader.load(sess, ["foo"], export_dir)
self.assertEqual(
42, tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)[0].eval())
# Restore the graph with tag "bar", whose variables were not saved.
with self.test_session(graph=tf.Graph()) as sess:
loader.load(sess, ["bar"], export_dir)
self.assertEqual(
42, tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)[0].eval())
示例12: testWriteEvents
# 需要导入模块: from tensorflow.python.util import compat [as 别名]
# 或者: from tensorflow.python.util.compat import as_text [as 别名]
def testWriteEvents(self):
file_prefix = os.path.join(self.get_temp_dir(), "events")
writer = pywrap_tensorflow.EventsWriter(compat.as_bytes(file_prefix))
filename = compat.as_text(writer.FileName())
event_written = event_pb2.Event(
wall_time=123.45, step=67,
summary=summary_pb2.Summary(
value=[summary_pb2.Summary.Value(tag="foo", simple_value=89.0)]))
writer.WriteEvent(event_written)
writer.Flush()
writer.Close()
with self.assertRaises(errors.NotFoundError):
for r in tf_record.tf_record_iterator(filename + "DOES_NOT_EXIST"):
self.assertTrue(False)
reader = tf_record.tf_record_iterator(filename)
event_read = event_pb2.Event()
event_read.ParseFromString(next(reader))
self.assertTrue(event_read.HasField("file_version"))
event_read.ParseFromString(next(reader))
# Second event
self.assertProtoEquals("""
wall_time: 123.45 step: 67
summary { value { tag: 'foo' simple_value: 89.0 } }
""", event_read)
with self.assertRaises(StopIteration):
next(reader)
示例13: raise_exception_on_not_ok_status
# 需要导入模块: from tensorflow.python.util import compat [as 别名]
# 或者: from tensorflow.python.util.compat import as_text [as 别名]
def raise_exception_on_not_ok_status():
try:
status = pywrap_tensorflow.TF_NewStatus()
yield status
if pywrap_tensorflow.TF_GetCode(status) != 0:
raise _make_specific_exception(
None, None,
compat.as_text(pywrap_tensorflow.TF_Message(status)),
pywrap_tensorflow.TF_GetCode(status))
finally:
pywrap_tensorflow.TF_DeleteStatus(status)
示例14: _get_test_attrs
# 需要导入模块: from tensorflow.python.util import compat [as 别名]
# 或者: from tensorflow.python.util.compat import as_text [as 别名]
def _get_test_attrs(self):
x = control_flow_ops.no_op()
try:
a = compat.as_text(x.get_attr("_A"))
except ValueError:
a = None
try:
b = compat.as_text(x.get_attr("_B"))
except ValueError:
b = None
print(a, b)
return (a, b)
示例15: device_name_to_device_path
# 需要导入模块: from tensorflow.python.util import compat [as 别名]
# 或者: from tensorflow.python.util.compat import as_text [as 别名]
def device_name_to_device_path(device_name):
"""Convert device name to device path."""
device_name_items = compat.as_text(device_name).split("/")
device_name_items = [item.replace(":", "_") for item in device_name_items]
return METADATA_FILE_PREFIX + DEVICE_TAG + ",".join(device_name_items)
开发者ID:PacktPublishing,项目名称:Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda,代码行数:7,代码来源:debug_data.py