A Reader that outputs the records from a TensorFlow Records file.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.TFRecordReaderV2


Creates a dataset that uses a custom thread pool to compute input_dataset.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.ThreadPoolDataset


Creates a dataset that uses a custom thread pool to compute input_dataset.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.ThreadPoolHandle


Generates labels for candidate sampling with a learned unigram distribution.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.ThreadUnsafeUnigramCandidateSampler
See explanations of candidate sampling and the data formats at go/candidate-sampling.
For each batch, this op picks a single set of sampled candidate labels.
The advantages of sampling candidates per-batch are simplicity and the possibility of efficient dense matrix multiplication. The disadvantage is that the sampled candidates must be chosen independently of the context and of the true labels.


Constructs a tensor by tiling a given tensor.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.Tile
This operation creates a new tensor by replicating input multiples times. The output tensor's i'th dimension has input.dims(i) * multiples[i] elements, and the values of input are replicated multiples[i] times along the 'i'th dimension. For example, tiling [a b c d] by [2] produces [a b c d a b c d].


Returns the gradient of Tile.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.TileGrad
Since Tile takes an input and repeats the input multiples times along each dimension, TileGrad takes in multiples and aggregates each repeated tile of input into output.


Provides the time since epoch in seconds.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.Timestamp
Returns the timestamp as a float64 for seconds since the Unix epoch.


Converts a tensor to a scalar predicate.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.ToBool
Converts a tensor to a scalar predicate with the following rules:
For 0D tensors, truthiness is determined by comparing against a "zero" value. For numerical types it is the obvious zero. For strings it is the empty string.
For >0D tensors, truthiness is determined by looking at the number of elements. If has zero elements, then the result is false. Otherwise the result is true.
This matches the behavior of If and While for determining if a tensor counts as true/false for a branch condition.


Finds values and indices of the k largest elements for the last dimension.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.TopK
If the input is a vector (rank-1), finds the k largest entries in the vector and outputs their values and indices as vectors. Thus values[j] is the j-th largest entry in input, and its index is indices[j].
For matrices (resp. higher rank input), computes the top k entries in each row (resp. vector along the last dimension). Thus,
If two elements are equal, the lower-index element appears first.
If k varies dynamically, use TopKV2 below.


Finds values and indices of the k largest elements for the last dimension.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.TopKV2
If the input is a vector (rank-1), finds the k largest entries in the vector and outputs their values and indices as vectors. Thus values[j] is the j-th largest entry in input, and its index is indices[j].
For matrices (resp. higher rank input), computes the top k entries in each row (resp. vector along the last dimension). Thus,
If two elements are equal, the lower-index element appears first.


Returns the result of a TPU compilation.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.TPUCompilationResult
This operation returns the result of a TPU compilation as a serialized CompilationResultProto, which holds a status and an error message if an error occurred during compilation.


An op enabling differentiation of TPU Embeddings.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.TPUEmbeddingActivations
This op simply returns its first input, which is assumed to have been sliced from the Tensors returned by TPUEmbeddingDequeueActivations. The presence of this op, and its first argument being a trainable Variable, enables automatic differentiation of graphs containing embeddings via the TPU Embedding Python libraries.


A TPU core selector Op.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.TPUOrdinalSelector
This Op produces a set of TPU cores (for warm-up) or a single TPU core (for regular inference) to execute the TPU program on. The output is consumed by TPUPartitionedCall.


Calls a function placed on a specified TPU device.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.TPUPartitionedCall


Connects N inputs to an N-way replicated TPU computation.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.TPUReplicatedInput
This operation holds a replicated input to a tpu.replicate() computation subgraph. Each replicated input has the same shape and type alongside the output.
The above computation has a replicated input of two replicas.


Connects N outputs from an N-way replicated TPU computation.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.TPUReplicatedOutput
This operation holds a replicated output from a tpu.replicate() computation subgraph. Each replicated output has the same shape and type alongside the input.
The above computation has a replicated output of two replicas.


Metadata indicating how the TPU computation should be replicated.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.TPUReplicateMetadata
This operation holds the metadata common to operations of a tpu.replicate() computation subgraph.


Shuffle dimensions of x according to a permutation.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.Transpose
The output y has the same rank as x. The shapes of x and y satisfy: y.shape[i] == x.shape[perm[i]] for i in [0, 1, ..., rank(x) - 1]


Calculate product with tridiagonal matrix.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.TridiagonalMatMul
Calculates product of two matrices, where left matrix is a tridiagonal matrix.


Solves tridiagonal systems of equations.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.TridiagonalSolve
Solves tridiagonal systems of equations. Supports batch dimensions and multiple right-hand sides per each left-hand side. On CPU, solution is computed via Gaussian elimination with or without partial pivoting, depending on partial_pivoting attribute. On GPU, Nvidia's cuSPARSE library is used: https://docs.nvidia.com/cuda/cusparse/index.html#gtsv Partial pivoting is not yet supported by XLA backends.


Returns x / y element-wise for integer types.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.TruncateDiv
Truncation designates that negative numbers will round fractional quantities toward zero. I.e. -7 / 5 = -1. This matches C semantics but it is different than Python semantics. See FloorDiv for a division function that matches Python Semantics.


Outputs random values from a truncated normal distribution.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.TruncatedNormal
The generated values follow a normal distribution with mean 0 and standard deviation 1, except that values whose magnitude is more than 2 standard deviations from the mean are dropped and re-picked.


Returns element-wise remainder of division. This emulates C semantics in that
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.TruncateMod
the result here is consistent with a truncating divide. E.g. truncate(x / y) * y + truncate_mod(x, y) = x.


Reverses the operation of Batch for a single output Tensor.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.Unbatch
An instance of Unbatch either receives an empty batched_tensor, in which case it asynchronously waits until the values become available from a concurrently running instance of Unbatch with the same container and shared_name, or receives a non-empty batched_tensor in which case it finalizes all other concurrently running instances and outputs its own element from the batch.
batched_tensor: The possibly transformed output of Batch. The size of the first dimension should remain unchanged by the transformations for the operation to work. batch_index: The matching batch_index obtained from Batch. id: The id scalar emitted by Batch. unbatched_tensor: The Tensor corresponding to this execution. timeout_micros: Maximum amount of time (in microseconds) to wait to receive the batched input tensor associated with a given invocation of the op. container: Container to control resource sharing. shared_name: Instances of Unbatch with the same container and shared_name are assumed to possibly belong to the same batch. If left empty, the op name will be used as the shared name.


A dataset that splits the elements of its input into multiple elements.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.UnbatchDataset


Gradient of Unbatch.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.UnbatchGrad
Acts like Batch but using the given batch_index index of batching things as they become available. This ensures that the gradients are propagated back in the same session which did the forward pass.
original_input: The input to the Unbatch operation this is the gradient of. batch_index: The batch_index given to the Unbatch operation this is the gradient of. grad: The downstream gradient. id: The id scalar emitted by Batch. batched_grad: The return value, either an empty tensor or the batched gradient. container: Container to control resource sharing. shared_name: Instances of UnbatchGrad with the same container and shared_name are assumed to possibly belong to the same batch. If left empty, the op name will be used as the shared name.


