前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >tf.Graph

tf.Graph

作者头像
狼啸风云
修改2022-09-04 21:42:51
1.5K0
修改2022-09-04 21:42:51
举报

原文链接:https://tensorflow.google.cn/api_docs/python/tf/Graph?hl=en


一个图包含一组tf.Operation对象,表示计算单位;和tf.Tensor对象,它表示在操作之间流动的数据单位。始终注册一个默认图,并通过调用tf.compat.v1.get_default_graph访问它。要向默认图形添加操作,只需调用定义新操作的函数之一:

c = tf.constant(4.0)
assert c.graph is tf.compat.v1.get_default_graph()

另一个典型的用法涉及tf.Graph.as_default上下文管理器,在上下文的生命周期内覆盖当前的默认图:

g = tf.Graph()
with g.as_default():
  # Define operations and tensors in `g`.
  c = tf.constant(30.0)
  assert c.graph is g

注意:这个类对于图的构造不是线程安全的。所有操作都应该从一个线程创建,或者必须提供外部同步。除非另外指定,否则所有方法都不是线程安全的。图实例支持任意数量的“集合”,这些集合由名称标识。为了方便构建大型图,集合可以存储相关对象组:例如tf.Variable使用一个集合(名为tf.GraphKeys.GLOBAL_VARIABLES)来处理在构建图的过程中创建的所有变量。调用者可以通过指定新名称来定义其他集合。

1、__init__

__init__()

性质

building_function

如果这个图表示一个函数,则返回True。

集合

返回该图所知集合的名称。

最终确定

如果这个图已经确定,则为真。

graph_def_versions

此图的GraphDef版本信息。

有关每个版本含义的详细信息,请参见GraphDef。

返回:

VersionDef。

种子

此图的图级随机种子。

版本

返回一个版本号,该版本号随着ops添加到图中而增加。

注意,这与tf.Graph.graph_def_versions无关。

返回:

一个整数版本,随着ops添加到图中而增加。

2、add_to_collection

add_to_collection(
    name,
    value
)

使用给定名称在集合中存储值。注意,集合不是集合,因此可以多次向集合添加值。

参数:

  • name:集合的键。GraphKeys类包含许多集合的标准名称。
  • value:要添加到集合中的值。

3、add_to_collections

add_to_collections(
    names,
    value
)

将值存储在由名称给出的集合中。注意,集合不是集合,因此可以多次向集合添加值。这个函数确保忽略名称中的重复项,但它不会检查name. names中的任何集合中值的现有成员关系。

参数:

  • names:要添加到的集合的键。GraphKeys类包含许多集合的标准名称。
  • value:要添加到集合中的值。

4、as_default

as_default()

返回使此图成为默认图的上下文管理器。如果希望在同一进程中创建多个图形,应该使用此方法。为了方便起见,我们提供了一个全局默认图,如果没有显式地创建一个新图,那么所有ops都将添加到这个图中。使用此方法和with关键字指定应该将在块范围内创建的操作系统添加到此图中。在本例中,一旦退出with的范围,前面的默认图将再次设置为默认。有一个堆栈,所以可以有多个嵌套级别的as_default调用。默认图形是当前线程的属性。如果您创建了一个新线程,并且希望在该线程中使用默认图形,则必须在该线程的函数中显式地添加一个带有g.as_default()。以下代码示例是等价的:

# 1. Using Graph.as_default():
g = tf.Graph()
with g.as_default():
  c = tf.constant(5.0)
  assert c.graph is g

# 2. Constructing and making default:
with tf.Graph().as_default() as g:
  c = tf.constant(5.0)
  assert c.graph is g

如果启用了立即执行,则在此上下文管理器下创建的ops将被添加到图中,而不是立即执行。

返回值:

  • 使用此图作为默认图的上下文管理器。

5、as_graph_def

as_graph_def(
    from_version=None,
    add_shapes=False
)

返回此图形的序列化GraphDef表示。序列化的GraphDef可以导入到另一个图形中(使用tf.import_graph_def),或者与c++会话API一起使用。这个方法是线程安全的。

参数:

  • from_version:可选的。如果设置了该值,则返回一个GraphDef,其中只包含添加到此图中的节点,因为其version属性具有给定的值。
  • add_shapes:如果为真,则向每个节点添加一个“_output_shapes”列表attr,其中包含每个输出的推断形状。

返回值:

  • 一个GraphDef协议缓冲区。

可能产生的异常:

  • ValueError: If the graph_def would be too large.

6、as_graph_element

as_graph_element(
    obj,
    allow_tensor=True,
    allow_operation=True
)

