什么是tensorflow.compat.as_str()?

Ron*_*hen 19 python tensorflow

Google/Udemy Tensorflow教程中,有以下代码:

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
Run Code Online (Sandbox Code Playgroud)

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

Q1:做compat.as_str什么?

Q2:这个张量流compat库是否记录在某处?

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

graph = tf.Graph()
with graph.as_default()
    ... tensorflow function calls here ...
Run Code Online (Sandbox Code Playgroud)

我正在运行python 2.7.

Jac*_*uot 18

基本上,它来自这样一个事实:在Python 2中,字符串主要作为字节处理,而不是unicode.
在Python 3中,所有字符串都是本机unicode.
该函数的目的是确保您使用的任何Python版本都不会被打扰,因此compat模块名称代表兼容性.

在引擎盖下,tensorflow.compat.as_str将两者bytesunicode字符串转换为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.
Run Code Online (Sandbox Code Playgroud)

该库在此处记录.


rra*_*rao 8

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

  2. 我找不到任何文档,但您可以在这里查看源代码

  3. Tensorflow充当python模块.的图表上下文用于定义将被用于训练模型的曲线图(数学计算).

典型用法涉及Graph.as_default()上下文管理器,它会覆盖上下文生命周期的当前默认图形