Uncompresses a compressed dataset element.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.UncompressElement


Decodes each string in input into a sequence of Unicode code points.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.UnicodeDecode
The character codepoints for all strings are returned using a single vector char_values, with strings expanded to characters in row-major order.
The row_splits tensor indicates where the codepoints for each input string begin and end within the char_values tensor. In particular, the values for the ith string (in row-major order) are stored in the slice [row_splits[i]:row_splits[i+1]]. Thus:


Decodes each string in input into a sequence of Unicode code points.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.UnicodeDecodeWithOffsets
The character codepoints for all strings are returned using a single vector char_values, with strings expanded to characters in row-major order. Similarly, the character start byte offsets are returned using a single vector char_to_byte_starts, with strings expanded in row-major order.
The row_splits tensor indicates where the codepoints and start offsets for each input string begin and end within the char_values and char_to_byte_starts tensors. In particular, the values for the ith string (in row-major order) are stored in the slice [row_splits[i]:row_splits[i+1]]. Thus:


Encode a tensor of ints into unicode strings.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.UnicodeEncode
Returns a vector of strings, where output[i] is constructed by encoding the Unicode codepoints in input_values[input_splits[i]:input_splits[i+1]] using output_encoding.


Determine the script codes of a given tensor of Unicode integer code points.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.UnicodeScript
This operation converts Unicode code points to script codes corresponding to each code point. Script codes correspond to International Components for Unicode (ICU) UScriptCode values.
See ICU project docs for more details on script codes.
For an example, see the unicode strings guide on unicode scripts.
Returns -1 (USCRIPT_INVALID_CODE) for invalid codepoints. Output shape will match input shape.


Transcode the input text from a source encoding to a destination encoding.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.UnicodeTranscode
The input is a string tensor of any shape. The output is a string tensor of the same shape containing the transcoded strings. Output strings are always valid unicode. If the input contains invalid encoding positions, the errors attribute sets the policy for how to deal with them. If the default error-handling policy is used, invalid formatting will be substituted in the output by the replacement_char. If the errors policy is to ignore, any invalid encoding positions in the input are skipped and not included in the output. If it set to strict then any invalid formatting will result in an InvalidArgument error.
This operation can be used with output_encoding = input_encoding to enforce correct formatting for inputs even if they are already in the desired encoding.
If the input is prefixed by a Byte Order Mark needed to determine encoding (e.g. if the encoding is UTF-16 and the BOM indicates big-endian), then that BOM will be consumed and not emitted into the output. If the input encoding is marked with an explicit endianness (e.g. UTF-16-BE), then the BOM is interpreted as a non-breaking-space and is preserved in the output (including always for UTF-8).
The end result is that if the input is marked as an explicit endianness the transcoding is faithful to all codepoints in the source. If it is not marked with an explicit endianness, the BOM is not considered part of the string itself but as metadata, and so is not preserved in the output.
Note that for UTF-8, passing a replacement character expressible in 1 byte, such as ' ', will preserve string alignment to the source since invalid bytes will be replaced with a 1-byte replacement. For UTF-16-BE and UTF-16-LE, any 1 or 2 byte replacement character will preserve byte alignment to the source.


Generates labels for candidate sampling with a uniform distribution.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.UniformCandidateSampler
See explanations of candidate sampling and the data formats at go/candidate-sampling.
For each batch, this op picks a single set of sampled candidate labels.
The advantages of sampling candidates per-batch are simplicity and the possibility of efficient dense matrix multiplication. The disadvantage is that the sampled candidates must be chosen independently of the context and of the true labels.


Finds unique elements in a 1-D tensor.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.Unique
This operation returns a tensor y containing all of the unique elements of x sorted in the same order that they occur in x; x does not need to be sorted. This operation also returns a tensor idx the same size as x that contains the index of each value of x in the unique output y. In other words:
y[idx[i]] = x[i] for i in [0, 1,...,rank(x) - 1]


Creates a dataset that contains the unique elements of input_dataset.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.UniqueDataset


Finds unique elements along an axis of a tensor.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.UniqueV2
This operation either returns a tensor y containing unique elements along the axis of a tensor. The returned unique elements is sorted in the same order as they occur along axis in x. This operation also returns a tensor idx that is the same size as the number of the elements in x along the axis dimension. It contains the index in the unique output y. In other words, for an 1-D tensor x with `axis = None:
y[idx[i]] = x[i] for i in [0, 1,...,rank(x) - 1]
For an 2-D tensor x with axis = 0:
For an 2-D tensor x with axis = 1:


Finds unique elements in a 1-D tensor.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.UniqueWithCounts
This operation returns a tensor y containing all of the unique elements of x sorted in the same order that they occur in x. This operation also returns a tensor idx the same size as x that contains the index of each value of x in the unique output y. Finally, it returns a third tensor count that contains the count of each element of y in x. In other words:
y[idx[i]] = x[i] for i in [0, 1,...,rank(x) - 1]


Finds unique elements along an axis of a tensor.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.UniqueWithCountsV2
This operation either returns a tensor y containing unique elements along the axis of a tensor. The returned unique elements is sorted in the same order as they occur along axis in x. This operation also returns a tensor idx and a tensor count that are the same size as the number of the elements in x along the axis dimension. The idx contains the index in the unique output y and the count contains the count in the unique output y. In other words, for an 1-D tensor x with `axis = None:
y[idx[i]] = x[i] for i in [0, 1,...,rank(x) - 1]
For an 2-D tensor x with axis = 0:
For an 2-D tensor x with axis = 1:


Unpacks a given dimension of a rank-R tensor into num rank-(R-1) tensors.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.Unpack
Unpacks num tensors from value by chipping it along the axis dimension. For example, given a tensor of shape (A, B, C, D);
If axis == 0 then the i'th tensor in output is the slice value[i, :, :, :] and each tensor in output will have shape (B, C, D). (Note that the dimension unpacked along is gone, unlike split).
If axis == 1 then the i'th tensor in output is the slice value[:, i, :, :] and each tensor in output will have shape (A, C, D). Etc.
This is the opposite of pack.


Converts an array of flat indices into a tuple of coordinate arrays.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.UnravelIndex
Equivalent to np.unravel_index


Joins the elements of inputs based on segment_ids.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.UnsortedSegmentJoin
Computes the string join along segments of a tensor. Given segment_ids with rank N and data with rank N+M:
where the join is over all [j1...jN] such that segment_ids[j1...jN] = i. Strings are joined in row-major order.