返回obj引用的对象,作为操作或张量。这个函数验证obj是否表示这个图的一个元素,如果不是,则给出一个有用的错误消息。此函数是从会话API中的外部参数引用获取/验证允许类型之一的对象的规范方法。可以从多个线程并发地调用此方法。

参数:

  • obj:一个张量,一个运算,或者一个张量或运算的名字。也可以是任何具有_as_graph_element()方法的对象,该方法返回这些类型之一的值。
  • allow_tensor:如果为真,obj可以引用一个张量。
  • allow_operation:如果为真,obj可以引用一个操作。

返回值:

  • 图中与obj对应的张量或运算。

可能产生的异常:

  • TypeError: If obj is not a type we support attempting to convert to types.
  • ValueError: If obj is of an appropriate type but invalid. For example, an invalid string.
  • KeyError: If obj is not an object in the graph.

7、clear_collection

clear_collection(name)

清除集合中的所有值。

参数:

  • name:集合的键。GraphKeys类包含许多集合的标准名称。

8、colocate_with

colocate_with(
    op,
    ignore_existing=False
)

返回指定要使用的op的上下文管理器。注意:此函数不供公众使用,仅供内部库使用。

例如:

a = tf.Variable([1.0])
with g.colocate_with(a):
  b = tf.constant(1.0)
  c = tf.add(a, b)

无论a最终放在哪里,b和c总是与a共存。注意,使用托管范围将重置任何现有设备约束。如果op为None,则ignore_exists必须为True,并且新范围将重置所有托管和设备约束。

参数:

  • op:将所有已创建的op(或没有)进行协作的op。
  • ignore_exists:如果为真,则只在上下文中应用此op的托管,而不是应用堆栈上的所有托管属性。如果op为None,则此值必须为True。

可能产生的异常:

  • ValueError: if op is None but ignore_existing is False.

范围:

  • 上下文管理器,指定要与之协作新创建的操作的op。

9、container

container(container_name)

返回指定要使用的资源容器的上下文管理器。有状态操作,例如变量和队列,可以在设备上维护它们的状态,以便它们可以被多个进程共享。资源容器是跟踪这些有状态操作的字符串名称。可以使用tf.Session.reset()释放或清除这些资源。

例:

with g.container('experiment0'):
  # All stateful Operations constructed in this context will be placed
  # in resource container "experiment0".
  v1 = tf.Variable([1.0])
  v2 = tf.Variable([2.0])
  with g.container("experiment1"):
    # All stateful Operations constructed in this context will be
    # placed in resource container "experiment1".
    v3 = tf.Variable([3.0])
    q1 = tf.queue.FIFOQueue(10, tf.float32)
  # All stateful Operations constructed in this context will be
  # be created in the "experiment0".
  v4 = tf.Variable([4.0])
  q1 = tf.queue.FIFOQueue(20, tf.float32)
  with g.container(""):
    # All stateful Operations constructed in this context will be
    # be placed in the default resource container.
    v5 = tf.Variable([5.0])
    q3 = tf.queue.FIFOQueue(30, tf.float32)

# Resets container "experiment0", after which the state of v1, v2, v4, q1
# will become undefined (such as uninitialized).
tf.Session.reset(target, ["experiment0"])

参数:

  • container_name:容器名称字符串。

返回值:

  • 用于为有状态操作定义资源容器的上下文管理器将生成容器名称。

10、control_dependencies

control_dependencies(control_inputs)

返回指定控件依赖项的上下文管理器。使用with with关键字指定上下文中构造的所有操作都应该对control_input具有控制依赖关系。例如:

with g.control_dependencies([a, b, c]):
  # `d` and `e` will only run after `a`, `b`, and `c` have executed.
  d = ...
  e = ...

可以嵌套对control_dependencies()的多个调用,在这种情况下,新操作将对来自所有活动上下文的control_input的联合具有控制依赖关系。

with g.control_dependencies([a, b]):
  # Ops constructed here run after `a` and `b`.
  with g.control_dependencies([c, d]):
    # Ops constructed here run after `a`, `b`, `c`, and `d`.

你可以传递None来清除控件依赖项:

with g.control_dependencies([a, b]):
  # Ops constructed here run after `a` and `b`.
  with g.control_dependencies(None):
    # Ops constructed here run normally, not waiting for either `a` or `b`.
    with g.control_dependencies([c, d]):
      # Ops constructed here run after `c` and `d`, also not waiting
      # for either `a` or `b`.

注意:控件依赖上下文仅适用于在上下文中构造的ops。仅仅在上下文中使用op或张量并不会添加控件依赖项。下面的例子说明了这一点:

