Adds a constraint, which will be enforced during program execution.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.register_validator
The constraint is validated when flags are initially parsed, and after each change of the corresponding flag's value. Args: flag_name: str, name of the flag to be checked. checker: callable, a function to validate the flag. input - A single positional argument: The value of the corresponding flag (string, boolean, etc. This value will be passed to checker by the library). output - bool, True if validator constraint is satisfied. If constraint is not satisfied, it should either return False or raise flags.ValidationError(desired_error_message). message: str, error text to be shown to the user if checker returns False. If checker raises flags.ValidationError, message from the raised error will be shown. flag_values: flags.FlagValues, optional FlagValues instance to validate against. Raises: AttributeError: Raised when flag_name is not registered as a valid flag name.


Wraps a given text to a maximum line length and returns it.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.text_wrap
It turns lines that only contain whitespace into empty lines, keeps new lines, and expands tabs using 4 spaces.


Base TFDecorator class and utility functions for working with decorators.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.tf_decorator
There are two ways to create decorators that TensorFlow can introspect into. This is important for documentation generation purposes, so that function signatures aren't obscured by the (*args, **kwds) signature that decorators often provide.
def print_hello_before_calling(target): def wrapper(*args, *kwargs): print('hello') return target(args, **kwargs) return tf_decorator.make_decorator(target, wrapper)
class CallCounter(tf_decorator.TFDecorator): def init(self, target): super(CallCounter, self).init('count_calls', target) self.call_count = 0
def call(self, *args, *kwargs): self.call_count += 1 return super(CallCounter, self).decorated_target(args, **kwargs)
def count_calls(target): return CallCounter(target)
tf_stack module: Functions used to extract and analyze stacks. Faster than Python libs.
class TFDecorator: Base class for all TensorFlow decorators.
make_decorator(...): Make a decorator from a wrapper and a target.
rewrap(...): Injects a new target into a function built by make_decorator.
unwrap(...): Unwraps an object into a list of TFDecorators and a final target.


Make a decorator from a wrapper and a target.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.tf_decorator.make_decorator


Injects a new target into a function built by make_decorator.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.tf_decorator.rewrap
This function allows replacing a function wrapped by decorator_func, assuming the decorator that wraps the function is written as described below.
The decorator function must use <decorator name>.__wrapped__ instead of the wrapped function that is normally used:
def simple_parametrized_wrapper(*args, *kwds): return wrapped_fn(args, **kwds)
tf_decorator.make_decorator(simple_parametrized_wrapper, wrapped_fn)
def simple_parametrized_wrapper(*args, *kwds): return simple_parametrizedwrapper.wrapped_(args, **kwds)
tf_decorator.make_decorator(simple_parametrized_wrapper, wrapped_fn)
Note that this process modifies decorator_func.


Base class for all TensorFlow decorators.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.tf_decorator.TFDecorator
TFDecorator captures and exposes the wrapped target, and provides details about the current decorator.
View source
Call self as a function.


Functions used to extract and analyze stacks. Faster than Python libs.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.tf_decorator.tf_stack
class CurrentModuleFilter: Filters stack frames from the module where this is used (best effort).
class FrameSummary
class StackSummary
class StackTraceFilter: Allows filtering traceback information by removing superfluous frames.
class StackTraceMapper: Allows remapping traceback information to different source code.
class StackTraceTransform: Base class for stack trace transformation functions.
extract_stack(...): A lightweight, extensible re-implementation of traceback.extract_stack.


Filters stack frames from the module where this is used (best effort).
Inherits From: StackTraceFilter, StackTraceTransform
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.tf_decorator.tf_stack.CurrentModuleFilter
View source
View source
View source
View source


A lightweight, extensible re-implementation of traceback.extract_stack.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.tf_decorator.tf_stack.extract_stack
NOTE(mrry): traceback.extract_stack eagerly retrieves the line of code for each stack frame using linecache, which results in an abundance of stat() calls. This implementation does not retrieve the code, and any consumer should apply _convert_stack to the result to obtain a traceback that can be formatted etc. using traceback methods.


Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.tf_decorator.tf_stack.FrameSummary
eq(self: tensorflow.python._tf_stack.FrameSummary, arg0: tensorflow.python._tf_stack.FrameSummary) -> bool
getitem(self: tensorflow.python._tf_stack.FrameSummary, arg0: object) -> object
iter(self: tensorflow.python._tf_stack.FrameSummary) -> iterator
len(self: tensorflow.python._tf_stack.FrameSummary) -> int
ne(self: tensorflow.python._tf_stack.FrameSummary, arg0: tensorflow.python._tf_stack.FrameSummary) -> bool


Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.tf_decorator.tf_stack.StackSummary
append(self: tensorflow.python._tf_stack.StackSummary, x: tensorflow.python._tf_stack.FrameSummary) -> None
Add an item to the end of the list
count(self: tensorflow.python._tf_stack.StackSummary, x: tensorflow.python._tf_stack.FrameSummary) -> int
Return the number of times x appears in the list
extend(*args, **kwargs) Overloaded function.
Extend the list by appending all the items in the given list
Extend the list by appending all the items in the given list
insert(self: tensorflow.python._tf_stack.StackSummary, i: int, x: tensorflow.python._tf_stack.FrameSummary) -> None
Insert an item at a given position.
pop(*args, **kwargs) Overloaded function.
Remove and return the last item
Remove and return the item at index i
remove(self: tensorflow.python._tf_stack.StackSummary, x: tensorflow.python._tf_stack.FrameSummary) -> None
Remove the first item from the list whose value is x. It is an error if there is no such item.
bool(self: tensorflow.python._tf_stack.StackSummary) -> bool
Check whether the list is nonempty
contains(self: tensorflow.python._tf_stack.StackSummary, x: tensorflow.python._tf_stack.FrameSummary) -> bool
Return true the container contains x
eq(self: tensorflow.python._tf_stack.StackSummary, arg0: tensorflow.python._tf_stack.StackSummary) -> bool
getitem(*args, **kwargs) Overloaded function.
Retrieve list elements using a slice object
getitem(self: tensorflow.python._tf_stack.StackSummary, arg0: int) -> tensorflow.python._tf_stack.FrameSummary
getitem(self: tensorflow.python._tf_stack.StackSummary, arg0: int) -> tensorflow.python._tf_stack.FrameSummary
iter(self: tensorflow.python._tf_stack.StackSummary) -> iterator
len(self: tensorflow.python._tf_stack.StackSummary) -> int
ne(self: tensorflow.python._tf_stack.StackSummary, arg0: tensorflow.python._tf_stack.StackSummary) -> bool


Allows filtering traceback information by removing superfluous frames.
Inherits From: StackTraceTransform
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.tf_decorator.tf_stack.StackTraceFilter
View source
View source
View source
View source


Allows remapping traceback information to different source code.
Inherits From: StackTraceTransform
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.tf_decorator.tf_stack.StackTraceMapper
View source
Returns a map (filename, lineno) -> (filename, lineno, function_name).
View source
View source
View source


Base class for stack trace transformation functions.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.tf_decorator.tf_stack.StackTraceTransform
View source
View source
View source


Unwraps an object into a list of TFDecorators and a final target.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.tf_decorator.unwrap


Raised when accessing the flag value from unparsed FlagValues.
Inherits From: Error
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.UnparsedFlagAccessError


Raised when a flag is unrecognized.
Inherits From: Error
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.UnrecognizedFlagError


Raised when flag validator constraint is not satisfied.
Inherits From: Error
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.ValidationError


A function decorator for defining a flag validator.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.validator
Registers the decorated function as a validator for flag_name, e.g.
@flags.validator('foo') def _CheckFoo(foo): ...
See register_validator() for the specification of checker function.


Parser for a whitespace-separated list of strings.
Inherits From: BaseListParser, ArgumentParser
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.WhitespaceSeparatedListParser
See base class.
Parses argument as whitespace-separated list of strings.
It also parses argument as comma-separated list of strings if requested.


foldl on the list of tensors unpacked from elems on dimension 0.
This foldl operator repeatedly applies the callable fn to a sequence of elements from first to last. The elements are made of the tensors unpacked from elems on dimension 0. The callable fn takes two tensors as arguments. The first argument is the accumulated value computed from the preceding invocation of fn, and the second is the value at the current position of elems. If initializer is None, elems must contain at least one element, and its first element is used as the initializer.
Suppose that elems is unpacked into values, a list of tensors. The shape of the result tensor is fn(initializer, values[0]).shape`.
This method also allows multi-arity elems and output of fn. If elems is a (possibly nested) list or tuple of tensors, then each of these tensors must have a matching first (unpack) dimension. The signature of fn may match the structure of elems. That is, if elems is (t1, [t2, t3, [t4, t5]]), then an appropriate signature for fn is: fn = lambda (t1, [t2, t3, [t4, t5]]):.


foldr on the list of tensors unpacked from elems on dimension 0.
This foldr operator repeatedly applies the callable fn to a sequence of elements from last to first. The elements are made of the tensors unpacked from elems. The callable fn takes two tensors as arguments. The first argument is the accumulated value computed from the preceding invocation of fn, and the second is the value at the current position of elems. If initializer is None, elems must contain at least one element, and its first element is used as the initializer.
Suppose that elems is unpacked into values, a list of tensors. The shape of the result tensor is fn(initializer, values[0]).shape.
This method also allows multi-arity elems and output of fn. If elems is a (possibly nested) list or tuple of tensors, then each of these tensors must have a matching first (unpack) dimension. The signature of fn may match the structure of elems. That is, if elems is (t1, [t2, t3, [t4, t5]]), then an appropriate signature for fn is: fn = lambda (t1, [t2, t3, [t4, t5]]):.


Gather slices from params axis axis according to indices.
Gather slices from params axis axis according to indices. indices must be an integer tensor of any dimension (usually 0-D or 1-D).
For 0-D (scalar) indices:
Where N = ndims(params).
For 1-D (vector) indices with batch_dims=0:
In the general case, produces an output tensor where:
Where N = ndims(params), M = ndims(indices), and B = batch_dims. Note that params.shape[:batch_dims] must be identical to indices.shape[:batch_dims].
The shape of the output tensor is:
output.shape = params.shape[:axis] + indices.shape[batch_dims:] + params.shape[axis + 1:].
Note that on CPU, if an out of bound index is found, an error is returned. On GPU, if an out of bound index is found, a 0 is stored in the corresponding output value.
See also tf.gather_nd.


Gather slices from params into a Tensor with shape specified by indices.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.manip.gather_nd
indices is an K-dimensional integer tensor, best thought of as a (K-1)-dimensional tensor of indices into params, where each element defines a slice of params:
Whereas in tf.gather indices defines slices into the first dimension of params, in tf.gather_nd, indices defines slices into the first N dimensions of params, where N = indices.shape[-1].
The last dimension of indices can be at most the rank of params:
The last dimension of indices corresponds to elements (if indices.shape[-1] == params.rank) or slices (if indices.shape[-1] < params.rank) along dimension indices.shape[-1] of params. The output tensor has shape
Additionally both 'params' and 'indices' can have M leading batch dimensions that exactly match. In this case 'batch_dims' must be M.
Note that on CPU, if an out of bound index is found, an error is returned. On GPU, if an out of bound index is found, a 0 is stored in the corresponding output value.
Some examples below.
Simple indexing into a matrix:
Slice indexing into a matrix:
Indexing into a 3-tensor:
The examples below are for the case when only indices have leading extra dimensions. If both 'params' and 'indices' have leading batch dimensions, use the 'batch_dims' parameter to run gather_nd in batch mode.
Batched indexing into a matrix:
Batched slice indexing into a matrix:
Batched indexing into a 3-tensor:
Examples with batched 'params' and 'indices':
See also tf.gather.


Wrapper for Graph.get_collection() using the default graph.
See tf.Graph.get_collection for more details.
Collections are not supported when eager execution is enabled.


Wrapper for Graph.get_collection_ref() using the default graph.
See tf.Graph.get_collection_ref for more details.
Collections are not supported when eager execution is enabled.


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.


Returns the default session for the current thread.
The returned Session will be the innermost session on which a Session or Session.as_default() context has been entered.


Gets an existing local variable or creates a new one.
Behavior is the same as in get_variable, except that variables are added to the LOCAL_VARIABLES collection and trainable is set to False. This function prefixes the name with the current variable scope and performs reuse checks. See the Variable Scope How To for an extensive description of how reusing works. Here is a basic example:
If initializer is None (the default), the default initializer passed in the variable scope will be used. If that one is None too, a glorot_uniform_initializer will be used. The initializer can also be a Tensor, in which case the variable is initialized to this value and shape.
Similarly, if the regularizer is None (the default), the default regularizer passed in the variable scope will be used (if that is None too, then by default no regularization is performed).
If a partitioner is provided, a PartitionedVariable is returned. Accessing this object as a Tensor returns the shards concatenated along the partition axis.
Some useful partitioners are available. See, e.g., variable_axis_size_partitioner and min_max_variable_partitioner.


Returns the local seeds an operation should use given an op-specific seed.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.random.get_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 tf.compat.v1.random.set_random_seed.


Return the handle of data.
This is EXPERIMENTAL and subject to change.
Keep data "in-place" in the runtime and create a handle that can be used to retrieve data in a subsequent run().
Combined with get_session_tensor, we can keep a tensor produced in one run call in place, and use it as the input in a future run call.


Get the tensor of type dtype by feeding a tensor handle.
This is EXPERIMENTAL and subject to change.
Get the value of the tensor from a tensor handle. The tensor is produced in a previous run() and stored in the state of the session.


Gets an existing variable with these parameters or create a new one.
This function prefixes the name with the current variable scope and performs reuse checks. See the Variable Scope How To for an extensive description of how reusing works. Here is a basic example:
If initializer is None (the default), the default initializer passed in the variable scope will be used. If that one is None too, a glorot_uniform_initializer will be used. The initializer can also be a Tensor, in which case the variable is initialized to this value and shape.
Similarly, if the regularizer is None (the default), the default regularizer passed in the variable scope will be used (if that is None too, then by default no regularization is performed).
If a partitioner is provided, a PartitionedVariable is returned. Accessing this object as a Tensor returns the shards concatenated along the partition axis.
Some useful partitioners are available. See, e.g., variable_axis_size_partitioner and min_max_variable_partitioner.


Import router for file_io.
class FastGFile: File I/O wrappers without thread locking.
class GFile: File I/O wrappers without thread locking.
class Open: File I/O wrappers without thread locking.
Copy(...): Copies data from oldpath to newpath.
DeleteRecursively(...): Deletes everything under dirname recursively.
Exists(...): Determines whether a path exists or not.
Glob(...): Returns a list of files that match the given pattern(s).
IsDirectory(...): Returns whether the path is a directory or not.
ListDirectory(...): Returns a list of entries contained within a directory.
MakeDirs(...): Creates a directory and all parent/intermediate directories.
MkDir(...): Creates a directory with the name dirname.
Remove(...): Deletes the file located at 'filename'.
Rename(...): Rename or move a file / directory.
Stat(...): Returns file statistics for a given path.
Walk(...): Recursive directory tree generator for directories.


Deletes everything under dirname recursively.


Determines whether a path exists or not.


File I/O wrappers without thread locking.
Note, that this is somewhat like builtin Python file I/O, but there are semantic differences to make it more efficient for some backing filesystems. For example, a write mode file will not be opened until the first write call (to minimize RPC invocations in network filesystems).
View source
Closes FileIO. Should be called for the WritableFile to be flushed.
View source
Flushes the Writable file.
This only ensures that the data has made its way out of the process without any guarantees on whether it's written to disk. This means that the data would survive an application crash but not necessarily an OS crash.
View source
View source
Returns the contents of a file as a string.
Starts reading from current position in file.
View source
Reads the next line, keeping \n. At EOF, returns ''.
View source
Returns all lines from the file in a list.
View source
Seeks to the offset in the file. (deprecated arguments)
View source
Returns True as FileIO supports random access ops of seek()/tell()
View source
Returns the size of the file.
View source
Returns the current position in the file.
View source
Writes file_content to the file. Appends to the end of the file.
View source
Make usable with "with" statement.
View source
Make usable with "with" statement.
View source


Returns a list of files that match the given pattern(s).


Returns whether the path is a directory or not.


Returns a list of entries contained within a directory.
The list is in arbitrary order. It does not contain the special entries "." and "..".


Creates a directory and all parent/intermediate directories.
It succeeds if dirname already exists and is writable.


Creates a directory with the name dirname.
Notes: The parent directories need to exist. Use tf.io.gfile.makedirs instead if there is the possibility that the parent dirs don't exist.


Returns file statistics for a given path.


Recursive directory tree generator for directories.


Returns global variables.
Global variables are variables that are shared across machines in a distributed environment. The Variable() constructor or get_variable() automatically adds new variables to the graph collection GraphKeys.GLOBAL_VARIABLES. This convenience function returns the contents of that collection.
An alternative to global variables are local variables. See tf.compat.v1.local_variables


Returns an Op that initializes global variables.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.initializers.global_variables
This is just a shortcut for variables_initializer(global_variables())


Constructs symbolic derivatives of sum of ys w.r.t. x in xs.
ys and xs are each a Tensor or a list of tensors. grad_ys is a list of Tensor, holding the gradients received by the ys. The list must be the same length as ys.
gradients() adds ops to the graph to output the derivatives of ys with respect to xs. It returns a list of Tensor of length len(xs) where each tensor is the sum(dy/dx) for y in ys and for x in xs.
grad_ys is a list of tensors of the same length as ys that holds the initial gradients for each y in ys. When grad_ys is None, we fill in a tensor of '1's of the shape of y for each y in ys. A user can provide their own initial grad_ys to compute the derivatives using a different initial gradient for each y (e.g., if one wanted to weight the gradient differently for each value in each y).
stop_gradients is a Tensor or a list of tensors to be considered constant with respect to all xs. These tensors will not be backpropagated through, as though they had been explicitly disconnected using stop_gradient. Among other things, this allows computation of partial derivatives as opposed to total derivatives. For example:
Here the partial derivatives g evaluate to [1.0, 1.0], compared to the total derivatives tf.gradients(a + b, [a, b]), which take into account the influence of a on b and evaluate to [3.0, 1.0]. Note that the above is equivalent to:
stop_gradients provides a way of stopping gradient after the graph has already been constructed, as compared to tf.stop_gradient which is used during graph construction. When the two approaches are combined, backpropagation stops at both tf.stop_gradient nodes and nodes in stop_gradients, whichever is encountered first.
All integer tensors are considered constant with respect to all xs, as if they were included in stop_gradients.
unconnected_gradients determines the value returned for each x in xs if it is unconnected in the graph to ys. By default this is None to safeguard against errors. Mathematically these gradients are zero which can be requested using the 'zero' option. tf.UnconnectedGradients provides the following options and behaviors:
Let us take one practical example which comes during the back propogation phase. This function is used to evaluate the derivatives of the cost function with respect to Weights Ws and Biases bs. Below sample implementation provides the exaplantion of what it is actually used for :


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:
The following standard keys are defined, but their collections are not automatically populated as many of the others are:


Helpers to manipulate a tensor graph in python.
convert_variables_to_constants(...): Replaces all the variables in a graph with constants of the same values. (deprecated)
extract_sub_graph(...): Extract the subgraph that can reach any of the nodes in 'dest_nodes'. (deprecated)
import_graph_def(...): Imports the graph from graph_def into the current default Graph. (deprecated arguments)
must_run_on_cpu(...): Returns True if the given node_def must run on CPU, otherwise False. (deprecated)
remove_training_nodes(...): Prunes out nodes that aren't needed for inference. (deprecated)
tensor_shape_from_node_def_name(...): Convenience function to get a shape from a NodeDef's input string. (deprecated)


Replaces all the variables in a graph with constants of the same values. (deprecated)
If you have a trained graph containing Variable ops, it can be convenient to convert them all to Const ops holding the same values. This makes it possible to describe the network fully with a single GraphDef file, and allows the removal of a lot of ops related to loading and saving the variables.


Extract the subgraph that can reach any of the nodes in 'dest_nodes'. (deprecated)


Returns True if the given node_def must run on CPU, otherwise False. (deprecated)


Prunes out nodes that aren't needed for inference. (deprecated)
There are nodes like Identity and CheckNumerics that are only useful during training, and can be removed in graphs that will be used for nothing but inference. Here we identify and remove them, returning an equivalent graph. To be specific, CheckNumerics nodes are always removed, and Identity nodes that aren't involved in control edges are spliced out so that their input and outputs are directly connected.


Convenience function to get a shape from a NodeDef's input string. (deprecated)


Constructs the Hessian of sum of ys with respect to x in xs.
hessians() adds ops to the graph to output the Hessian matrix of ys with respect to xs. It returns a list of Tensor of length len(xs) where each tensor is the Hessian of sum(ys).
The Hessian is a matrix of second-order partial derivatives of a scalar tensor (see https://en.wikipedia.org/wiki/Hessian_matrix for more details).


A Reader that outputs the queued work as both the key and value.
Inherits From: ReaderBase
To use, enqueue strings in a Queue. Read will take the front work string and output (work, work).
See ReaderBase for supported methods.
Readers are not compatible with eager execution. Instead, please use tf.data to get data into your model.
View source
Returns the number of records this reader has produced.
This is the same as the number of Read executions that have succeeded.
View source
Returns the number of work units this reader has finished processing.
View source
Returns the next record (key, value) pair produced by a reader.
Will dequeue a work unit from queue if necessary (e.g. when the Reader needs to start reading from a new file since it has finished with the previous file).
View source
Returns up to num_records (key, value) pairs produced by a reader.
Will dequeue a work unit from queue if necessary (e.g., when the Reader needs to start reading from a new file since it has finished with the previous file). It may return less than num_records even before the last batch.
View source
Restore a reader to its initial clean state.
View source
Restore a reader to a previously saved state.
Not all Readers support being restored, so this can produce an Unimplemented error.
View source
Produce a string tensor that encodes the state of a reader.
Not all Readers support being serialized, so this can produce an Unimplemented error.


Image ops.
The tf.image module contains various functions for image processing and decoding-encoding Ops.
Many of the encoding/decoding functions are also available in the core tf.io module.
The resizing Ops accept input images as tensors of several types. They always output resized images as float32 tensors.
The convenience function tf.image.resize supports both 4-D and 3-D tensors as input and output. 4-D tensors are for batches of images, 3-D tensors for individual images.
Resized images will be distorted if their original aspect ratio is not the same as size. To avoid distortions see tf.image.resize_with_pad.
The Class tf.image.ResizeMethod provides various resize methods like bilinear, nearest_neighbor.
Image ops work either on individual images or on batches of images, depending on the shape of their input Tensor.
If 3-D, the shape is [height, width, channels], and the Tensor represents one image. If 4-D, the shape is [batch_size, height, width, channels], and the Tensor represents batch_size images.
Currently, channels can usefully be 1, 2, 3, or 4. Single-channel images are grayscale, images with 3 channels are encoded as either RGB or HSV. Images with 2 or 4 channels include an alpha channel, which has to be stripped from the image before passing the image to most image processing functions (and can be re-attached later).
Internally, images are either stored in as one float32 per channel per pixel (implicitly, values are assumed to lie in [0,1)) or one uint8 per channel per pixel (values are assumed to lie in [0,255]).
TensorFlow can convert between images in RGB or HSV or YIQ.
TensorFlow provides functions to adjust images in various ways: brightness, contrast, hue, and saturation. Each adjustment can be done with predefined parameters or with random parameters picked from predefined intervals. Random adjustments are often useful to expand a training set and reduce overfitting.
If several adjustments are chained it is advisable to minimize the number of redundant conversions by first converting the images to the most natural data type and representation.
TensorFlow provides Ops to decode and encode JPEG and PNG formats. Encoded images are represented by scalar string Tensors, decoded images by 3-D uint8 tensors of shape [height, width, channels]. (PNG also supports uint16.)
The encode and decode Ops apply to one image at a time. Their input and output are all of variable size. If you need fixed size images, pass the output of the decode Ops to one of the cropping and resizing Ops.
class ResizeMethod: See v1.image.resize for details.
adjust_brightness(...): Adjust the brightness of RGB or Grayscale images.
adjust_contrast(...): Adjust contrast of RGB or grayscale images.
adjust_gamma(...): Performs Gamma Correction.
adjust_hue(...): Adjust hue of RGB images.
adjust_jpeg_quality(...): Adjust jpeg encoding quality of an image.
adjust_saturation(...): Adjust saturation of RGB images.
central_crop(...): Crop the central region of the image(s).
combined_non_max_suppression(...): Greedily selects a subset of bounding boxes in descending order of score.
convert_image_dtype(...): Convert image to dtype, scaling its values if needed.
crop_and_resize(...): Extracts crops from the input image tensor and resizes them.
crop_to_bounding_box(...): Crops an image to a specified bounding box.
decode_and_crop_jpeg(...): Decode and Crop a JPEG-encoded image to a uint8 tensor.
decode_bmp(...): Decode the first frame of a BMP-encoded image to a uint8 tensor.
decode_gif(...): Decode the frame(s) of a GIF-encoded image to a uint8 tensor.
decode_image(...): Function for decode_bmp, decode_gif, decode_jpeg, and decode_png.
decode_jpeg(...): Decode a JPEG-encoded image to a uint8 tensor.
decode_png(...): Decode a PNG-encoded image to a uint8 or uint16 tensor.
draw_bounding_boxes(...): Draw bounding boxes on a batch of images.
encode_jpeg(...): JPEG-encode an image.
encode_png(...): PNG-encode an image.
extract_glimpse(...): Extracts a glimpse from the input tensor.
extract_image_patches(...): Extract patches from images and put them in the "depth" output dimension.
extract_jpeg_shape(...): Extract the shape information of a JPEG-encoded image.
extract_patches(...): Extract patches from images.
flip_left_right(...): Flip an image horizontally (left to right).
flip_up_down(...): Flip an image vertically (upside down).
generate_bounding_box_proposals(...): Generate bounding box proposals from encoded bounding boxes.
grayscale_to_rgb(...): Converts one or more images from Grayscale to RGB.
hsv_to_rgb(...): Convert one or more images from HSV to RGB.
image_gradients(...): Returns image gradients (dy, dx) for each color channel.
is_jpeg(...): Convenience function to check if the 'contents' encodes a JPEG image.
non_max_suppression(...): Greedily selects a subset of bounding boxes in descending order of score.
non_max_suppression_overlaps(...): Greedily selects a subset of bounding boxes in descending order of score.
non_max_suppression_padded(...): Greedily selects a subset of bounding boxes in descending order of score.
non_max_suppression_with_scores(...): Greedily selects a subset of bounding boxes in descending order of score.
pad_to_bounding_box(...): Pad image with zeros to the specified height and width.
per_image_standardization(...): Linearly scales each image in image to have mean 0 and variance 1.
psnr(...): Returns the Peak Signal-to-Noise Ratio between a and b.
random_brightness(...): Adjust the brightness of images by a random factor.
random_contrast(...): Adjust the contrast of an image or images by a random factor.
random_crop(...): Randomly crops a tensor to a given size.
random_flip_left_right(...): Randomly flip an image horizontally (left to right).
random_flip_up_down(...): Randomly flips an image vertically (upside down).
random_hue(...): Adjust the hue of RGB images by a random factor.
random_jpeg_quality(...): Randomly changes jpeg encoding quality for inducing jpeg noise.
random_saturation(...): Adjust the saturation of RGB images by a random factor.
resize(...): Resize images to size using the specified method.
resize_area(...): Resize images to size using area interpolation.
resize_bicubic(...)
resize_bilinear(...)
resize_image_with_crop_or_pad(...): Crops and/or pads an image to a target width and height.
resize_image_with_pad(...): Resizes and pads an image to a target width and height.
resize_images(...): Resize images to size using the specified method.
resize_nearest_neighbor(...)
resize_with_crop_or_pad(...): Crops and/or pads an image to a target width and height.
rgb_to_grayscale(...): Converts one or more images from RGB to Grayscale.
rgb_to_hsv(...): Converts one or more images from RGB to HSV.
rgb_to_yiq(...): Converts one or more images from RGB to YIQ.
rgb_to_yuv(...): Converts one or more images from RGB to YUV.
rot90(...): Rotate image(s) counter-clockwise by 90 degrees.
sample_distorted_bounding_box(...): Generate a single randomly distorted bounding box for an image. (deprecated)
sobel_edges(...): Returns a tensor holding Sobel edge maps.
ssim(...): Computes SSIM index between img1 and img2.
ssim_multiscale(...): Computes the MS-SSIM between img1 and img2.
total_variation(...): Calculate and return the total variation for one or more images.
transpose(...): Transpose image(s) by swapping the height and width dimension.
transpose_image(...): Transpose image(s) by swapping the height and width dimension.
yiq_to_rgb(...): Converts one or more images from YIQ to RGB.
yuv_to_rgb(...): Converts one or more images from YUV to RGB.


Extracts crops from the input image tensor and resizes them.
Extracts crops from the input image tensor and resizes them using bilinear sampling or nearest neighbor sampling (possibly with aspect ratio change) to a common output size specified by crop_size. This is more general than the crop_to_bounding_box op which extracts a fixed size slice from the input image and does not allow resizing or aspect ratio change.
Returns a tensor with crops from the input image at positions defined at the bounding box locations in boxes. The cropped boxes are all resized (with bilinear or nearest neighbor interpolation) to a fixed size = [crop_height, crop_width]. The result is a 4-D tensor [num_boxes, crop_height, crop_width, depth]. The resizing is corner aligned. In particular, if boxes = [[0, 0, 1, 1]], the method will give identical results to using tf.image.resize_bilinear() or tf.image.resize_nearest_neighbor()(depends on the method argument) with align_corners=True.


Draw bounding boxes on a batch of images.
Outputs a copy of images but draws on top of the pixels zero or more bounding boxes specified by the locations in boxes. The coordinates of the each bounding box in boxes are encoded as [y_min, x_min, y_max, x_max]. The bounding box coordinates are floats in [0.0, 1.0] relative to the width and the height of the underlying image.
For example, if an image is 100 x 200 pixels (height x width) and the bounding box is [0.1, 0.2, 0.5, 0.9], the upper-left and bottom-right coordinates of the bounding box will be (40, 10) to (180, 50) (in (x,y) coordinates).
Parts of the bounding box may fall outside the image.


Extracts a glimpse from the input tensor.
Returns a set of windows called glimpses extracted at location offsets from the input tensor. If the windows only partially overlaps the inputs, the non-overlapping areas will be filled with random noise.
The result is a 4-D tensor of shape [batch_size, glimpse_height, glimpse_width, channels]. The channels and batch dimensions are the same as that of the input tensor. The height and width of the output windows are specified in the size parameter.
The argument normalized and centered controls how the windows are built:


Resize images to size using the specified method.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.image.resize_images
Resized images will be distorted if their original aspect ratio is not the same as size. To avoid distortions see tf.image.resize_with_pad or tf.image.resize_with_crop_or_pad.
The method can be one of:
The return value has the same type as images if method is tf.image.ResizeMethod.NEAREST_NEIGHBOR. It will also have the same type as images if the size of images can be statically determined to be the same as size, because images is returned in this case. Otherwise, the return value has type float32.


Resize images to size using area interpolation.
Input images can be of different types but output images are always float.
The range of pixel values for the output image might be slightly different from the range for the input image because of limited numerical precision. To guarantee an output range, for example [0.0, 1.0], apply tf.clip_by_value to the output.
Each output pixel is computed by first transforming the pixel's footprint into the input tensor and then averaging the pixels that intersect the footprint. An input pixel's contribution to the average is weighted by the fraction of its area that intersects the footprint. This is the same as OpenCV's INTER_AREA.


Resizes and pads an image to a target width and height.
Resizes an image to a target width and height by keeping the aspect ratio the same without distortion. If the target dimensions don't match the image dimensions, the image is resized and then padded with zeroes to match requested dimensions.


Generate a single randomly distorted bounding box for an image. (deprecated)
Bounding box annotations are often supplied in addition to ground-truth labels in image recognition or object localization tasks. A common technique for training such a system is to randomly distort an image while preserving its content, i.e. data augmentation. This Op outputs a randomly distorted localization of an object, i.e. bounding box, given an image_size, bounding_boxes and a series of constraints.
The output of this Op is a single bounding box that may be used to crop the original image. The output is returned as 3 tensors: begin, size and bboxes. The first 2 tensors can be fed directly into tf.slice to crop the image. The latter may be supplied to tf.image.draw_bounding_boxes to visualize what the bounding box looks like.
Bounding boxes are supplied and returned as [y_min, x_min, y_max, x_max]. The bounding box coordinates are floats in [0.0, 1.0] relative to the width and height of the underlying image.
For example,
Note that if no bounding box information is available, setting use_image_if_no_bounding_boxes = True will assume there is a single implicit bounding box covering the whole image. If use_image_if_no_bounding_boxes is false and no bounding boxes are supplied, an error is raised.


Public API for tf.initializers namespace.
class constant: Initializer that generates tensors with constant values.
class glorot_normal: The Glorot normal initializer, also called Xavier normal initializer.
class glorot_uniform: The Glorot uniform initializer, also called Xavier uniform initializer.
class identity: Initializer that generates the identity matrix.
class ones: Initializer that generates tensors initialized to 1.
class orthogonal: Initializer that generates an orthogonal matrix.
class random_normal: Initializer that generates tensors with a normal distribution.
class random_uniform: Initializer that generates tensors with a uniform distribution.
class truncated_normal: Initializer that generates a truncated normal distribution.
class uniform_unit_scaling: Initializer that generates tensors without scaling variance.
class variance_scaling: Initializer capable of adapting its scale to the shape of weights tensors.
class zeros: Initializer that generates tensors initialized to 0.
global_variables(...): Returns an Op that initializes global variables.
he_normal(...): He normal initializer.
he_uniform(...): He uniform variance scaling initializer.
lecun_normal(...): LeCun normal initializer.
lecun_uniform(...): LeCun uniform initializer.
local_variables(...): Returns an Op that initializes all local variables.
tables_initializer(...): Returns an Op that initializes all tables of the default graph.
variables(...): Returns an Op that initializes a list of variables.


He normal initializer.
It draws samples from a truncated normal distribution centered on 0 with standard deviation (after truncation) given by stddev = sqrt(2 / fan_in) where fan_in is the number of input units in the weight tensor.
He et al., 2015
(pdf)


He uniform variance scaling initializer.
It draws samples from a uniform distribution within [-limit, limit] where limit is sqrt(6 / fan_in) where fan_in is the number of input units in the weight tensor.
He et al., 2015
(pdf)


LeCun normal initializer.
It draws samples from a truncated normal distribution centered on 0 with standard deviation (after truncation) given by stddev = sqrt(1 / fan_in) where fan_in is the number of input units in the weight tensor.
(pdf)


LeCun uniform initializer.
It draws samples from a uniform distribution within [-limit, limit] where limit is sqrt(3 / fan_in) where fan_in is the number of input units in the weight tensor.
(pdf)


Returns an Op that initializes all tables of the default graph. (deprecated)


A TensorFlow Session for use in interactive contexts, such as a shell.
The only difference with a regular Session is that an InteractiveSession installs itself as the default session on construction. The methods tf.Tensor.eval and tf.Operation.run will use that session to run ops.
This is convenient in interactive shells and IPython notebooks, as it avoids having to pass an explicit Session object to run ops.
Note that a regular session installs itself as the default session when it is created in a with statement. The common usage in non-interactive programs is to follow that pattern:
View source
Returns a context manager that makes this object the default session.
Use with the with keyword to specify that calls to tf.Operation.run or tf.Tensor.eval should be executed in this session.
To get the current default session, use tf.compat.v1.get_default_session.
Alternatively, you can use with tf.compat.v1.Session(): to create a session that is automatically closed on exiting the context, including when an uncaught exception is raised.
View source
Closes an InteractiveSession.
View source
Lists available devices in this session.
Each element in the list has the following properties
View source
Returns a Python callable that runs a particular step.
The returned callable will take len(feed_list) arguments whose types must be compatible feed values for the respective elements of feed_list. For example, if element i of feed_list is a tf.Tensor, the ith argument to the returned callable must be a numpy ndarray (or something convertible to an ndarray) with matching element type and shape. See tf.Session.run for details of the allowable feed key and value types.
The returned callable will have the same return type as tf.Session.run(fetches, ...). For example, if fetches is a tf.Tensor, the callable will return a numpy ndarray; if fetches is a tf.Operation, it will return None.
View source
Continues the execution with more feeds and fetches.
This is EXPERIMENTAL and subject to change.
To use partial execution, a user first calls partial_run_setup() and then a sequence of partial_run(). partial_run_setup specifies the list of feeds and fetches that will be used in the subsequent partial_run calls.
The optional feed_dict argument allows the caller to override the value of tensors in the graph. See run() for more information.
Below is a simple example:
View source
Sets up a graph with feeds and fetches for partial run.
This is EXPERIMENTAL and subject to change.
Note that contrary to run, feeds only specifies the graph elements. The tensors will be supplied by the subsequent partial_run calls.
View source
Runs operations and evaluates tensors in fetches.
This method runs one "step" of TensorFlow computation, by running the necessary graph fragment to execute every Operation and evaluate every Tensor in fetches, substituting the values in feed_dict for the corresponding input values.
The fetches argument may be a single graph element, or an arbitrarily nested list, tuple, namedtuple, dict, or OrderedDict containing graph elements at its leaves. A graph element can be one of the following types:
The value returned by run() has the same shape as the fetches argument, where the leaves are replaced by the corresponding values returned by TensorFlow.
The optional feed_dict argument allows the caller to override the value of tensors in the graph. Each key in feed_dict can be one of the following types:
Each value in feed_dict must be convertible to a numpy array of the dtype of the corresponding key.
The optional options argument expects a [RunOptions] proto. The options allow controlling the behavior of this particular step (e.g. turning tracing on).
The optional run_metadata argument expects a [RunMetadata] proto. When appropriate, the non-Tensor output of this step will be collected there. For example, when users turn on tracing in options, the profiled info will be collected into this argument and passed back.


Public API for tf.io namespace.
gfile module: Public API for tf.io.gfile namespace.
class FixedLenFeature: Configuration for parsing a fixed-length input feature.
class FixedLenSequenceFeature: Configuration for parsing a variable-length input feature into a Tensor.
class PaddingFIFOQueue: A FIFOQueue that supports batching variable-sized tensors by padding.
class PriorityQueue: A queue implementation that dequeues elements in prioritized order.
class QueueBase: Base class for queue implementations.
class RaggedFeature: Configuration for passing a RaggedTensor input feature.
class RandomShuffleQueue: A queue implementation that dequeues elements in a random order.
class SparseFeature: Configuration for parsing a sparse input feature from an Example.
class TFRecordCompressionType: The type of compression for the record.
class TFRecordOptions: Options used for manipulating TFRecord files.
class TFRecordWriter: A class to write records to a TFRecords file.
class VarLenFeature: Configuration for parsing a variable-length input feature.
decode_and_crop_jpeg(...): Decode and Crop a JPEG-encoded image to a uint8 tensor.
decode_base64(...): Decode web-safe base64-encoded strings.
decode_bmp(...): Decode the first frame of a BMP-encoded image to a uint8 tensor.
decode_compressed(...): Decompress strings.
decode_csv(...): Convert CSV records to tensors. Each column maps to one tensor.
decode_gif(...): Decode the frame(s) of a GIF-encoded image to a uint8 tensor.
decode_image(...): Function for decode_bmp, decode_gif, decode_jpeg, and decode_png.
decode_jpeg(...): Decode a JPEG-encoded image to a uint8 tensor.
decode_json_example(...): Convert JSON-encoded Example records to binary protocol buffer strings.
decode_png(...): Decode a PNG-encoded image to a uint8 or uint16 tensor.
decode_proto(...): The op extracts fields from a serialized protocol buffers message into tensors.
decode_raw(...): Convert raw byte strings into tensors. (deprecated arguments)
deserialize_many_sparse(...): Deserialize and concatenate SparseTensors from a serialized minibatch.
encode_base64(...): Encode strings into web-safe base64 format.
encode_jpeg(...): JPEG-encode an image.
encode_png(...): PNG-encode an image.
encode_proto(...): The op serializes protobuf messages provided in the input tensors.
extract_jpeg_shape(...): Extract the shape information of a JPEG-encoded image.
is_jpeg(...): Convenience function to check if the 'contents' encodes a JPEG image.
match_filenames_once(...): Save the list of files matching pattern, so it is only computed once.
matching_files(...): Returns the set of files matching one or more glob patterns.
parse_example(...): Parses Example protos into a dict of tensors.
parse_sequence_example(...): Parses a batch of SequenceExample protos.
parse_single_example(...): Parses a single Example proto.
parse_single_sequence_example(...): Parses a single SequenceExample proto.
parse_tensor(...): Transforms a serialized tensorflow.TensorProto proto into a Tensor.
read_file(...): Reads and outputs the entire contents of the input filename.
serialize_many_sparse(...): Serialize N-minibatch SparseTensor into an [N, 3] Tensor.
serialize_sparse(...): Serialize a SparseTensor into a 3-vector (1-D Tensor) object.
serialize_tensor(...): Transforms a Tensor into a serialized TensorProto proto.
tf_record_iterator(...): An iterator that read the records from a TFRecords file. (deprecated)
write_file(...): Writes contents to the file at input filename. Creates file and recursively
write_graph(...): Writes a graph proto to a file.


Public API for tf.io.gfile namespace.
class GFile: File I/O wrappers without thread locking.
copy(...): Copies data from src to dst.
exists(...): Determines whether a path exists or not.
glob(...): Returns a list of files that match the given pattern(s).
isdir(...): Returns whether the path is a directory or not.
listdir(...): Returns a list of entries contained within a directory.
makedirs(...): Creates a directory and all parent/intermediate directories.
mkdir(...): Creates a directory with the name given by path.
remove(...): Deletes the path located at 'path'.
rename(...): Rename or move a file / directory.
rmtree(...): Deletes everything under path recursively.
stat(...): Returns file statistics for a given path.
walk(...): Recursive directory tree generator for directories.


The type of compression for the record.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.python_io.TFRecordCompressionType


An iterator that read the records from a TFRecords file. (deprecated)
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.python_io.tf_record_iterator


Tests if a variable has been initialized.


Implementation of the Keras API meant to be a high-level API for TensorFlow.
Detailed documentation and user guides are available at tensorflow.org.
activations module: Built-in activation functions.
applications module: Keras Applications are canned architectures with pre-trained weights.
backend module: Keras backend API.
callbacks module: Callbacks: utilities called at certain points during model training.
constraints module: Constraints: functions that impose constraints on weight values.
datasets module: Public API for tf.keras.datasets namespace.
estimator module: Keras estimator API.
experimental module: Public API for tf.keras.experimental namespace.
initializers module: Keras initializer serialization / deserialization.
layers module: Keras layers API.
losses module: Built-in loss functions.
metrics module: Built-in metrics.
mixed_precision module: Keras mixed precision API.
models module: Code for model cloning, plus model-related API entries.
optimizers module: Built-in optimizer classes.
preprocessing module: Keras data preprocessing utils.
regularizers module: Built-in regularizers.
utils module: Public API for tf.keras.utils namespace.
wrappers module: Public API for tf.keras.wrappers namespace.
class Model: Model groups layers into an object with training and inference features.
class Sequential: Sequential groups a linear stack of layers into a tf.keras.Model.
Input(...): Input() is used to instantiate a Keras tensor.


Built-in activation functions.
deserialize(...): Returns activation function given a string identifier.
elu(...): Exponential Linear Unit.
exponential(...): Exponential activation function.
get(...): Returns function.
hard_sigmoid(...): Hard sigmoid activation function.
linear(...): Linear activation function (pass-through).
relu(...): Applies the rectified linear unit activation function.
selu(...): Scaled Exponential Linear Unit (SELU).
serialize(...): Returns the string identifier of an activation function.
sigmoid(...): Sigmoid activation function, sigmoid(x) = 1 / (1 + exp(-x)).
softmax(...): Softmax converts a real vector to a vector of categorical probabilities.
softplus(...): Softplus activation function, softplus(x) = log(exp(x) + 1).
softsign(...): Softsign activation function, softsign(x) = x / (abs(x) + 1).
swish(...): Swish activation function, swish(x) = x * sigmoid(x).
tanh(...): Hyperbolic tangent activation function.


Keras Applications are canned architectures with pre-trained weights.
densenet module: DenseNet models for Keras.
efficientnet module: EfficientNet models for Keras.
imagenet_utils module: Utilities for ImageNet data preprocessing & prediction decoding.
inception_resnet_v2 module: Inception-ResNet V2 model for Keras.
inception_v3 module: Inception V3 model for Keras.
mobilenet module: MobileNet v1 models for Keras.
mobilenet_v2 module: MobileNet v2 models for Keras.
mobilenet_v3 module: MobileNet v3 models for Keras.
nasnet module: NASNet-A models for Keras.
resnet module: ResNet models for Keras.
resnet50 module: Public API for tf.keras.applications.resnet50 namespace.
resnet_v2 module: ResNet v2 models for Keras.
vgg16 module: VGG16 model for Keras.
vgg19 module: VGG19 model for Keras.
xception module: Xception V1 model for Keras.
DenseNet121(...): Instantiates the Densenet121 architecture.
DenseNet169(...): Instantiates the Densenet169 architecture.
DenseNet201(...): Instantiates the Densenet201 architecture.
EfficientNetB0(...): Instantiates the EfficientNetB0 architecture.
EfficientNetB1(...): Instantiates the EfficientNetB1 architecture.
EfficientNetB2(...): Instantiates the EfficientNetB2 architecture.
EfficientNetB3(...): Instantiates the EfficientNetB3 architecture.
EfficientNetB4(...): Instantiates the EfficientNetB4 architecture.
EfficientNetB5(...): Instantiates the EfficientNetB5 architecture.
EfficientNetB6(...): Instantiates the EfficientNetB6 architecture.
EfficientNetB7(...): Instantiates the EfficientNetB7 architecture.
InceptionResNetV2(...): Instantiates the Inception-ResNet v2 architecture.
InceptionV3(...): Instantiates the Inception v3 architecture.
MobileNet(...): Instantiates the MobileNet architecture.
MobileNetV2(...): Instantiates the MobileNetV2 architecture.
MobileNetV3Large(...): Instantiates the MobileNetV3Large architecture.
MobileNetV3Small(...): Instantiates the MobileNetV3Small architecture.
NASNetLarge(...): Instantiates a NASNet model in ImageNet mode.
NASNetMobile(...): Instantiates a Mobile NASNet model in ImageNet mode.
ResNet101(...): Instantiates the ResNet101 architecture.
ResNet101V2(...): Instantiates the ResNet101V2 architecture.
ResNet152(...): Instantiates the ResNet152 architecture.
ResNet152V2(...): Instantiates the ResNet152V2 architecture.
ResNet50(...): Instantiates the ResNet50 architecture.
ResNet50V2(...): Instantiates the ResNet50V2 architecture.
VGG16(...): Instantiates the VGG16 model.
VGG19(...): Instantiates the VGG19 architecture.
Xception(...): Instantiates the Xception architecture.


DenseNet models for Keras.
DenseNet121(...): Instantiates the Densenet121 architecture.
DenseNet169(...): Instantiates the Densenet169 architecture.
DenseNet201(...): Instantiates the Densenet201 architecture.
decode_predictions(...): Decodes the prediction of an ImageNet model.
preprocess_input(...): Preprocesses a tensor or Numpy array encoding a batch of images.


EfficientNet models for Keras.
EfficientNetB0(...): Instantiates the EfficientNetB0 architecture.
EfficientNetB1(...): Instantiates the EfficientNetB1 architecture.
EfficientNetB2(...): Instantiates the EfficientNetB2 architecture.
EfficientNetB3(...): Instantiates the EfficientNetB3 architecture.
EfficientNetB4(...): Instantiates the EfficientNetB4 architecture.
EfficientNetB5(...): Instantiates the EfficientNetB5 architecture.
EfficientNetB6(...): Instantiates the EfficientNetB6 architecture.
EfficientNetB7(...): Instantiates the EfficientNetB7 architecture.
decode_predictions(...): Decodes the prediction of an ImageNet model.
preprocess_input(...)


Utilities for ImageNet data preprocessing & prediction decoding.
decode_predictions(...): Decodes the prediction of an ImageNet model.
preprocess_input(...): Preprocesses a tensor or Numpy array encoding a batch of images.


Inception-ResNet V2 model for Keras.
InceptionResNetV2(...): Instantiates the Inception-ResNet v2 architecture.
decode_predictions(...): Decodes the prediction of an ImageNet model.
preprocess_input(...): Preprocesses a tensor or Numpy array encoding a batch of images.


Inception V3 model for Keras.
InceptionV3(...): Instantiates the Inception v3 architecture.
decode_predictions(...): Decodes the prediction of an ImageNet model.
preprocess_input(...): Preprocesses a tensor or Numpy array encoding a batch of images.


MobileNet v1 models for Keras.
MobileNet is a general architecture and can be used for multiple use cases. Depending on the use case, it can use different input layer size and different width factors. This allows different width models to reduce the number of multiply-adds and thereby reduce inference cost on mobile devices.
MobileNets support any input size greater than 32 x 32, with larger image sizes offering better performance. The number of parameters and number of multiply-adds can be modified by using the alpha parameter, which increases/decreases the number of filters in each layer. By altering the image size and alpha parameter, all 16 models from the paper can be built, with ImageNet weights provided.
The paper demonstrates the performance of MobileNets using alpha values of 1.0 (also called 100 % MobileNet), 0.75, 0.5 and 0.25. For each of these alpha values, weights for 4 different input image sizes are provided (224, 192, 160, 128).
The following table describes the size and accuracy of the 100% MobileNet
| 1.0 MobileNet-224 | 70.6 % | 529 | 4.2 | | 0.75 MobileNet-224 | 68.4 % | 325 | 2.6 | | 0.50 MobileNet-224 | 63.7 % | 149 | 1.3 |
The following table describes the performance of
| 1.0 MobileNet-224 | 70.6 % | 529 | 4.2 | | 1.0 MobileNet-192 | 69.1 % | 529 | 4.2 | | 1.0 MobileNet-160 | 67.2 % | 529 | 4.2 |
MobileNet(...): Instantiates the MobileNet architecture.
decode_predictions(...): Decodes the prediction of an ImageNet model.
preprocess_input(...): Preprocesses a tensor or Numpy array encoding a batch of images.


MobileNet v2 models for Keras.
MobileNetV2 is a general architecture and can be used for multiple use cases. Depending on the use case, it can use different input layer size and different width factors. This allows different width models to reduce the number of multiply-adds and thereby reduce inference cost on mobile devices.
MobileNetV2 is very similar to the original MobileNet, except that it uses inverted residual blocks with bottlenecking features. It has a drastically lower parameter count than the original MobileNet. MobileNets support any input size greater than 32 x 32, with larger image sizes offering better performance.
The number of parameters and number of multiply-adds can be modified by using the alpha parameter, which increases/decreases the number of filters in each layer. By altering the image size and alpha parameter, all 22 models from the paper can be built, with ImageNet weights provided.
The paper demonstrates the performance of MobileNets using alpha values of 1.0 (also called 100 % MobileNet), 0.35, 0.5, 0.75, 1.0, 1.3, and 1.4 For each of these alpha values, weights for 5 different input image sizes are provided (224, 192, 160, 128, and 96).
The following table describes the performance of
MACs stands for Multiply Adds Classification Checkpoint|MACs (M)|Parameters (M)|Top 1 Accuracy|Top 5 Accuracy --------------------------|------------|---------------|---------|----|--------- | [mobilenet_v2_1.4_224] | 582 | 6.06 | 75.0 | 92.5 | | [mobilenet_v2_1.3_224] | 509 | 5.34 | 74.4 | 92.1 | | [mobilenet_v2_1.0_224] | 300 | 3.47 | 71.8 | 91.0 | | [mobilenet_v2_1.0_192] | 221 | 3.47 | 70.7 | 90.1 | | [mobilenet_v2_1.0_160] | 154 | 3.47 | 68.8 | 89.0 | | [mobilenet_v2_1.0_128] | 99 | 3.47 | 65.3 | 86.9 | | [mobilenet_v2_1.0_96] | 56 | 3.47 | 60.3 | 83.2 | | [mobilenet_v2_0.75_224] | 209 | 2.61 | 69.8 | 89.6 | | [mobilenet_v2_0.75_192] | 153 | 2.61 | 68.7 | 88.9 | | [mobilenet_v2_0.75_160] | 107 | 2.61 | 66.4 | 87.3 | | [mobilenet_v2_0.75_128] | 69 | 2.61 | 63.2 | 85.3 | | [mobilenet_v2_0.75_96] | 39 | 2.61 | 58.8 | 81.6 | | [mobilenet_v2_0.5_224] | 97 | 1.95 | 65.4 | 86.4 | | [mobilenet_v2_0.5_192] | 71 | 1.95 | 63.9 | 85.4 | | [mobilenet_v2_0.5_160] | 50 | 1.95 | 61.0 | 83.2 | | [mobilenet_v2_0.5_128] | 32 | 1.95 | 57.7 | 80.8 | | [mobilenet_v2_0.5_96] | 18 | 1.95 | 51.2 | 75.8 | | [mobilenet_v2_0.35_224] | 59 | 1.66 | 60.3 | 82.9 | | [mobilenet_v2_0.35_192] | 43 | 1.66 | 58.2 | 81.2 | | [mobilenet_v2_0.35_160] | 30 | 1.66 | 55.7 | 79.1 | | [mobilenet_v2_0.35_128] | 20 | 1.66 | 50.8 | 75.0 | | [mobilenet_v2_0.35_96] | 11 | 1.66 | 45.5 | 70.4 |
Reference:
MobileNetV2(...): Instantiates the MobileNetV2 architecture.
decode_predictions(...): Decodes the prediction of an ImageNet model.
preprocess_input(...): Preprocesses a tensor or Numpy array encoding a batch of images.


MobileNet v3 models for Keras.
decode_predictions(...): Decodes the prediction of an ImageNet model.
preprocess_input(...): Preprocesses a tensor or Numpy array encoding a batch of images.


NASNet-A models for Keras.
NASNet refers to Neural Architecture Search Network, a family of models that were designed automatically by learning the model architectures directly on the dataset of interest.
Here we consider NASNet-A, the highest performance model that was found for the CIFAR-10 dataset, and then extended to ImageNet 2012 dataset, obtaining state of the art performance on CIFAR-10 and ImageNet 2012. Only the NASNet-A models, and their respective weights, which are suited for ImageNet 2012 are provided.
| NASNet-A (4 @ 1056) | 74.0 % | 91.6 % | 564 M | 5.3 |
NASNetLarge(...): Instantiates a NASNet model in ImageNet mode.
NASNetMobile(...): Instantiates a Mobile NASNet model in ImageNet mode.
decode_predictions(...): Decodes the prediction of an ImageNet model.
preprocess_input(...): Preprocesses a tensor or Numpy array encoding a batch of images.


ResNet models for Keras.
ResNet101(...): Instantiates the ResNet101 architecture.
ResNet152(...): Instantiates the ResNet152 architecture.
ResNet50(...): Instantiates the ResNet50 architecture.
decode_predictions(...): Decodes the prediction of an ImageNet model.
preprocess_input(...): Preprocesses a tensor or Numpy array encoding a batch of images.


Public API for tf.keras.applications.resnet50 namespace.
ResNet50(...): Instantiates the ResNet50 architecture.
decode_predictions(...): Decodes the prediction of an ImageNet model.
preprocess_input(...): Preprocesses a tensor or Numpy array encoding a batch of images.


ResNet v2 models for Keras.
ResNet101V2(...): Instantiates the ResNet101V2 architecture.
ResNet152V2(...): Instantiates the ResNet152V2 architecture.
ResNet50V2(...): Instantiates the ResNet50V2 architecture.
decode_predictions(...): Decodes the prediction of an ImageNet model.
preprocess_input(...): Preprocesses a tensor or Numpy array encoding a batch of images.


VGG16 model for Keras.
VGG16(...): Instantiates the VGG16 model.
decode_predictions(...): Decodes the prediction of an ImageNet model.
preprocess_input(...): Preprocesses a tensor or Numpy array encoding a batch of images.


VGG19 model for Keras.
VGG19(...): Instantiates the VGG19 architecture.
decode_predictions(...): Decodes the prediction of an ImageNet model.
preprocess_input(...): Preprocesses a tensor or Numpy array encoding a batch of images.


Xception V1 model for Keras.
On ImageNet, this model gets to a top-1 validation accuracy of 0.790 and a top-5 validation accuracy of 0.945.
Xception(...): Instantiates the Xception architecture.
decode_predictions(...): Decodes the prediction of an ImageNet model.
preprocess_input(...): Preprocesses a tensor or Numpy array encoding a batch of images.


Keras backend API.
class name_scope: A context manager for use when defining a Python op.
clear_session(...): Resets all state generated by Keras.
epsilon(...): Returns the value of the fuzz factor used in numeric expressions.
floatx(...): Returns the default float type, as a string.
get_session(...): Returns the TF session to be used by the backend.
get_uid(...): Associates a string prefix with an integer counter in a TensorFlow graph.
image_data_format(...): Returns the default image data format convention.
is_keras_tensor(...): Returns whether x is a Keras tensor.
reset_uids(...): Resets graph identifiers.
rnn(...): Iterates over the time dimension of a tensor.
set_epsilon(...): Sets the value of the fuzz factor used in numeric expressions.
set_floatx(...): Sets the default float type.
set_image_data_format(...): Sets the value of the image data format convention.
set_session(...): Sets the global TensorFlow session.


Returns the TF session to be used by the backend.
If a default TensorFlow session is available, we will return it.
Else, we will return the global Keras session assuming it matches the current graph.
If no global Keras session exists at this point: we will create a new global session.
Note that you can manually set the global session via K.set_session(sess).


A context manager for use when defining a Python op.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.name_scope
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 tf.Graph.name_scope for more details on that).
For example, to define a new Python op called my_op:
View source
View source


Callbacks: utilities called at certain points during model training.
class BaseLogger: Callback that accumulates epoch averages of metrics.
class CSVLogger: Callback that streams epoch results to a CSV file.
class Callback: Abstract base class used to build new callbacks.
class CallbackList: Container abstracting a list of callbacks.
class EarlyStopping: Stop training when a monitored metric has stopped improving.
class History: Callback that records events into a History object.
class LambdaCallback: Callback for creating simple, custom callbacks on-the-fly.
class LearningRateScheduler: Learning rate scheduler.
class ModelCheckpoint: Callback to save the Keras model or model weights at some frequency.
class ProgbarLogger: Callback that prints metrics to stdout.
class ReduceLROnPlateau: Reduce learning rate when a metric has stopped improving.
class RemoteMonitor: Callback used to stream events to a server.
class TensorBoard: Enable visualizations for TensorBoard.
class TerminateOnNaN: Callback that terminates training when a NaN loss is encountered.


Enable visualizations for TensorBoard.
Inherits From: TensorBoard, Callback
TensorBoard is a visualization tool provided with TensorFlow.
This callback logs events for TensorBoard, including:
If you have installed TensorFlow with pip, you should be able to launch TensorBoard from the command line:
You can find more information about TensorBoard here.
Using the TensorBoard callback will work when eager execution is enabled, with the restriction that outputting histogram summaries of weights and gradients is not supported. Consequently, histogram_freq will be ignored.
View source
Sets Keras model and creates summary ops.
View source


Constraints: functions that impose constraints on weight values.
class Constraint
class MaxNorm: MaxNorm weight constraint.
class MinMaxNorm: MinMaxNorm weight constraint.
class NonNeg: Constrains the weights to be non-negative.
class RadialConstraint: Constrains Conv2D kernel weights to be the same for each radius.
class UnitNorm: Constrains the weights incident to each hidden unit to have unit norm.
class max_norm: MaxNorm weight constraint.
class min_max_norm: MinMaxNorm weight constraint.
class non_neg: Constrains the weights to be non-negative.
class radial_constraint: Constrains Conv2D kernel weights to be the same for each radius.
class unit_norm: Constrains the weights incident to each hidden unit to have unit norm.
deserialize(...)
get(...)
serialize(...)


Public API for tf.keras.datasets namespace.
boston_housing module: Boston housing price regression dataset.
cifar10 module: CIFAR10 small images classification dataset.
cifar100 module: CIFAR100 small images classification dataset.
fashion_mnist module: Fashion-MNIST dataset.
imdb module: IMDB sentiment classification dataset.
mnist module: MNIST handwritten digits dataset.
reuters module: Reuters topic classification dataset.


Boston housing price regression dataset.
load_data(...): Loads the Boston Housing dataset.


CIFAR10 small images classification dataset.
load_data(...): Loads CIFAR10 dataset.


CIFAR100 small images classification dataset.
load_data(...): Loads CIFAR100 dataset.


Fashion-MNIST dataset.
load_data(...): Loads the Fashion-MNIST dataset.


IMDB sentiment classification dataset.
get_word_index(...): Retrieves a dict mapping words to their index in the IMDB dataset.
load_data(...): Loads the IMDB dataset.


MNIST handwritten digits dataset.
load_data(...): Loads the MNIST dataset.


Reuters topic classification dataset.
get_word_index(...): Retrieves a dict mapping words to their index in the Reuters dataset.
load_data(...): Loads the Reuters newswire classification dataset.


Keras estimator API.
model_to_estimator(...): Constructs an Estimator instance from given keras model.


Constructs an Estimator instance from given keras model.
If you use infrastructure or other tooling that relies on Estimators, you can still build a Keras model and use model_to_estimator to convert the Keras model to an Estimator for use with downstream systems.
For usage example, please see: Creating estimators from Keras Models.
Estimators returned by model_to_estimator are configured so that they can handle sample weights (similar to keras_model.fit(x, y, sample_weights)).
To pass sample weights when training or evaluating the Estimator, the first item returned by the input function should be a dictionary with keys features and sample_weights. Example below:
Example with customized export signature:


Public API for tf.keras.experimental namespace.
class CosineDecay: A LearningRateSchedule that uses a cosine decay schedule.
class CosineDecayRestarts: A LearningRateSchedule that uses a cosine decay schedule with restarts.
class LinearCosineDecay: A LearningRateSchedule that uses a linear cosine decay schedule.
class LinearModel: Linear Model for regression and classification problems.
class NoisyLinearCosineDecay: A LearningRateSchedule that uses a noisy linear cosine decay schedule.
class PeepholeLSTMCell: Equivalent to LSTMCell class but adds peephole connections.
class SequenceFeatures: A layer for sequence input.
class WideDeepModel: Wide & Deep Model for regression and classification problems.
export_saved_model(...): Exports a tf.keras.Model as a Tensorflow SavedModel.
load_from_saved_model(...): Loads a keras Model from a SavedModel created by export_saved_model().


Exports a tf.keras.Model as a Tensorflow SavedModel.
Note that at this time, subclassed models can only be saved using serving_only=True.
The exported SavedModel is a standalone serialization of Tensorflow objects, and is supported by TF language APIs and the Tensorflow Serving system. To load the model, use the function tf.keras.experimental.load_from_saved_model.
The SavedModel contains:


Loads a keras Model from a SavedModel created by export_saved_model().
This function reinstantiates model state by:
1) loading model topology from json (this will eventually come from metagraph). 2) loading model weights from checkpoint.


Keras initializer serialization / deserialization.
class Constant: Initializer that generates tensors with constant values.
class Identity: Initializer that generates the identity matrix.
class Initializer: Initializer base class: all Keras initializers inherit from this class.
class Ones: Initializer that generates tensors initialized to 1.
class Orthogonal: Initializer that generates an orthogonal matrix.
class RandomNormal: Initializer that generates tensors with a normal distribution.
class RandomUniform: Initializer that generates tensors with a uniform distribution.
class TruncatedNormal: Initializer that generates a truncated normal distribution.
class VarianceScaling: Initializer capable of adapting its scale to the shape of weights tensors.
class Zeros: Initializer that generates tensors initialized to 0.
class constant: Initializer that generates tensors with constant values.
class glorot_normal: The Glorot normal initializer, also called Xavier normal initializer.
class glorot_uniform: The Glorot uniform initializer, also called Xavier uniform initializer.
class he_normal: Initializer capable of adapting its scale to the shape of weights tensors.
class he_uniform: Initializer capable of adapting its scale to the shape of weights tensors.
class identity: Initializer that generates the identity matrix.
class lecun_normal: Initializer capable of adapting its scale to the shape of weights tensors.
class lecun_uniform: Initializer capable of adapting its scale to the shape of weights tensors.
class normal: Initializer that generates tensors with a normal distribution.
class ones: Initializer that generates tensors initialized to 1.
class orthogonal: Initializer that generates an orthogonal matrix.
class random_normal: Initializer that generates tensors with a normal distribution.
class random_uniform: Initializer that generates tensors with a uniform distribution.
class truncated_normal: Initializer that generates a truncated normal distribution.
class uniform: Initializer that generates tensors with a uniform distribution.
class zeros: Initializer that generates tensors initialized to 0.
deserialize(...): Return an Initializer object from its config.
get(...)
serialize(...)


Initializer that generates tensors with constant values.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.constant_initializer, tf.compat.v1.initializers.constant, tf.compat.v1.keras.initializers.constant
The resulting tensor is populated with values of type dtype, as specified by arguments value following the desired shape of the new tensor (see examples below).
The argument value can be a constant value, or a list of values of type dtype. If value is a list, then the length of the list must be less than or equal to the number of elements implied by the desired shape of the tensor. In the case where the total number of elements in value is less than the number of elements required by the tensor shape, the last element in value will be used to fill the remaining entries. If the total number of elements in value is greater than the number of elements required by the tensor shape, the initializer will raise a ValueError.
The following example can be rewritten using a numpy.ndarray instead of the value list, even reshaped, as shown in the two commented lines below the value list initialization.
View source
Instantiates an initializer from a configuration dictionary.
View source
Returns the configuration of the initializer as a JSON-serializable dict.
View source
Returns a tensor object initialized as specified by the initializer.


The Glorot normal initializer, also called Xavier normal initializer.
Inherits From: VarianceScaling
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.glorot_normal_initializer, tf.compat.v1.initializers.glorot_normal
It draws samples from a truncated normal distribution centered on 0 with standard deviation (after truncation) given by stddev = sqrt(2 / (fan_in + fan_out)) where fan_in is the number of input units in the weight tensor and fan_out is the number of output units in the weight tensor.
Glorot et al., 2010 (pdf)
View source
Instantiates an initializer from a configuration dictionary.
View source
Returns the configuration of the initializer as a JSON-serializable dict.
View source
Returns a tensor object initialized as specified by the initializer.


The Glorot uniform initializer, also called Xavier uniform initializer.
Inherits From: VarianceScaling
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.glorot_uniform_initializer, tf.compat.v1.initializers.glorot_uniform
It draws samples from a uniform distribution within [-limit, limit] where limit is sqrt(6 / (fan_in + fan_out)) where fan_in is the number of input units in the weight tensor and fan_out is the number of output units in the weight tensor.
Glorot et al., 2010 (pdf)
View source
Instantiates an initializer from a configuration dictionary.
View source
Returns the configuration of the initializer as a JSON-serializable dict.
View source
Returns a tensor object initialized as specified by the initializer.


Initializer capable of adapting its scale to the shape of weights tensors.
Inherits From: VarianceScaling
With distribution="truncated_normal" or "untruncated_normal", samples are drawn from a truncated/untruncated normal distribution with a mean of zero and a standard deviation (after truncation, if used) stddev = sqrt(scale / n) where n is:
With distribution="uniform", samples are drawn from a uniform distribution within [-limit, limit], with limit = sqrt(3 * scale / n).
View source
Instantiates an initializer from a configuration dictionary.
View source
Returns the configuration of the initializer as a JSON-serializable dict.
View source
Returns a tensor object initialized as specified by the initializer.


Initializer that generates the identity matrix.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.initializers.identity, tf.compat.v1.keras.initializers.identity
Only use for 2D matrices.
View source
Instantiates an initializer from a configuration dictionary.
View source
Returns the configuration of the initializer as a JSON-serializable dict.
View source
Returns a tensor object initialized as specified by the initializer.


Initializer that generates tensors initialized to 1.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.initializers.ones, tf.compat.v1.keras.initializers.ones, tf.compat.v1.ones_initializer
View source
Instantiates an initializer from a configuration dictionary.
View source
Returns the configuration of the initializer as a JSON-serializable dict.
View source
Returns a tensor object initialized as specified by the initializer.


Initializer that generates an orthogonal matrix.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.initializers.orthogonal, tf.compat.v1.keras.initializers.orthogonal, tf.compat.v1.orthogonal_initializer
If the shape of the tensor to initialize is two-dimensional, it is initialized with an orthogonal matrix obtained from the QR decomposition of a matrix of random numbers drawn from a normal distribution. If the matrix has fewer rows than columns then the output will have orthogonal rows. Otherwise, the output will have orthogonal columns.
If the shape of the tensor to initialize is more than two-dimensional, a matrix of shape (shape[0] * ... * shape[n - 2], shape[n - 1]) is initialized, where n is the length of the shape vector. The matrix is subsequently reshaped to give a tensor of the desired shape.
Saxe et al., 2014 (pdf)
View source
Instantiates an initializer from a configuration dictionary.
View source
Returns the configuration of the initializer as a JSON-serializable dict.
View source
Returns a tensor object initialized as specified by the initializer.


Initializer that generates tensors with a normal distribution.
Inherits From: random_normal_initializer
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.initializers.normal, tf.compat.v1.keras.initializers.random_normal
View source
Instantiates an initializer from a configuration dictionary.
View source
Returns the configuration of the initializer as a JSON-serializable dict.
View source
Returns a tensor object initialized as specified by the initializer.


Initializer that generates tensors with a uniform distribution.
Inherits From: random_uniform_initializer
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.initializers.random_uniform, tf.compat.v1.keras.initializers.uniform
View source
Instantiates an initializer from a configuration dictionary.
View source
Returns the configuration of the initializer as a JSON-serializable dict.
View source
Returns a tensor object initialized as specified by the initializer.


Initializer that generates a truncated normal distribution.
Inherits From: truncated_normal_initializer
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.initializers.truncated_normal
These values are similar to values from a random_normal_initializer except that values more than two standard deviations from the mean are discarded and re-drawn. This is the recommended initializer for neural network weights and filters.
View source
Instantiates an initializer from a configuration dictionary.
View source
Returns the configuration of the initializer as a JSON-serializable dict.
View source
Returns a tensor object initialized as specified by the initializer.


Initializer capable of adapting its scale to the shape of weights tensors.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.initializers.variance_scaling, tf.compat.v1.variance_scaling_initializer
With distribution="truncated_normal" or "untruncated_normal", samples are drawn from a truncated/untruncated normal distribution with a mean of zero and a standard deviation (after truncation, if used) stddev = sqrt(scale / n) where n is:
With distribution="uniform", samples are drawn from a uniform distribution within [-limit, limit], with limit = sqrt(3 * scale / n).
View source
Instantiates an initializer from a configuration dictionary.
View source
Returns the configuration of the initializer as a JSON-serializable dict.
View source
Returns a tensor object initialized as specified by the initializer.


Initializer that generates tensors initialized to 0.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.initializers.zeros, tf.compat.v1.keras.initializers.zeros, tf.compat.v1.zeros_initializer
View source
Instantiates an initializer from a configuration dictionary.
View source
Returns the configuration of the initializer as a JSON-serializable dict.
View source
Returns a tensor object initialized as specified by the initializer.


Keras layers API.
experimental module: Public API for tf.keras.layers.experimental namespace.
class AbstractRNNCell: Abstract object representing an RNN cell.
class Activation: Applies an activation function to an output.
class ActivityRegularization: Layer that applies an update to the cost function based input activity.
class Add: Layer that adds a list of inputs.
class AdditiveAttention: Additive attention layer, a.k.a. Bahdanau-style attention.
class AlphaDropout: Applies Alpha Dropout to the input.
class Attention: Dot-product attention layer, a.k.a. Luong-style attention.
class Average: Layer that averages a list of inputs element-wise.
class AveragePooling1D: Average pooling for temporal data.
class AveragePooling2D: Average pooling operation for spatial data.
class AveragePooling3D: Average pooling operation for 3D data (spatial or spatio-temporal).
class AvgPool1D: Average pooling for temporal data.
class AvgPool2D: Average pooling operation for spatial data.
class AvgPool3D: Average pooling operation for 3D data (spatial or spatio-temporal).
class BatchNormalization: Layer that normalizes its inputs.
class Bidirectional: Bidirectional wrapper for RNNs.
class Concatenate: Layer that concatenates a list of inputs.
class Conv1D: 1D convolution layer (e.g. temporal convolution).
class Conv1DTranspose: Transposed convolution layer (sometimes called Deconvolution).
class Conv2D: 2D convolution layer (e.g. spatial convolution over images).
class Conv2DTranspose: Transposed convolution layer (sometimes called Deconvolution).
class Conv3D: 3D convolution layer (e.g. spatial convolution over volumes).
class Conv3DTranspose: Transposed convolution layer (sometimes called Deconvolution).
class ConvLSTM2D: Convolutional LSTM.
class Convolution1D: 1D convolution layer (e.g. temporal convolution).
class Convolution1DTranspose: Transposed convolution layer (sometimes called Deconvolution).
class Convolution2D: 2D convolution layer (e.g. spatial convolution over images).
class Convolution2DTranspose: Transposed convolution layer (sometimes called Deconvolution).
class Convolution3D: 3D convolution layer (e.g. spatial convolution over volumes).
class Convolution3DTranspose: Transposed convolution layer (sometimes called Deconvolution).
class Cropping1D: Cropping layer for 1D input (e.g. temporal sequence).
class Cropping2D: Cropping layer for 2D input (e.g. picture).
class Cropping3D: Cropping layer for 3D data (e.g. spatial or spatio-temporal).
class CuDNNGRU: Fast GRU implementation backed by cuDNN.
class CuDNNLSTM: Fast LSTM implementation backed by cuDNN.
class Dense: Just your regular densely-connected NN layer.
class DenseFeatures: A layer that produces a dense Tensor based on given feature_columns.
class DepthwiseConv2D: Depthwise separable 2D convolution.
class Dot: Layer that computes a dot product between samples in two tensors.
class Dropout: Applies Dropout to the input.
class ELU: Exponential Linear Unit.
class Embedding: Turns positive integers (indexes) into dense vectors of fixed size.
class Flatten: Flattens the input. Does not affect the batch size.
class GRU: Gated Recurrent Unit - Cho et al. 2014.
class GRUCell: Cell class for the GRU layer.
class GaussianDropout: Apply multiplicative 1-centered Gaussian noise.
class GaussianNoise: Apply additive zero-centered Gaussian noise.
class GlobalAveragePooling1D: Global average pooling operation for temporal data.
class GlobalAveragePooling2D: Global average pooling operation for spatial data.
class GlobalAveragePooling3D: Global Average pooling operation for 3D data.
class GlobalAvgPool1D: Global average pooling operation for temporal data.
class GlobalAvgPool2D: Global average pooling operation for spatial data.
class GlobalAvgPool3D: Global Average pooling operation for 3D data.
class GlobalMaxPool1D: Global max pooling operation for 1D temporal data.
class GlobalMaxPool2D: Global max pooling operation for spatial data.
class GlobalMaxPool3D: Global Max pooling operation for 3D data.
class GlobalMaxPooling1D: Global max pooling operation for 1D temporal data.
class GlobalMaxPooling2D: Global max pooling operation for spatial data.
class GlobalMaxPooling3D: Global Max pooling operation for 3D data.
class InputLayer: Layer to be used as an entry point into a Network (a graph of layers).
class InputSpec: Specifies the rank, dtype and shape of every input to a layer.
class LSTM: Long Short-Term Memory layer - Hochreiter 1997.
class LSTMCell: Cell class for the LSTM layer.
class Lambda: Wraps arbitrary expressions as a Layer object.
class Layer: This is the class from which all layers inherit.
class LayerNormalization: Layer normalization layer (Ba et al., 2016).
class LeakyReLU: Leaky version of a Rectified Linear Unit.
class LocallyConnected1D: Locally-connected layer for 1D inputs.
class LocallyConnected2D: Locally-connected layer for 2D inputs.
class Masking: Masks a sequence by using a mask value to skip timesteps.
class MaxPool1D: Max pooling operation for 1D temporal data.
class MaxPool2D: Max pooling operation for 2D spatial data.
class MaxPool3D: Max pooling operation for 3D data (spatial or spatio-temporal).
class MaxPooling1D: Max pooling operation for 1D temporal data.
class MaxPooling2D: Max pooling operation for 2D spatial data.
class MaxPooling3D: Max pooling operation for 3D data (spatial or spatio-temporal).
class Maximum: Layer that computes the maximum (element-wise) a list of inputs.
class Minimum: Layer that computes the minimum (element-wise) a list of inputs.
class MultiHeadAttention: MultiHeadAttention layer.
class Multiply: Layer that multiplies (element-wise) a list of inputs.
class PReLU: Parametric Rectified Linear Unit.
class Permute: Permutes the dimensions of the input according to a given pattern.
class RNN: Base class for recurrent layers.
class ReLU: Rectified Linear Unit activation function.
class RepeatVector: Repeats the input n times.
class Reshape: Layer that reshapes inputs into the given shape.
class SeparableConv1D: Depthwise separable 1D convolution.
class SeparableConv2D: Depthwise separable 2D convolution.
class SeparableConvolution1D: Depthwise separable 1D convolution.
class SeparableConvolution2D: Depthwise separable 2D convolution.
class SimpleRNN: Fully-connected RNN where the output is to be fed back to input.
class SimpleRNNCell: Cell class for SimpleRNN.
class Softmax: Softmax activation function.
class SpatialDropout1D: Spatial 1D version of Dropout.
class SpatialDropout2D: Spatial 2D version of Dropout.
class SpatialDropout3D: Spatial 3D version of Dropout.
class StackedRNNCells: Wrapper allowing a stack of RNN cells to behave as a single cell.
class Subtract: Layer that subtracts two inputs.
class ThresholdedReLU: Thresholded Rectified Linear Unit.
class TimeDistributed: This wrapper allows to apply a layer to every temporal slice of an input.
class UpSampling1D: Upsampling layer for 1D inputs.
class UpSampling2D: Upsampling layer for 2D inputs.
class UpSampling3D: Upsampling layer for 3D inputs.
class Wrapper: Abstract wrapper base class.
class ZeroPadding1D: Zero-padding layer for 1D input (e.g. temporal sequence).
class ZeroPadding2D: Zero-padding layer for 2D input (e.g. picture).
class ZeroPadding3D: Zero-padding layer for 3D data (spatial or spatio-temporal).
Input(...): Input() is used to instantiate a Keras tensor.
add(...): Functional interface to the tf.keras.layers.Add layer.
average(...): Functional interface to the tf.keras.layers.Average layer.
concatenate(...): Functional interface to the Concatenate layer.
deserialize(...): Instantiates a layer from a config dictionary.
disable_v2_dtype_behavior(...): Disables the V2 dtype behavior for Keras layers.
dot(...): Functional interface to the Dot layer.
enable_v2_dtype_behavior(...): Enable the V2 dtype behavior for Keras layers.
maximum(...): Functional interface to compute maximum (element-wise) list of inputs.
minimum(...): Functional interface to the Minimum layer.
multiply(...): Functional interface to the Multiply layer.
serialize(...)
subtract(...): Functional interface to the Subtract layer.


Layer that normalizes its inputs.
Inherits From: Layer, Module
Batch normalization applies a transformation that maintains the mean output close to 0 and the output standard deviation close to 1.
Importantly, batch normalization works differently during training and during inference.
During training (i.e. when using fit() or when calling the layer/model with the argument training=True), the layer normalizes its output using the mean and standard deviation of the current batch of inputs. That is to say, for each channel being normalized, the layer returns (batch - mean(batch)) / (var(batch) + epsilon) * gamma + beta, where:
During inference (i.e. when using evaluate() or predict() or when calling the layer/model with the argument training=False (which is the default), the layer normalizes its output using a moving average of the mean and standard deviation of the batches it has seen during training. That is to say, it returns (batch - self.moving_mean) / (self.moving_var + epsilon) * gamma + beta.
self.moving_mean and self.moving_var are non-trainable variables that are updated each time the layer in called in training mode, as such:
As such, the layer will only normalize its inputs during inference after having been trained on data that has similar statistics as the inference data.
Input shape: Arbitrary. Use the keyword argument input_shape (tuple of integers, does not include the samples axis) when using this layer as the first layer in a model.
Output shape: Same shape as input.


Fast GRU implementation backed by cuDNN.
Inherits From: RNN, Layer, Module
More information about cuDNN can be found on the NVIDIA developer website. Can only be run on GPU.
View source
Reset the recorded states for the stateful RNN layer.
Can only be used when RNN layer is constructed with stateful = True. Args: states: Numpy arrays that contains the value for the initial state, which will be feed to cell at the first time step. When the value is None, zero filled numpy array will be created based on the cell state size.


Fast LSTM implementation backed by cuDNN.
Inherits From: RNN, Layer, Module
More information about cuDNN can be found on the NVIDIA developer website. Can only be run on GPU.
View source
Reset the recorded states for the stateful RNN layer.
Can only be used when RNN layer is constructed with stateful = True. Args: states: Numpy arrays that contains the value for the initial state, which will be feed to cell at the first time step. When the value is None, zero filled numpy array will be created based on the cell state size.


A layer that produces a dense Tensor based on given feature_columns.
Inherits From: Layer, Module
Generally a single example in training data is described with FeatureColumns. At the first layer of the model, this column-oriented data should be converted to a single Tensor.
This layer can be called multiple times with different features.
This is the V1 version of this layer that uses variable_scope's or partitioner to create variables which works well with PartitionedVariables. Variable scopes are deprecated in V2, so the V2 version uses name_scopes instead. But currently that lacks support for partitioned variables. Use this if you need partitioned variables. Use the partitioner argument if you have a Keras model and uses tf.compat.v1.keras.estimator.model_to_estimator for training.


Disables the V2 dtype behavior for Keras layers.
See tf.compat.v1.keras.layers.enable_v2_dtype_behavior.


Enable the V2 dtype behavior for Keras layers.
By default, the V2 dtype behavior is enabled in TensorFlow 2, so this function is only useful if tf.compat.v1.disable_v2_behavior has been called. Since mixed precision requires V2 dtype behavior to be enabled, this function allows you to use mixed precision in Keras layers if disable_v2_behavior has been called.
When enabled, the dtype of Keras layers defaults to floatx (which is typically float32) instead of None. In addition, layers will automatically cast floating-point inputs to the layer's dtype.
A layer author can opt-out their layer from the automatic input casting by passing autocast=False to the base Layer's constructor. This disables the autocasting part of the V2 behavior for that layer, but not the defaulting to floatx part of the V2 behavior.
When a global tf.keras.mixed_precision.Policy is set, a Keras layer's dtype will default to the global policy instead of floatx. Layers will automatically cast inputs to the policy's compute_dtype.


Public API for tf.keras.layers.experimental namespace.
preprocessing module: Public API for tf.keras.layers.experimental.preprocessing namespace.
class EinsumDense: A layer that uses tf.einsum as the backing computation.
class RandomFourierFeatures: Layer that projects its inputs into a random feature space.


Public API for tf.keras.layers.experimental.preprocessing namespace.
class CategoryCrossing: Category crossing layer.
class CategoryEncoding: CategoryEncoding layer.
class CenterCrop: Crop the central portion of the images to target height and width.
class Discretization: Buckets data into discrete ranges.
class Hashing: Implements categorical feature hashing, also known as "hashing trick".
class IntegerLookup: Maps integers from a vocabulary to integer indices.
class Normalization: Feature-wise normalization of the data.
class PreprocessingLayer: Base class for PreprocessingLayers.
class RandomContrast: Adjust the contrast of an image or images by a random factor.
class RandomCrop: Randomly crop the images to target height and width.
class RandomFlip: Randomly flip each image horizontally and vertically.
class RandomHeight: Randomly vary the height of a batch of images during training.
class RandomRotation: Randomly rotate each image.
class RandomTranslation: Randomly translate each image during training.
class RandomWidth: Randomly vary the width of a batch of images during training.
class RandomZoom: Randomly zoom each image during training.
class Rescaling: Multiply inputs by scale and adds offset.
class Resizing: Image resizing layer.
class StringLookup: Maps strings from a vocabulary to integer indices.
class TextVectorization: Text vectorization layer.