Computes the maximum along segments of a tensor.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.UnsortedSegmentMax
Read the section on segmentation for an explanation of segments.
This operator is similar to the unsorted segment sum operator found (here). Instead of computing the sum over segments, it computes the maximum such that:
\(output_i = \max_{j...} data[j...]\) where max is over tuples j... such that segment_ids[j...] == i.
If the maximum is empty for a given segment ID i, it outputs the smallest possible value for the specific numeric type, output[i] = numeric_limits<T>::lowest().
If the given segment ID i is negative, then the corresponding value is dropped, and will not be included in the result.


Computes the minimum along segments of a tensor.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.UnsortedSegmentMin
Read the section on segmentation for an explanation of segments.
This operator is similar to the unsorted segment sum operator found (here). Instead of computing the sum over segments, it computes the minimum such that:
\(output_i = \min_{j...} data_[j...]\) where min is over tuples j... such that segment_ids[j...] == i.
If the minimum is empty for a given segment ID i, it outputs the largest possible value for the specific numeric type, output[i] = numeric_limits<T>::max().
If the given segment ID i is negative, then the corresponding value is dropped, and will not be included in the result.


Computes the product along segments of a tensor.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.UnsortedSegmentProd
Read the section on segmentation for an explanation of segments.
This operator is similar to the unsorted segment sum operator found (here). Instead of computing the sum over segments, it computes the product of all entries belonging to a segment such that:
\(output_i = \prod_{j...} data[j...]\) where the product is over tuples j... such that segment_ids[j...] == i.
If there is no entry for a given segment ID i, it outputs 1.
If the given segment ID i is negative, then the corresponding value is dropped, and will not be included in the result.


Computes the sum along segments of a tensor.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.UnsortedSegmentSum
Read the section on segmentation for an explanation of segments.
Computes a tensor such that \(output[i] = \sum_{j...} data[j...]\) where the sum is over tuples j... such that segment_ids[j...] == i. Unlike SegmentSum, segment_ids need not be sorted and need not cover all values in the full range of valid values.
If the sum is empty for a given segment ID i, output[i] = 0. If the given segment ID i is negative, the value is dropped and will not be added to the sum of the segment.
num_segments should equal the number of distinct segment IDs.


Op is similar to a lightweight Dequeue.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.Unstage
The basic functionality is similar to dequeue with many fewer capabilities and options. This Op is optimized for performance.


Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.UnwrapDatasetVariant


Applies upper_bound(sorted_search_values, values) along each row.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.UpperBound
Each set of rows with the same index in (sorted_inputs, values) is treated independently. The resulting row is the equivalent of calling np.searchsorted(sorted_inputs, values, side='right').
The result is not a global index to the entire Tensor, but rather just the index in the last dimension.
A 2-D example: sorted_sequence = [[0, 3, 9, 9, 10], [1, 2, 3, 4, 5]] values = [[2, 4, 9], [0, 2, 6]]
result = UpperBound(sorted_sequence, values)
result == [[1, 2, 4], [0, 2, 5]]


Creates a handle to a Variable resource.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.VarHandleOp


Use VariableV2 instead.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.Variable


Returns the shape of the variable pointed to by resource.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.VariableShape
This operation returns a 1-D integer tensor representing the shape of input.


Holds state in the form of a tensor that persists across steps.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.VariableV2
Outputs a ref to the tensor state so it may be read or modified.
about sharing states in tensorflow.


Checks whether a resource handle-based variable has been initialized.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.VarIsInitializedOp


Returns locations of nonzero / true values in a tensor.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.Where
This operation returns the coordinates of true elements in condition. The coordinates are returned in a 2-D tensor where the first dimension (rows) represents the number of true elements, and the second dimension (columns) represents the coordinates of the true elements. Keep in mind, the shape of the output tensor can vary depending on how many true values there are in condition. Indices are output in row-major order.


output = input; While (Cond(output)) { output = Body(output) }
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.While


A Reader that outputs the entire contents of a file as a value.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.WholeFileReader
To use, enqueue filenames in a Queue. The output of ReaderRead will be a filename (key) and the contents of that file (value).


A Reader that outputs the entire contents of a file as a value.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.WholeFileReaderV2
To use, enqueue filenames in a Queue. The output of ReaderRead will be a filename (key) and the contents of that file (value).


Combines (nests of) input elements into a dataset of (nests of) windows.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.WindowDataset
A "window" is a finite dataset of flat elements of size size (or possibly fewer if there are not enough input elements to fill the window and drop_remainder evaluates to false).
The shift argument determines the number of input elements by which the window moves on each iteration. The first element in the kth window will be element
of the input dataset. In particular, the first element of the first window will always be the first element of the input dataset.
If the stride parameter is greater than 1, then each window will skip (stride - 1) input elements between each element that appears in the window. Output windows will still contain size elements regardless of the value of stride.
The stride argument determines the stride of the input elements, and the shift argument determines the shift of the window.
For example, letting {...} to represent a Dataset:
Note that when the window transformation is applied to a dataset of nested elements, it produces a dataset of nested windows.


Worker heartbeat op.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.WorkerHeartbeat
Heartbeats may be sent periodically to indicate the coordinator is still active, to retrieve the current worker status and to expedite shutdown when necessary.


Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.WrapDatasetVariant


Writes an audio summary.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.WriteAudioSummary
Writes encoded audio summary tensor at step with tag using summary writer. sample_rate is the audio sample rate is Hz.


Writes contents to the file at input filename. Creates file and recursively
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.WriteFile
creates directory if not existing.


Writes a graph summary.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.WriteGraphSummary
Writes TensorFlow graph tensor at step using summary writer.


Writes a histogram summary.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.WriteHistogramSummary
Writes histogram values at step with tag using summary writer.


Writes an image summary.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.WriteImageSummary
Writes image tensor at step with tag using summary writer. tensor is image with shape [height, width, channels].


Writes a serialized proto summary.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.WriteRawProtoSummary
Writes tensor, a serialized proto at step using summary writer.


Writes a scalar summary.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.WriteScalarSummary
Writes scalar value at step with tag using summary writer.


Writes a tensor summary.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.WriteSummary
Writes tensor at step with tag using summary writer.


Returns 0 if x == 0, and x / y otherwise, elementwise.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.Xdivy


Returns 0 if x == 0, and x * log1p(y) otherwise, elementwise.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.Xlog1py


Returns 0 if x == 0, and x * log(y) otherwise, elementwise.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.Xlogy


Returns a tensor of zeros with the same shape and type as x.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.ZerosLike


Compute the Hurwitz zeta function \(\zeta(x, q)\).
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.Zeta
The Hurwitz zeta function is defined as:
\(\zeta(x, q) = \sum_{n=0}^{\infty} (q + n)^{-x}\)


Creates a dataset that zips together input_datasets.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.raw_ops.ZipDataset
The elements of the resulting dataset are created by zipping corresponding elements from each of the input datasets.
The size of the resulting dataset will match the size of the smallest input dataset, and no error will be raised if input datasets have different sizes.


Returns x / y element-wise for real types.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.realdiv
If x and y are reals, this will return the floating-point division.


An eager-compatible version of recompute_grad.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.recompute_grad
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.


A decorator for registering the gradient function for an op type.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.RegisterGradient
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:
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.
View source
Registers the function f as gradient function for op_type.


Registers a function for converting objects of base_type to Tensor.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.register_tensor_conversion_function
The conversion function must have the following signature:
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.


Repeat elements of input.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.repeat
See also tf.concat, tf.stack, tf.tile.


Calculate padding required to make block_shape divide input_shape.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.required_space_to_batch_paddings
This function can be used to calculate a suitable paddings argument for use with space_to_batch_nd and batch_to_space_nd.
paddings and crops are int32 Tensors of rank 2 and shape [N, 2]
crops[i, 0] = 0 crops[i, 1] = paddings[i, 1] - base_paddings[i, 1]
Raises: ValueError if called with incompatible shapes.


Reshapes a tensor.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.manip.reshape, tf.compat.v1.reshape
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.
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.
To instead reorder the data to rearrange the dimensions of a tensor, see tf.transpose.
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.
tf.reshape(t, []) reshapes a tensor t with one element to a scalar.


Reverses specific dimensions of a tensor.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.manip.reverse, tf.compat.v1.reverse, tf.compat.v1.reverse_v2
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.


Reverses variable length slices.
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.


Rolls the elements of a tensor along an axis.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.manip.roll, tf.compat.v1.roll
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.


Public API for tf.saved_model namespace.
experimental module: Public API for tf.saved_model.experimental namespace.
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.
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.


Represents a file asset to hermetically include in a SavedModel.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.saved_model.Asset
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.


Checks whether the provided export directory could contain a SavedModel.
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.


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


Enum defining options for variable handling when saving.
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:
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.


Load a SavedModel from export_dir.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.saved_model.load_v2
Signatures associated with the SavedModel are available as functions:
Objects exported with tf.saved_model.save additionally have trackable objects and functions assigned to attributes:
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__.
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:
.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.
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.


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


Exports the Trackable object obj to SavedModel format.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.saved_model.experimental.save, tf.compat.v1.saved_model.save
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:
Exporting from a function without a fixed signature:
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.
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.
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.


Options for saving to SavedModel.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.saved_model.SaveOptions
This function may be used in the options argument in functions that save a SavedModel (tf.saved_model.save, tf.keras.models.save_model).
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.


scan on the list of tensors unpacked from elems on dimension 0. (deprecated argument values)
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.


Scatter updates into a new tensor according to indices.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.manip.scatter_nd, tf.compat.v1.scatter_nd
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).
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:
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
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:
The resulting tensor would look like this:
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:
The resulting tensor would look like this:
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.


Searches input tensor for values on the innermost dimension.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.searchsorted
A 2-D example:


Returns a mask tensor representing the first N positions of each cell.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.sequence_mask
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


Tensorflow set operations.
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.


Compute set difference of elements in last dimension of a and b.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.sets.difference, tf.compat.v1.sets.set_difference
All but the last dimension of a and b must match.


Compute set intersection of elements in last dimension of a and b.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.sets.intersection, tf.compat.v1.sets.set_intersection
All but the last dimension of a and b must match.


Compute number of unique elements along last dimension of a.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.sets.set_size, tf.compat.v1.sets.size


Compute set union of elements in last dimension of a and b.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.sets.set_union, tf.compat.v1.sets.union
All but the last dimension of a and b must match.


Returns a tensor containing the shape of the input tensor.
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. []).
In these cases, using tf.Tensor.shape will return more informative results.
(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.


Returns shape of tensors.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.shape_n


Signal processing operations.
See the tf.signal guide.
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].


Computes the 1D Discrete Cosine Transform (DCT) of input.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.signal.dct, tf.compat.v1.spectral.dct
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.
Equivalent to scipy.fftpack.dct for Type-I, Type-II, Type-III and Type-IV DCT.


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


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


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


Shift the zero-frequency component to the center of the spectrum.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.signal.fftshift
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.
Equivalent to numpy.fft.fftshift. https://docs.scipy.org/doc/numpy/reference/generated/numpy.fft.fftshift.html


Expands signal's axis dimension into frames of frame_length.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.signal.frame
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.
If the dimension along axis is N, and pad_end=False, the number of frames can be computed by:
If pad_end=True, the number of frames can be computed by:


Generate a Hamming window.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.signal.hamming_window


Generate a Hann window.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.signal.hann_window


Computes the 1D Inverse Discrete Cosine Transform (DCT) of input.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.signal.idct, tf.compat.v1.spectral.idct
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').
Equivalent to scipy.fftpack.idct for Type-I, Type-II, Type-III and Type-IV DCT.


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


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


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


The inverse of fftshift.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.signal.ifftshift
Although identical for even-length x, the functions differ by one sample for odd-length x.
Equivalent to numpy.fft.ifftshift. https://docs.scipy.org/doc/numpy/reference/generated/numpy.fft.ifftshift.html


Computes the inverse modified DCT of mdcts.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.signal.inverse_mdct
To reconstruct an original waveform, the same window function should be used with mdct and inverse_mdct.
Implemented with TPU/GPU-compatible ops and supports gradients.


Computes the inverse Short-time Fourier Transform of stfts.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.signal.inverse_stft
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:
If a custom window_fn is used with tf.signal.stft, it must be passed to tf.signal.inverse_stft_window_fn:
Implemented with TPU/GPU-compatible ops and supports gradients.


Generates a window function that can be used in inverse_stft.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.signal.inverse_stft_window_fn
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.


Inverse real-valued fast Fourier transform.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.signal.irfft, tf.compat.v1.spectral.irfft
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.


Inverse 2D real-valued fast Fourier transform.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.signal.irfft2d, tf.compat.v1.spectral.irfft2d
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.


Inverse 3D real-valued fast Fourier transform.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.signal.irfft3d, tf.compat.v1.spectral.irfft3d
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.


Generate a Kaiser Bessel derived window.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.signal.kaiser_bessel_derived_window


Generate a Kaiser window.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.signal.kaiser_window


Returns a matrix to warp linear scale spectrograms to the mel scale.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.signal.linear_to_mel_weight_matrix
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:
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].
The matrix can be used with tf.tensordot to convert an arbitrary rank Tensor of linear-scale spectral bins into the mel scale.


Computes the Modified Discrete Cosine Transform of signals.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.signal.mdct
Implemented with TPU/GPU-compatible ops and supports gradients.


Computes MFCCs of log_mel_spectrograms.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.signal.mfccs_from_log_mel_spectrograms
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.


Reconstructs a signal from a framed representation.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.signal.overlap_and_add
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


Real-valued fast Fourier transform.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.signal.rfft, tf.compat.v1.spectral.rfft
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.


2D real-valued fast Fourier transform.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.signal.rfft2d, tf.compat.v1.spectral.rfft2d
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.