# WRONG
def my_func(pred, tensor):
  t = tf.matmul(tensor, tensor)
  with tf.control_dependencies([pred]):
    # The matmul op is created outside the context, so no control
    # dependency will be added.
    return t

# RIGHT
def my_func(pred, tensor):
  with tf.control_dependencies([pred]):
    # The matmul op is created in the context, so a control dependency
    # will be added.
    return tf.matmul(tensor, tensor)

还要注意的是,尽管在这个范围内创建的操作的执行将触发依赖项的执行,但是在这个范围内创建的操作仍然可能从一个普通的tensorflow图中删除。例如,在下面的代码片段中,依赖项永远不会执行:

  loss = model.loss()
  with tf.control_dependencies(dependencies):
    loss = loss + tf.constant(1)  # note: dependencies ignored in the
                                  # backward pass
  return tf.gradients(loss, model.variables)

这是因为计算梯度图不需要计算在正向传递中创建的常数(1)op。

参数:

  • control_input:在运行上下文中定义的操作之前必须执行或计算的操作或张量对象的列表。也可以是None来清除控件依赖项。

返回值:

  • 上下文管理器,为在上下文中构造的所有操作指定控制依赖项。

可能产生的异常:

  • TypeError: If control_inputs is not a list of Operation or Tensor objects.

11、create_op

  • create_op( op_type, inputs, dtypes=None, input_types=None, name=None, attrs=None, op_def=None, compute_shapes=True, compute_device=True )

在此图中创建操作。警告:一些参数被弃用:(compute_shapes)。它们将在未来的版本中被删除。更新说明:始终计算形状;不要使用compute_shapes,因为它没有效果。这是一个用于创建操作的底层接口。大多数程序不会直接调用这个方法,而是使用Python op构造函数,比如tf.constant(),它将ops添加到默认图中。

参数:

  • op_type:要创建的操作类型。这对应于定义操作的原型的OpDef.name字段。
  • inputs:张量对象的列表,这些张量对象将作为操作的输入。
  • dtypes:(可选)一个DType对象列表,该对象将是操作生成的张量的类型。
  • input_types:(可选)将是操作所使用的张量的类型的DTypes列表。默认情况下,在输入中使用每个输入的基本DType。期望引用类型输入的操作必须显式指定input_types。
  • name:(可选)。操作的字符串名称。如果没有指定,则根据op_type生成一个名称。
  • attrs:(可选)一个字典,其中键是属性名(字符串),值是表示操作的NodeDef proto的相应attr属性(AttrValue proto)。
  • op_def:(可选)。描述操作将具有的op_type的OpDef原型。
  • compute_shapes:(可选)。弃用。没有效果(总是计算形状)。
  • compute_device:(可选)。如果为真,将执行设备函数来计算操作的设备属性。

可能产生的异常:

  • TypeError: if any of the inputs is not a Tensor.
  • ValueError: if colocation conflicts with existing device assignment.

返回值:

  • 一个操作对象。

12、device

device(device_name_or_function)

返回指定要使用的默认设备的上下文管理器。device_name_or_function参数可以是设备名称字符串、设备函数,也可以是None:

  • 如果它是一个设备名称字符串,除非被嵌套的设备()上下文覆盖,否则在此上下文中构造的所有操作都将分配给具有该名称的设备。
  • 如果它是一个函数,那么它将被视为从操作对象到设备名称字符串的函数,并在每次创建新操作时调用。操作将分配给具有返回名称的设备。
  • 如果没有,则将忽略来自封闭上下文的所有device()调用。

有关设备名称字符串的有效语法的信息,请参阅DeviceNameUtils中的文档。

例:

with g.device('/device:GPU:0'):
  # All operations constructed in this context will be placed
  # on GPU 0.
  with g.device(None):
    # All operations constructed in this context will have no
    # assigned device.

# Defines a function from `Operation` to device string.
def matmul_on_gpu(n):
  if n.type == "MatMul":
    return "/device:GPU:0"
  else:
    return "/cpu:0"

with g.device(matmul_on_gpu):
  # All operations of type "MatMul" constructed in this context
  # will be placed on GPU 0; all other operations will be placed
  # on CPU 0.

注意:设备范围可能被op包装器或其他库代码覆盖。例如,变量赋值op .assign()必须与tf协同使用。变量v和不兼容的设备范围将被忽略。

参数:

  • device_name_or_function:要在上下文中使用的设备名称或函数。

范围:

  • 上下文管理器,指定新创建的操作系统使用的默认设备。

可能产生的异常:

  • RuntimeError: If device scopes are not properly nested.

13、finalize

finalize()

将此图形定格为只读。调用g.finalize()后,不能向g添加任何新操作。这个方法用于确保在多个线程之间共享一个图时,例如在使用tf.compat.v1.train.QueueRunner时,不会向图添加任何操作。

14、get_all_collection_keys

get_all_collection_keys()

返回此图中使用的集合列表。

15、get_collection

get_collection(
    name,
    scope=None
)

返回集合中具有给定名称的值列表。这与get_collection_ref()不同,get_collection_ref()总是返回实际的集合列表(如果它存在的话),因为每次调用它都会返回一个新列表。

参数:

  • name:集合的键。例如,GraphKeys类包含许多集合的标准名称。
  • scope:(可选)。一个字符串。如果提供,则筛选结果列表,使其只包含名称属性与使用re.match的范围相匹配的项。如果提供范围,则永远不会返回没有name属性的项。选择re.match意味着没有特殊令牌的范围将通过前缀过滤。

返回值:

  • 集合中具有给定名称的值的列表,如果没有向该集合添加值,则为空列表。该列表包含按收集值的顺序排列的值。

16、get_collection_ref

get_collection_ref(name)

返回集合中具有给定名称的值列表。如果集合存在,则返回列表本身,可以在适当的位置修改列表以更改集合。如果集合不存在,则将其创建为空列表,并返回列表。这与get_collection()不同,如果集合列表存在,get_collection()总是返回集合列表的副本,并且从不创建空集合。

参数:

  • 名称:集合的键。例如,GraphKeys类包含许多集合的标准名称。

返回值:

  • 集合中具有给定名称的值的列表,如果没有向该集合添加值,则为空列表。

17、get_name_scope

get_name_scope()

返回当前名称作用域。

例:

with tf.name_scope('scope1'):
  with tf.name_scope('scope2'):
    print(tf.compat.v1.get_default_graph().get_name_scope())

将打印字符串scope1/scope2。

返回值:

  • 表示当前名称作用域的字符串。

18、get_operation_by_name

get_operation_by_name(name)

返回具有给定名称的操作。可以从多个线程并发地调用此方法。

参数:

  • name:要返回的操作的名称。

返回值:

  • 指定名称的操作。

可能产生的异常:

  • TypeError: If name is not a string.
  • KeyError: If name does not correspond to an operation in this graph.

19、get_operations

get_operations()

返回图中的操作列表。您可以在适当的位置修改操作,但是对列表的修改(如insert /delete)对图中已知的操作列表没有影响。可以从多个线程并发地调用此方法。

返回值:

  • 操作列表。

20、get_tensor_by_name

get_tensor_by_name(name)

返回给定名称的张量。可以从多个线程并发地调用此方法。

参数:

  • name:返回的张量的名称。

返回值:

  • 给定的张量。

可能产生的异常:

  • TypeError: If name is not a string.
  • KeyError: If name does not correspond to a tensor in this graph.

21、gradient_override_map

gradient_override_map(op_type_map)

实验性:用于覆盖梯度函数的上下文管理器。此上下文管理器可用于覆盖将在上下文范围内用于ops的梯度函数。

例:

@tf.RegisterGradient("CustomSquare")
def _custom_square_grad(op, grad):
  # ...

with tf.Graph().as_default() as g:
  c = tf.constant(5.0)
  s_1 = tf.square(c)  # Uses the default gradient for tf.square.
  with g.gradient_override_map({"Square": "CustomSquare"}):
    s_2 = tf.square(s_2)  # Uses _custom_square_grad to compute the
                          # gradient of s_2.

参数:

  • op_type_map:将op类型字符串映射到其他op类型字符串的字典。

返回值:

  • 上下文管理器,它设置可选的op类型,用于在该上下文中创建的一个或多个ops。

可能产生的异常:

  • TypeError: If op_type_map is not a dictionary mapping strings to strings.

22、is_feedable

is_feedable(tensor)

当且仅当张量是可馈的时,返回True。

23、is_fetchable

is_fetchable(tensor_or_op)

当且仅当tensor_or_op可获取时返回True。

24、name_scope

name_scope(name)

返回为操作创建层次名称的上下文管理器。图维护名称作用域的堆栈。A with name_scope(…):语句在上下文的生存期中将一个新名称推入堆栈。name参数的解释如下:

  • 字符串(不以'/'结尾)将创建一个新的name作用域,其中name被附加到上下文中创建的所有操作的前缀。如果以前使用过name,它将通过调用self.unique_name(name)变得惟一。
  • 以前从A中捕获的作用域g.name_scope(…)作为作用域:语句将被视为“绝对”名称作用域,这使得重新输入现有作用域成为可能。
  • 如果值为None或空字符串,则将当前名称作用域重置为顶级(空)名称作用域。

例:

with tf.Graph().as_default() as g:
  c = tf.constant(5.0, name="c")
  assert c.op.name == "c"
  c_1 = tf.constant(6.0, name="c")
  assert c_1.op.name == "c_1"

  # Creates a scope called "nested"
  with g.name_scope("nested") as scope:
    nested_c = tf.constant(10.0, name="c")
    assert nested_c.op.name == "nested/c"

    # Creates a nested scope called "inner".
    with g.name_scope("inner"):
      nested_inner_c = tf.constant(20.0, name="c")
      assert nested_inner_c.op.name == "nested/inner/c"

    # Create a nested scope called "inner_1".
    with g.name_scope("inner"):
      nested_inner_1_c = tf.constant(30.0, name="c")
      assert nested_inner_1_c.op.name == "nested/inner_1/c"

      # Treats `scope` as an absolute name scope, and
      # switches to the "nested/" scope.
      with g.name_scope(scope):
        nested_d = tf.constant(40.0, name="d")
        assert nested_d.op.name == "nested/d"

        with g.name_scope(""):
          e = tf.constant(50.0, name="e")
          assert e.op.name == "e"

作用域本身的名称可以用g.name_scope(…)作为作用域:来捕获,它将作用域的名称存储在变量作用域中。此值可用于命名表示在范围内执行操作的总体结果的操作。例如:

inputs = tf.constant(...)
with g.name_scope('my_layer') as scope:
  weights = tf.Variable(..., name="weights")
  biases = tf.Variable(..., name="biases")
  affine = tf.matmul(inputs, weights) + biases
  output = tf.nn.relu(affine, name=scope)

注意:这个构造函数验证给定的名称。有效的范围名称匹配下列正则表达式之一:

[A-Za-z0-9.][A-Za-z0-9_.\-/]* (for scopes at the root)
[A-Za-z0-9_.\-/]* (for other scopes)

参数:

  • name:范围的名称。

返回值:

  • 将名称安装为新名称作用域的上下文管理器。

可能产生的异常:

  • ValueError: If name is not a valid scope name, according to the rules above.

25、prevent_feeding

prevent_feeding(tensor)

在这个图中把给定的张量标记为不可给的。

26、prevent_fetching

prevent_fetching(op)

在这个图中将给定的op标记为unfetchable。

27、switch_to_thread_local

switch_to_thread_local()

使设备、托管和依赖项堆栈线程本地。设备、托管和依赖项堆栈不是线程本地的缺省值。如果多个线程访问它们,则共享状态。这意味着一个线程可能会影响另一个线程的行为。调用此方法后,堆栈将成为线程本地的。如果多个线程访问它们,则不共享状态。每个线程使用自己的值;线程不会通过修改这样的堆栈来影响其他线程。当第一次调用switch_to_thread_local()时,每个线程堆栈的初值被设置为堆栈的当前值。

28、unique_name

unique_name(
    name,
    mark_as_used=True
)

为名称返回唯一的操作名称。注意:很少需要直接调用unique_name()。大多数时候,您只需要使用g.name_scope()块来创建结构名称。

unique_name用于生成由“/”分隔的结构化名称,以帮助在调试图时识别操作。操作名显示在TensorFlow运行时报告的错误消息中,以及各种可视化工具(如TensorBoard)中。如果mark_as_used被设置为True(这是缺省值),那么将创建一个新的惟一名称并将其标记为use。如果将其设置为False,则返回唯一的名称,而实际上没有将其标记为used。当调用者只想知道要创建的名称是什么时,这很有用。

参数:

  • name:操作的名称。
  • mark_as_used:是否将此名称标记为正在使用。

返回值:

  • 传递给create_op()的字符串,该字符串将用于命名正在创建的操作
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019年08月13日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1、__init__
  • 2、add_to_collection
  • 3、add_to_collections
  • 4、as_default
  • 5、as_graph_def
  • 6、as_graph_element
  • 7、clear_collection
  • 8、colocate_with
  • 9、container
  • 10、control_dependencies
  • 11、create_op
  • 12、device
  • 13、finalize
  • 14、get_all_collection_keys
  • 15、get_collection
  • 16、get_collection_ref
  • 17、get_name_scope
  • 18、get_operation_by_name
  • 19、get_operations
  • 20、get_tensor_by_name
  • 21、gradient_override_map
  • 22、is_feedable
  • 23、is_fetchable
  • 24、name_scope
  • 25、prevent_feeding
  • 26、prevent_fetching
  • 27、switch_to_thread_local
  • 28、unique_name
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档