原文链接: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)来处理在构建图的过程中创建的所有变量。调用者可以通过指定新名称来定义其他集合。
__init__()
性质
building_function
如果这个图表示一个函数,则返回True。
集合
返回该图所知集合的名称。
最终确定
如果这个图已经确定,则为真。
graph_def_versions
此图的GraphDef版本信息。
有关每个版本含义的详细信息,请参见GraphDef。
返回:
VersionDef。
种子
此图的图级随机种子。
版本
返回一个版本号,该版本号随着ops添加到图中而增加。
注意,这与tf.Graph.graph_def_versions无关。
返回:
一个整数版本,随着ops添加到图中而增加。
add_to_collection
add_to_collection(
name,
value
)
使用给定名称在集合中存储值。注意,集合不是集合,因此可以多次向集合添加值。
参数:
name
:集合的键。GraphKeys类包含许多集合的标准名称。add_to_collections
add_to_collections(
names,
value
)
将值存储在由名称给出的集合中。注意,集合不是集合,因此可以多次向集合添加值。这个函数确保忽略名称中的重复项,但它不会检查name. names中的任何集合中值的现有成员关系。
参数:
names
:要添加到的集合的键。GraphKeys类包含许多集合的标准名称。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一起使用。这个方法是线程安全的。
参数:
返回值:
可能产生的异常:
ValueError
: If the graph_def
would be too large.as_graph_element
as_graph_element(
obj,
allow_tensor=True,
allow_operation=True
)
返回obj引用的对象,作为操作或张量。这个函数验证obj是否表示这个图的一个元素,如果不是,则给出一个有用的错误消息。此函数是从会话API中的外部参数引用获取/验证允许类型之一的对象的规范方法。可以从多个线程并发地调用此方法。
参数:
obj:
一个张量,一个运算,或者一个张量或运算的名字。也可以是任何具有_as_graph_element()方法的对象,该方法返回这些类型之一的值。allow_tensor
:如果为真,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.clear_collection
clear_collection(name)
清除集合中的所有值。
参数:
name
:集合的键。GraphKeys类包含许多集合的标准名称。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,并且新范围将重置所有托管和设备约束。
参数:
可能产生的异常:
ValueError
: if op is None but ignore_existing is False.范围:
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 ?developer/article/1489064/undefined (such as uninitialized).
tf.Session.reset(target, ["experiment0"])
参数:
返回值:
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。
参数:
返回值:
可能产生的异常:
TypeError
: If control_inputs
is not a list of Operation
or Tensor
objects.create_op
在此图中创建操作。警告:一些参数被弃用:(compute_shapes)。它们将在未来的版本中被删除。更新说明:始终计算形状;不要使用compute_shapes,因为它没有效果。这是一个用于创建操作的底层接口。大多数程序不会直接调用这个方法,而是使用Python op构造函数,比如tf.constant(),它将ops添加到默认图中。
参数:
inputs
:张量对象的列表,这些张量对象将作为操作的输入。input_types
:(可选)将是操作所使用的张量的类型的DTypes列表。默认情况下,在输入中使用每个输入的基本DType。期望引用类型输入的操作必须显式指定input_types。name
:(可选)。操作的字符串名称。如果没有指定,则根据op_type生成一个名称。可能产生的异常:
TypeError
: if any of the inputs is not a Tensor
.ValueError
: if colocation conflicts with existing device assignment.返回值:
device
device(device_name_or_function)
返回指定要使用的默认设备的上下文管理器。device_name_or_function参数可以是设备名称字符串、设备函数,也可以是None:
有关设备名称字符串的有效语法的信息,请参阅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和不兼容的设备范围将被忽略。
参数:
范围:
可能产生的异常:
RuntimeError
: If device scopes are not properly nested.finalize
finalize()
将此图形定格为只读。调用g.finalize()后,不能向g添加任何新操作。这个方法用于确保在多个线程之间共享一个图时,例如在使用tf.compat.v1.train.QueueRunner时,不会向图添加任何操作。
get_all_collection_keys
get_all_collection_keys()
返回此图中使用的集合列表。
get_collection
get_collection(
name,
scope=None
)
返回集合中具有给定名称的值列表。这与get_collection_ref()不同,get_collection_ref()总是返回实际的集合列表(如果它存在的话),因为每次调用它都会返回一个新列表。
参数:
name
:集合的键。例如,GraphKeys类包含许多集合的标准名称。scope
:(可选)。一个字符串。如果提供,则筛选结果列表,使其只包含名称属性与使用re.match的范围相匹配的项。如果提供范围,则永远不会返回没有name属性的项。选择re.match意味着没有特殊令牌的范围将通过前缀过滤。返回值:
get_collection_ref
get_collection_ref(name)
返回集合中具有给定名称的值列表。如果集合存在,则返回列表本身,可以在适当的位置修改列表以更改集合。如果集合不存在,则将其创建为空列表,并返回列表。这与get_collection()不同,如果集合列表存在,get_collection()总是返回集合列表的副本,并且从不创建空集合。
参数:
返回值:
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)
返回具有给定名称的操作。可以从多个线程并发地调用此方法。
参数:
返回值:
可能产生的异常:
TypeError
: If name
is not a string.KeyError
: If name
does not correspond to an operation in this graph.get_operations
get_operations()
返回图中的操作列表。您可以在适当的位置修改操作,但是对列表的修改(如insert /delete)对图中已知的操作列表没有影响。可以从多个线程并发地调用此方法。
返回值:
get_tensor_by_name
get_tensor_by_name(name)
返回给定名称的张量。可以从多个线程并发地调用此方法。
参数:
返回值:
可能产生的异常:
TypeError
: If name
is not a string.KeyError
: If name
does not correspond to a tensor in this graph.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.
参数:
返回值:
可能产生的异常:
TypeError
: If op_type_map
is not a dictionary mapping strings to strings.is_feedable
is_feedable(tensor)
当且仅当张量是可馈的时,返回True。
is_fetchable
is_fetchable(tensor_or_op)
当且仅当tensor_or_op可获取时返回True。
name_scope
name_scope(name)
返回为操作创建层次名称的上下文管理器。图维护名称作用域的堆栈。A with name_scope(…):语句在上下文的生存期中将一个新名称推入堆栈。name参数的解释如下:
例:
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.prevent_feeding
prevent_feeding(tensor)
在这个图中把给定的张量标记为不可给的。
prevent_fetching
prevent_fetching(op)
在这个图中将给定的op标记为unfetchable。
switch_to_thread_local
switch_to_thread_local()
使设备、托管和依赖项堆栈线程本地。设备、托管和依赖项堆栈不是线程本地的缺省值。如果多个线程访问它们,则共享状态。这意味着一个线程可能会影响另一个线程的行为。调用此方法后,堆栈将成为线程本地的。如果多个线程访问它们,则不共享状态。每个线程使用自己的值;线程不会通过修改这样的堆栈来影响其他线程。当第一次调用switch_to_thread_local()时,每个线程堆栈的初值被设置为堆栈的当前值。
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。当调用者只想知道要创建的名称是什么时,这很有用。
参数:
返回值: