[TOC]
Classes and functions for building TensorFlow graphs.
A TensorFlow computation, represented as a dataflow graph.
A Graph
contains a set of
Operation
objects,
which represent units of computation; and
Tensor
objects, which represent
the units of data that flow between operations.
A default Graph
is always registered, and accessible by calling
tf.get_default_graph()
.
To add an operation to the default graph, simply call one of the functions
that defines a new Operation
:
c = tf.constant(4.0)
assert c.graph is tf.get_default_graph()
Another typical usage involves the
Graph.as_default()
context manager, which overrides the current default graph for the
lifetime of the context:
g = tf.Graph()
with g.as_default():
# Define operations and tensors in `g`.
c = tf.constant(30.0)
assert c.graph is g
Important note: This class is not thread-safe for graph construction. All operations should be created from a single thread, or external synchronization must be provided. Unless otherwise specified, all methods are not thread-safe.
Creates a new, empty Graph.
Returns a context manager that makes this Graph
the default graph.
This method should be used if you want to create multiple graphs
in the same process. For convenience, a global default graph is
provided, and all ops will be added to this graph if you do not
create a new graph explicitly. Use this method with the with
keyword
to specify that ops created within the scope of a block should be
added to this graph.
The default graph is a property of the current thread. If you
create a new thread, and wish to use the default graph in that
thread, you must explicitly add a with g.as_default():
in that
thread's function.
The following code examples are equivalent:
# 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
A context manager for using this graph as the default graph.
Returns a serialized GraphDef
representation of this graph.
The serialized GraphDef
can be imported into another Graph
(using import_graph_def()
) or used with the
C++ Session API.
This method is thread-safe.
from_version
: Optional. If this is set, returns aGraphDef
containing only the nodes that were added to this graph since itsversion
property had the given value.add_shapes
: If true, adds an "_output_shapes" list attr to each node with the inferred shapes of each of its outputs.
A GraphDef
protocol buffer.
ValueError
: If thegraph_def
would be too large.
Finalizes this graph, making it read-only.
After calling g.finalize()
, no new operations can be added to
g
. This method is used to ensure that no operations are added
to a graph when it is shared between multiple threads, for example
when using a QueueRunner
.
True if this graph has been finalized.
Returns a context manager that specifies control dependencies.
Use with the with
keyword to specify that all operations constructed
within the context should have control dependencies on
control_inputs
. For example:
with g.control_dependencies([a, b, c]):
# `d` and `e` will only run after `a`, `b`, and `c` have executed.
d = ...
e = ...
Multiple calls to control_dependencies()
can be nested, and in
that case a new Operation
will have control dependencies on the union
of control_inputs
from all active contexts.
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`.
You can pass None to clear the control dependencies:
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`.
N.B. The control dependencies context applies only to ops that are constructed within the context. Merely using an op or tensor in the context does not add a control dependency. The following example illustrates this point:
# 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)
control_inputs
: A list ofOperation
orTensor
objects which must be executed or computed before running the operations defined in the context. Can also beNone
to clear the control dependencies.
A context manager that specifies control dependencies for all operations constructed within the context.
TypeError
: Ifcontrol_inputs
is not a list ofOperation
orTensor
objects.
Returns a context manager that specifies the default device to use.
The device_name_or_function
argument may either be a device name
string, a device function, or None:
- If it is a device name string, all operations constructed in
this context will be assigned to the device with that name, unless
overridden by a nested
device()
context. - If it is a function, it will be treated as a function from Operation objects to device name strings, and invoked each time a new Operation is created. The Operation will be assigned to the device with the returned name.
- If it is None, all
device()
invocations from the enclosing context will be ignored.
For information about the valid syntax of device name strings, see
the documentation in
DeviceNameUtils
.
For example:
with g.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 "/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.
N.B. The device scope may be overridden by op wrappers or
other library code. For example, a variable assignment op
v.assign()
must be colocated with the tf.Variable
v
, and
incompatible device scopes will be ignored.
device_name_or_function
: The device name or function to use in the context.
A context manager that specifies the default device to use for newly created ops.
Returns a context manager that creates hierarchical names for operations.
A graph maintains a stack of name scopes. A with name_scope(...):
statement pushes a new name onto the stack for the lifetime of the context.
The name
argument will be interpreted as follows:
- A string (not ending with '/') will create a new name scope, in which
name
is appended to the prefix of all operations created in the context. Ifname
has been used before, it will be made unique by callingself.unique_name(name)
. - A scope previously captured from a
with g.name_scope(...) as scope:
statement will be treated as an "absolute" name scope, which makes it possible to re-enter existing scopes. - A value of
None
or the empty string will reset the current name scope to the top-level (empty) name scope.
For example:
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"
The name of the scope itself can be captured by with g.name_scope(...) as scope:
, which stores the name of the scope
in the variable scope
. This value can be used to name an
operation that represents the overall result of executing the ops
in a scope. For example:
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)
NOTE: This constructor validates the given name
. Valid scope
names match one of the following regular expressions:
[A-Za-z0-9.][A-Za-z0-9_.\\-/]* (for scopes at the root)
[A-Za-z0-9_.\\-/]* (for other scopes)
name
: A name for the scope.
A context manager that installs name
as a new name scope.
ValueError
: Ifname
is not a valid scope name. The rules are the
A Graph
instance supports an arbitrary number of "collections"
that are identified by name. For convenience when building a large
graph, collections can store groups of related objects: for
example, the tf.Variable
uses a collection (named
tf.GraphKeys.GLOBAL_VARIABLES
) for
all variables that are created during the construction of a graph. The caller
may define additional collections by specifying a new name.
Stores value
in the collection with the given name
.
Note that collections are not sets, so it is possible to add a value to a collection several times.
name
: The key for the collection. TheGraphKeys
class contains many standard names for collections.value
: The value to add to the collection.
Stores value
in the collections given by names
.
Note that collections are not sets, so it is possible to add a value to
a collection several times. This function makes sure that duplicates in
names
are ignored, but it will not check for pre-existing membership of
value
in any of the collections in names
.
names
can be any iterable, but if names
is a string, it is treated as a
single collection name.
names
: The keys for the collections to add to. TheGraphKeys
class contains many standard names for collections.value
: The value to add to the collections.
Returns a list of values in the collection with the given name
.
This is different from get_collection_ref()
which always returns the
actual collection list if it exists in that it returns a new list each time
it is called.
name
: The key for the collection. For example, theGraphKeys
class contains many standard names for collections.scope
: (Optional.) If supplied, the resulting list is filtered to include only items whosename
attribute matches usingre.match
. Items without aname
attribute are never returned if a scope is supplied and the choice orre.match
means that ascope
without special tokens filters by prefix.
The list of values in the collection with the given name
, or
an empty list if no value has been added to that collection. The
list contains the values in the order under which they were
collected.
Returns a list of values in the collection with the given name
.
If the collection exists, this returns the list itself, which can be modified in place to change the collection. If the collection does not exist, it is created as an empty list and the list is returned.
This is different from get_collection()
which always returns a copy of
the collection list if it exists and never creates an empty collection.
name
: The key for the collection. For example, theGraphKeys
class contains many standard names for collections.
The list of values in the collection with the given name
, or an empty
list if no value has been added to that collection.
Returns the object referred to by obj
, as an Operation
or Tensor
.
This function validates that obj
represents an element of this
graph, and gives an informative error message if it is not.
This function is the canonical way to get/validate an object of one of the allowed types from an external argument reference in the Session API.
This method may be called concurrently from multiple threads.
obj
: ATensor
, anOperation
, or the name of a tensor or operation. Can also be any object with an_as_graph_element()
method that returns a value of one of these types.allow_tensor
: If true,obj
may refer to aTensor
.allow_operation
: If true,obj
may refer to anOperation
.
The Tensor
or Operation
in the Graph corresponding to obj
.
TypeError
: Ifobj
is not a type we support attempting to convert to types.ValueError
: Ifobj
is of an appropriate type but invalid. For example, an invalid string.KeyError
: Ifobj
is not an object in the graph.
Returns the Operation
with the given name
.
This method may be called concurrently from multiple threads.
name
: The name of theOperation
to return.
The Operation
with the given name
.
TypeError
: Ifname
is not a string.KeyError
: Ifname
does not correspond to an operation in this graph.
Returns the Tensor
with the given name
.
This method may be called concurrently from multiple threads.
name
: The name of theTensor
to return.
The Tensor
with the given name
.
TypeError
: Ifname
is not a string.KeyError
: Ifname
does not correspond to a tensor in this graph.
Return the list of operations in the graph.
You can modify the operations in place, but modifications to the list such as inserts/delete have no effect on the list of operations known to the graph.
This method may be called concurrently from multiple threads.
A list of Operations.
The graph-level random seed of this graph.
Return a unique operation name for name
.
Note: You rarely need to call unique_name()
directly. Most of
the time you just need to create with g.name_scope()
blocks to
generate structured names.
unique_name
is used to generate structured names, separated by
"/"
, to help identify operations when debugging a graph.
Operation names are displayed in error messages reported by the
TensorFlow runtime, and in various visualization tools such as
TensorBoard.
If mark_as_used
is set to True
, which is the default, a new
unique name is created and marked as in use. If it's set to False
,
the unique name is returned without actually being marked as used.
This is useful when the caller simply wants to know what the name
to be created will be.
name
: The name for an operation.mark_as_used
: Whether to mark this name as being used.
A string to be passed to create_op()
that will be used
to name the operation being created.
Returns a version number that increases as ops are added to the graph.
Note that this is unrelated to the GraphDef version.
The GraphDef version information of this graph.
For details on the meaning of each version, see
GraphDef
.
A VersionDef
.
tf.Graph.create_op(op_type, inputs, dtypes, input_types=None, name=None, attrs=None, op_def=None, compute_shapes=True, compute_device=True)
{#Graph.create_op}
Creates an Operation
in this graph.
This is a low-level interface for creating an Operation
. Most
programs will not call this method directly, and instead use the
Python op constructors, such as tf.constant()
, which add ops to
the default graph.
op_type
: TheOperation
type to create. This corresponds to theOpDef.name
field for the proto that defines the operation.inputs
: A list ofTensor
objects that will be inputs to theOperation
.dtypes
: A list ofDType
objects that will be the types of the tensors that the operation produces.input_types
: (Optional.) A list ofDType
s that will be the types of the tensors that the operation consumes. By default, uses the baseDType
of each input ininputs
. Operations that expect reference-typed inputs must specifyinput_types
explicitly.name
: (Optional.) A string name for the operation. If not specified, a name is generated based onop_type
.attrs
: (Optional.) A dictionary where the key is the attribute name (a string) and the value is the respectiveattr
attribute of theNodeDef
proto that will represent the operation (anAttrValue
proto).op_def
: (Optional.) TheOpDef
proto that describes theop_type
that the operation will have.compute_shapes
: (Optional.) If True, shape inference will be performed to compute the shapes of the outputs.compute_device
: (Optional.) If True, device functions will be executed to compute the device property of the Operation.
TypeError
: if any of the inputs is not aTensor
.ValueError
: if colocation conflicts with existing device assignment.
An Operation
object.
EXPERIMENTAL: A context manager for overriding gradient functions.
This context manager can be used to override the gradient function that will be used for ops within the scope of the context.
For example:
@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
: A dictionary mapping op type strings to alternative op type strings.
A context manager that sets the alternative op type to be used for one or more ops created in that context.
TypeError
: Ifop_type_map
is not a dictionary mapping strings to strings.
Returns True iff this graph represents a function.
Clears all values in a collection.
name
: The key for the collection. TheGraphKeys
class contains many standard names for collections.
Returns a context manager that specifies an op to colocate with.
Note: this function is not for public use, only for internal libraries.
For example:
a = tf.Variable([1.0])
with g.colocate_with(a):
b = tf.constant(1.0)
c = tf.add(a, b)
b
and c
will always be colocated with a
, no matter where a
is eventually placed.
NOTE Using a colocation scope resets any existing device constraints.
If op
is None
then ignore_existing
must be True
and the new
scope resets all colocation and device constraints.
op
: The op to colocate all created ops with, orNone
.ignore_existing
: If true, only applies colocation of this op within the context, rather than applying all colocation properties on the stack. Ifop
isNone
, this value must beTrue
.
ValueError
: if op is None but ignore_existing is False.
A context manager that specifies the op with which to colocate newly created ops.
Returns a context manager that specifies the resource container to use.
Stateful operations, such as variables and queues, can maintain their
states on devices so that they can be shared by multiple processes.
A resource container is a string name under which these stateful
operations are tracked. These resources can be released or cleared
with tf.Session.reset()
.
For example:
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.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.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.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
: container name string.
A context manager for defining resource containers for stateful ops, yields the container name.
Returns a list of collections used in this graph.
Returns True
if and only if tensor
is feedable.
Returns True
if and only if tensor_or_op
is fetchable.
Marks the given tensor
as unfeedable in this graph.
Marks the given op
as unfetchable in this graph.
Represents a graph node that performs computation on tensors.
An Operation
is a node in a TensorFlow Graph
that takes zero or
more Tensor
objects as input, and produces zero or more Tensor
objects as output. Objects of type Operation
are created by
calling a Python op constructor (such as
tf.matmul()
)
or Graph.create_op()
.
For example c = tf.matmul(a, b)
creates an Operation
of type
"MatMul" that takes tensors a
and b
as input, and produces c
as output.
After the graph has been launched in a session, an Operation
can
be executed by passing it to
Session.run()
.
op.run()
is a shortcut for calling tf.get_default_session().run(op)
.
The full name of this operation.
The type of the op (e.g. "MatMul"
).
The list of Tensor
objects representing the data inputs of this op.
The Operation
objects on which this op has a control dependency.
Before this op is executed, TensorFlow will ensure that the
operations in self.control_inputs
have finished executing. This
mechanism can be used to run ops sequentially for performance
reasons, or to ensure that the side effects of an op are observed
in the correct order.
A list of Operation
objects.
The list of Tensor
objects representing the outputs of this op.
The name of the device to which this op has been assigned, if any.
The string name of the device to which this op has been assigned, or an empty string if it has not been assigned to a device.
The Graph
that contains this operation.
Runs this operation in a Session
.
Calling this method will execute all preceding operations that produce the inputs needed for this operation.
N.B. Before invoking Operation.run()
, its graph must have been
launched in a session, and either a default session must be
available, or session
must be specified explicitly.
feed_dict
: A dictionary that mapsTensor
objects to feed values. SeeSession.run()
for a description of the valid feed values.session
: (Optional.) TheSession
to be used to run to this operation. If none, the default session will be used.
Returns the value of the attr of this op with the given name
.
name
: The name of the attr to fetch.
The value of the attr, as a Python object.
ValueError
: If this op does not have an attr with the givenname
.
Returns the call stack from when this operation was constructed.
tf.Operation.__init__(node_def, g, inputs=None, output_types=None, control_inputs=None, input_types=None, original_op=None, op_def=None)
{#Operation.init}
Creates an Operation
.
NOTE: This constructor validates the name of the Operation
(passed
as node_def.name
). Valid Operation
names match the following
regular expression:
[A-Za-z0-9.][A-Za-z0-9_.\\-/]*
node_def
:node_def_pb2.NodeDef
.NodeDef
for theOperation
. Used for attributes ofnode_def_pb2.NodeDef
, typicallyname
,op
, anddevice
. Theinput
attribute is irrelevant here as it will be computed when generating the model.g
:Graph
. The parent graph.inputs
: list ofTensor
objects. The inputs to thisOperation
.output_types
: list ofDType
objects. List of the types of theTensors
computed by this operation. The length of this list indicates the number of output endpoints of theOperation
.control_inputs
: list of operations or tensors from which to have a control dependency.input_types
: List ofDType
objects representing the types of the tensors accepted by theOperation
. By default uses[x.dtype.base_dtype for x in inputs]
. Operations that expect reference-typed inputs must specify these explicitly.original_op
: Optional. Used to associate the newOperation
with an existingOperation
(for example, a replica with the op that was replicated).op_def
: Optional. Theop_def_pb2.OpDef
proto that describes the op type that thisOperation
represents.
TypeError
: if control inputs are not Operations or Tensors, or ifnode_def
is not aNodeDef
, or ifg
is not aGraph
, or ifinputs
are not tensors, or ifinputs
andinput_types
are incompatible.ValueError
: if thenode_def
name is not valid.
Returns the list of colocation groups of the op.
Returns a serialized NodeDef
representation of this operation.
A
NodeDef
protocol buffer.
Returns the OpDef
proto that represents the type of this op.
An
OpDef
protocol buffer.
DEPRECATED: Use outputs.
Represents one of the outputs of an Operation
.
A Tensor
is a symbolic handle to one of the outputs of an
Operation
. It does not hold the values of that operation's output,
but instead provides a means of computing those values in a
TensorFlow Session
.
This class has two primary purposes:
-
A
Tensor
can be passed as an input to anotherOperation
. This builds a dataflow connection between operations, which enables TensorFlow to execute an entireGraph
that represents a large, multi-step computation. -
After the graph has been launched in a session, the value of the
Tensor
can be computed by passing it toSession.run()
.t.eval()
is a shortcut for callingtf.get_default_session().run(t)
.
In the following example, c
, d
, and e
are symbolic Tensor
objects, whereas result
is a numpy array that stores a concrete
value:
# Build a dataflow graph.
c = tf.constant([[1.0, 2.0], [3.0, 4.0]])
d = tf.constant([[1.0, 1.0], [0.0, 1.0]])
e = tf.matmul(c, d)
# Construct a `Session` to execute the graph.
sess = tf.Session()
# Execute the graph and store the value that `e` represents in `result`.
result = sess.run(e)
The DType
of elements in this tensor.
The string name of this tensor.
The index of this tensor in the outputs of its Operation
.
The Graph
that contains this tensor.
The Operation
that produces this tensor as an output.
Returns a list of Operation
s that consume this tensor.
A list of Operation
s.
Evaluates this tensor in a Session
.
Calling this method will execute all preceding operations that produce the inputs needed for the operation that produces this tensor.
N.B. Before invoking Tensor.eval()
, its graph must have been
launched in a session, and either a default session must be
available, or session
must be specified explicitly.
feed_dict
: A dictionary that mapsTensor
objects to feed values. SeeSession.run()
for a description of the valid feed values.session
: (Optional.) TheSession
to be used to evaluate this tensor. If none, the default session will be used.
A numpy array corresponding to the value of this tensor.
Alias of Tensor.shape.
Returns the TensorShape
that represents the shape of this tensor.
The shape is computed using shape inference functions that are
registered in the Op for each Operation
. See
TensorShape
for more details of what a shape represents.
The inferred shape of a tensor is used to provide shape information without having to launch the graph in a session. This can be used for debugging, and providing early error messages. For example:
c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
print(c.shape)
==> TensorShape([Dimension(2), Dimension(3)])
d = tf.constant([[1.0, 0.0], [0.0, 1.0], [1.0, 0.0], [0.0, 1.0]])
print(d.shape)
==> TensorShape([Dimension(4), Dimension(2)])
# Raises a ValueError, because `c` and `d` do not have compatible
# inner dimensions.
e = tf.matmul(c, d)
f = tf.matmul(c, d, transpose_a=True, transpose_b=True)
print(f.shape)
==> TensorShape([Dimension(3), Dimension(4)])
In some cases, the inferred shape may have unknown dimensions. If
the caller has additional information about the values of these
dimensions, Tensor.set_shape()
can be used to augment the
inferred shape.
A TensorShape
representing the shape of this tensor.
Updates the shape of this tensor.
This method can be called multiple times, and will merge the given
shape
with the current shape of this tensor. It can be used to
provide additional information about the shape of this tensor that
cannot be inferred from the graph alone. For example, this can be used
to provide additional information about the shapes of images:
_, image_data = tf.TFRecordReader(...).read(...)
image = tf.image.decode_png(image_data, channels=3)
# The height and width dimensions of `image` are data dependent, and
# cannot be computed without executing the op.
print(image.shape)
==> TensorShape([Dimension(None), Dimension(None), Dimension(3)])
# We know that each image in this dataset is 28 x 28 pixels.
image.set_shape([28, 28, 3])
print(image.shape)
==> TensorShape([Dimension(28), Dimension(28), Dimension(3)])
shape
: ATensorShape
representing the shape of this tensor.
ValueError
: Ifshape
is not compatible with the current shape of this tensor.
Computes the absolute value of a tensor.
Given a tensor of real numbers x
, this operation returns a tensor
containing the absolute value of each element in x
. For example, if x is
an input element and y is an output element, this operation computes
\(y = |x|\).
x
: ATensor
orSparseTensor
of typefloat32
,float64
,int32
, orint64
.name
: A name for the operation (optional).
A Tensor
or SparseTensor
the same size and type as x
with absolute
values.
Returns x + y element-wise.
NOTE: Add
supports broadcasting. AddN
does not. More about broadcasting
here
x
: ATensor
. Must be one of the following types:half
,float32
,float64
,uint8
,int8
,int16
,int32
,int64
,complex64
,complex128
,string
.y
: ATensor
. Must have the same type asx
.name
: A name for the operation (optional).
A Tensor
. Has the same type as x
.
Returns the truth value of x AND y element-wise.
NOTE: LogicalAnd
supports broadcasting. More about broadcasting
here
x
: ATensor
of typebool
.y
: ATensor
of typebool
.name
: A name for the operation (optional).
A Tensor
of type bool
.
Dummy method to prevent a tensor from being used as a Python bool
.
This overload raises a TypeError
when the user inadvertently
treats a Tensor
as a boolean (e.g. in an if
statement). For
example:
if tf.constant(True): # Will raise.
# ...
if tf.constant(5) < tf.constant(7): # Will raise.
# ...
This disallows ambiguities between testing the Python value vs testing the
dynamic condition of the Tensor
.
TypeError
.
Divide two values using Python 2 semantics. Used for Tensor.div.
x
:Tensor
numerator of real numeric type.y
:Tensor
denominator of real numeric type.name
: A name for the operation (optional).
x / y
returns the quotient of x and y.
Divides x / y
elementwise, rounding toward the most negative integer.
The same as tf.div(x,y)
for integers, but uses tf.floor(tf.div(x,y))
for
floating point arguments so that the result is always an integer (though
possibly an integer represented as floating point). This op is generated by
x // y
floor division in Python 3 and in Python 2.7 with
from __future__ import division
.
Note that for efficiency, floordiv
uses C semantics for negative numbers
(unlike Python and Numpy).
x
and y
must have the same type, and the result will have the same type
as well.
x
:Tensor
numerator of real numeric type.y
:Tensor
denominator of real numeric type.name
: A name for the operation (optional).
x / y
rounded down (except possibly towards zero for negative integers).
TypeError
: If the inputs are complex.
Returns the truth value of (x >= y) element-wise.
NOTE: GreaterEqual
supports broadcasting. More about broadcasting
here
x
: ATensor
. Must be one of the following types:float32
,float64
,int32
,int64
,uint8
,int16
,int8
,uint16
,half
.y
: ATensor
. Must have the same type asx
.name
: A name for the operation (optional).
A Tensor
of type bool
.
Overload for Tensor.getitem.
This operation extracts the specified region from the tensor. The notation is similar to NumPy with the restriction that currently only support basic indexing. That means that using a tensor as input is not currently allowed
Some useful examples:
# strip leading and trailing 2 elements
foo = tf.constant([1,2,3,4,5,6])
print(foo[2:-2].eval()) # => [3,4]
# skip every row and reverse every column
foo = tf.constant([[1,2,3], [4,5,6], [7,8,9]])
print(foo[::2,::-1].eval()) # => [[3,2,1], [9,8,7]]
# Insert another dimension
foo = tf.constant([[1,2,3], [4,5,6], [7,8,9]])
print(foo[tf.newaxis, :, :].eval()) # => [[[3,2,1], [9,8,7]]]
print(foo[:, tf.newaxis, :].eval()) # => [[[3,2,1]], [[9,8,7]]]
print(foo[:, :, tf.newaxis].eval()) # => [[[3],[2],[1]], [[9],[8],[7]]]
# Ellipses (3 equivalent operations)
print(foo[tf.newaxis, :, :].eval()) # => [[[3,2,1], [9,8,7]]]
print(foo[tf.newaxis, ...].eval()) # => [[[3,2,1], [9,8,7]]]
print(foo[tf.newaxis].eval()) # => [[[3,2,1], [9,8,7]]]
tf.newaxis
isNone
as in NumPy.- An implicit ellipsis is placed at the end of the
slice_spec
- NumPy advanced indexing is currently not supported.
tensor
: An ops.Tensor object.slice_spec
: The arguments to Tensor.getitem.var
: In the case of variable slice assignment, the Variable object to slice (i.e. tensor is the read-only view of this variable).
The appropriate slice of "tensor", based on "slice_spec".
ValueError
: If a slice range is negative size.TypeError
: If the slice indices aren't int, slice, or Ellipsis.
Returns the truth value of (x > y) element-wise.
NOTE: Greater
supports broadcasting. More about broadcasting
here
x
: ATensor
. Must be one of the following types:float32
,float64
,int32
,int64
,uint8
,int16
,int8
,uint16
,half
.y
: ATensor
. Must have the same type asx
.name
: A name for the operation (optional).
A Tensor
of type bool
.
Creates a new Tensor
.
op
: AnOperation
.Operation
that computes this tensor.value_index
: Anint
. Index of the operation's endpoint that produces this tensor.dtype
: ADType
. Type of elements stored in this tensor.
TypeError
: If the op is not anOperation
.
Returns the truth value of NOT x element-wise.
x
: ATensor
of typebool
.name
: A name for the operation (optional).
A Tensor
of type bool
.
Dummy method to prevent iteration. Do not call.
NOTE(mrry): If we register getitem as an overloaded operator, Python will valiantly attempt to iterate over the Tensor from 0 to infinity. Declaring this method prevents this unintended behavior.
TypeError
: when invoked.
Returns the truth value of (x <= y) element-wise.
NOTE: LessEqual
supports broadcasting. More about broadcasting
here
x
: ATensor
. Must be one of the following types:float32
,float64
,int32
,int64
,uint8
,int16
,int8
,uint16
,half
.y
: ATensor
. Must have the same type asx
.name
: A name for the operation (optional).
A Tensor
of type bool
.
Returns the truth value of (x < y) element-wise.
NOTE: Less
supports broadcasting. More about broadcasting
here
x
: ATensor
. Must be one of the following types:float32
,float64
,int32
,int64
,uint8
,int16
,int8
,uint16
,half
.y
: ATensor
. Must have the same type asx
.name
: A name for the operation (optional).
A Tensor
of type bool
.
Returns element-wise remainder of division. When x < 0
xor y < 0
is
true, this follows Python semantics in that the result here is consistent
with a flooring divide. E.g. floor(x / y) * y + mod(x, y) = x
.
NOTE: FloorMod
supports broadcasting. More about broadcasting
here
x
: ATensor
. Must be one of the following types:int32
,int64
,float32
,float64
.y
: ATensor
. Must have the same type asx
.name
: A name for the operation (optional).
A Tensor
. Has the same type as x
.
Dispatches cwise mul for "DenseDense" and "DenseSparse".
Computes numerical negative value element-wise.
I.e., \(y = -x\).
x
: ATensor
. Must be one of the following types:half
,float32
,float64
,int32
,int64
,complex64
,complex128
.name
: A name for the operation (optional).
A Tensor
. Has the same type as x
.
Dummy method to prevent a tensor from being used as a Python bool
.
This is the Python 2.x counterpart to __bool__()
above.
TypeError
.
Returns the truth value of x OR y element-wise.
NOTE: LogicalOr
supports broadcasting. More about broadcasting
here
x
: ATensor
of typebool
.y
: ATensor
of typebool
.name
: A name for the operation (optional).
A Tensor
of type bool
.
Computes the power of one value to another.
Given a tensor x
and a tensor y
, this operation computes \(x^y\) for
corresponding elements in x
and y
. For example:
# tensor 'x' is [[2, 2], [3, 3]]
# tensor 'y' is [[8, 16], [2, 3]]
tf.pow(x, y) ==> [[256, 65536], [9, 27]]
x
: ATensor
of typefloat32
,float64
,int32
,int64
,complex64
, orcomplex128
.y
: ATensor
of typefloat32
,float64
,int32
,int64
,complex64
, orcomplex128
.name
: A name for the operation (optional).
A Tensor
.
Returns x + y element-wise.
NOTE: Add
supports broadcasting. AddN
does not. More about broadcasting
here
x
: ATensor
. Must be one of the following types:half
,float32
,float64
,uint8
,int8
,int16
,int32
,int64
,complex64
,complex128
,string
.y
: ATensor
. Must have the same type asx
.name
: A name for the operation (optional).
A Tensor
. Has the same type as x
.
Returns the truth value of x AND y element-wise.
NOTE: LogicalAnd
supports broadcasting. More about broadcasting
here
x
: ATensor
of typebool
.y
: ATensor
of typebool
.name
: A name for the operation (optional).
A Tensor
of type bool
.
Divide two values using Python 2 semantics. Used for Tensor.div.
x
:Tensor
numerator of real numeric type.y
:Tensor
denominator of real numeric type.name
: A name for the operation (optional).
x / y
returns the quotient of x and y.
Divides x / y
elementwise, rounding toward the most negative integer.
The same as tf.div(x,y)
for integers, but uses tf.floor(tf.div(x,y))
for
floating point arguments so that the result is always an integer (though
possibly an integer represented as floating point). This op is generated by
x // y
floor division in Python 3 and in Python 2.7 with
from __future__ import division
.
Note that for efficiency, floordiv
uses C semantics for negative numbers
(unlike Python and Numpy).
x
and y
must have the same type, and the result will have the same type
as well.
x
:Tensor
numerator of real numeric type.y
:Tensor
denominator of real numeric type.name
: A name for the operation (optional).
x / y
rounded down (except possibly towards zero for negative integers).
TypeError
: If the inputs are complex.
Returns element-wise remainder of division. When x < 0
xor y < 0
is
true, this follows Python semantics in that the result here is consistent
with a flooring divide. E.g. floor(x / y) * y + mod(x, y) = x
.
NOTE: FloorMod
supports broadcasting. More about broadcasting
here
x
: ATensor
. Must be one of the following types:int32
,int64
,float32
,float64
.y
: ATensor
. Must have the same type asx
.name
: A name for the operation (optional).
A Tensor
. Has the same type as x
.
Dispatches cwise mul for "DenseDense" and "DenseSparse".
Returns the truth value of x OR y element-wise.
NOTE: LogicalOr
supports broadcasting. More about broadcasting
here
x
: ATensor
of typebool
.y
: ATensor
of typebool
.name
: A name for the operation (optional).
A Tensor
of type bool
.
Computes the power of one value to another.
Given a tensor x
and a tensor y
, this operation computes \(x^y\) for
corresponding elements in x
and y
. For example:
# tensor 'x' is [[2, 2], [3, 3]]
# tensor 'y' is [[8, 16], [2, 3]]
tf.pow(x, y) ==> [[256, 65536], [9, 27]]
x
: ATensor
of typefloat32
,float64
,int32
,int64
,complex64
, orcomplex128
.y
: ATensor
of typefloat32
,float64
,int32
,int64
,complex64
, orcomplex128
.name
: A name for the operation (optional).
A Tensor
.
Returns x - y element-wise.
NOTE: Sub
supports broadcasting. More about broadcasting
here
x
: ATensor
. Must be one of the following types:half
,float32
,float64
,int32
,int64
,complex64
,complex128
.y
: ATensor
. Must have the same type asx
.name
: A name for the operation (optional).
A Tensor
. Has the same type as x
.
x ^ y = (x | y) & ~(x & y).
Returns x - y element-wise.
NOTE: Sub
supports broadcasting. More about broadcasting
here
x
: ATensor
. Must be one of the following types:half
,float32
,float64
,int32
,int64
,complex64
,complex128
.y
: ATensor
. Must have the same type asx
.name
: A name for the operation (optional).
A Tensor
. Has the same type as x
.
x ^ y = (x | y) & ~(x & y).
The name of the device on which this tensor will be produced, or None.
Represents the type of the elements in a Tensor
.
The following DType
objects are defined:
tf.float16
: 16-bit half-precision floating-point.tf.float32
: 32-bit single-precision floating-point.tf.float64
: 64-bit double-precision floating-point.tf.bfloat16
: 16-bit truncated floating-point.tf.complex64
: 64-bit single-precision complex.tf.complex128
: 128-bit double-precision complex.tf.int8
: 8-bit signed integer.tf.uint8
: 8-bit unsigned integer.tf.uint16
: 16-bit unsigned integer.tf.int16
: 16-bit signed integer.tf.int32
: 32-bit signed integer.tf.int64
: 64-bit signed integer.tf.bool
: Boolean.tf.string
: String.tf.qint8
: Quantized 8-bit signed integer.tf.quint8
: Quantized 8-bit unsigned integer.tf.qint16
: Quantized 16-bit signed integer.tf.quint16
: Quantized 16-bit unsigned integer.tf.qint32
: Quantized 32-bit signed integer.tf.resource
: Handle to a mutable resource.
In addition, variants of these types with the _ref
suffix are
defined for reference-typed tensors.
The tf.as_dtype()
function converts numpy types and string type
names to a DType
object.
Returns True if the other
DType will be converted to this DType.
The conversion rules are as follows:
DType(T) .is_compatible_with(DType(T)) == True
DType(T) .is_compatible_with(DType(T).as_ref) == True
DType(T).as_ref.is_compatible_with(DType(T)) == False
DType(T).as_ref.is_compatible_with(DType(T).as_ref) == True
other
: ADType
(or object that may be converted to aDType
).
True if a Tensor of the other
DType
will be implicitly converted to
this DType
.
Returns the string name for this DType
.
Returns a non-reference DType
based on this DType
.
Returns the dtype correspond to this dtype's real part.
Returns whether this is a boolean data type
Returns whether this is a (non-quantized, real) floating point type.
Returns whether this is a complex floating point type.
Returns whether this is a (non-quantized) integer type.
Returns whether this is a quantized data type.
Returns whether this type is unsigned.
Non-numeric, unordered, and quantized types are not considered unsigned, and
this function returns False
.
Whether a DType
is unsigned.
Returns a numpy.dtype
based on this DType
.
Returns a types_pb2.DataType
enum value based on this DType
.
Return intensity limits, i.e. (min, max) tuple, of the dtype.
clip_negative : bool, optional If True, clip the negative range (i.e. return 0 for min intensity) even if the image dtype allows negative values. Returns min, max : tuple Lower and upper intensity limits.
Returns True iff this DType refers to the same type as other
.
Creates a new DataType
.
NOTE(mrry): In normal circumstances, you should not need to
construct a DataType
object directly. Instead, use the
tf.as_dtype()
function.
type_enum
: Atypes_pb2.DataType
enum value.
TypeError
: Iftype_enum
is not a valuetypes_pb2.DataType
.
Returns True iff self != other.
Returns the maximum representable value in this data type.
TypeError
: if this is a non-numeric, unordered, or quantized type.
Returns the minimum representable value in this data type.
TypeError
: if this is a non-numeric, unordered, or quantized type.
Converts the given type_value
to a DType
.
type_value
: A value that can be converted to atf.DType
object. This may currently be atf.DType
object, aDataType
enum, a string type name, or anumpy.dtype
.
A DType
corresponding to type_value
.
TypeError
: Iftype_value
cannot be converted to aDType
.
Wrapper for Graph.device()
using the default graph.
See
Graph.device()
for more details.
device_name_or_function
: The device name or function to use in the context.
A context manager that specifies the default device to use for newly created ops.
Wrapper for Graph.container()
using the default graph.
container_name
: The container string to use in the context.
A context manager that specifies the default container to use for newly created stateful ops.
Returns a context manager for use when defining a Python op.
This context manager validates that the given values
are from the
same graph, makes that graph the default graph, and pushes a
name scope in that graph (see
Graph.name_scope()
for more details on that).
For example, to define a new Python op called my_op
:
def my_op(a, b, c, name=None):
with tf.name_scope(name, "MyOp", [a, b, c]) as scope:
a = tf.convert_to_tensor(a, name="a")
b = tf.convert_to_tensor(b, name="b")
c = tf.convert_to_tensor(c, name="c")
# Define some computation that uses `a`, `b`, and `c`.
return foo_op(..., name=scope)
name
: The name argument that is passed to the op function.default_name
: The default name to use if thename
argument isNone
.values
: The list ofTensor
arguments that are passed to the op function.
A context manager for use in defining Python ops. Yields the name scope.
ValueError
: if neithername
nordefault_name
is provided butvalues
are.
Wrapper for Graph.control_dependencies()
using the default graph.
See Graph.control_dependencies()
for more details.
control_inputs
: A list ofOperation
orTensor
objects which must be executed or computed before running the operations defined in the context. Can also beNone
to clear the control dependencies.
A context manager that specifies control dependencies for all operations constructed within the context.
Converts the given value
to a Tensor
.
This function converts Python objects of various types to Tensor
objects. It accepts Tensor
objects, numpy arrays, Python lists,
and Python scalars. For example:
import numpy as np
def my_func(arg):
arg = tf.convert_to_tensor(arg, dtype=tf.float32)
return tf.matmul(arg, arg) + arg
# The following calls are equivalent.
value_1 = my_func(tf.constant([[1.0, 2.0], [3.0, 4.0]]))
value_2 = my_func([[1.0, 2.0], [3.0, 4.0]])
value_3 = my_func(np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32))
This function can be useful when composing a new operation in Python
(such as my_func
in the example above). All standard Python op
constructors apply this function to each of their Tensor-valued
inputs, which allows those ops to accept numpy arrays, Python lists,
and scalars in addition to Tensor
objects.
value
: An object whose type has a registeredTensor
conversion function.dtype
: Optional element type for the returned tensor. If missing, the type is inferred from the type ofvalue
.name
: Optional name to use if a newTensor
is created.preferred_dtype
: Optional element type for the returned tensor, used when dtype is None. In some cases, a caller may not have a dtype in mind when converting to a tensor, so preferred_dtype can be used as a soft preference. If the conversion topreferred_dtype
is not possible, this argument has no effect.
An Output
based on value
.
TypeError
: If no conversion function is registered forvalue
.RuntimeError
: If a registered conversion function returns an invalid value.
tf.convert_to_tensor_or_indexed_slices(value, dtype=None, name=None)
{#convert_to_tensor_or_indexed_slices}
Converts the given object to a Tensor
or an IndexedSlices
.
If value
is an IndexedSlices
or SparseTensor
it is returned
unmodified. Otherwise, it is converted to a Tensor
using
convert_to_tensor()
.
value
: AnIndexedSlices
,SparseTensor
, or an object that can be consumed byconvert_to_tensor()
.dtype
: (Optional.) The requiredDType
of the returnedTensor
orIndexedSlices
.name
: (Optional.) A name to use if a newTensor
is created.
An Tensor
, IndexedSlices
, or SparseTensor
based on value
.
ValueError
: Ifdtype
does not match the element type ofvalue
.
tf.convert_to_tensor_or_sparse_tensor(value, dtype=None, name=None)
{#convert_to_tensor_or_sparse_tensor}
Converts value to a SparseTensor
or Tensor
.
value
: ASparseTensor
,SparseTensorValue
, or an object whose type has a registeredTensor
conversion function.dtype
: Optional element type for the returned tensor. If missing, the type is inferred from the type ofvalue
.name
: Optional name to use if a newTensor
is created.
A SparseTensor
or Tensor
based on value
.
RuntimeError
: If result type is incompatible withdtype
.
Returns the default graph for the current thread.
The returned graph will be the innermost graph on which a
Graph.as_default()
context has been entered, or a global default
graph if none has been explicitly created.
NOTE: The default graph is a property of the current thread. If you
create a new thread, and wish to use the default graph in that
thread, you must explicitly add a with g.as_default():
in that
thread's function.
The default Graph
being used in the current thread.
Clears the default graph stack and resets the global default graph.
NOTE: The default graph is a property of the current thread. This
function applies only to the current thread. Calling this function while
a tf.Session
or tf.InteractiveSession
is active will result in undefined
behavior. Using any previously created tf.Operation
or tf.Tensor
objects
after calling this function will result in undefined behavior.
tf.import_graph_def(graph_def, input_map=None, return_elements=None, name=None, op_dict=None, producer_op_list=None)
{#import_graph_def}
Imports the TensorFlow graph in graph_def
into the Python Graph
.
This function provides a way to import a serialized TensorFlow
GraphDef
protocol buffer, and extract individual objects in the GraphDef
as
Tensor
and Operation
objects. See
Graph.as_graph_def()
for a way to create a
GraphDef
proto.
graph_def
: AGraphDef
proto containing operations to be imported into the default graph.input_map
: A dictionary mapping input names (as strings) ingraph_def
toTensor
objects. The values of the named input tensors in the imported graph will be re-mapped to the respectiveTensor
values.return_elements
: A list of strings containing operation names ingraph_def
that will be returned asOperation
objects; and/or tensor names ingraph_def
that will be returned asTensor
objects.name
: (Optional.) A prefix that will be prepended to the names ingraph_def
. Defaults to"import"
.op_dict
: (Optional.) A dictionary mapping op type names toOpDef
protos. Must contain anOpDef
proto for each op type named ingraph_def
. If omitted, uses theOpDef
protos registered in the global registry.producer_op_list
: (Optional.) AnOpList
proto with the (possibly stripped) list ofOpDef
s used by the producer of the graph. If provided, attrs for ops ingraph_def
that are not inop_dict
that have their default value according toproducer_op_list
will be removed. This will allow some moreGraphDef
s produced by later binaries to be accepted by earlier binaries.
A list of Operation
and/or Tensor
objects from the imported graph,
corresponding to the names in return_elements
.
TypeError
: Ifgraph_def
is not aGraphDef
proto,input_map
is not a dictionary mapping strings toTensor
objects, orreturn_elements
is not a list of strings.ValueError
: Ifinput_map
, orreturn_elements
contains names that do not appear ingraph_def
, orgraph_def
is not well-formed (e.g. it refers to an unknown tensor).
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.
library_filename
: Path to the plugin. Relative or absolute filesystem path to a dynamic library file.
None.
RuntimeError
: when unable to load the library.
Loads a TensorFlow plugin, containing custom ops and kernels.
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. When the
library is loaded, ops and kernels registered in the library via the
REGISTER_*
macros are made available in the TensorFlow process. Note
that ops with the same name as an existing op are rejected and not
registered with the process.
library_filename
: Path to the plugin. Relative or absolute filesystem path to a dynamic library file.
A python module containing the Python wrappers for Ops defined in the plugin.
RuntimeError
: when unable to load the library or get the python wrappers.
Wrapper for Graph.add_to_collection()
using the default graph.
See Graph.add_to_collection()
for more details.
name
: The key for the collection. For example, theGraphKeys
class contains many standard names for collections.value
: The value to add to the collection.
Wrapper for Graph.get_collection()
using the default graph.
See Graph.get_collection()
for more details.
key
: The key for the collection. For example, theGraphKeys
class contains many standard names for collections.scope
: (Optional.) If supplied, the resulting list is filtered to include only items whosename
attribute matches usingre.match
. Items without aname
attribute are never returned if a scope is supplied and the choice orre.match
means that ascope
without special tokens filters by prefix.
The list of values in the collection with the given name
, or
an empty list if no value has been added to that collection. The
list contains the values in the order under which they were
collected.
Wrapper for Graph.get_collection_ref()
using the default graph.
See Graph.get_collection_ref()
for more details.
key
: The key for the collection. For example, theGraphKeys
class contains many standard names for collections.
The list of values in the collection with the given name
, or an empty
list if no value has been added to that collection. Note that this returns
the collection list itself, which can be modified in place to change the
collection.
Standard names to use for graph collections.
The standard library uses various well-known names to collect and
retrieve values associated with a graph. For example, the
tf.Optimizer
subclasses default to optimizing the variables
collected under tf.GraphKeys.TRAINABLE_VARIABLES
if none is
specified, but it is also possible to pass an explicit list of
variables.
The following standard keys are defined:
GLOBAL_VARIABLES
: the default collection ofVariable
objects, shared across distributed environment (model variables are subset of these). Seetf.global_variables()
for more details. Commonly, allTRAINABLE_VARIABLES
variables will be inMODEL_VARIABLES
, and allMODEL_VARIABLES
variables will be inGLOBAL_VARIABLES
.LOCAL_VARIABLES
: the subset ofVariable
objects that are local to each machine. Usually used for temporarily variables, like counters. Note: usetf.contrib.framework.local_variable
to add to this collection.MODEL_VARIABLES
: the subset ofVariable
objects that are used in the model for inference (feed forward). Note: usetf.contrib.framework.model_variable
to add to this collection.TRAINABLE_VARIABLES
: the subset ofVariable
objects that will be trained by an optimizer. Seetf.trainable_variables()
for more details.SUMMARIES
: the summaryTensor
objects that have been created in the graph. Seetf.summary.merge_all()
for more details.QUEUE_RUNNERS
: theQueueRunner
objects that are used to produce input for a computation. Seetf.start_queue_runners()
for more details.MOVING_AVERAGE_VARIABLES
: the subset ofVariable
objects that will also keep moving averages. Seetf.moving_average_variables()
for more details.REGULARIZATION_LOSSES
: regularization losses collected during graph construction.WEIGHTS
: weights inside neural network layersBIASES
: biases inside neural network layersACTIVATIONS
: activations of neural network layers
A decorator for registering the gradient function for an op type.
This decorator is only used when defining a new op type. For an op
with m
inputs and n
outputs, the gradient function is a function
that takes the original Operation
and n
Tensor
objects
(representing the gradients with respect to each output of the op),
and returns m
Tensor
objects (representing the partial gradients
with respect to each input of the op).
For example, assuming that operations of type "Sub"
take two
inputs x
and y
, and return a single output x - y
, the
following gradient function would be registered:
@tf.RegisterGradient("Sub")
def _sub_grad(unused_op, grad):
return grad, tf.negative(grad)
The decorator argument op_type
is the string type of an
operation. This corresponds to the OpDef.name
field for the proto
that defines the operation.
Creates a new decorator with op_type
as the Operation type.
op_type
: The string type of an operation. This corresponds to theOpDef.name
field for the proto that defines the operation.
Registers the function f
as gradient function for op_type
.
Specifies that ops of type op_type
is not differentiable.
This function should not be used for operations that have a well-defined gradient that is not yet implemented.
This function is only used when defining a new op type. It may be
used for ops such as tf.size()
that are not differentiable. For
example:
tf.NotDifferentiable("Size")
The gradient computed for 'op_type' will then propagate zeros.
For ops that have a well-defined gradient but are not yet implemented, no declaration should be made, and an error must be thrown if an attempt to request its gradient is made.
op_type
: The string type of an operation. This corresponds to theOpDef.name
field for the proto that defines the operation.
TypeError
: Ifop_type
is not a string.
Specifies that ops of type op_type
is not differentiable.
This function should not be used for operations that have a well-defined gradient that is not yet implemented.
This function is only used when defining a new op type. It may be
used for ops such as tf.size()
that are not differentiable. For
example:
tf.NotDifferentiable("Size")
The gradient computed for 'op_type' will then propagate zeros.
For ops that have a well-defined gradient but are not yet implemented, no declaration should be made, and an error must be thrown if an attempt to request its gradient is made.
op_type
: The string type of an operation. This corresponds to theOpDef.name
field for the proto that defines the operation.
TypeError
: Ifop_type
is not a string.
Represents the shape of a Tensor
.
A TensorShape
represents a possibly-partial shape specification for a
Tensor
. It may be one of the following:
- Fully-known shape: has a known number of dimensions and a known size for each dimension.
- Partially-known shape: has a known number of dimensions, and an unknown size for one or more dimension.
- Unknown shape: has an unknown number of dimensions, and an unknown size in all dimensions.
If a tensor is produced by an operation of type "Foo"
, its shape
may be inferred if there is a registered shape function for
"Foo"
. See Shape functions in C++
for
details of shape functions and how to register them. Alternatively,
the shape may be set explicitly using
Tensor.set_shape()
.
Returns a TensorShape
combining the information in self
and other
.
The dimensions in self
and other
are merged elementwise,
according to the rules defined for Dimension.merge_with()
.
other
: AnotherTensorShape
.
A TensorShape
containing the combined information of self
and
other
.
ValueError
: Ifself
andother
are not compatible.
Returns the concatenation of the dimension in self
and other
.
N.B. If either self
or other
is completely unknown,
concatenation will discard information about the other shape. In
future, we might support concatenation that preserves this
information for use with slicing.
other
: AnotherTensorShape
.
A TensorShape
whose dimensions are the concatenation of the
dimensions in self
and other
.
Returns the rank of this shape, or None if it is unspecified.
Returns a list of Dimensions, or None if the shape is unspecified.
Returns a list of integers or None
for each dimension.
A list of integers or None
for each dimension.
ValueError
: Ifself
is an unknown shape with an unknown rank.
Returns this shape as a TensorShapeProto
.
Returns True iff self
is compatible with other
.
Two possibly-partially-defined shapes are compatible if there exists a fully-defined shape that both shapes can represent. Thus, compatibility allows the shape inference code to reason about partially-defined shapes. For example:
-
TensorShape(None) is compatible with all shapes.
-
TensorShape([None, None]) is compatible with all two-dimensional shapes, such as TensorShape([32, 784]), and also TensorShape(None). It is not compatible with, for example, TensorShape([None]) or TensorShape([None, None, None]).
-
TensorShape([32, None]) is compatible with all two-dimensional shapes with size 32 in the 0th dimension, and also TensorShape([None, None]) and TensorShape(None). It is not compatible with, for example, TensorShape([32]), TensorShape([32, None, 1]) or TensorShape([64, None]).
-
TensorShape([32, 784]) is compatible with itself, and also TensorShape([32, None]), TensorShape([None, 784]), TensorShape([None, None]) and TensorShape(None). It is not compatible with, for example, TensorShape([32, 1, 784]) or TensorShape([None]).
The compatibility relation is reflexive and symmetric, but not transitive. For example, TensorShape([32, 784]) is compatible with TensorShape(None), and TensorShape(None) is compatible with TensorShape([4, 4]), but TensorShape([32, 784]) is not compatible with TensorShape([4, 4]).
other
: Another TensorShape.
True iff self
is compatible with other
.
Returns True iff self
is fully defined in every dimension.
Returns a shape based on self
with the given rank.
This method promotes a completely unknown shape to one with a known rank.
rank
: An integer.
A shape that is at least as specific as self
with the given rank.
ValueError
: Ifself
does not represent a shape with the givenrank
.
Returns a shape based on self
with at least the given rank.
rank
: An integer.
A shape that is at least as specific as self
with at least the given
rank.
ValueError
: Ifself
does not represent a shape with at least the givenrank
.
Returns a shape based on self
with at most the given rank.
rank
: An integer.
A shape that is at least as specific as self
with at most the given
rank.
ValueError
: Ifself
does not represent a shape with at most the givenrank
.
Raises an exception if self
is not compatible with the given rank
.
rank
: An integer.
ValueError
: Ifself
does not represent a shape with the givenrank
.
Raises an exception if self
and other
do not have compatible ranks.
other
: AnotherTensorShape
.
ValueError
: Ifself
andother
do not represent shapes with the same rank.
Raises exception if self
and other
do not represent the same shape.
This method can be used to assert that there exists a shape that both
self
and other
represent.
other
: Another TensorShape.
ValueError
: Ifself
andother
do not represent the same shape.
Raises an exception if self
is not fully defined in every dimension.
ValueError
: Ifself
does not have a known value for every dimension.
Returns True if this shape contains non-zero information.
Returns True if self
is equivalent to other
.
Returns the value of a dimension or a shape, depending on the key.
key
: Ifkey
is an integer, returns the dimension at that index; otherwise ifkey
is a slice, returns a TensorShape whose dimensions are those selected by the slice fromself
.
A dimension if key
is an integer, or a TensorShape
if key
is a
slice.
ValueError
: Ifkey
is a slice, and any of its elements are negative, or ifself
is completely unknown and the step is set.
Creates a new TensorShape with the given dimensions.
dims
: A list of Dimensions, or None if the shape is unspecified.DEPRECATED
: A single integer is treated as a singleton list.
TypeError
: If dims cannot be converted to a list of dimensions.
Returns self.dims
if the rank is known, otherwise raises ValueError.
Returns the rank of this shape, or raises ValueError if unspecified.
Returns True if self
is known to be different from other
.
Returns True if this shape contains non-zero information.
Returns the total number of elements, or none for incomplete shapes.
Represents the value of one dimension in a TensorShape.
Returns the sum of self
and other
.
Dimensions are summed as follows:
Dimension(m) + Dimension(n) == Dimension(m + n) Dimension(m) + Dimension(None) == Dimension(None) Dimension(None) + Dimension(n) == Dimension(None) Dimension(None) + Dimension(None) == Dimension(None)
other
: Another Dimension.
A Dimension whose value is the sum of self
and other
.
DEPRECATED: Use __floordiv__
via x // y
instead.
This function exists only for backwards compatibility purposes; new code
should use __floordiv__
via the syntax x // y
. Using x // y
communicates clearly that the result rounds down, and is forward compatible
to Python 3.
other
: AnotherDimension
.
A Dimension
whose value is the integer quotient of self
and other
.
Returns true if other
has the same known value as this Dimension.
Returns the quotient of self
and other
rounded down.
Dimensions are divided as follows:
Dimension(m) // Dimension(n) == Dimension(m // n) Dimension(m) // Dimension(None) == Dimension(None) Dimension(None) // Dimension(n) == Dimension(None) Dimension(None) // Dimension(None) == Dimension(None)
other
: AnotherDimension
.
A Dimension
whose value is the integer quotient of self
and other
.
Returns True if self
is known to be greater than or equal to other
.
Dimensions are compared as follows:
Dimension(m) >= Dimension(n) == m >= n Dimension(m) >= Dimension(None) == None Dimension(None) >= Dimension(n) == None Dimension(None) >= Dimension(None) == None
other
: Another Dimension.
The value of self.value >= other.value
if both are known, otherwise
None.
Returns True if self
is known to be greater than other
.
Dimensions are compared as follows:
Dimension(m) > Dimension(n) == m > n Dimension(m) > Dimension(None) == None Dimension(None) > Dimension(n) == None Dimension(None) > Dimension(None) == None
other
: Another Dimension.
The value of self.value > other.value
if both are known, otherwise
None.
Creates a new Dimension with the given value.
Returns True if self
is known to be less than or equal to other
.
Dimensions are compared as follows:
Dimension(m) <= Dimension(n) == m <= n Dimension(m) <= Dimension(None) == None Dimension(None) <= Dimension(n) == None Dimension(None) <= Dimension(None) == None
other
: Another Dimension.
The value of self.value <= other.value
if both are known, otherwise
None.
Returns True if self
is known to be less than other
.
Dimensions are compared as follows:
Dimension(m) < Dimension(n) == m < n Dimension(m) < Dimension(None) == None Dimension(None) < Dimension(n) == None Dimension(None) < Dimension(None) == None
other
: Another Dimension.
The value of self.value < other.value
if both are known, otherwise
None.
Returns self
modulo `other.
Dimension moduli are computed as follows:
Dimension(m) % Dimension(n) == Dimension(m % n) Dimension(m) % Dimension(None) == Dimension(None) Dimension(None) % Dimension(n) == Dimension(None) Dimension(None) % Dimension(None) == Dimension(None)
other
: Another Dimension.
A Dimension whose value is self
modulo other
.
Returns the product of self
and other
.
Dimensions are summed as follows:
Dimension(m) * Dimension(n) == Dimension(m * n)
Dimension(m) * Dimension(None) == Dimension(None)
Dimension(None) * Dimension(n) == Dimension(None)
Dimension(None) * Dimension(None) == Dimension(None)
other
: Another Dimension.
A Dimension whose value is the product of self
and other
.
Returns true if other
has a different known value from self
.
Returns the subtraction of other
from self
.
Dimensions are subtracted as follows:
Dimension(m) - Dimension(n) == Dimension(m - n) Dimension(m) - Dimension(None) == Dimension(None) Dimension(None) - Dimension(n) == Dimension(None) Dimension(None) - Dimension(None) == Dimension(None)
other
: Another Dimension.
A Dimension whose value is the subtraction of sum of other
from self
.
Raises an exception if other
is not compatible with this Dimension.
other
: Another Dimension.
ValueError
: Ifself
andother
are not compatible (see is_compatible_with).
Returns true if other
is compatible with this Dimension.
Two known Dimensions are compatible if they have the same value. An unknown Dimension is compatible with all other Dimensions.
other
: Another Dimension.
True if this Dimension and other
are compatible.
Returns a Dimension that combines the information in self
and other
.
Dimensions are combined as follows:
Dimension(n) .merge_with(Dimension(n)) == Dimension(n)
Dimension(n) .merge_with(Dimension(None)) == Dimension(n)
Dimension(None).merge_with(Dimension(n)) == Dimension(n)
Dimension(None).merge_with(Dimension(None)) == Dimension(None)
Dimension(n) .merge_with(Dimension(m)) raises ValueError for n != m
other
: Another Dimension.
A Dimension containing the combined information of self
and
other
.
ValueError
: Ifself
andother
are not compatible (see is_compatible_with).
The value of this dimension, or None if it is unknown.
DEPRECATED. Same as name_scope above, just different argument order.
Returns the local seeds an operation should use given an op-specific seed.
Given operation-specific seed, op_seed
, this helper function returns two
seeds derived from graph-level and op-level seeds. Many random operations
internally use the two seeds to allow user to change the seed globally for a
graph, or for only specific operations.
For details on how the graph-level seed interacts with op seeds, see
set_random_seed
.
op_seed
: integer.
A tuple of two integers that should be used for the local seed of this operation.
tf.register_tensor_conversion_function(base_type, conversion_func, priority=100)
{#register_tensor_conversion_function}
Registers a function for converting objects of base_type
to Tensor
.
The conversion function must have the following signature:
def conversion_func(value, dtype=None, name=None, as_ref=False):
# ...
It must return a Tensor
with the given dtype
if specified. If the
conversion function creates a new Tensor
, it should use the given
name
if specified. All exceptions will be propagated to the caller.
The conversion function may return NotImplemented
for some
inputs. In this case, the conversion process will continue to try
subsequent conversion functions.
If as_ref
is true, the function must return a Tensor
reference,
such as a Variable
.
NOTE: The conversion functions will execute in order of priority,
followed by order of registration. To ensure that a conversion function
F
runs before another conversion function G
, ensure that F
is
registered with a smaller priority than G
.
base_type
: The base type or tuple of base types for all objects thatconversion_func
accepts.conversion_func
: A function that converts instances ofbase_type
toTensor
.priority
: Optional integer that indicates the priority for applying this conversion function. Conversion functions with smaller priority values run earlier than conversion functions with larger priority values. Defaults to 100.
TypeError
: If the arguments do not have the appropriate type.
Represents a (possibly partial) specification for a TensorFlow device.
DeviceSpec
s are used throughout TensorFlow to describe where state is stored
and computations occur. Using DeviceSpec
allows you to parse device spec
strings to verify their validity, merge them or compose them programmatically.
Example:
# Place the operations on device "GPU:0" in the "ps" job.
device_spec = DeviceSpec(job="ps", device_type="GPU", device_index=0)
with tf.device(device_spec):
# Both my_var and squared_var will be placed on /job:ps/device:GPU:0.
my_var = tf.Variable(..., name="my_variable")
squared_var = tf.square(my_var)
If a DeviceSpec
is partially specified, it will be merged with other
DeviceSpec
s according to the scope in which it is defined. DeviceSpec
components defined in inner scopes take precedence over those defined in
outer scopes.
with tf.device(DeviceSpec(job="train", )):
with tf.device(DeviceSpec(job="ps", device_type="GPU", device_index=0):
# Nodes created here will be assigned to /job:ps/device:GPU:0.
with tf.device(DeviceSpec(device_type="GPU", device_index=1):
# Nodes created here will be assigned to /job:train/device:GPU:1.
A DeviceSpec
consists of 5 components -- each of
which is optionally specified:
- Job: The job name.
- Replica: The replica index.
- Task: The task index.
- Device type: The device type string (e.g. "CPU" or "GPU").
- Device index: The device index.
tf.DeviceSpec.__init__(job=None, replica=None, task=None, device_type=None, device_index=None)
{#DeviceSpec.init}
Create a new DeviceSpec
object.
job
: string. Optional job name.replica
: int. Optional replica index.task
: int. Optional task index.device_type
: Optional device type string (e.g. "CPU" or "GPU")device_index
: int. Optional device index. If left unspecified, device represents 'any' device_index.
Construct a DeviceSpec
from a string.
spec
: a string of the form /job:/replica:/task:/device:CPU: or /job:/replica:/task:/device:GPU: as cpu and gpu are mutually exclusive. All entries are optional.
A DeviceSpec.
Merge the properties of "dev" into this DeviceSpec
.
dev
: aDeviceSpec
.
Parse a DeviceSpec
name into its components.
spec
: a string of the form /job:/replica:/task:/device:CPU: or /job:/replica:/task:/device:GPU: as cpu and gpu are mutually exclusive. All entries are optional.
The DeviceSpec
.
ValueError
: if the spec was not valid.
Return a string representation of this DeviceSpec
.
a string of the form /job:/replica:/task:/device:<device_type>:.