tf.recompute_grad     View source on GitHub    An eager-compatible version of recompute_grad.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.recompute_grad
tf.recompute_grad(
    f
)
 For f(*args, **kwargs), this supports gradients with respect to args or kwargs, but kwargs are currently only supported in eager-mode. Note that for keras layer and model objects, this is handled automatically. Warning: If f was originally a tf.keras Model or Layer object, g will not be able to access the member variables of that object, because g returns through the wrapper function inner. When recomputing gradients through objects that inherit from keras, we suggest keeping a reference to the underlying object around for the purpose of accessing these variables.

 Args
  f   function f(*x) that returns a Tensor or sequence of Tensor outputs.

 Returns   A function g that wraps f, but which recomputes f on the backwards pass of a gradient call.


tf.RegisterGradient     View source on GitHub    A decorator for registering the gradient function for an op type.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.RegisterGradient
tf.RegisterGradient(
    op_type
)
 This decorator is only used when defining a new op type. For an op with m inputs and n outputs, the gradient function is a function that takes the original Operation and n Tensor objects (representing the gradients with respect to each output of the op), and returns m Tensor objects (representing the partial gradients with respect to each input of the op). For example, assuming that operations of type "Sub" take two inputs x and y, and return a single output x - y, the following gradient function would be registered: @tf.RegisterGradient("Sub")
def _sub_grad(unused_op, grad):
  return grad, tf.negative(grad)
 The decorator argument op_type is the string type of an operation. This corresponds to the OpDef.name field for the proto that defines the operation.

 Args
  op_type   The string type of an operation. This corresponds to the OpDef.name field for the proto that defines the operation.

 Raises
  TypeError   If op_type is not string.    Methods __call__ View source
__call__(
    f
)
 Registers the function f as gradient function for op_type.


tf.register_tensor_conversion_function     View source on GitHub    Registers a function for converting objects of base_type to Tensor.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.register_tensor_conversion_function
tf.register_tensor_conversion_function(
    base_type, conversion_func, priority=100
)
 The conversion function must have the following signature: def conversion_func(value, dtype=None, name=None, as_ref=False):
  # ...
 It must return a Tensor with the given dtype if specified. If the conversion function creates a new Tensor, it should use the given name if specified. All exceptions will be propagated to the caller. The conversion function may return NotImplemented for some inputs. In this case, the conversion process will continue to try subsequent conversion functions. If as_ref is true, the function must return a Tensor reference, such as a Variable.
Note: The conversion functions will execute in order of priority, followed by order of registration. To ensure that a conversion function F runs before another conversion function G, ensure that F is registered with a smaller priority than G.

 Args
  base_type   The base type or tuple of base types for all objects that conversion_func accepts.
  conversion_func   A function that converts instances of base_type to Tensor.
  priority   Optional integer that indicates the priority for applying this conversion function. Conversion functions with smaller priority values run earlier than conversion functions with larger priority values. Defaults to 100.

 Raises
  TypeError   If the arguments do not have the appropriate type.


tf.repeat     View source on GitHub    Repeat elements of input.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.repeat
tf.repeat(
    input, repeats, axis=None, name=None
)
 See also tf.concat, tf.stack, tf.tile.

 Args
  input   An N-dimensional Tensor.
  repeats   An 1-D int Tensor. The number of repetitions for each element. repeats is broadcasted to fit the shape of the given axis. len(repeats) must equal input.shape[axis] if axis is not None.
  axis   An int. The axis along which to repeat values. By default (axis=None), use the flattened input array, and return a flat output array.
  name   A name for the operation.

 Returns   A Tensor which has the same shape as input, except along the given axis. If axis is None then the output array is flattened to match the flattened input array.
 Example usage:
repeat(['a', 'b', 'c'], repeats=[3, 0, 2], axis=0)
<tf.Tensor: shape=(5,), dtype=string,
numpy=array([b'a', b'a', b'a', b'c', b'c'], dtype=object)>

repeat([[1, 2], [3, 4]], repeats=[2, 3], axis=0)
<tf.Tensor: shape=(5, 2), dtype=int32, numpy=
array([[1, 2],
       [1, 2],
       [3, 4],
       [3, 4],
       [3, 4]], dtype=int32)>

repeat([[1, 2], [3, 4]], repeats=[2, 3], axis=1)
<tf.Tensor: shape=(2, 5), dtype=int32, numpy=
array([[1, 1, 2, 2, 2],
       [3, 3, 4, 4, 4]], dtype=int32)>

repeat(3, repeats=4)
<tf.Tensor: shape=(4,), dtype=int32, numpy=array([3, 3, 3, 3], dtype=int32)>

repeat([[1,2], [3,4]], repeats=2)
<tf.Tensor: shape=(8,), dtype=int32,
numpy=array([1, 1, 2, 2, 3, 3, 4, 4], dtype=int32)>


tf.required_space_to_batch_paddings     View source on GitHub    Calculate padding required to make block_shape divide input_shape.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.required_space_to_batch_paddings
tf.required_space_to_batch_paddings(
    input_shape, block_shape, base_paddings=None, name=None
)
 This function can be used to calculate a suitable paddings argument for use with space_to_batch_nd and batch_to_space_nd.

 Args
  input_shape   int32 Tensor of shape [N].
  block_shape   int32 Tensor of shape [N].
  base_paddings   Optional int32 Tensor of shape [N, 2]. Specifies the minimum amount of padding to use. All elements must be >= 0. If not specified, defaults to 0.
  name   string. Optional name prefix.

 Returns   (paddings, crops), where: paddings and crops are int32 Tensors of rank 2 and shape [N, 2]
    satisfying   paddings[i, 0] = base_paddings[i, 0]. 0 <= paddings[i, 1] - base_paddings[i, 1] < block_shapei % block_shape[i] == 0 crops[i, 0] = 0 crops[i, 1] = paddings[i, 1] - base_paddings[i, 1]
   Raises: ValueError if called with incompatible shapes.


tf.reshape     View source on GitHub    Reshapes a tensor.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.manip.reshape, tf.compat.v1.reshape
tf.reshape(
    tensor, shape, name=None
)
 Given tensor, this operation returns a new tf.Tensor that has the same values as tensor in the same order, except with a new shape given by shape.
t1 = [[1, 2, 3],
      [4, 5, 6]]
print(tf.shape(t1).numpy())
[2 3]
t2 = tf.reshape(t1, [6])
t2
<tf.Tensor: shape=(6,), dtype=int32,
  numpy=array([1, 2, 3, 4, 5, 6], dtype=int32)>
tf.reshape(t2, [3, 2])
<tf.Tensor: shape=(3, 2), dtype=int32, numpy=
  array([[1, 2],
         [3, 4],
         [5, 6]], dtype=int32)>
 The tf.reshape does not change the order of or the total number of elements in the tensor, and so it can reuse the underlying data buffer. This makes it a fast operation independent of how big of a tensor it is operating on.
tf.reshape([1, 2, 3], [2, 2])
Traceback (most recent call last):

InvalidArgumentError: Input to reshape is a tensor with 3 values, but the
requested shape has 4
 To instead reorder the data to rearrange the dimensions of a tensor, see tf.transpose.
t = [[1, 2, 3],
     [4, 5, 6]]
tf.reshape(t, [3, 2]).numpy()
array([[1, 2],
       [3, 4],
       [5, 6]], dtype=int32)
tf.transpose(t, perm=[1, 0]).numpy()
array([[1, 4],
       [2, 5],
       [3, 6]], dtype=int32)
 If one component of shape is the special value -1, the size of that dimension is computed so that the total size remains constant. In particular, a shape of [-1] flattens into 1-D. At most one component of shape can be -1.
t = [[1, 2, 3],
     [4, 5, 6]]
tf.reshape(t, [-1])
<tf.Tensor: shape=(6,), dtype=int32,
  numpy=array([1, 2, 3, 4, 5, 6], dtype=int32)>
tf.reshape(t, [3, -1])
<tf.Tensor: shape=(3, 2), dtype=int32, numpy=
  array([[1, 2],
         [3, 4],
         [5, 6]], dtype=int32)>
tf.reshape(t, [-1, 2])
<tf.Tensor: shape=(3, 2), dtype=int32, numpy=
  array([[1, 2],
         [3, 4],
         [5, 6]], dtype=int32)>
 tf.reshape(t, []) reshapes a tensor t with one element to a scalar.
tf.reshape([7], []).numpy()
7
 More examples:
t = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(tf.shape(t).numpy())
[9]
tf.reshape(t, [3, 3])
<tf.Tensor: shape=(3, 3), dtype=int32, numpy=
  array([[1, 2, 3],
         [4, 5, 6],
         [7, 8, 9]], dtype=int32)>

t = [[[1, 1], [2, 2]],
     [[3, 3], [4, 4]]]
print(tf.shape(t).numpy())
[2 2 2]
tf.reshape(t, [2, 4])
<tf.Tensor: shape=(2, 4), dtype=int32, numpy=
  array([[1, 1, 2, 2],
         [3, 3, 4, 4]], dtype=int32)>

t = [[[1, 1, 1],
      [2, 2, 2]],
     [[3, 3, 3],
      [4, 4, 4]],
     [[5, 5, 5],
      [6, 6, 6]]]
print(tf.shape(t).numpy())
[3 2 3]
# Pass '[-1]' to flatten 't'.
tf.reshape(t, [-1])
<tf.Tensor: shape=(18,), dtype=int32,
  numpy=array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6],
  dtype=int32)>
# -- Using -1 to infer the shape --
# Here -1 is inferred to be 9:
tf.reshape(t, [2, -1])
<tf.Tensor: shape=(2, 9), dtype=int32, numpy=
  array([[1, 1, 1, 2, 2, 2, 3, 3, 3],
         [4, 4, 4, 5, 5, 5, 6, 6, 6]], dtype=int32)>
# -1 is inferred to be 2:
tf.reshape(t, [-1, 9])
<tf.Tensor: shape=(2, 9), dtype=int32, numpy=
  array([[1, 1, 1, 2, 2, 2, 3, 3, 3],
         [4, 4, 4, 5, 5, 5, 6, 6, 6]], dtype=int32)>
# -1 is inferred to be 3:
tf.reshape(t, [ 2, -1, 3])
<tf.Tensor: shape=(2, 3, 3), dtype=int32, numpy=
  array([[[1, 1, 1],
          [2, 2, 2],
          [3, 3, 3]],
         [[4, 4, 4],
          [5, 5, 5],
          [6, 6, 6]]], dtype=int32)>

 Args
  tensor   A Tensor.
  shape   A Tensor. Must be one of the following types: int32, int64. Defines the shape of the output tensor.
  name   Optional string. A name for the operation.

 Returns   A Tensor. Has the same type as tensor.


tf.reverse Reverses specific dimensions of a tensor.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.manip.reverse, tf.compat.v1.reverse, tf.compat.v1.reverse_v2
tf.reverse(
    tensor, axis, name=None
)
 NOTE tf.reverse has now changed behavior in preparation for 1.0. tf.reverse_v2 is currently an alias that will be deprecated before TF 1.0. Given a tensor, and a int32 tensor axis representing the set of dimensions of tensor to reverse. This operation reverses each dimension i for which there exists j s.t. axis[j] == i. tensor can have up to 8 dimensions. The number of dimensions specified in axis may be 0 or more entries. If an index is specified more than once, a InvalidArgument error is raised. For example: # tensor 't' is [[[[ 0,  1,  2,  3],
#                  [ 4,  5,  6,  7],
#                  [ 8,  9, 10, 11]],
#                 [[12, 13, 14, 15],
#                  [16, 17, 18, 19],
#                  [20, 21, 22, 23]]]]
# tensor 't' shape is [1, 2, 3, 4]

# 'dims' is [3] or 'dims' is [-1]
reverse(t, dims) ==> [[[[ 3,  2,  1,  0],
                        [ 7,  6,  5,  4],
                        [ 11, 10, 9, 8]],
                       [[15, 14, 13, 12],
                        [19, 18, 17, 16],
                        [23, 22, 21, 20]]]]

# 'dims' is '[1]' (or 'dims' is '[-3]')
reverse(t, dims) ==> [[[[12, 13, 14, 15],
                        [16, 17, 18, 19],
                        [20, 21, 22, 23]
                       [[ 0,  1,  2,  3],
                        [ 4,  5,  6,  7],
                        [ 8,  9, 10, 11]]]]

# 'dims' is '[2]' (or 'dims' is '[-2]')
reverse(t, dims) ==> [[[[8, 9, 10, 11],
                        [4, 5, 6, 7],
                        [0, 1, 2, 3]]
                       [[20, 21, 22, 23],
                        [16, 17, 18, 19],
                        [12, 13, 14, 15]]]]

 Args
  tensor   A Tensor. Must be one of the following types: uint8, int8, uint16, int16, int32, int64, bool, bfloat16, half, float32, float64, complex64, complex128, string. Up to 8-D.
  axis   A Tensor. Must be one of the following types: int32, int64. 1-D. The indices of the dimensions to reverse. Must be in the range [-rank(tensor), rank(tensor)).
  name   A name for the operation (optional).

 Returns   A Tensor. Has the same type as tensor.


tf.reverse_sequence     View source on GitHub    Reverses variable length slices.
tf.reverse_sequence(
    input, seq_lengths, seq_axis=None, batch_axis=None, name=None
)
 This op first slices input along the dimension batch_axis, and for each slice i, reverses the first seq_lengths[i] elements along the dimension seq_axis. The elements of seq_lengths must obey seq_lengths[i] <= input.dims[seq_axis], and seq_lengths must be a vector of length input.dims[batch_axis]. The output slice i along dimension batch_axis is then given by input slice i, with the first seq_lengths[i] slices along dimension seq_axis reversed. Example usage:
seq_lengths = [7, 2, 3, 5]
input = [[1, 2, 3, 4, 5, 0, 0, 0], [1, 2, 0, 0, 0, 0, 0, 0],
         [1, 2, 3, 4, 0, 0, 0, 0], [1, 2, 3, 4, 5, 6, 7, 8]]
output = tf.reverse_sequence(input, seq_lengths, seq_axis=1, batch_axis=0)
output
<tf.Tensor: shape=(4, 8), dtype=int32, numpy=
array([[0, 0, 5, 4, 3, 2, 1, 0],
       [2, 1, 0, 0, 0, 0, 0, 0],
       [3, 2, 1, 4, 0, 0, 0, 0],
       [5, 4, 3, 2, 1, 6, 7, 8]], dtype=int32)>

 Args
  input   A Tensor. The input to reverse.
  seq_lengths   A Tensor. Must be one of the following types: int32, int64. 1-D with length input.dims(batch_axis) and max(seq_lengths) <= input.dims(seq_axis)
  seq_axis   An int. The dimension which is partially reversed.
  batch_axis   An optional int. Defaults to 0. The dimension along which reversal is performed.
  name   A name for the operation (optional).

 Returns   A Tensor. Has the same type as input.


tf.roll     View source on GitHub    Rolls the elements of a tensor along an axis.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.manip.roll, tf.compat.v1.roll
tf.roll(
    input, shift, axis, name=None
)
 The elements are shifted positively (towards larger indices) by the offset of shift along the dimension of axis. Negative shift values will shift elements in the opposite direction. Elements that roll passed the last position will wrap around to the first and vice versa. Multiple shifts along multiple axes may be specified. For example: # 't' is [0, 1, 2, 3, 4]
roll(t, shift=2, axis=0) ==> [3, 4, 0, 1, 2]

# shifting along multiple dimensions
# 't' is [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]
roll(t, shift=[1, -2], axis=[0, 1]) ==> [[7, 8, 9, 5, 6], [2, 3, 4, 0, 1]]

# shifting along the same axis multiple times
# 't' is [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]
roll(t, shift=[2, -3], axis=[1, 1]) ==> [[1, 2, 3, 4, 0], [6, 7, 8, 9, 5]]

 Args
  input   A Tensor.
  shift   A Tensor. Must be one of the following types: int32, int64. Dimension must be 0-D or 1-D. shift[i] specifies the number of places by which elements are shifted positively (towards larger indices) along the dimension specified by axis[i]. Negative shifts will roll the elements in the opposite direction.
  axis   A Tensor. Must be one of the following types: int32, int64. Dimension must be 0-D or 1-D. axis[i] specifies the dimension that the shift shift[i] should occur. If the same axis is referenced more than once, the total shift for that axis will be the sum of all the shifts that belong to that axis.
  name   A name for the operation (optional).

 Returns   A Tensor. Has the same type as input.


Module: tf.saved_model Public API for tf.saved_model namespace. Modules experimental module: Public API for tf.saved_model.experimental namespace. Classes class Asset: Represents a file asset to hermetically include in a SavedModel. class LoadOptions: Options for loading a SavedModel. class SaveOptions: Options for saving to SavedModel. Functions contains_saved_model(...): Checks whether the provided export directory could contain a SavedModel. load(...): Load a SavedModel from export_dir. save(...): Exports the Trackable object obj to SavedModel format.

 Other Members
  ASSETS_DIRECTORY   'assets'
  ASSETS_KEY   'saved_model_assets'
  CLASSIFY_INPUTS   'inputs'
  CLASSIFY_METHOD_NAME   'tensorflow/serving/classify'
  CLASSIFY_OUTPUT_CLASSES   'classes'
  CLASSIFY_OUTPUT_SCORES   'scores'
  DEBUG_DIRECTORY   'debug'
  DEBUG_INFO_FILENAME_PB   'saved_model_debug_info.pb'
  DEFAULT_SERVING_SIGNATURE_DEF_KEY   'serving_default'
  GPU   'gpu'
  PREDICT_INPUTS   'inputs'
  PREDICT_METHOD_NAME   'tensorflow/serving/predict'
  PREDICT_OUTPUTS   'outputs'
  REGRESS_INPUTS   'inputs'
  REGRESS_METHOD_NAME   'tensorflow/serving/regress'
  REGRESS_OUTPUTS   'outputs'
  SAVED_MODEL_FILENAME_PB   'saved_model.pb'
  SAVED_MODEL_FILENAME_PBTXT   'saved_model.pbtxt'
  SAVED_MODEL_SCHEMA_VERSION   1
  SERVING   'serve'
  TPU   'tpu'
  TRAINING   'train'
  VARIABLES_DIRECTORY   'variables'
  VARIABLES_FILENAME   'variables'


tf.saved_model.Asset Represents a file asset to hermetically include in a SavedModel.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.saved_model.Asset
tf.saved_model.Asset(
    path
)
 A SavedModel can include arbitrary files, called assets, that are needed for its use. For example a vocabulary file used initialize a lookup table. When a trackable object is exported via tf.saved_model.save(), all the Assets reachable from it are copied into the SavedModel assets directory. Upon loading, the assets and the serialized functions that depend on them will refer to the correct filepaths inside the SavedModel directory. Example: filename = tf.saved_model.Asset("file.txt")

@tf.function(input_signature=[])
def func():
  return tf.io.read_file(filename)

trackable_obj = tf.train.Checkpoint()
trackable_obj.func = func
trackable_obj.filename = filename
tf.saved_model.save(trackable_obj, "/tmp/saved_model")

# The created SavedModel is hermetic, it does not depend on
# the original file and can be moved to another path.
tf.io.gfile.remove("file.txt")
tf.io.gfile.rename("/tmp/saved_model", "/tmp/new_location")

reloaded_obj = tf.saved_model.load("/tmp/new_location")
print(reloaded_obj.func())

 Attributes
  asset_path   A 0-D tf.string tensor with path to the asset.


tf.saved_model.contains_saved_model     View source on GitHub    Checks whether the provided export directory could contain a SavedModel.
tf.saved_model.contains_saved_model(
    export_dir
)
 Note that the method does not load any data by itself. If the method returns false, the export directory definitely does not contain a SavedModel. If the method returns true, the export directory may contain a SavedModel but provides no guarantee that it can be loaded.

 Args
  export_dir   Absolute string path to possible export location. For example, '/my/foo/model'.

 Returns   True if the export directory contains SavedModel files, False otherwise.


Module: tf.saved_model.experimental Public API for tf.saved_model.experimental namespace. Classes class VariablePolicy: Enum defining options for variable handling when saving.


tf.saved_model.experimental.VariablePolicy Enum defining options for variable handling when saving.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.saved_model.experimental.VariablePolicy  NONE No policy applied: Distributed variables are saved as one variable, with no device attached. SAVE_VARIABLE_DEVICES When saving variables, also save their device assignment. This is useful if one wants to hardcode devices in saved models, but it also makes them non-portable if soft device placement is disabled (more details in tf.config.set_soft_device_placement). This is currently not fully supported by saved_model.load, and is mainly intended to be used when one will be reading the saved model at a lower API level. In the example below, the graph saved by the call to saved_model.save will have the variable devices correctly specified: exported = tf.train.Checkpoint()
with tf.device('/GPU:0'):
  exported.x_gpu = tf.Variable(1.0)
with tf.device('/CPU:0'):
  exported.x_cpu = tf.Variable(1.0)
tf.saved_model.save(exported, export_dir,
    options = tf.saved_model.SaveOptions(
        experimental_variable_policy=
          tf.saved_model.experimental.VariablePolicy.SAVE_VARIABLE_DEVICES))
 Distributed variables are still saved as one variable under this policy. EXPAND_DISTRIBUTED_VARIABLES Distributed variables will be saved with information about their components, allowing for their restoration on load. Also, the saved graph will contain references to those variables. This is useful when one wants to use the model for training in environments where the original distribution strategy is not available.

 Class Variables
  EXPAND_DISTRIBUTED_VARIABLES   tf.saved_model.experimental.VariablePolicy
  NONE   tf.saved_model.experimental.VariablePolicy
  SAVE_VARIABLE_DEVICES   tf.saved_model.experimental.VariablePolicy


tf.saved_model.load     View source on GitHub    Load a SavedModel from export_dir.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.saved_model.load_v2
tf.saved_model.load(
    export_dir, tags=None, options=None
)
 Signatures associated with the SavedModel are available as functions: imported = tf.saved_model.load(path)
f = imported.signatures["serving_default"]
print(f(x=tf.constant([[1.]])))
 Objects exported with tf.saved_model.save additionally have trackable objects and functions assigned to attributes: exported = tf.train.Checkpoint(v=tf.Variable(3.))
exported.f = tf.function(
    lambda x: exported.v * x,
    input_signature=[tf.TensorSpec(shape=None, dtype=tf.float32)])
tf.saved_model.save(exported, path)
imported = tf.saved_model.load(path)
assert 3. == imported.v.numpy()
assert 6. == imported.f(x=tf.constant(2.)).numpy()
 Loading Keras models Keras models are trackable, so they can be saved to SavedModel. The object returned by tf.saved_model.load is not a Keras object (i.e. doesn't have .fit, .predict, etc. methods). A few attributes and functions are still available: .variables, .trainable_variables and .__call__. model = tf.keras.Model(...)
tf.saved_model.save(model, path)
imported = tf.saved_model.load(path)
outputs = imported(inputs)
 Use tf.keras.models.load_model to restore the Keras model. Importing SavedModels from TensorFlow 1.x SavedModels from tf.estimator.Estimator or 1.x SavedModel APIs have a flat graph instead of tf.function objects. These SavedModels will be loaded with the following attributes:
.signatures: A dictionary mapping signature names to functions.
.prune(feeds, fetches): A method which allows you to extract functions for new subgraphs. This is equivalent to importing the SavedModel and naming feeds and fetches in a Session from TensorFlow 1.x. imported = tf.saved_model.load(path_to_v1_saved_model)
pruned = imported.prune("x:0", "out:0")
pruned(tf.ones([]))
 See tf.compat.v1.wrap_function for details.
 .variables: A list of imported variables. .graph: The whole imported graph. .restore(save_path): A function that restores variables from a checkpoint saved from tf.compat.v1.Saver.  Consuming SavedModels asynchronously When consuming SavedModels asynchronously (the producer is a separate process), the SavedModel directory will appear before all files have been written, and tf.saved_model.load will fail if pointed at an incomplete SavedModel. Rather than checking for the directory, check for "saved_model_dir/saved_model.pb". This file is written atomically as the last tf.saved_model.save file operation.

 Args
  export_dir   The SavedModel directory to load from.
  tags   A tag or sequence of tags identifying the MetaGraph to load. Optional if the SavedModel contains a single MetaGraph, as for those exported from tf.saved_model.save.
  options   tf.saved_model.LoadOptions object that specifies options for loading.

 Returns   A trackable object with a signatures attribute mapping from signature keys to functions. If the SavedModel was exported by tf.saved_model.load, it also points to trackable objects, functions, debug info which it has been saved.

 Raises
  ValueError   If tags don't match a MetaGraph in the SavedModel.


tf.saved_model.LoadOptions Options for loading a SavedModel.
tf.saved_model.LoadOptions(
    experimental_io_device=None
)
 This function may be used in the options argument in functions that load a SavedModel (tf.saved_model.load, tf.keras.models.load_model).

 Args
  experimental_io_device   string. Applies in a distributed setting. Tensorflow device to use to access the filesystem. If None (default) then for each variable the filesystem is accessed from the CPU:0 device of the host where that variable is assigned. If specified, the filesystem is instead accessed from that device for all variables. This is for example useful if you want to load from a local directory, such as "/tmp" when running in a distributed setting. In that case pass a device for the host where the "/tmp" directory is accessible.

 Class Variables
  experimental_io_device


tf.saved_model.save     View source on GitHub    Exports the Trackable object obj to SavedModel format.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.saved_model.experimental.save, tf.compat.v1.saved_model.save
tf.saved_model.save(
    obj, export_dir, signatures=None, options=None
)
 Example usage: class Adder(tf.Module):

  @tf.function(input_signature=[tf.TensorSpec(shape=None, dtype=tf.float32)])
  def add(self, x):
    return x + x + 1.

to_export = Adder()
tf.saved_model.save(to_export, '/tmp/adder')
 The resulting SavedModel is then servable with an input named "x", its value having any shape and dtype float32. The optional signatures argument controls which methods in obj will be available to programs which consume SavedModels, for example, serving APIs. Python functions may be decorated with @tf.function(input_signature=...) and passed as signatures directly, or lazily with a call to get_concrete_function on the method decorated with @tf.function. If the signatures argument is omitted, obj will be searched for @tf.function-decorated methods. If exactly one @tf.function is found, that method will be used as the default signature for the SavedModel. This behavior is expected to change in the future, when a corresponding tf.saved_model.load symbol is added. At that point signatures will be completely optional, and any @tf.function attached to obj or its dependencies will be exported for use with load. When invoking a signature in an exported SavedModel, Tensor arguments are identified by name. These names will come from the Python function's argument names by default. They may be overridden by specifying a name=... argument in the corresponding tf.TensorSpec object. Explicit naming is required if multiple Tensors are passed through a single argument to the Python function. The outputs of functions used as signatures must either be flat lists, in which case outputs will be numbered, or a dictionary mapping string keys to Tensor, in which case the keys will be used to name outputs. Signatures are available in objects returned by tf.saved_model.load as a .signatures attribute. This is a reserved attribute: tf.saved_model.save on an object with a custom .signatures attribute will raise an exception. Since tf.keras.Model objects are also Trackable, this function can be used to export Keras models. For example, exporting with a signature specified: class Model(tf.keras.Model):

  @tf.function(input_signature=[tf.TensorSpec(shape=[None], dtype=tf.string)])
  def serve(self, serialized):
    ...

m = Model()
tf.saved_model.save(m, '/tmp/saved_model/')
 Exporting from a function without a fixed signature: class Model(tf.keras.Model):

  @tf.function
  def call(self, x):
    ...

m = Model()
tf.saved_model.save(
    m, '/tmp/saved_model/',
    signatures=m.call.get_concrete_function(
        tf.TensorSpec(shape=[None, 3], dtype=tf.float32, name="inp")))
 tf.keras.Model instances constructed from inputs and outputs already have a signature and so do not require a @tf.function decorator or a signatures argument. If neither are specified, the model's forward pass is exported. x = input_layer.Input((4,), name="x")
y = core.Dense(5, name="out")(x)
model = training.Model(x, y)
tf.saved_model.save(model, '/tmp/saved_model/')
# The exported SavedModel takes "x" with shape [None, 4] and returns "out"
# with shape [None, 5]
 Variables must be tracked by assigning them to an attribute of a tracked object or to an attribute of obj directly. TensorFlow objects (e.g. layers from tf.keras.layers, optimizers from tf.train) track their variables automatically. This is the same tracking scheme that tf.train.Checkpoint uses, and an exported Checkpoint object may be restored as a training checkpoint by pointing tf.train.Checkpoint.restore to the SavedModel's "variables/" subdirectory. Currently, variables are the only stateful objects supported by tf.saved_model.save, but others (e.g. tables) will be supported in the future. tf.function does not hard-code device annotations from outside the function body, instead of using the calling context's device. This means for example that exporting a model that runs on a GPU and serving it on a CPU will generally work, with some exceptions. tf.device annotations inside the body of the function will be hard-coded in the exported model; this type of annotation is discouraged. Device-specific operations, e.g. with "cuDNN" in the name or with device-specific layouts, may cause issues. Currently a DistributionStrategy is another exception: active distribution strategies will cause device placements to be hard-coded in a function. Exporting a single-device computation and importing under a DistributionStrategy is not currently supported, but may be in the future. SavedModels exported with tf.saved_model.save strip default-valued attributes automatically, which removes one source of incompatibilities when the consumer of a SavedModel is running an older TensorFlow version than the producer. There are however other sources of incompatibilities which are not handled automatically, such as when the exported model contains operations which the consumer does not have definitions for. A single tf.function can generate many ConcreteFunctions. If a downstream tool wants to refer to all concrete functions generated by a single tf.function you can use the function_aliases argument to store a map from the alias name to all concrete function names. E.g. class MyModel:
@tf.function
def func():
  ...

@tf.function
def serve():
  ...
  func()

model = MyModel()
signatures = {
    'serving_default': model.serve.get_concrete_function(),
}
options = tf.saved_model.SaveOptions(function_aliases={
    'my_func': func,
})
tf.saved_model.save(model, export_dir, signatures, options)

 Args
  obj   A trackable object to export.
  export_dir   A directory in which to write the SavedModel.
  signatures   Optional, one of three types:  a tf.function with an input signature specified, which will use the default serving signature key, the result of f.get_concrete_function on a @tf.function-decorated function f, in which case f will be used to generate a signature for the SavedModel under the default serving signature key, a dictionary, which maps signature keys to either tf.function instances with input signatures or concrete functions. Keys of such a dictionary may be arbitrary strings, but will typically be from the tf.saved_model.signature_constants module.

  options   Optional, tf.saved_model.SaveOptions object that specifies options for saving.

 Raises
  ValueError   If obj is not trackable.    Eager Compatibility Not well supported when graph building. From TensorFlow 1.x, tf.compat.v1.enable_eager_execution() should run first. Calling tf.saved_model.save in a loop when graph building from TensorFlow 1.x will add new save operations to the default graph each iteration. May not be called from within a function body.


tf.saved_model.SaveOptions Options for saving to SavedModel.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.saved_model.SaveOptions
tf.saved_model.SaveOptions(
    namespace_whitelist=None, save_debug_info=False, function_aliases=None,
    experimental_io_device=None, experimental_variable_policy=None
)
 This function may be used in the options argument in functions that save a SavedModel (tf.saved_model.save, tf.keras.models.save_model).

 Args
  namespace_whitelist   List of strings containing op namespaces to whitelist when saving a model. Saving an object that uses namespaced ops must explicitly add all namespaces to the whitelist. The namespaced ops must be registered into the framework when loading the SavedModel.
  save_debug_info   Boolean indicating whether debug information is saved. If True, then a debug/saved_model_debug_info.pb file will be written with the contents of a GraphDebugInfo binary protocol buffer containing stack trace information for all ops and functions that are saved.
  function_aliases   Python dict. Mapping from string to object returned by @tf.function. A single tf.function can generate many ConcreteFunctions. If a downstream tool wants to refer to all concrete functions generated by a single tf.function you can use the function_aliases argument to store a map from the alias name to all concrete function names. E.g. class MyModel:
@tf.function
def func():
...

@tf.function
def serve():
...
func()

model = MyModel()
signatures = {
'serving_default': model.serve.get_concrete_function(),
}
options = tf.saved_model.SaveOptions(function_aliases={
'my_func': func,
})
tf.saved_model.save(model, export_dir, signatures, options)

  experimental_io_device   string. Applies in a distributed setting. Tensorflow device to use to access the filesystem. If None (default) then for each variable the filesystem is accessed from the CPU:0 device of the host where that variable is assigned. If specified, the filesystem is instead accessed from that device for all variables. This is for example useful if you want to save to a local directory, such as "/tmp" when running in a distributed setting. In that case pass a device for the host where the "/tmp" directory is accessible.

  experimental_variable_policy   The policy to apply to variables when saving. This is either a saved_model.experimental.VariablePolicy enum instance or one of its value strings (case is not important). See that enum documentation for details. A value of None corresponds to the default policy.

 Class Variables
  experimental_io_device

  experimental_variable_policy

  function_aliases

  namespace_whitelist

  save_debug_info


tf.scan     View source on GitHub    scan on the list of tensors unpacked from elems on dimension 0. (deprecated argument values)
tf.scan(
    fn, elems, initializer=None, parallel_iterations=10, back_prop=True,
    swap_memory=False, infer_shape=True, reverse=False, name=None
)
 Warning: SOME ARGUMENT VALUES ARE DEPRECATED: (back_prop=False). They will be removed in a future version. Instructions for updating: back_prop=False is deprecated. Consider using tf.stop_gradient instead. Instead of: results = tf.scan(fn, elems, back_prop=False) Use: results = tf.nest.map_structure(tf.stop_gradient, tf.scan(fn, elems)) The simplest version of scan 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 [len(values)] + fn(initializer, values[0]).shape. If reverse=True, it's fn(initializer, values[-1]).shape. This method also allows multi-arity elems and accumulator. If elems is a (possibly nested) list or tuple of tensors, then each of these tensors must have a matching first (unpack) dimension. The second argument of fn must match the structure of elems. If no initializer is provided, the output structure and dtypes of fn are assumed to be the same as its input; and in this case, the first argument of fn must match the structure of elems. If an initializer is provided, then the output of fn must have the same structure as initializer; and the first argument of fn must match this structure. For example, if elems is (t1, [t2, t3]) and initializer is [i1, i2] then an appropriate signature for fn in python2 is: fn = lambda (acc_p1, acc_p2), (t1, [t2, t3]): and fn must return a list, [acc_n1, acc_n2]. An alternative correct signature for fn, and the one that works in python3, is: fn = lambda a, t:, where a and t correspond to the input tuples.

 Args
  fn   The callable to be performed. It accepts two arguments. The first will have the same structure as initializer if one is provided, otherwise it will have the same structure as elems. The second will have the same (possibly nested) structure as elems. Its output must have the same structure as initializer if one is provided, otherwise it must have the same structure as elems.
  elems   A tensor or (possibly nested) sequence of tensors, each of which will be unpacked along their first dimension. The nested sequence of the resulting slices will be the first argument to fn.
  initializer   (optional) A tensor or (possibly nested) sequence of tensors, initial value for the accumulator, and the expected output type of fn.
  parallel_iterations   (optional) The number of iterations allowed to run in parallel.
  back_prop   (optional) Deprecated. False disables support for back propagation. Prefer using tf.stop_gradient instead.
  swap_memory   (optional) True enables GPU-CPU memory swapping.
  infer_shape   (optional) False disables tests for consistent output shapes.
  reverse   (optional) True scans the tensor last to first (instead of first to last).
  name   (optional) Name prefix for the returned tensors.

 Returns   A tensor or (possibly nested) sequence of tensors. Each tensor packs the results of applying fn to tensors unpacked from elems along the first dimension, and the previous accumulator value(s), from first to last (or last to first, if reverse=True).

 Raises
  TypeError   if fn is not callable or the structure of the output of fn and initializer do not match.
  ValueError   if the lengths of the output of fn and initializer do not match.    Examples: elems = np.array([1, 2, 3, 4, 5, 6])
sum = scan(lambda a, x: a + x, elems)
# sum == [1, 3, 6, 10, 15, 21]
sum = scan(lambda a, x: a + x, elems, reverse=True)
# sum == [21, 20, 18, 15, 11, 6]

elems = np.array([1, 2, 3, 4, 5, 6])
initializer = np.array(0)
sum_one = scan(
    lambda a, x: x[0] - x[1] + a, (elems + 1, elems), initializer)
# sum_one == [1, 2, 3, 4, 5, 6]

elems = np.array([1, 0, 0, 0, 0, 0])
initializer = (np.array(0), np.array(1))
fibonaccis = scan(lambda a, _: (a[1], a[0] + a[1]), elems, initializer)
# fibonaccis == ([1, 1, 2, 3, 5, 8], [1, 2, 3, 5, 8, 13])


tf.scatter_nd Scatter updates into a new tensor according to indices.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.manip.scatter_nd, tf.compat.v1.scatter_nd
tf.scatter_nd(
    indices, updates, shape, name=None
)
 Creates a new tensor by applying sparse updates to individual values or slices within a tensor (initially zero for numeric, empty for string) of the given shape according to indices. This operator is the inverse of the tf.gather_nd operator which extracts values or slices from a given tensor. This operation is similar to tensor_scatter_add, except that the tensor is zero-initialized. Calling tf.scatter_nd(indices, values, shape) is identical to tensor_scatter_add(tf.zeros(shape, values.dtype), indices, values) If indices contains duplicates, then their updates are accumulated (summed). Warning: The order in which updates are applied is nondeterministic, so the output will be nondeterministic if indices contains duplicates -- because of some numerical approximation issues, numbers summed in different order may yield different results. indices is an integer tensor containing indices into a new tensor of shape shape. The last dimension of indices can be at most the rank of shape: indices.shape[-1] <= shape.rank
 The last dimension of indices corresponds to indices into elements (if indices.shape[-1] = shape.rank) or slices (if indices.shape[-1] < shape.rank) along dimension indices.shape[-1] of shape. updates is a tensor with shape indices.shape[:-1] + shape[indices.shape[-1]:]
 The simplest form of scatter is to insert individual elements in a tensor by index. For example, say we want to insert 4 scattered elements in a rank-1 tensor with 8 elements.    In Python, this scatter operation would look like this: indices = tf.constant([[4], [3], [1], [7]])
updates = tf.constant([9, 10, 11, 12])
shape = tf.constant([8])
scatter = tf.scatter_nd(indices, updates, shape)
print(scatter)
 The resulting tensor would look like this: [0, 11, 0, 10, 9, 0, 0, 12]
 We can also, insert entire slices of a higher rank tensor all at once. For example, if we wanted to insert two slices in the first dimension of a rank-3 tensor with two matrices of new values.    In Python, this scatter operation would look like this: indices = tf.constant([[0], [2]])
updates = tf.constant([[[5, 5, 5, 5], [6, 6, 6, 6],
                        [7, 7, 7, 7], [8, 8, 8, 8]],
                       [[5, 5, 5, 5], [6, 6, 6, 6],
                        [7, 7, 7, 7], [8, 8, 8, 8]]])
shape = tf.constant([4, 4, 4])
scatter = tf.scatter_nd(indices, updates, shape)
print(scatter)
 The resulting tensor would look like this: [[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]],
 [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]],
 [[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]],
 [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]]
 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, the index is ignored.

 Args
  indices   A Tensor. Must be one of the following types: int32, int64. Index tensor.
  updates   A Tensor. Updates to scatter into output.
  shape   A Tensor. Must have the same type as indices. 1-D. The shape of the resulting tensor.
  name   A name for the operation (optional).

 Returns   A Tensor. Has the same type as updates.


tf.searchsorted     View source on GitHub    Searches input tensor for values on the innermost dimension.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.searchsorted
tf.searchsorted(
    sorted_sequence, values, side='left', out_type=tf.dtypes.int32,
    name=None
)
 A 2-D example: sorted_sequence = [[0, 3, 9, 9, 10],
                   [1, 2, 3, 4, 5]]
values = [[2, 4, 9],
          [0, 2, 6]]

result = searchsorted(sorted_sequence, values, side="left")

result == [[1, 2, 2],
           [0, 1, 5]]

result = searchsorted(sorted_sequence, values, side="right")

result == [[1, 2, 4],
           [0, 2, 5]]

 Args
  sorted_sequence   N-D Tensor containing a sorted sequence.
  values   N-D Tensor containing the search values.
  side   'left' or 'right'; 'left' corresponds to lower_bound and 'right' to upper_bound.
  out_type   The output type (int32 or int64). Default is tf.int32.
  name   Optional name for the operation.

 Returns   An N-D Tensor the size of values containing the result of applying either lower_bound or upper_bound (depending on side) to each value. The result is not a global index to the entire Tensor, but the index in the last dimension.

 Raises
  ValueError   If the last dimension of sorted_sequence >= 2^31-1 elements. If the total size of values exceeds 2^31 - 1 elements. If the first N-1 dimensions of the two tensors don't match.


tf.sequence_mask     View source on GitHub    Returns a mask tensor representing the first N positions of each cell.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.sequence_mask
tf.sequence_mask(
    lengths, maxlen=None, dtype=tf.dtypes.bool, name=None
)
 If lengths has shape [d_1, d_2, ..., d_n] the resulting tensor mask has dtype dtype and shape [d_1, d_2, ..., d_n, maxlen], with mask[i_1, i_2, ..., i_n, j] = (j < lengths[i_1, i_2, ..., i_n])
 Examples: tf.sequence_mask([1, 3, 2], 5)  # [[True, False, False, False, False],
                                #  [True, True, True, False, False],
                                #  [True, True, False, False, False]]

tf.sequence_mask([[1, 3],[2,0]])  # [[[True, False, False],
                                  #   [True, True, True]],
                                  #  [[True, True, False],
                                  #   [False, False, False]]]

 Args
  lengths   integer tensor, all its values <= maxlen.
  maxlen   scalar integer tensor, size of last dimension of returned tensor. Default is the maximum value in lengths.
  dtype   output type of the resulting tensor.
  name   name of the op.

 Returns   A mask tensor of shape lengths.shape + (maxlen,), cast to specified dtype.

 Raises
  ValueError   if maxlen is not a scalar.


Module: tf.sets Tensorflow set operations. Functions difference(...): Compute set difference of elements in last dimension of a and b. intersection(...): Compute set intersection of elements in last dimension of a and b. size(...): Compute number of unique elements along last dimension of a. union(...): Compute set union of elements in last dimension of a and b.


tf.sets.difference     View source on GitHub    Compute set difference of elements in last dimension of a and b.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.sets.difference, tf.compat.v1.sets.set_difference
tf.sets.difference(
    a, b, aminusb=True, validate_indices=True
)
 All but the last dimension of a and b must match. Example: import tensorflow as tf
import collections

# Represent the following array of sets as a sparse tensor:
# a = np.array([[{1, 2}, {3}], [{4}, {5, 6}]])
a = collections.OrderedDict([
    ((0, 0, 0), 1),
    ((0, 0, 1), 2),
    ((0, 1, 0), 3),
    ((1, 0, 0), 4),
    ((1, 1, 0), 5),
    ((1, 1, 1), 6),
])
a = tf.sparse.SparseTensor(list(a.keys()), list(a.values()),
                           dense_shape=[2, 2, 2])

# np.array([[{1, 3}, {2}], [{4, 5}, {5, 6, 7, 8}]])
b = collections.OrderedDict([
    ((0, 0, 0), 1),
    ((0, 0, 1), 3),
    ((0, 1, 0), 2),
    ((1, 0, 0), 4),
    ((1, 0, 1), 5),
    ((1, 1, 0), 5),
    ((1, 1, 1), 6),
    ((1, 1, 2), 7),
    ((1, 1, 3), 8),
])
b = tf.sparse.SparseTensor(list(b.keys()), list(b.values()),
                           dense_shape=[2, 2, 4])

# `set_difference` is applied to each aligned pair of sets.
tf.sets.difference(a, b)

# The result will be equivalent to either of:
#
# np.array([[{2}, {3}], [{}, {}]])
#
# collections.OrderedDict([
#     ((0, 0, 0), 2),
#     ((0, 1, 0), 3),
# ])

 Args
  a   Tensor or SparseTensor of the same type as b. If sparse, indices must be sorted in row-major order.
  b   Tensor or SparseTensor of the same type as a. If sparse, indices must be sorted in row-major order.
  aminusb   Whether to subtract b from a, vs vice versa.
  validate_indices   Whether to validate the order and range of sparse indices in a and b.

 Returns   A SparseTensor whose shape is the same rank as a and b, and all but the last dimension the same. Elements along the last dimension contain the differences.

 Raises
  TypeError   If inputs are invalid types, or if a and b have different types.
  ValueError   If a is sparse and b is dense.
  errors_impl.InvalidArgumentError   If the shapes of a and b do not match in any dimension other than the last dimension.


tf.sets.intersection     View source on GitHub    Compute set intersection of elements in last dimension of a and b.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.sets.intersection, tf.compat.v1.sets.set_intersection
tf.sets.intersection(
    a, b, validate_indices=True
)
 All but the last dimension of a and b must match. Example: import tensorflow as tf
import collections

# Represent the following array of sets as a sparse tensor:
# a = np.array([[{1, 2}, {3}], [{4}, {5, 6}]])
a = collections.OrderedDict([
    ((0, 0, 0), 1),
    ((0, 0, 1), 2),
    ((0, 1, 0), 3),
    ((1, 0, 0), 4),
    ((1, 1, 0), 5),
    ((1, 1, 1), 6),
])
a = tf.sparse.SparseTensor(list(a.keys()), list(a.values()),
                           dense_shape=[2,2,2])

# b = np.array([[{1}, {}], [{4}, {5, 6, 7, 8}]])
b = collections.OrderedDict([
    ((0, 0, 0), 1),
    ((1, 0, 0), 4),
    ((1, 1, 0), 5),
    ((1, 1, 1), 6),
    ((1, 1, 2), 7),
    ((1, 1, 3), 8),
])
b = tf.sparse.SparseTensor(list(b.keys()), list(b.values()),
                           dense_shape=[2, 2, 4])

# `tf.sets.intersection` is applied to each aligned pair of sets.
tf.sets.intersection(a, b)

# The result will be equivalent to either of:
#
# np.array([[{1}, {}], [{4}, {5, 6}]])
#
# collections.OrderedDict([
#     ((0, 0, 0), 1),
#     ((1, 0, 0), 4),
#     ((1, 1, 0), 5),
#     ((1, 1, 1), 6),
# ])

 Args
  a   Tensor or SparseTensor of the same type as b. If sparse, indices must be sorted in row-major order.
  b   Tensor or SparseTensor of the same type as a. If sparse, indices must be sorted in row-major order.
  validate_indices   Whether to validate the order and range of sparse indices in a and b.

 Returns   A SparseTensor whose shape is the same rank as a and b, and all but the last dimension the same. Elements along the last dimension contain the intersections.


tf.sets.size     View source on GitHub    Compute number of unique elements along last dimension of a.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.sets.set_size, tf.compat.v1.sets.size
tf.sets.size(
    a, validate_indices=True
)

 Args
  a   SparseTensor, with indices sorted in row-major order.
  validate_indices   Whether to validate the order and range of sparse indices in a.

 Returns   int32 Tensor of set sizes. For a ranked n, this is a Tensor with rank n-1, and the same 1st n-1 dimensions as a. Each value is the number of unique elements in the corresponding [0...n-1] dimension of a.

 Raises
  TypeError   If a is an invalid types.


tf.sets.union     View source on GitHub    Compute set union of elements in last dimension of a and b.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.sets.set_union, tf.compat.v1.sets.union
tf.sets.union(
    a, b, validate_indices=True
)
 All but the last dimension of a and b must match. Example: import tensorflow as tf
import collections

# [[{1, 2}, {3}], [{4}, {5, 6}]]
a = collections.OrderedDict([
    ((0, 0, 0), 1),
    ((0, 0, 1), 2),
    ((0, 1, 0), 3),
    ((1, 0, 0), 4),
    ((1, 1, 0), 5),
    ((1, 1, 1), 6),
])
a = tf.sparse.SparseTensor(list(a.keys()), list(a.values()),
                           dense_shape=[2, 2, 2])

# [[{1, 3}, {2}], [{4, 5}, {5, 6, 7, 8}]]
b = collections.OrderedDict([
    ((0, 0, 0), 1),
    ((0, 0, 1), 3),
    ((0, 1, 0), 2),
    ((1, 0, 0), 4),
    ((1, 0, 1), 5),
    ((1, 1, 0), 5),
    ((1, 1, 1), 6),
    ((1, 1, 2), 7),
    ((1, 1, 3), 8),
])
b = tf.sparse.SparseTensor(list(b.keys()), list(b.values()),
                           dense_shape=[2, 2, 4])

# `set_union` is applied to each aligned pair of sets.
tf.sets.union(a, b)

# The result will be a equivalent to either of:
#
# np.array([[{1, 2, 3}, {2, 3}], [{4, 5}, {5, 6, 7, 8}]])
#
# collections.OrderedDict([
#     ((0, 0, 0), 1),
#     ((0, 0, 1), 2),
#     ((0, 0, 2), 3),
#     ((0, 1, 0), 2),
#     ((0, 1, 1), 3),
#     ((1, 0, 0), 4),
#     ((1, 0, 1), 5),
#     ((1, 1, 0), 5),
#     ((1, 1, 1), 6),
#     ((1, 1, 2), 7),
#     ((1, 1, 3), 8),
# ])

 Args
  a   Tensor or SparseTensor of the same type as b. If sparse, indices must be sorted in row-major order.
  b   Tensor or SparseTensor of the same type as a. If sparse, indices must be sorted in row-major order.
  validate_indices   Whether to validate the order and range of sparse indices in a and b.

 Returns   A SparseTensor whose shape is the same rank as a and b, and all but the last dimension the same. Elements along the last dimension contain the unions.


tf.shape     View source on GitHub    Returns a tensor containing the shape of the input tensor.
tf.shape(
    input, out_type=tf.dtypes.int32, name=None
)
 See also tf.size, tf.rank. tf.shape returns a 1-D integer tensor representing the shape of input. For a scalar input, the tensor returned has a shape of (0,) and its value is the empty vector (i.e. []). For example:
tf.shape(1.)
<tf.Tensor: shape=(0,), dtype=int32, numpy=array([], dtype=int32)>

t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]])
tf.shape(t)
<tf.Tensor: shape=(3,), dtype=int32, numpy=array([2, 2, 3], dtype=int32)>

Note: When using symbolic tensors, such as when using the Keras API, tf.shape() will return the shape of the symbolic tensor.

a = tf.keras.layers.Input((None, 10))
tf.shape(a)
<... shape=(3,) dtype=int32...>
 In these cases, using tf.Tensor.shape will return more informative results.
a.shape
TensorShape([None, None, 10])
 (The first None represents the as yet unknown batch size.) tf.shape and Tensor.shape should be identical in eager mode. Within tf.function or within a compat.v1 context, not all dimensions may be known until execution time. Hence when defining custom layers and models for graph mode, prefer the dynamic tf.shape(x) over the static x.shape.

 Args
  input   A Tensor or SparseTensor.
  out_type   (Optional) The specified output type of the operation (int32 or int64). Defaults to tf.int32.
  name   A name for the operation (optional).

 Returns   A Tensor of type out_type.


tf.shape_n     View source on GitHub    Returns shape of tensors.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.shape_n
tf.shape_n(
    input, out_type=tf.dtypes.int32, name=None
)

 Args
  input   A list of at least 1 Tensor object with the same type.
  out_type   The specified output type of the operation (int32 or int64). Defaults to tf.int32(optional).
  name   A name for the operation (optional).

 Returns   A list with the same length as input of Tensor objects with type out_type.


Module: tf.signal Signal processing operations. See the tf.signal guide. Functions dct(...): Computes the 1D [Discrete Cosine Transform (DCT)][dct] of input. fft(...): Fast Fourier transform. fft2d(...): 2D fast Fourier transform. fft3d(...): 3D fast Fourier transform. fftshift(...): Shift the zero-frequency component to the center of the spectrum. frame(...): Expands signal's axis dimension into frames of frame_length. hamming_window(...): Generate a Hamming window. hann_window(...): Generate a Hann window. idct(...): Computes the 1D [Inverse Discrete Cosine Transform (DCT)][idct] of input. ifft(...): Inverse fast Fourier transform. ifft2d(...): Inverse 2D fast Fourier transform. ifft3d(...): Inverse 3D fast Fourier transform. ifftshift(...): The inverse of fftshift. inverse_mdct(...): Computes the inverse modified DCT of mdcts. inverse_stft(...): Computes the inverse Short-time Fourier Transform of stfts. inverse_stft_window_fn(...): Generates a window function that can be used in inverse_stft. irfft(...): Inverse real-valued fast Fourier transform. irfft2d(...): Inverse 2D real-valued fast Fourier transform. irfft3d(...): Inverse 3D real-valued fast Fourier transform. kaiser_bessel_derived_window(...): Generate a [Kaiser Bessel derived window][kbd]. kaiser_window(...): Generate a [Kaiser window][kaiser]. linear_to_mel_weight_matrix(...): Returns a matrix to warp linear scale spectrograms to the mel scale. mdct(...): Computes the [Modified Discrete Cosine Transform][mdct] of signals. mfccs_from_log_mel_spectrograms(...): Computes MFCCs of log_mel_spectrograms. overlap_and_add(...): Reconstructs a signal from a framed representation. rfft(...): Real-valued fast Fourier transform. rfft2d(...): 2D real-valued fast Fourier transform. rfft3d(...): 3D real-valued fast Fourier transform. stft(...): Computes the Short-time Fourier Transform of signals. vorbis_window(...): Generate a [Vorbis power complementary window][vorbis].


tf.signal.dct     View source on GitHub    Computes the 1D Discrete Cosine Transform (DCT) of input.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.dct, tf.compat.v1.spectral.dct
tf.signal.dct(
    input, type=2, n=None, axis=-1, norm=None, name=None
)
 Types I, II, III and IV are supported. Type I is implemented using a length 2N padded tf.signal.rfft. Type II is implemented using a length 2N padded tf.signal.rfft, as described here: Type 2 DCT using 2N FFT padded (Makhoul). Type III is a fairly straightforward inverse of Type II (i.e. using a length 2N padded tf.signal.irfft). Type IV is calculated through 2N length DCT2 of padded signal and picking the odd indices.

 Args
  input   A [..., samples] float32/float64 Tensor containing the signals to take the DCT of.
  type   The DCT type to perform. Must be 1, 2, 3 or 4.
  n   The length of the transform. If length is less than sequence length, only the first n elements of the sequence are considered for the DCT. If n is greater than the sequence length, zeros are padded and then the DCT is computed as usual.
  axis   For future expansion. The axis to compute the DCT along. Must be -1.
  norm   The normalization to apply. None for no normalization or 'ortho' for orthonormal normalization.
  name   An optional name for the operation.

 Returns   A [..., samples] float32/float64 Tensor containing the DCT of input.

 Raises
  ValueError   If type is not 1, 2, 3 or 4, axis is not -1, n is not None or greater than 0, or norm is not None or 'ortho'.
  ValueError   If type is 1 and norm is ortho.    Scipy Compatibility Equivalent to scipy.fftpack.dct for Type-I, Type-II, Type-III and Type-IV DCT.


tf.signal.fft Fast Fourier transform.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.fft, tf.compat.v1.signal.fft, tf.compat.v1.spectral.fft
tf.signal.fft(
    input, name=None
)
 Computes the 1-dimensional discrete Fourier transform over the inner-most dimension of input.

 Args
  input   A Tensor. Must be one of the following types: complex64, complex128. A complex tensor.
  name   A name for the operation (optional).

 Returns   A Tensor. Has the same type as input.


tf.signal.fft2d 2D fast Fourier transform.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.fft2d, tf.compat.v1.signal.fft2d, tf.compat.v1.spectral.fft2d
tf.signal.fft2d(
    input, name=None
)
 Computes the 2-dimensional discrete Fourier transform over the inner-most 2 dimensions of input.

 Args
  input   A Tensor. Must be one of the following types: complex64, complex128. A complex tensor.
  name   A name for the operation (optional).

 Returns   A Tensor. Has the same type as input.


tf.signal.fft3d 3D fast Fourier transform.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.fft3d, tf.compat.v1.signal.fft3d, tf.compat.v1.spectral.fft3d
tf.signal.fft3d(
    input, name=None
)
 Computes the 3-dimensional discrete Fourier transform over the inner-most 3 dimensions of input.

 Args
  input   A Tensor. Must be one of the following types: complex64, complex128. A complex tensor.
  name   A name for the operation (optional).

 Returns   A Tensor. Has the same type as input.


tf.signal.fftshift     View source on GitHub    Shift the zero-frequency component to the center of the spectrum.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.fftshift
tf.signal.fftshift(
    x, axes=None, name=None
)
 This function swaps half-spaces for all axes listed (defaults to all). Note that y[0] is the Nyquist component only if len(x) is even. For example: x = tf.signal.fftshift([ 0.,  1.,  2.,  3.,  4., -5., -4., -3., -2., -1.])
x.numpy() # array([-5., -4., -3., -2., -1.,  0.,  1.,  2.,  3.,  4.])

 Args
  x   Tensor, input tensor.
  axes   int or shape tuple, optional Axes over which to shift. Default is None, which shifts all axes.
  name   An optional name for the operation.

 Returns   A Tensor, The shifted tensor.
 Numpy Compatibility Equivalent to numpy.fft.fftshift. https://docs.scipy.org/doc/numpy/reference/generated/numpy.fft.fftshift.html


tf.signal.frame     View source on GitHub    Expands signal's axis dimension into frames of frame_length.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.frame
tf.signal.frame(
    signal, frame_length, frame_step, pad_end=False, pad_value=0, axis=-1, name=None
)
 Slides a window of size frame_length over signal's axis dimension with a stride of frame_step, replacing the axis dimension with [frames, frame_length] frames. If pad_end is True, window positions that are past the end of the axis dimension are padded with pad_value until the window moves fully past the end of the dimension. Otherwise, only window positions that fully overlap the axis dimension are produced. For example:
# A batch size 3 tensor of 9152 audio samples.
audio = tf.random.normal([3, 9152])

# Compute overlapping frames of length 512 with a step of 180 (frames overlap
# by 332 samples). By default, only 49 frames are generated since a frame
# with start position j*180 for j > 48 would overhang the end.
frames = tf.signal.frame(audio, 512, 180)
frames.shape.assert_is_compatible_with([3, 49, 512])