3D real-valued fast Fourier transform.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.signal.rfft3d, tf.compat.v1.spectral.rfft3d
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.


Computes the Short-time Fourier Transform of signals.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.signal.stft
Implemented with TPU/GPU-compatible ops and supports gradients.


Generate a Vorbis power complementary window.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.signal.vorbis_window


Returns the size of a tensor.
See also tf.shape.
Returns a 0-D Tensor representing the number of elements in input of type out_type. Defaults to tf.int32.
Equivalent to np.size()


Extracts a slice from a tensor.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.slice
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]


Sorts a tensor.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.sort


SpaceToBatch for N-D tensors of type T.
Main aliases
tf.nn.space_to_batch
This operation divides "spatial" dimensions [1, ..., M] of the input into a grid of blocks of shape block_shape, and interleaves these blocks with the "batch" dimension (0) such that in the output, the spatial dimensions [1, ..., M] correspond to the position within the grid, and the batch dimension combines both the position within a spatial block and the original batch position. Prior to division into blocks, the spatial dimensions of the input are optionally zero padded according to paddings. See below for a precise description.
This operation is equivalent to the following steps:
Zero-pad the start and end of dimensions [1, ..., M] of the input according to paddings to produce padded of shape padded_shape.
Reshape padded to reshaped_padded of shape:
[batch] + [padded_shape[1] / block_shape[0], block_shape[0], ..., padded_shape[M] / block_shape[M-1], block_shape[M-1]] + remaining_shape
block_shape + [batch] + [padded_shape[1] / block_shape[0], ..., padded_shape[M] / block_shape[M-1]] + remaining_shape
[batch * prod(block_shape)] + [padded_shape[1] / block_shape[0], ..., padded_shape[M] / block_shape[M-1]] + remaining_shape
Some examples:
(1) For the following input of shape [1, 2, 2, 1], block_shape = [2, 2], and paddings = [[0, 0], [0, 0]]:
The output tensor has shape [4, 1, 1, 1] and value:
(2) For the following input of shape [1, 2, 2, 3], block_shape = [2, 2], and paddings = [[0, 0], [0, 0]]:
The output tensor has shape [4, 1, 1, 3] and value:
(3) For the following input of shape [1, 4, 4, 1], block_shape = [2, 2], and paddings = [[0, 0], [0, 0]]:
The output tensor has shape [4, 2, 2, 1] and value:
(4) For the following input of shape [2, 2, 4, 1], block_shape = [2, 2], and paddings = [[0, 0], [2, 0]]:
The output tensor has shape [8, 1, 3, 1] and value:
Among others, this operation is useful for reducing atrous convolution into regular convolution.


SpaceToBatch for N-D tensors of type T.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.manip.space_to_batch_nd, tf.compat.v1.space_to_batch_nd
This operation divides "spatial" dimensions [1, ..., M] of the input into a grid of blocks of shape block_shape, and interleaves these blocks with the "batch" dimension (0) such that in the output, the spatial dimensions [1, ..., M] correspond to the position within the grid, and the batch dimension combines both the position within a spatial block and the original batch position. Prior to division into blocks, the spatial dimensions of the input are optionally zero padded according to paddings. See below for a precise description.
This operation is equivalent to the following steps:
Zero-pad the start and end of dimensions [1, ..., M] of the input according to paddings to produce padded of shape padded_shape.
Reshape padded to reshaped_padded of shape:
[batch] + [padded_shape[1] / block_shape[0], block_shape[0], ..., padded_shape[M] / block_shape[M-1], block_shape[M-1]] + remaining_shape
block_shape + [batch] + [padded_shape[1] / block_shape[0], ..., padded_shape[M] / block_shape[M-1]] + remaining_shape
[batch * prod(block_shape)] + [padded_shape[1] / block_shape[0], ..., padded_shape[M] / block_shape[M-1]] + remaining_shape
Some examples:
(1) For the following input of shape [1, 2, 2, 1], block_shape = [2, 2], and paddings = [[0, 0], [0, 0]]:
The output tensor has shape [4, 1, 1, 1] and value:
(2) For the following input of shape [1, 2, 2, 3], block_shape = [2, 2], and paddings = [[0, 0], [0, 0]]:
The output tensor has shape [4, 1, 1, 3] and value:
(3) For the following input of shape [1, 4, 4, 1], block_shape = [2, 2], and paddings = [[0, 0], [0, 0]]:
The output tensor has shape [4, 2, 2, 1] and value:
(4) For the following input of shape [2, 2, 4, 1], block_shape = [2, 2], and paddings = [[0, 0], [2, 0]]:
The output tensor has shape [8, 1, 3, 1] and value:
Among others, this operation is useful for reducing atrous convolution into regular convolution.


Sparse Tensor Representation.
See also tf.sparse.SparseTensor.
class SparseTensor: Represents a sparse tensor.
add(...): Adds two tensors, at least one of each is a SparseTensor.
bincount(...): Count the number of times an integer value appears in a tensor.
concat(...): Concatenates a list of SparseTensor along the specified dimension. (deprecated arguments)
cross(...): Generates sparse cross from a list of sparse and dense tensors.
cross_hashed(...): Generates hashed sparse cross from a list of sparse and dense tensors.
expand_dims(...): Returns a tensor with an length 1 axis inserted at index axis.
eye(...): Creates a two-dimensional sparse tensor with ones along the diagonal.
fill_empty_rows(...): Fills empty rows in the input 2-D SparseTensor with a default value.
from_dense(...): Converts a dense tensor into a sparse tensor.
map_values(...): Applies op to the .values tensor of one or more SparseTensors.
mask(...): Masks elements of IndexedSlices.
maximum(...): Returns the element-wise max of two SparseTensors.
minimum(...): Returns the element-wise min of two SparseTensors.
reduce_max(...): Computes the max of elements across dimensions of a SparseTensor.
reduce_sum(...): Computes the sum of elements across dimensions of a SparseTensor.
reorder(...): Reorders a SparseTensor into the canonical, row-major ordering.
reset_shape(...): Resets the shape of a SparseTensor with indices and values unchanged.
reshape(...): Reshapes a SparseTensor to represent values in a new dense shape.
retain(...): Retains specified non-empty values within a SparseTensor.
segment_mean(...): Computes the mean along sparse segments of a tensor.
segment_sqrt_n(...): Computes the sum along sparse segments of a tensor divided by the sqrt(N).
segment_sum(...): Computes the sum along sparse segments of a tensor.
slice(...): Slice a SparseTensor based on the start and `size.
softmax(...): Applies softmax to a batched N-D SparseTensor.
sparse_dense_matmul(...): Multiply SparseTensor (or dense Matrix) (of rank 2) "A" by dense matrix
split(...): Split a SparseTensor into num_split tensors along axis.
to_dense(...): Converts a SparseTensor into a dense tensor.
to_indicator(...): Converts a SparseTensor of ids into a dense bool indicator tensor.
transpose(...): Transposes a SparseTensor


Adds two tensors, at least one of each is a SparseTensor.
If one SparseTensor and one Tensor are passed in, returns a Tensor. If both arguments are SparseTensors, this returns a SparseTensor. The order of arguments does not matter. Use vanilla tf.add() for adding two dense Tensors.
The shapes of the two operands must match: broadcasting is not supported.
The indices of any input SparseTensor are assumed ordered in standard lexicographic order. If this is not the case, before this step run SparseReorder to restore index ordering.
If both arguments are sparse, we perform "clipping" as follows. By default, if two values sum to zero at some index, the output SparseTensor would still include that particular location in its index, storing a zero in the corresponding value slot. To override this, callers can specify threshold, indicating that if the sum has a magnitude strictly smaller than threshold, its corresponding value and index would then not be included. In particular, threshold == 0.0 (default) means everything is kept and actual thresholding happens only for a positive value.
For example, suppose the logical sum of two sparse operands is (densified):
Then,


Count the number of times an integer value appears in a tensor.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.sparse.bincount
This op takes an N-dimensional Tensor, RaggedTensor, or SparseTensor, and returns an N-dimensional int64 SparseTensor where element [i0...i[axis], j] contains the number of times the value j appears in slice [i0...i[axis], :] of the input tensor. Currently, only N=0 and N=-1 are supported.
Bin-counting every item in individual batches
This example takes an input (which could be a Tensor, RaggedTensor, or SparseTensor) and returns a SparseTensor where the value of (i,j) is the number of times value j appears in batch i.
Bin-counting with defined output shape
This example takes an input (which could be a Tensor, RaggedTensor, or SparseTensor) and returns a SparseTensor where the value of (i,j) is the number of times value j appears in batch i. However, all values of j above 'maxlength' are ignored. The dense_shape of the output sparse tensor is set to 'minlength'. Note that, while the input is identical to the example above, the value '10001' in batch item 2 is dropped, and the dense shape is [2, 500] instead of [2,10002] or [2, 102].
Binary bin-counting
This example takes an input (which could be a Tensor, RaggedTensor, or SparseTensor) and returns a SparseTensor where (i,j) is 1 if the value j appears in batch i at least once and is 0 otherwise. Note that, even though some values (like 20 in batch 1 and 11 in batch 2) appear more than once, the 'values' tensor is all 1s.
Weighted bin-counting
This example takes two inputs - a values tensor and a weights tensor. These tensors must be identically shaped, and have the same row splits or indices in the case of RaggedTensors or SparseTensors. When performing a weighted count, the op will output a SparseTensor where the value of (i, j) is the sum of the values in the weight tensor's batch i in the locations where the values tensor has the value j. In this case, the output dtype is the same as the dtype of the weights tensor.


Concatenates a list of SparseTensor along the specified dimension. (deprecated arguments)
Concatenation is with respect to the dense versions of each sparse input. It is assumed that each inputs is a SparseTensor whose elements are ordered along increasing dimension number.
If expand_nonconcat_dim is False, all inputs' shapes must match, except for the concat dimension. If expand_nonconcat_dim is True, then inputs' shapes are allowed to vary among all inputs.
The indices, values, and shapes lists must have the same length.
If expand_nonconcat_dim is False, then the output shape is identical to the inputs', except along the concat dimension, where it is the sum of the inputs' sizes along that dimension.
If expand_nonconcat_dim is True, then the output shape along the non-concat dimensions will be expand to be the largest among all inputs, and it is the sum of the inputs sizes along the concat dimension.
The output elements will be resorted to preserve the sort order along increasing dimension number.
This op runs in O(M log M) time, where M is the total number of non-empty values across all inputs. This is due to the need for an internal sort in order to concatenate efficiently across an arbitrary dimension.
For example, if axis = 1 and the inputs are
then the output will be
Graphically this is equivalent to doing
Another example, if 'axis = 1' and the inputs are
if expand_nonconcat_dim = False, this will result in an error. But if expand_nonconcat_dim = True, this will result in:
Graphically this is equivalent to doing


Generates sparse cross from a list of sparse and dense tensors.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.sparse.cross
For example, if the inputs are
then the output will be:
Customized separator "Y":


Generates hashed sparse cross from a list of sparse and dense tensors.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.sparse.cross_hashed
For example, if the inputs are
then the output will be:


Returns a tensor with an length 1 axis inserted at index axis.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.sparse.expand_dims
Given a tensor input, this operation inserts a dimension of length 1 at the dimension index axis of input's shape. The dimension index follows python indexing rules: It's zero-based, a negative index it is counted backward from the end.
This operation is useful to:
If you have a sparse tensor with shape [height, width, depth]:
You can add an outer batch axis by passing axis=0:
The new axis location matches Python list.insert(axis, 1):
Following standard python indexing rules, a negative axis counts from the end so axis=-1 adds an inner most dimension:
This operation requires that axis is a valid index for input.shape, following python indexing rules:
This operation is related to:


Creates a two-dimensional sparse tensor with ones along the diagonal.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.sparse.eye


Fills empty rows in the input 2-D SparseTensor with a default value.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.sparse.fill_empty_rows, tf.compat.v1.sparse_fill_empty_rows
This op adds entries with the specified default_value at index [row, 0] for any row in the input that does not already have a value.
For example, suppose sp_input has shape [5, 6] and non-empty values:
Rows 1 and 4 are empty, so the output will be of shape [5, 6] with values:
Note that the input may have empty columns at the end, with no effect on this op.
The output SparseTensor will be in row-major order and will have the same shape as the input.
This op also returns an indicator vector such that


Converts a dense tensor into a sparse tensor.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.sparse.from_dense
Only elements not equal to zero will be present in the result. The resulting SparseTensor has the same dtype and shape as the input.


Applies op to the .values tensor of one or more SparseTensors.
Replaces any SparseTensor in args or kwargs with its values tensor (which contains the non-default values for the SparseTensor), and then calls op. Returns a SparseTensor that is constructed from the input SparseTensors' indices, dense_shape, and the value returned by the op.
If the input arguments contain multiple SparseTensors, then they must have equal indices and dense shapes.


Masks elements of IndexedSlices.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.sparse.mask, tf.compat.v1.sparse_mask
Given an IndexedSlices instance a, returns another IndexedSlices that contains a subset of the slices of a. Only the slices at indices not specified in mask_indices are returned.
This is useful when you need to extract a subset of slices in an IndexedSlices object.


Returns the element-wise max of two SparseTensors.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.sparse.maximum, tf.compat.v1.sparse_maximum
Assumes the two SparseTensors have the same shape, i.e., no broadcasting. Example:


Returns the element-wise min of two SparseTensors.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.sparse.minimum, tf.compat.v1.sparse_minimum
Assumes the two SparseTensors have the same shape, i.e., no broadcasting. Example:


Computes the max of elements across dimensions of a SparseTensor.
This Op takes a SparseTensor and is the sparse counterpart to tf.reduce_max(). In particular, this Op also returns a dense Tensor if output_is_sparse is False, or a SparseTensor if output_is_sparse is True.
Reduces sp_input along the dimensions given in axis. Unless keepdims is true, the rank of the tensor is reduced by 1 for each entry in axis. If keepdims is true, the reduced dimensions are retained with length 1.
If axis has no entries, all dimensions are reduced, and a tensor with a single element is returned. Additionally, the axes can be negative, similar to the indexing rules in Python.
The values not defined in sp_input don't participate in the reduce max, as opposed to be implicitly assumed 0 -- hence it can return negative values for sparse axis. But, in case there are no values in axis, it will reduce to 0. See second example below.


Computes the sum of elements across dimensions of a SparseTensor.
This Op takes a SparseTensor and is the sparse counterpart to tf.reduce_sum(). In particular, this Op also returns a dense Tensor if output_is_sparse is False, or a SparseTensor if output_is_sparse is True.
Reduces sp_input along the dimensions given in axis. Unless keepdims is true, the rank of the tensor is reduced by 1 for each entry in axis. If keepdims is true, the reduced dimensions are retained with length 1.
If axis has no entries, all dimensions are reduced, and a tensor with a single element is returned. Additionally, the axes can be negative, similar to the indexing rules in Python.


Reorders a SparseTensor into the canonical, row-major ordering.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.sparse.reorder, tf.compat.v1.sparse_reorder
Note that by convention, all sparse ops preserve the canonical ordering along increasing dimension number. The only time ordering can be violated is during manual manipulation of the indices and values to add entries.
Reordering does not affect the shape of the SparseTensor.
For example, if sp_input has shape [4, 5] and indices / values:
then the output will be a SparseTensor of shape [4, 5] and indices / values:


Resets the shape of a SparseTensor with indices and values unchanged.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.sparse.reset_shape, tf.compat.v1.sparse_reset_shape
If new_shape is None, returns a copy of sp_input with its shape reset to the tight bounding box of sp_input. This will be a shape consisting of all zeros if sp_input has no values.
If new_shape is provided, then it must be larger or equal in all dimensions compared to the shape of sp_input. When this condition is met, the returned SparseTensor will have its shape reset to new_shape and its indices and values unchanged from that of sp_input.
Consider a sp_input with shape [2, 3, 5]:
It is an error to set new_shape as [3, 7] since this represents a rank-2 tensor while sp_input is rank-3. This is either a ValueError during graph construction (if both shapes are known) or an OpError during run time.
Setting new_shape as [2, 3, 6] will be fine as this shape is larger or equal in every dimension compared to the original shape [2, 3, 5].
On the other hand, setting new_shape as [2, 3, 4] is also an error: The third dimension is smaller than the original shape 2, 3, 5.
If new_shape is None, the returned SparseTensor will have a shape [2, 3, 4], which is the tight bounding box of sp_input.


Reshapes a SparseTensor to represent values in a new dense shape.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.sparse.reshape, tf.compat.v1.sparse_reshape
This operation has the same semantics as reshape on the represented dense tensor. The indices of non-empty values in sp_input are recomputed based on the new dense shape, and a new SparseTensor is returned containing the new indices and new shape. The order of non-empty values in sp_input is unchanged.
If one component of shape is the special value -1, the size of that dimension is computed so that the total dense size remains constant. At most one component of shape can be -1. The number of dense elements implied by shape must be the same as the number of dense elements originally represented by sp_input.
For example, if sp_input has shape [2, 3, 6] and indices / values:
and shape is [9, -1], then the output will be a SparseTensor of shape [9, 4] and indices / values:


Retains specified non-empty values within a SparseTensor.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.sparse.retain, tf.compat.v1.sparse_retain
For example, if sp_input has shape [4, 5] and 4 non-empty string values:
and to_retain = [True, False, False, True], then the output will be a SparseTensor of shape [4, 5] with 2 non-empty values:


Computes the mean along sparse segments of a tensor.
Read the section on segmentation for an explanation of segments.
Like tf.math.segment_mean, but segment_ids can have rank less than data's first dimension, selecting a subset of dimension 0, specified by indices. segment_ids is allowed to have missing ids, in which case the output will be zeros at those indices. In those cases num_segments is used to determine the size of the output.


Computes the sum along sparse segments of a tensor divided by the sqrt(N).
Read the section on segmentation for an explanation of segments.
Like tf.sparse.segment_mean, but instead of dividing by the size of the segment, N, divide by sqrt(N) instead.


Computes the sum along sparse segments of a tensor.
Read the section on segmentation for an explanation of segments.
Like tf.math.segment_sum, but segment_ids can have rank less than data's first dimension, selecting a subset of dimension 0, specified by indices. segment_ids is allowed to have missing ids, in which case the output will be zeros at those indices. In those cases num_segments is used to determine the size of the output.


Slice a SparseTensor based on the start and `size.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.sparse.slice, tf.compat.v1.sparse_slice
For example, if the input is
Graphically the output tensors are:


Applies softmax to a batched N-D SparseTensor.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.sparse.softmax, tf.compat.v1.sparse_softmax
The inputs represent an N-D SparseTensor with logical shape [..., B, C] (where N >= 2), and with indices sorted in the canonical lexicographic order.
This op is equivalent to applying the normal tf.nn.softmax() to each innermost logical submatrix with shape [B, C], but with the catch that the implicitly zero elements do not participate. Specifically, the algorithm is equivalent to:
(1) Applies tf.nn.softmax() to a densified view of each innermost submatrix with shape [B, C], along the size-C dimension; (2) Masks out the original implicitly-zero locations; (3) Renormalizes the remaining elements.
Hence, the SparseTensor result has exactly the same non-zero indices and shape.


Represents a sparse tensor.
Main aliases
tf.SparseTensor
See Migration guide for more details.
tf.compat.v1.SparseTensor, tf.compat.v1.sparse.SparseTensor
TensorFlow represents a sparse tensor as three separate dense tensors: indices, values, and dense_shape. In Python, the three tensors are collected into a SparseTensor class for ease of use. If you have separate indices, values, and dense_shape tensors, wrap them in a SparseTensor object before passing to the ops below.
Concretely, the sparse tensor SparseTensor(indices, values, dense_shape) comprises the following components, where N and ndims are the number of values and number of dimensions in the SparseTensor, respectively:
indices: A 2-D int64 tensor of shape [N, ndims], which specifies the indices of the elements in the sparse tensor that contain nonzero values (elements are zero-indexed). For example, indices=[[1,3], [2,4]] specifies that the elements with indexes of [1,3] and [2,4] have nonzero values.
values: A 1-D tensor of any type and shape [N], which supplies the values for each element in indices. For example, given indices=[[1,3], [2,4]], the parameter values=[18, 3.6] specifies that element [1,3] of the sparse tensor has a value of 18, and element [2,4] of the tensor has a value of 3.6.
dense_shape: A 1-D int64 tensor of shape [ndims], which specifies the dense_shape of the sparse tensor. Takes a list indicating the number of elements in each dimension. For example, dense_shape=[3,6] specifies a two-dimensional 3x6 tensor, dense_shape=[2,3,4] specifies a three-dimensional 2x3x4 tensor, and dense_shape=[9] specifies a one-dimensional tensor with 9 elements.
The corresponding dense tensor satisfies:
By convention, indices should be sorted in row-major order (or equivalently lexicographic order on the tuples indices[i]). This is not enforced when SparseTensor objects are constructed, but most ops assume correct ordering. If the ordering of sparse tensor st is wrong, a fixed version can be obtained by calling tf.sparse.reorder(st).
Example: The sparse tensor
represents the dense tensor
View source
View source
Evaluates this sparse tensor in a Session.
Calling this method will execute all preceding operations that produce the inputs needed for the operation that produces this tensor.
View source
View source
Get the TensorShape representing the shape of the dense tensor.
View source
Returns a copy of self with values replaced by new_values.
This method produces a new SparseTensor that has the same nonzero indices and same dense_shape, but updated values.
View source
Component-wise divides a SparseTensor by a dense Tensor.
Limitation: this Op only broadcasts the dense side to the sparse side, but not the other direction.
View source
Component-wise multiplies a SparseTensor by a dense Tensor.
The output locations corresponding to the implicitly zero elements in the sparse tensor will be zero (i.e., will not take up storage space), regardless of the contents of the dense tensor (even if it's +/-INF and that INF*0 == NaN).
Limitation: this Op only broadcasts the dense side to the sparse side, but not the other direction.
View source
Internal helper function for 'sp_t / dense_t'.


Multiply SparseTensor (or dense Matrix) (of rank 2) "A" by dense matrix
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.sparse.matmul, tf.compat.v1.sparse.sparse_dense_matmul, tf.compat.v1.sparse_tensor_dense_matmul
(or SparseTensor) "B". Please note that one and only one of the inputs MUST be a SparseTensor and the other MUST be a dense matrix.
No validity checking is performed on the indices of A. However, the following input format is recommended for optimal behavior:
Using tf.nn.embedding_lookup_sparse for sparse multiplication:
It's not obvious but you can consider embedding_lookup_sparse as another sparse and dense multiplication. In some situations, you may prefer to use embedding_lookup_sparse even though you're not dealing with embeddings.
There are two questions to ask in the decision process: Do you need gradients computed as sparse too? Is your sparse data represented as two SparseTensors: ids and values? There is more explanation about data format below. If you answer any of these questions as yes, consider using tf.nn.embedding_lookup_sparse.
Following explains differences between the expected SparseTensors: For example if dense form of your sparse data has shape [3, 5] and values:
SparseTensor format expected by sparse_tensor_dense_matmul: sp_a (indices, values):
SparseTensor format expected by embedding_lookup_sparse: sp_ids sp_weights
Deciding when to use sparse_tensor_dense_matmul vs. matmul(a_is_sparse=True):
There are a number of questions to ask in the decision process, including:
If the answer to several of these questions is yes, consider converting the SparseTensor to a dense one and using tf.matmul with a_is_sparse=True.
This operation tends to perform well when A is more sparse, if the column size of the product is small (e.g. matrix-vector multiplication), if sp_a.dense_shape takes on large values.
Below is a rough speed comparison between sparse_tensor_dense_matmul, labeled 'sparse', and matmul(a_is_sparse=True), labeled 'dense'. For purposes of the comparison, the time spent converting from a SparseTensor to a dense Tensor is not included, so it is overly conservative with respect to the time ratio.
CPU: Intel Ivybridge with HyperThreading (6 cores) dL1:32KB dL2:256KB dL3:12MB GPU: NVidia Tesla k40c
-c opt --config=cuda --copt=-mavx


Split a SparseTensor into num_split tensors along axis.
If the sp_input.dense_shape[axis] is not an integer multiple of num_split each slice starting from 0:shape[axis] % num_split gets extra one dimension. For example:


Converts a SparseTensor into a dense tensor.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.sparse.to_dense, tf.compat.v1.sparse_tensor_to_dense
This op is a convenience wrapper around sparse_to_dense for SparseTensors.
For example, if sp_input has shape [3, 5] and non-empty string values:
and default_value is x, then the output will be a dense [3, 5] string tensor with values:
Indices must be without repeats. This is only tested if validate_indices is True.


Converts a SparseTensor of ids into a dense bool indicator tensor.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.sparse.to_indicator, tf.compat.v1.sparse_to_indicator
The last dimension of sp_input.indices is discarded and replaced with the values of sp_input. If sp_input.dense_shape = [D0, D1, ..., Dn, K], then output.shape = [D0, D1, ..., Dn, vocab_size], where
and False elsewhere in output.
For example, if sp_input.dense_shape = [2, 3, 4] with non-empty values:
and vocab_size = 200, then the output will be a [2, 3, 200] dense bool tensor with False everywhere except at positions
Note that repeats are allowed in the input SparseTensor. This op is useful for converting SparseTensors into dense formats for compatibility with ops that expect dense tensors.
The input SparseTensor must be in row-major order.


Transposes a SparseTensor
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.sparse.transpose, tf.compat.v1.sparse_transpose
The returned tensor's dimension i will correspond to the input dimension perm[i]. If perm is not given, it is set to (n-1...0), where n is the rank of the input tensor. Hence by default, this operation performs a regular matrix transpose on 2-D input Tensors.
For example, if sp_input has shape [4, 5] and indices / values:
then the output will be a SparseTensor of shape [5, 4] and indices / values:


Type specification for a tf.sparse.SparseTensor.
Inherits From: TypeSpec
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.SparseTensorSpec
View source
View source
Returns true if spec_or_value is compatible with this TypeSpec.
View source
Returns the most specific TypeSpec compatible with self and other.
View source
Return self==value.
View source
Return self!=value.


Splits a tensor value into a list of sub tensors.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.split
See also tf.unstack.
If num_or_size_splits is an integer, then value is split along the dimension axis into num_or_size_splits smaller tensors. This requires that value.shape[axis] is divisible by num_or_size_splits.
If num_or_size_splits is a 1-D Tensor (or list), then value is split into len(num_or_size_splits) elements. The shape of the i-th element has the same size as the value except along dimension axis where the size is num_or_size_splits[i].


Removes dimensions of size 1 from the shape of a tensor.
Given a tensor input, this operation returns a tensor of the same type with all dimensions of size 1 removed. If you don't want to remove all size 1 dimensions, you can remove specific size 1 dimensions by specifying axis.
Or, to remove specific size 1 dimensions:
Unlike the older op tf.compat.v1.squeeze, this op does not accept a deprecated squeeze_dims argument.