什么是 tensorflow.compat.as_str()?

What is tensorflow.compat.as_str()?

Google/Udemy Tensorflow tutorial中有如下代码:

import tensorflow as tf
...
def read_data(filename):
    """Extract the first file enclosed in a zip file as a list of words"""
    with zipfile.ZipFile(filename) as f:
    data = tf.compat.as_str(f.read(f.namelist()[0])).split()
return data

这执行得很好,但我在 Tensorflow 文档或其他任何地方找不到 compat.as_str

Q1:compat.as_str是做什么的?

问题 2:这个 tensorflow compat 库是否在某处记录?

Q3:这是对 tensorflow 库的调用,那么它如何以及为什么在普通 python 代码中工作,而不是在 tensorflow 图中工作? IE。我认为 tensorflow 库调用必须在 tensorflow 图形定义块内:

graph = tf.Graph()
with graph.as_default()
    ... tensorflow function calls here ...

我是运行python2.7。

  1. tf.compat.as_str 将输入转换为字符串

  2. 我找不到任何文档,但你可以查看源代码here

  3. Tensorflow 用作 python 模块。 graph context 用于定义将用于训练模型的图(数学计算)。

typical usage involves the Graph.as_default() context manager, which overrides the current default graph for the lifetime of the contex

基本上,这是因为在 Python 2 中,字符串主要作为字节处理,而不是 unicode。
在 Python 3 中,所有字符串都是原生 unicode。
该功能的目的是确保无论您使用哪个 Python 版本,您都不会被打扰,因此 compat 模块名称代表兼容性。

在后台,tensorflow.compat.as_strbytesunicode 字符串转换为 unicode 字符串。

Signature: tensorflow.compat.as_str(bytes_or_text, encoding='utf-8')
Docstring:
Returns the given argument as a unicode string.

Args:
  bytes_or_text: A `bytes`, `str, or `unicode` object.
  encoding: A string indicating the charset for decoding unicode.

Returns:
  A `unicode` (Python 2) or `str` (Python 3) object.

Raises:
  TypeError: If `bytes_or_text` is not a binary or unicode string.

库已记录 here

在当前版本的 TF 中,整个 tf.compat 组都有很好的记录。

基本上 python 2 和 3 中有些东西的行为有所不同(可能有点不准确,python 专家可以帮助我解决这个问题)。 Python3 使用 64 位浮点数和 python2 个 32 位浮点数,相对于 strings. Compat module tries things to behave in the same way (if you will check the source code 也有区别你会发现它们根据你使用的是 2 还是 3 做不同的事情).


tf.compat.as_str:

Converts either bytes or unicode to bytes, using utf-8 encoding for text.

如果您将数据保存在 tfrecords 中并希望确保无论使用哪个 python 版本,它都将以相同的方式保存,这会很有帮助。