# When pad_end is enabled, the final two frames are kept (padded with zeros).
frames = tf.signal.frame(audio, 512, 180, pad_end=True)
frames.shape.assert_is_compatible_with([3, 51, 512])
 If the dimension along axis is N, and pad_end=False, the number of frames can be computed by: num_frames = 1 + (N - frame_size) // frame_step
 If pad_end=True, the number of frames can be computed by: num_frames = -(-N // frame_step) # ceiling division

 Args
  signal   A [..., samples, ...] Tensor. The rank and dimensions may be unknown. Rank must be at least 1.
  frame_length   The frame length in samples. An integer or scalar Tensor.
  frame_step   The frame hop size in samples. An integer or scalar Tensor.
  pad_end   Whether to pad the end of signal with pad_value.
  pad_value   An optional scalar Tensor to use where the input signal does not exist when pad_end is True.
  axis   A scalar integer Tensor indicating the axis to frame. Defaults to the last axis. Supports negative values for indexing from the end.
  name   An optional name for the operation.

 Returns   A Tensor of frames with shape [..., num_frames, frame_length, ...].

 Raises
  ValueError   If frame_length, frame_step, pad_value, or axis are not scalar.


tf.signal.hamming_window     View source on GitHub    Generate a Hamming window.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.hamming_window
tf.signal.hamming_window(
    window_length, periodic=True, dtype=tf.dtypes.float32, name=None
)

 Args
  window_length   A scalar Tensor indicating the window length to generate.
  periodic   A bool Tensor indicating whether to generate a periodic or symmetric window. Periodic windows are typically used for spectral analysis while symmetric windows are typically used for digital filter design.
  dtype   The data type to produce. Must be a floating point type.
  name   An optional name for the operation.

 Returns   A Tensor of shape [window_length] of type dtype.

 Raises
  ValueError   If dtype is not a floating point type.


tf.signal.hann_window     View source on GitHub    Generate a Hann window.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.hann_window
tf.signal.hann_window(
    window_length, periodic=True, dtype=tf.dtypes.float32, name=None
)

 Args
  window_length   A scalar Tensor indicating the window length to generate.
  periodic   A bool Tensor indicating whether to generate a periodic or symmetric window. Periodic windows are typically used for spectral analysis while symmetric windows are typically used for digital filter design.
  dtype   The data type to produce. Must be a floating point type.
  name   An optional name for the operation.

 Returns   A Tensor of shape [window_length] of type dtype.

 Raises
  ValueError   If dtype is not a floating point type.


tf.signal.idct     View source on GitHub    Computes the 1D Inverse Discrete Cosine Transform (DCT) of input.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.idct, tf.compat.v1.spectral.idct
tf.signal.idct(
    input, type=2, n=None, axis=-1, norm=None, name=None
)
 Currently Types I, II, III, IV are supported. Type III is the inverse of Type II, and vice versa. Note that you must re-normalize by 1/(2n) to obtain an inverse if norm is not 'ortho'. That is: signal == idct(dct(signal)) * 0.5 / signal.shape[-1]. When norm='ortho', we have: signal == idct(dct(signal, norm='ortho'), norm='ortho').

 Args
  input   A [..., samples] float32/float64 Tensor containing the signals to take the DCT of.
  type   The IDCT type to perform. Must be 1, 2, 3 or 4.
  n   For future expansion. The length of the transform. Must be None.
  axis   For future expansion. The axis to compute the DCT along. Must be -1.
  norm   The normalization to apply. None for no normalization or 'ortho' for orthonormal normalization.
  name   An optional name for the operation.

 Returns   A [..., samples] float32/float64 Tensor containing the IDCT of input.

 Raises
  ValueError   If type is not 1, 2 or 3, n is not None,axisis not-1, ornormis notNoneor'ortho'`.    Scipy Compatibility Equivalent to scipy.fftpack.idct for Type-I, Type-II, Type-III and Type-IV DCT.


tf.signal.ifft Inverse fast Fourier transform.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.ifft, tf.compat.v1.signal.ifft, tf.compat.v1.spectral.ifft
tf.signal.ifft(
    input, name=None
)
 Computes the inverse 1-dimensional discrete Fourier transform over the inner-most dimension of input.

 Args
  input   A Tensor. Must be one of the following types: complex64, complex128. A complex tensor.
  name   A name for the operation (optional).

 Returns   A Tensor. Has the same type as input.


tf.signal.ifft2d Inverse 2D fast Fourier transform.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.ifft2d, tf.compat.v1.signal.ifft2d, tf.compat.v1.spectral.ifft2d
tf.signal.ifft2d(
    input, name=None
)
 Computes the inverse 2-dimensional discrete Fourier transform over the inner-most 2 dimensions of input.

 Args
  input   A Tensor. Must be one of the following types: complex64, complex128. A complex tensor.
  name   A name for the operation (optional).

 Returns   A Tensor. Has the same type as input.


tf.signal.ifft3d Inverse 3D fast Fourier transform.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.ifft3d, tf.compat.v1.signal.ifft3d, tf.compat.v1.spectral.ifft3d
tf.signal.ifft3d(
    input, name=None
)
 Computes the inverse 3-dimensional discrete Fourier transform over the inner-most 3 dimensions of input.

 Args
  input   A Tensor. Must be one of the following types: complex64, complex128. A complex tensor.
  name   A name for the operation (optional).

 Returns   A Tensor. Has the same type as input.


tf.signal.ifftshift     View source on GitHub    The inverse of fftshift.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.ifftshift
tf.signal.ifftshift(
    x, axes=None, name=None
)
 Although identical for even-length x, the functions differ by one sample for odd-length x. For example: x = tf.signal.ifftshift([[ 0.,  1.,  2.],[ 3.,  4., -4.],[-3., -2., -1.]])
x.numpy() # array([[ 4., -4.,  3.],[-2., -1., -3.],[ 1.,  2.,  0.]])

 Args
  x   Tensor, input tensor.
  axes   int or shape tuple Axes over which to calculate. Defaults to None, which shifts all axes.
  name   An optional name for the operation.

 Returns   A Tensor, The shifted tensor.
 Numpy Compatibility Equivalent to numpy.fft.ifftshift. https://docs.scipy.org/doc/numpy/reference/generated/numpy.fft.ifftshift.html


tf.signal.inverse_mdct Computes the inverse modified DCT of mdcts.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.inverse_mdct
tf.signal.inverse_mdct(
    mdcts, window_fn=tf.signal.vorbis_window, norm=None, name=None
)
 To reconstruct an original waveform, the same window function should be used with mdct and inverse_mdct. Example usage:
@tf.function
def compare_round_trip():
  samples = 1000
  frame_length = 400
  halflen = frame_length // 2
  waveform = tf.random.normal(dtype=tf.float32, shape=[samples])
  waveform_pad = tf.pad(waveform, [[halflen, 0],])
  mdct = tf.signal.mdct(waveform_pad, frame_length, pad_end=True,
                        window_fn=tf.signal.vorbis_window)
  inverse_mdct = tf.signal.inverse_mdct(mdct,
                                        window_fn=tf.signal.vorbis_window)
  inverse_mdct = inverse_mdct[halflen: halflen + samples]
  return waveform, inverse_mdct
waveform, inverse_mdct = compare_round_trip()
np.allclose(waveform.numpy(), inverse_mdct.numpy(), rtol=1e-3, atol=1e-4)
True
 Implemented with TPU/GPU-compatible ops and supports gradients.

 Args
  mdcts   A float32/float64 [..., frames, frame_length // 2] Tensor of MDCT bins representing a batch of frame_length // 2-point MDCTs.
  window_fn   A callable that takes a frame_length and a dtype keyword argument and returns a [frame_length] Tensor of samples in the provided datatype. If set to None, a rectangular window with a scale of 1/sqrt(2) is used. For perfect reconstruction of a signal from mdct followed by inverse_mdct, please use tf.signal.vorbis_window, tf.signal.kaiser_bessel_derived_window or None. If using another window function, make sure that w[n]^2 + w[n + frame_length // 2]^2 = 1 and w[n] = w[frame_length - n - 1] for n = 0,...,frame_length // 2 - 1 to achieve perfect reconstruction.
  norm   If "ortho", orthonormal inverse DCT4 is performed, if it is None, a regular dct4 followed by scaling of 1/frame_length is performed.
  name   An optional name for the operation.

 Returns   A [..., samples] Tensor of float32/float64 signals representing the inverse MDCT for each input MDCT in mdcts where samples is (frames - 1) * (frame_length // 2) + frame_length.

 Raises
  ValueError   If mdcts is not at least rank 2.


tf.signal.inverse_stft     View source on GitHub    Computes the inverse Short-time Fourier Transform of stfts.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.inverse_stft
tf.signal.inverse_stft(
    stfts, frame_length, frame_step, fft_length=None,
    window_fn=tf.signal.hann_window, name=None
)
 To reconstruct an original waveform, a complementary window function should be used with inverse_stft. Such a window function can be constructed with tf.signal.inverse_stft_window_fn. Example: frame_length = 400
frame_step = 160
waveform = tf.random.normal(dtype=tf.float32, shape=[1000])
stft = tf.signal.stft(waveform, frame_length, frame_step)
inverse_stft = tf.signal.inverse_stft(
    stft, frame_length, frame_step,
    window_fn=tf.signal.inverse_stft_window_fn(frame_step))
 If a custom window_fn is used with tf.signal.stft, it must be passed to tf.signal.inverse_stft_window_fn: frame_length = 400
frame_step = 160
window_fn = tf.signal.hamming_window
waveform = tf.random.normal(dtype=tf.float32, shape=[1000])
stft = tf.signal.stft(
    waveform, frame_length, frame_step, window_fn=window_fn)
inverse_stft = tf.signal.inverse_stft(
    stft, frame_length, frame_step,
    window_fn=tf.signal.inverse_stft_window_fn(
       frame_step, forward_window_fn=window_fn))
 Implemented with TPU/GPU-compatible ops and supports gradients.

 Args
  stfts   A complex64/complex128 [..., frames, fft_unique_bins] Tensor of STFT bins representing a batch of fft_length-point STFTs where fft_unique_bins is fft_length // 2 + 1
  frame_length   An integer scalar Tensor. The window length in samples.
  frame_step   An integer scalar Tensor. The number of samples to step.
  fft_length   An integer scalar Tensor. The size of the FFT that produced stfts. If not provided, uses the smallest power of 2 enclosing frame_length.
  window_fn   A callable that takes a window length and a dtype keyword argument and returns a [window_length] Tensor of samples in the provided datatype. If set to None, no windowing is used.
  name   An optional name for the operation.

 Returns   A [..., samples] Tensor of float32/float64 signals representing the inverse STFT for each input STFT in stfts.

 Raises
  ValueError   If stfts is not at least rank 2, frame_length is not scalar, frame_step is not scalar, or fft_length is not scalar.


tf.signal.inverse_stft_window_fn     View source on GitHub    Generates a window function that can be used in inverse_stft.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.inverse_stft_window_fn
tf.signal.inverse_stft_window_fn(
    frame_step, forward_window_fn=tf.signal.hann_window, name=None
)
 Constructs a window that is equal to the forward window with a further pointwise amplitude correction. inverse_stft_window_fn is equivalent to forward_window_fn in the case where it would produce an exact inverse. See examples in inverse_stft documentation for usage.

 Args
  frame_step   An integer scalar Tensor. The number of samples to step.
  forward_window_fn   window_fn used in the forward transform, stft.
  name   An optional name for the operation.

 Returns   A callable that takes a window length and a dtype keyword argument and returns a [window_length] Tensor of samples in the provided datatype. The returned window is suitable for reconstructing original waveform in inverse_stft.


tf.signal.irfft     View source on GitHub    Inverse real-valued fast Fourier transform.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.irfft, tf.compat.v1.spectral.irfft
tf.signal.irfft(
    input_tensor, fft_length=None, name=None
)
 Computes the inverse 1-dimensional discrete Fourier transform of a real-valued signal over the inner-most dimension of input. The inner-most dimension of input is assumed to be the result of RFFT: the fft_length / 2 + 1 unique components of the DFT of a real-valued signal. If fft_length is not provided, it is computed from the size of the inner-most dimension of input (fft_length = 2 * (inner - 1)). If the FFT length used to compute input is odd, it should be provided since it cannot be inferred properly. Along the axis IRFFT is computed on, if fft_length / 2 + 1 is smaller than the corresponding dimension of input, the dimension is cropped. If it is larger, the dimension is padded with zeros.

 Args
  input   A Tensor. Must be one of the following types: complex64, complex128. A complex tensor.
  fft_length   A Tensor of type int32. An int32 tensor of shape [1]. The FFT length.
  Treal   An optional tf.DType from: tf.float32, tf.float64. Defaults to tf.float32.
  name   A name for the operation (optional).

 Returns   A Tensor of type Treal.


tf.signal.irfft2d     View source on GitHub    Inverse 2D real-valued fast Fourier transform.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.irfft2d, tf.compat.v1.spectral.irfft2d
tf.signal.irfft2d(
    input_tensor, fft_length=None, name=None
)
 Computes the inverse 2-dimensional discrete Fourier transform of a real-valued signal over the inner-most 2 dimensions of input. The inner-most 2 dimensions of input are assumed to be the result of RFFT2D: The inner-most dimension contains the fft_length / 2 + 1 unique components of the DFT of a real-valued signal. If fft_length is not provided, it is computed from the size of the inner-most 2 dimensions of input. If the FFT length used to compute input is odd, it should be provided since it cannot be inferred properly. Along each axis IRFFT2D is computed on, if fft_length (or fft_length / 2 + 1 for the inner-most dimension) is smaller than the corresponding dimension of input, the dimension is cropped. If it is larger, the dimension is padded with zeros.

 Args
  input   A Tensor. Must be one of the following types: complex64, complex128. A complex tensor.
  fft_length   A Tensor of type int32. An int32 tensor of shape [2]. The FFT length for each dimension.
  Treal   An optional tf.DType from: tf.float32, tf.float64. Defaults to tf.float32.
  name   A name for the operation (optional).

 Returns   A Tensor of type Treal.


tf.signal.irfft3d     View source on GitHub    Inverse 3D real-valued fast Fourier transform.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.irfft3d, tf.compat.v1.spectral.irfft3d
tf.signal.irfft3d(
    input_tensor, fft_length=None, name=None
)
 Computes the inverse 3-dimensional discrete Fourier transform of a real-valued signal over the inner-most 3 dimensions of input. The inner-most 3 dimensions of input are assumed to be the result of RFFT3D: The inner-most dimension contains the fft_length / 2 + 1 unique components of the DFT of a real-valued signal. If fft_length is not provided, it is computed from the size of the inner-most 3 dimensions of input. If the FFT length used to compute input is odd, it should be provided since it cannot be inferred properly. Along each axis IRFFT3D is computed on, if fft_length (or fft_length / 2 + 1 for the inner-most dimension) is smaller than the corresponding dimension of input, the dimension is cropped. If it is larger, the dimension is padded with zeros.

 Args
  input   A Tensor. Must be one of the following types: complex64, complex128. A complex tensor.
  fft_length   A Tensor of type int32. An int32 tensor of shape [3]. The FFT length for each dimension.
  Treal   An optional tf.DType from: tf.float32, tf.float64. Defaults to tf.float32.
  name   A name for the operation (optional).

 Returns   A Tensor of type Treal.


tf.signal.kaiser_bessel_derived_window Generate a Kaiser Bessel derived window.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.kaiser_bessel_derived_window
tf.signal.kaiser_bessel_derived_window(
    window_length, beta=12.0, dtype=tf.dtypes.float32, name=None
)

 Args
  window_length   A scalar Tensor indicating the window length to generate.
  beta   Beta parameter for Kaiser window.
  dtype   The data type to produce. Must be a floating point type.
  name   An optional name for the operation.

 Returns   A Tensor of shape [window_length] of type dtype.


tf.signal.kaiser_window Generate a Kaiser window.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.kaiser_window
tf.signal.kaiser_window(
    window_length, beta=12.0, dtype=tf.dtypes.float32, name=None
)

 Args
  window_length   A scalar Tensor indicating the window length to generate.
  beta   Beta parameter for Kaiser window, see reference below.
  dtype   The data type to produce. Must be a floating point type.
  name   An optional name for the operation.

 Returns   A Tensor of shape [window_length] of type dtype.


tf.signal.linear_to_mel_weight_matrix       View source on GitHub    Returns a matrix to warp linear scale spectrograms to the mel scale.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.linear_to_mel_weight_matrix
tf.signal.linear_to_mel_weight_matrix(
    num_mel_bins=20, num_spectrogram_bins=129, sample_rate=8000,
    lower_edge_hertz=125.0, upper_edge_hertz=3800.0, dtype=tf.dtypes.float32,
    name=None
)
 Returns a weight matrix that can be used to re-weight a Tensor containing num_spectrogram_bins linearly sampled frequency information from [0, sample_rate / 2] into num_mel_bins frequency information from [lower_edge_hertz, upper_edge_hertz] on the mel scale. This function follows the Hidden Markov Model Toolkit (HTK) convention, defining the mel scale in terms of a frequency in hertz according to the following formula:  $$ extrm{mel}(f) = 2595 * extrm{log}_{10}(1 + rac{f}{700})$$  In the returned matrix, all the triangles (filterbanks) have a peak value of 1.0. For example, the returned matrix A can be used to right-multiply a spectrogram S of shape [frames, num_spectrogram_bins] of linear scale spectrum values (e.g. STFT magnitudes) to generate a "mel spectrogram" M of shape [frames, num_mel_bins]. # `S` has shape [frames, num_spectrogram_bins]
# `M` has shape [frames, num_mel_bins]
M = tf.matmul(S, A)
 The matrix can be used with tf.tensordot to convert an arbitrary rank Tensor of linear-scale spectral bins into the mel scale. # S has shape [..., num_spectrogram_bins].
# M has shape [..., num_mel_bins].
M = tf.tensordot(S, A, 1)

 Args
  num_mel_bins   Python int. How many bands in the resulting mel spectrum.
  num_spectrogram_bins   An integer Tensor. How many bins there are in the source spectrogram data, which is understood to be fft_size // 2 + 1, i.e. the spectrogram only contains the nonredundant FFT bins.
  sample_rate   An integer or float Tensor. Samples per second of the input signal used to create the spectrogram. Used to figure out the frequencies corresponding to each spectrogram bin, which dictates how they are mapped into the mel scale.
  lower_edge_hertz   Python float. Lower bound on the frequencies to be included in the mel spectrum. This corresponds to the lower edge of the lowest triangular band.
  upper_edge_hertz   Python float. The desired top edge of the highest frequency band.
  dtype   The DType of the result matrix. Must be a floating point type.
  name   An optional name for the operation.

 Returns   A Tensor of shape [num_spectrogram_bins, num_mel_bins].

 Raises
  ValueError   If num_mel_bins/num_spectrogram_bins/sample_rate are not positive, lower_edge_hertz is negative, frequency edges are incorrectly ordered, upper_edge_hertz is larger than the Nyquist frequency.


tf.signal.mdct Computes the Modified Discrete Cosine Transform of signals.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.mdct
tf.signal.mdct(
    signals, frame_length, window_fn=tf.signal.vorbis_window, pad_end=False,
    norm=None, name=None
)
 Implemented with TPU/GPU-compatible ops and supports gradients.

 Args
  signals   A [..., samples] float32/float64 Tensor of real-valued signals.
  frame_length   An integer scalar Tensor. The window length in samples which must be divisible by 4.
  window_fn   A callable that takes a frame_length and a dtype keyword argument and returns a [frame_length] Tensor of samples in the provided datatype. If set to None, a rectangular window with a scale of 1/sqrt(2) is used. For perfect reconstruction of a signal from mdct followed by inverse_mdct, please use tf.signal.vorbis_window, tf.signal.kaiser_bessel_derived_window or None. If using another window function, make sure that w[n]^2 + w[n + frame_length // 2]^2 = 1 and w[n] = w[frame_length - n - 1] for n = 0,...,frame_length // 2 - 1 to achieve perfect reconstruction.
  pad_end   Whether to pad the end of signals with zeros when the provided frame length and step produces a frame that lies partially past its end.
  norm   If it is None, unnormalized dct4 is used, if it is "ortho" orthonormal dct4 is used.
  name   An optional name for the operation.

 Returns   A [..., frames, frame_length // 2] Tensor of float32/float64 MDCT values where frames is roughly samples // (frame_length // 2) when pad_end=False.

 Raises
  ValueError   If signals is not at least rank 1, frame_length is not scalar, or frame_length is not a multiple of 4.


tf.signal.mfccs_from_log_mel_spectrograms     View source on GitHub    Computes MFCCs of log_mel_spectrograms.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.mfccs_from_log_mel_spectrograms
tf.signal.mfccs_from_log_mel_spectrograms(
    log_mel_spectrograms, name=None
)
 Implemented with GPU-compatible ops and supports gradients. Mel-Frequency Cepstral Coefficient (MFCC) calculation consists of taking the DCT-II of a log-magnitude mel-scale spectrogram. HTK's MFCCs use a particular scaling of the DCT-II which is almost orthogonal normalization. We follow this convention. All num_mel_bins MFCCs are returned and it is up to the caller to select a subset of the MFCCs based on their application. For example, it is typical to only use the first few for speech recognition, as this results in an approximately pitch-invariant representation of the signal. For example: batch_size, num_samples, sample_rate = 32, 32000, 16000.0
# A Tensor of [batch_size, num_samples] mono PCM samples in the range [-1, 1].
pcm = tf.random.normal([batch_size, num_samples], dtype=tf.float32)

# A 1024-point STFT with frames of 64 ms and 75% overlap.
stfts = tf.signal.stft(pcm, frame_length=1024, frame_step=256,
                       fft_length=1024)
spectrograms = tf.abs(stfts)

# Warp the linear scale spectrograms into the mel-scale.
num_spectrogram_bins = stfts.shape[-1].value
lower_edge_hertz, upper_edge_hertz, num_mel_bins = 80.0, 7600.0, 80
linear_to_mel_weight_matrix = tf.signal.linear_to_mel_weight_matrix(
  num_mel_bins, num_spectrogram_bins, sample_rate, lower_edge_hertz,
  upper_edge_hertz)
mel_spectrograms = tf.tensordot(
  spectrograms, linear_to_mel_weight_matrix, 1)
mel_spectrograms.set_shape(spectrograms.shape[:-1].concatenate(
  linear_to_mel_weight_matrix.shape[-1:]))

# Compute a stabilized log to get log-magnitude mel-scale spectrograms.
log_mel_spectrograms = tf.math.log(mel_spectrograms + 1e-6)

# Compute MFCCs from log_mel_spectrograms and take the first 13.
mfccs = tf.signal.mfccs_from_log_mel_spectrograms(
  log_mel_spectrograms)[..., :13]

 Args
  log_mel_spectrograms   A [..., num_mel_bins] float32/float64 Tensor of log-magnitude mel-scale spectrograms.
  name   An optional name for the operation.

 Returns   A [..., num_mel_bins] float32/float64 Tensor of the MFCCs of log_mel_spectrograms.

 Raises
  ValueError   If num_mel_bins is not positive.


tf.signal.overlap_and_add     View source on GitHub    Reconstructs a signal from a framed representation.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.overlap_and_add
tf.signal.overlap_and_add(
    signal, frame_step, name=None
)
 Adds potentially overlapping frames of a signal with shape [..., frames, frame_length], offsetting subsequent frames by frame_step. The resulting tensor has shape [..., output_size] where output_size = (frames - 1) * frame_step + frame_length

 Args
  signal   A [..., frames, frame_length] Tensor. All dimensions may be unknown, and rank must be at least 2.
  frame_step   An integer or scalar Tensor denoting overlap offsets. Must be less than or equal to frame_length.
  name   An optional name for the operation.

 Returns   A Tensor with shape [..., output_size] containing the overlap-added frames of signal's inner-most two dimensions.

 Raises
  ValueError   If signal's rank is less than 2, or frame_step is not a scalar integer.


tf.signal.rfft     View source on GitHub    Real-valued fast Fourier transform.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.rfft, tf.compat.v1.spectral.rfft
tf.signal.rfft(
    input_tensor, fft_length=None, name=None
)
 Computes the 1-dimensional discrete Fourier transform of a real-valued signal over the inner-most dimension of input. Since the DFT of a real signal is Hermitian-symmetric, RFFT only returns the fft_length / 2 + 1 unique components of the FFT: the zero-frequency term, followed by the fft_length / 2 positive-frequency terms. Along the axis RFFT is computed on, if fft_length is smaller than the corresponding dimension of input, the dimension is cropped. If it is larger, the dimension is padded with zeros.

 Args
  input   A Tensor. Must be one of the following types: float32, float64. A float32 tensor.
  fft_length   A Tensor of type int32. An int32 tensor of shape [1]. The FFT length.
  Tcomplex   An optional tf.DType from: tf.complex64, tf.complex128. Defaults to tf.complex64.
  name   A name for the operation (optional).

 Returns   A Tensor of type Tcomplex.


tf.signal.rfft2d     View source on GitHub    2D real-valued fast Fourier transform.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.rfft2d, tf.compat.v1.spectral.rfft2d
tf.signal.rfft2d(
    input_tensor, fft_length=None, name=None
)
 Computes the 2-dimensional discrete Fourier transform of a real-valued signal over the inner-most 2 dimensions of input. Since the DFT of a real signal is Hermitian-symmetric, RFFT2D only returns the fft_length / 2 + 1 unique components of the FFT for the inner-most dimension of output: the zero-frequency term, followed by the fft_length / 2 positive-frequency terms. Along each axis RFFT2D is computed on, if fft_length is smaller than the corresponding dimension of input, the dimension is cropped. If it is larger, the dimension is padded with zeros.

 Args
  input   A Tensor. Must be one of the following types: float32, float64. A float32 tensor.
  fft_length   A Tensor of type int32. An int32 tensor of shape [2]. The FFT length for each dimension.
  Tcomplex   An optional tf.DType from: tf.complex64, tf.complex128. Defaults to tf.complex64.
  name   A name for the operation (optional).

 Returns   A Tensor of type Tcomplex.


tf.signal.rfft3d     View source on GitHub    3D real-valued fast Fourier transform.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.rfft3d, tf.compat.v1.spectral.rfft3d
tf.signal.rfft3d(
    input_tensor, fft_length=None, name=None
)
 Computes the 3-dimensional discrete Fourier transform of a real-valued signal over the inner-most 3 dimensions of input. Since the DFT of a real signal is Hermitian-symmetric, RFFT3D only returns the fft_length / 2 + 1 unique components of the FFT for the inner-most dimension of output: the zero-frequency term, followed by the fft_length / 2 positive-frequency terms. Along each axis RFFT3D is computed on, if fft_length is smaller than the corresponding dimension of input, the dimension is cropped. If it is larger, the dimension is padded with zeros.

 Args
  input   A Tensor. Must be one of the following types: float32, float64. A float32 tensor.
  fft_length   A Tensor of type int32. An int32 tensor of shape [3]. The FFT length for each dimension.
  Tcomplex   An optional tf.DType from: tf.complex64, tf.complex128. Defaults to tf.complex64.
  name   A name for the operation (optional).

 Returns   A Tensor of type Tcomplex.


tf.signal.stft     View source on GitHub    Computes the Short-time Fourier Transform of signals.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.stft
tf.signal.stft(
    signals, frame_length, frame_step, fft_length=None,
    window_fn=tf.signal.hann_window, pad_end=False, name=None
)
 Implemented with TPU/GPU-compatible ops and supports gradients.

 Args
  signals   A [..., samples] float32/float64 Tensor of real-valued signals.
  frame_length   An integer scalar Tensor. The window length in samples.
  frame_step   An integer scalar Tensor. The number of samples to step.
  fft_length   An integer scalar Tensor. The size of the FFT to apply. If not provided, uses the smallest power of 2 enclosing frame_length.
  window_fn   A callable that takes a window length and a dtype keyword argument and returns a [window_length] Tensor of samples in the provided datatype. If set to None, no windowing is used.
  pad_end   Whether to pad the end of signals with zeros when the provided frame length and step produces a frame that lies partially past its end.
  name   An optional name for the operation.

 Returns   A [..., frames, fft_unique_bins] Tensor of complex64/complex128 STFT values where fft_unique_bins is fft_length // 2 + 1 (the unique components of the FFT).

 Raises
  ValueError   If signals is not at least rank 1, frame_length is not scalar, or frame_step is not scalar.


tf.signal.vorbis_window Generate a Vorbis power complementary window.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.vorbis_window
tf.signal.vorbis_window(
    window_length, dtype=tf.dtypes.float32, name=None
)

 Args
  window_length   A scalar Tensor indicating the window length to generate.
  dtype   The data type to produce. Must be a floating point type.
  name   An optional name for the operation.

 Returns   A Tensor of shape [window_length] of type dtype.


tf.size     View source on GitHub    Returns the size of a tensor.
tf.size(
    input, out_type=tf.dtypes.int32, name=None
)
 See also tf.shape. Returns a 0-D Tensor representing the number of elements in input of type out_type. Defaults to tf.int32. For example:
t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]])
tf.size(t)
<tf.Tensor: shape=(), dtype=int32, numpy=12>

 Args
  input   A Tensor or SparseTensor.
  name   A name for the operation (optional).
  out_type   (Optional) The specified non-quantized numeric output type of the operation. Defaults to tf.int32.

 Returns   A Tensor of type out_type. Defaults to tf.int32.
 Numpy Compatibility Equivalent to np.size()


tf.slice     View source on GitHub    Extracts a slice from a tensor.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.slice
tf.slice(
    input_, begin, size, name=None
)
 See also tf.strided_slice. This operation extracts a slice of size size from a tensor input_ starting at the location specified by begin. The slice size is represented as a tensor shape, where size[i] is the number of elements of the 'i'th dimension of input_ that you want to slice. The starting location (begin) for the slice is represented as an offset in each dimension of input_. In other words, begin[i] is the offset into the i'th dimension of input_ that you want to slice from. Note that tf.Tensor.getitem is typically a more pythonic way to perform slices, as it allows you to write foo[3:7, :-2] instead of tf.slice(foo, [3, 0], [4, foo.get_shape()[1]-2]). begin is zero-based; size is one-based. If size[i] is -1, all remaining elements in dimension i are included in the slice. In other words, this is equivalent to setting: size[i] = input_.dim_size(i) - begin[i] This operation requires that: 0 <= begin[i] <= begin[i] + size[i] <= Di for i in [0, n] For example: t = tf.constant([[[1, 1, 1], [2, 2, 2]],
                 [[3, 3, 3], [4, 4, 4]],
                 [[5, 5, 5], [6, 6, 6]]])
tf.slice(t, [1, 0, 0], [1, 1, 3])  # [[[3, 3, 3]]]
tf.slice(t, [1, 0, 0], [1, 2, 3])  # [[[3, 3, 3],
                                   #   [4, 4, 4]]]
tf.slice(t, [1, 0, 0], [2, 1, 3])  # [[[3, 3, 3]],
                                   #  [[5, 5, 5]]]

 Args
  input_   A Tensor.
  begin   An int32 or int64 Tensor.
  size   An int32 or int64 Tensor.
  name   A name for the operation (optional).

 Returns   A Tensor the same type as input_.


tf.sort     View source on GitHub    Sorts a tensor.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.sort
tf.sort(
    values, axis=-1, direction='ASCENDING', name=None
)
 Usage: import tensorflow as tf
a = [1, 10, 26.9, 2.8, 166.32, 62.3]
b = tf.sort(a,axis=-1,direction='ASCENDING',name=None)
c = tf.keras.backend.eval(b)
# Here, c = [  1.     2.8   10.    26.9   62.3  166.32]

 Args
  values   1-D or higher numeric Tensor.
  axis   The axis along which to sort. The default is -1, which sorts the last axis.
  direction   The direction in which to sort the values ('ASCENDING' or 'DESCENDING').
  name   Optional name for the operation.

 Returns   A Tensor with the same dtype and shape as values, with the elements sorted along the given axis.

 Raises
  ValueError   If axis is not a constant scalar, or the direction is invalid.