doc_content
stringlengths 1
386k
| doc_id
stringlengths 5
188
|
---|---|
tf.signal.irfft View source on GitHub Inverse real-valued fast Fourier transform. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.irfft, tf.compat.v1.spectral.irfft
tf.signal.irfft(
input_tensor, fft_length=None, name=None
)
Computes the inverse 1-dimensional discrete Fourier transform of a real-valued signal over the inner-most dimension of input. The inner-most dimension of input is assumed to be the result of RFFT: the fft_length / 2 + 1 unique components of the DFT of a real-valued signal. If fft_length is not provided, it is computed from the size of the inner-most dimension of input (fft_length = 2 * (inner - 1)). If the FFT length used to compute input is odd, it should be provided since it cannot be inferred properly. Along the axis IRFFT is computed on, if fft_length / 2 + 1 is smaller than the corresponding dimension of input, the dimension is cropped. If it is larger, the dimension is padded with zeros.
Args
input A Tensor. Must be one of the following types: complex64, complex128. A complex tensor.
fft_length A Tensor of type int32. An int32 tensor of shape [1]. The FFT length.
Treal An optional tf.DType from: tf.float32, tf.float64. Defaults to tf.float32.
name A name for the operation (optional).
Returns A Tensor of type Treal. | tensorflow.signal.irfft |
tf.signal.irfft2d View source on GitHub Inverse 2D real-valued fast Fourier transform. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.irfft2d, tf.compat.v1.spectral.irfft2d
tf.signal.irfft2d(
input_tensor, fft_length=None, name=None
)
Computes the inverse 2-dimensional discrete Fourier transform of a real-valued signal over the inner-most 2 dimensions of input. The inner-most 2 dimensions of input are assumed to be the result of RFFT2D: The inner-most dimension contains the fft_length / 2 + 1 unique components of the DFT of a real-valued signal. If fft_length is not provided, it is computed from the size of the inner-most 2 dimensions of input. If the FFT length used to compute input is odd, it should be provided since it cannot be inferred properly. Along each axis IRFFT2D is computed on, if fft_length (or fft_length / 2 + 1 for the inner-most dimension) is smaller than the corresponding dimension of input, the dimension is cropped. If it is larger, the dimension is padded with zeros.
Args
input A Tensor. Must be one of the following types: complex64, complex128. A complex tensor.
fft_length A Tensor of type int32. An int32 tensor of shape [2]. The FFT length for each dimension.
Treal An optional tf.DType from: tf.float32, tf.float64. Defaults to tf.float32.
name A name for the operation (optional).
Returns A Tensor of type Treal. | tensorflow.signal.irfft2d |
tf.signal.irfft3d View source on GitHub Inverse 3D real-valued fast Fourier transform. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.irfft3d, tf.compat.v1.spectral.irfft3d
tf.signal.irfft3d(
input_tensor, fft_length=None, name=None
)
Computes the inverse 3-dimensional discrete Fourier transform of a real-valued signal over the inner-most 3 dimensions of input. The inner-most 3 dimensions of input are assumed to be the result of RFFT3D: The inner-most dimension contains the fft_length / 2 + 1 unique components of the DFT of a real-valued signal. If fft_length is not provided, it is computed from the size of the inner-most 3 dimensions of input. If the FFT length used to compute input is odd, it should be provided since it cannot be inferred properly. Along each axis IRFFT3D is computed on, if fft_length (or fft_length / 2 + 1 for the inner-most dimension) is smaller than the corresponding dimension of input, the dimension is cropped. If it is larger, the dimension is padded with zeros.
Args
input A Tensor. Must be one of the following types: complex64, complex128. A complex tensor.
fft_length A Tensor of type int32. An int32 tensor of shape [3]. The FFT length for each dimension.
Treal An optional tf.DType from: tf.float32, tf.float64. Defaults to tf.float32.
name A name for the operation (optional).
Returns A Tensor of type Treal. | tensorflow.signal.irfft3d |
tf.signal.kaiser_bessel_derived_window Generate a Kaiser Bessel derived window. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.kaiser_bessel_derived_window
tf.signal.kaiser_bessel_derived_window(
window_length, beta=12.0, dtype=tf.dtypes.float32, name=None
)
Args
window_length A scalar Tensor indicating the window length to generate.
beta Beta parameter for Kaiser window.
dtype The data type to produce. Must be a floating point type.
name An optional name for the operation.
Returns A Tensor of shape [window_length] of type dtype. | tensorflow.signal.kaiser_bessel_derived_window |
tf.signal.kaiser_window Generate a Kaiser window. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.kaiser_window
tf.signal.kaiser_window(
window_length, beta=12.0, dtype=tf.dtypes.float32, name=None
)
Args
window_length A scalar Tensor indicating the window length to generate.
beta Beta parameter for Kaiser window, see reference below.
dtype The data type to produce. Must be a floating point type.
name An optional name for the operation.
Returns A Tensor of shape [window_length] of type dtype. | tensorflow.signal.kaiser_window |
tf.signal.linear_to_mel_weight_matrix View source on GitHub Returns a matrix to warp linear scale spectrograms to the mel scale. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.linear_to_mel_weight_matrix
tf.signal.linear_to_mel_weight_matrix(
num_mel_bins=20, num_spectrogram_bins=129, sample_rate=8000,
lower_edge_hertz=125.0, upper_edge_hertz=3800.0, dtype=tf.dtypes.float32,
name=None
)
Returns a weight matrix that can be used to re-weight a Tensor containing num_spectrogram_bins linearly sampled frequency information from [0, sample_rate / 2] into num_mel_bins frequency information from [lower_edge_hertz, upper_edge_hertz] on the mel scale. This function follows the Hidden Markov Model Toolkit (HTK) convention, defining the mel scale in terms of a frequency in hertz according to the following formula: $$ extrm{mel}(f) = 2595 * extrm{log}_{10}(1 + rac{f}{700})$$ In the returned matrix, all the triangles (filterbanks) have a peak value of 1.0. For example, the returned matrix A can be used to right-multiply a spectrogram S of shape [frames, num_spectrogram_bins] of linear scale spectrum values (e.g. STFT magnitudes) to generate a "mel spectrogram" M of shape [frames, num_mel_bins]. # `S` has shape [frames, num_spectrogram_bins]
# `M` has shape [frames, num_mel_bins]
M = tf.matmul(S, A)
The matrix can be used with tf.tensordot to convert an arbitrary rank Tensor of linear-scale spectral bins into the mel scale. # S has shape [..., num_spectrogram_bins].
# M has shape [..., num_mel_bins].
M = tf.tensordot(S, A, 1)
Args
num_mel_bins Python int. How many bands in the resulting mel spectrum.
num_spectrogram_bins An integer Tensor. How many bins there are in the source spectrogram data, which is understood to be fft_size // 2 + 1, i.e. the spectrogram only contains the nonredundant FFT bins.
sample_rate An integer or float Tensor. Samples per second of the input signal used to create the spectrogram. Used to figure out the frequencies corresponding to each spectrogram bin, which dictates how they are mapped into the mel scale.
lower_edge_hertz Python float. Lower bound on the frequencies to be included in the mel spectrum. This corresponds to the lower edge of the lowest triangular band.
upper_edge_hertz Python float. The desired top edge of the highest frequency band.
dtype The DType of the result matrix. Must be a floating point type.
name An optional name for the operation.
Returns A Tensor of shape [num_spectrogram_bins, num_mel_bins].
Raises
ValueError If num_mel_bins/num_spectrogram_bins/sample_rate are not positive, lower_edge_hertz is negative, frequency edges are incorrectly ordered, upper_edge_hertz is larger than the Nyquist frequency. | tensorflow.signal.linear_to_mel_weight_matrix |
tf.signal.mdct Computes the Modified Discrete Cosine Transform of signals. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.mdct
tf.signal.mdct(
signals, frame_length, window_fn=tf.signal.vorbis_window, pad_end=False,
norm=None, name=None
)
Implemented with TPU/GPU-compatible ops and supports gradients.
Args
signals A [..., samples] float32/float64 Tensor of real-valued signals.
frame_length An integer scalar Tensor. The window length in samples which must be divisible by 4.
window_fn A callable that takes a frame_length and a dtype keyword argument and returns a [frame_length] Tensor of samples in the provided datatype. If set to None, a rectangular window with a scale of 1/sqrt(2) is used. For perfect reconstruction of a signal from mdct followed by inverse_mdct, please use tf.signal.vorbis_window, tf.signal.kaiser_bessel_derived_window or None. If using another window function, make sure that w[n]^2 + w[n + frame_length // 2]^2 = 1 and w[n] = w[frame_length - n - 1] for n = 0,...,frame_length // 2 - 1 to achieve perfect reconstruction.
pad_end Whether to pad the end of signals with zeros when the provided frame length and step produces a frame that lies partially past its end.
norm If it is None, unnormalized dct4 is used, if it is "ortho" orthonormal dct4 is used.
name An optional name for the operation.
Returns A [..., frames, frame_length // 2] Tensor of float32/float64 MDCT values where frames is roughly samples // (frame_length // 2) when pad_end=False.
Raises
ValueError If signals is not at least rank 1, frame_length is not scalar, or frame_length is not a multiple of 4. | tensorflow.signal.mdct |
tf.signal.mfccs_from_log_mel_spectrograms View source on GitHub Computes MFCCs of log_mel_spectrograms. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.mfccs_from_log_mel_spectrograms
tf.signal.mfccs_from_log_mel_spectrograms(
log_mel_spectrograms, name=None
)
Implemented with GPU-compatible ops and supports gradients. Mel-Frequency Cepstral Coefficient (MFCC) calculation consists of taking the DCT-II of a log-magnitude mel-scale spectrogram. HTK's MFCCs use a particular scaling of the DCT-II which is almost orthogonal normalization. We follow this convention. All num_mel_bins MFCCs are returned and it is up to the caller to select a subset of the MFCCs based on their application. For example, it is typical to only use the first few for speech recognition, as this results in an approximately pitch-invariant representation of the signal. For example: batch_size, num_samples, sample_rate = 32, 32000, 16000.0
# A Tensor of [batch_size, num_samples] mono PCM samples in the range [-1, 1].
pcm = tf.random.normal([batch_size, num_samples], dtype=tf.float32)
# A 1024-point STFT with frames of 64 ms and 75% overlap.
stfts = tf.signal.stft(pcm, frame_length=1024, frame_step=256,
fft_length=1024)
spectrograms = tf.abs(stfts)
# Warp the linear scale spectrograms into the mel-scale.
num_spectrogram_bins = stfts.shape[-1].value
lower_edge_hertz, upper_edge_hertz, num_mel_bins = 80.0, 7600.0, 80
linear_to_mel_weight_matrix = tf.signal.linear_to_mel_weight_matrix(
num_mel_bins, num_spectrogram_bins, sample_rate, lower_edge_hertz,
upper_edge_hertz)
mel_spectrograms = tf.tensordot(
spectrograms, linear_to_mel_weight_matrix, 1)
mel_spectrograms.set_shape(spectrograms.shape[:-1].concatenate(
linear_to_mel_weight_matrix.shape[-1:]))
# Compute a stabilized log to get log-magnitude mel-scale spectrograms.
log_mel_spectrograms = tf.math.log(mel_spectrograms + 1e-6)
# Compute MFCCs from log_mel_spectrograms and take the first 13.
mfccs = tf.signal.mfccs_from_log_mel_spectrograms(
log_mel_spectrograms)[..., :13]
Args
log_mel_spectrograms A [..., num_mel_bins] float32/float64 Tensor of log-magnitude mel-scale spectrograms.
name An optional name for the operation.
Returns A [..., num_mel_bins] float32/float64 Tensor of the MFCCs of log_mel_spectrograms.
Raises
ValueError If num_mel_bins is not positive. | tensorflow.signal.mfccs_from_log_mel_spectrograms |
tf.signal.overlap_and_add View source on GitHub Reconstructs a signal from a framed representation. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.overlap_and_add
tf.signal.overlap_and_add(
signal, frame_step, name=None
)
Adds potentially overlapping frames of a signal with shape [..., frames, frame_length], offsetting subsequent frames by frame_step. The resulting tensor has shape [..., output_size] where output_size = (frames - 1) * frame_step + frame_length
Args
signal A [..., frames, frame_length] Tensor. All dimensions may be unknown, and rank must be at least 2.
frame_step An integer or scalar Tensor denoting overlap offsets. Must be less than or equal to frame_length.
name An optional name for the operation.
Returns A Tensor with shape [..., output_size] containing the overlap-added frames of signal's inner-most two dimensions.
Raises
ValueError If signal's rank is less than 2, or frame_step is not a scalar integer. | tensorflow.signal.overlap_and_add |
tf.signal.rfft View source on GitHub Real-valued fast Fourier transform. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.rfft, tf.compat.v1.spectral.rfft
tf.signal.rfft(
input_tensor, fft_length=None, name=None
)
Computes the 1-dimensional discrete Fourier transform of a real-valued signal over the inner-most dimension of input. Since the DFT of a real signal is Hermitian-symmetric, RFFT only returns the fft_length / 2 + 1 unique components of the FFT: the zero-frequency term, followed by the fft_length / 2 positive-frequency terms. Along the axis RFFT is computed on, if fft_length is smaller than the corresponding dimension of input, the dimension is cropped. If it is larger, the dimension is padded with zeros.
Args
input A Tensor. Must be one of the following types: float32, float64. A float32 tensor.
fft_length A Tensor of type int32. An int32 tensor of shape [1]. The FFT length.
Tcomplex An optional tf.DType from: tf.complex64, tf.complex128. Defaults to tf.complex64.
name A name for the operation (optional).
Returns A Tensor of type Tcomplex. | tensorflow.signal.rfft |
tf.signal.rfft2d View source on GitHub 2D real-valued fast Fourier transform. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.rfft2d, tf.compat.v1.spectral.rfft2d
tf.signal.rfft2d(
input_tensor, fft_length=None, name=None
)
Computes the 2-dimensional discrete Fourier transform of a real-valued signal over the inner-most 2 dimensions of input. Since the DFT of a real signal is Hermitian-symmetric, RFFT2D only returns the fft_length / 2 + 1 unique components of the FFT for the inner-most dimension of output: the zero-frequency term, followed by the fft_length / 2 positive-frequency terms. Along each axis RFFT2D is computed on, if fft_length is smaller than the corresponding dimension of input, the dimension is cropped. If it is larger, the dimension is padded with zeros.
Args
input A Tensor. Must be one of the following types: float32, float64. A float32 tensor.
fft_length A Tensor of type int32. An int32 tensor of shape [2]. The FFT length for each dimension.
Tcomplex An optional tf.DType from: tf.complex64, tf.complex128. Defaults to tf.complex64.
name A name for the operation (optional).
Returns A Tensor of type Tcomplex. | tensorflow.signal.rfft2d |
tf.signal.rfft3d View source on GitHub 3D real-valued fast Fourier transform. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.rfft3d, tf.compat.v1.spectral.rfft3d
tf.signal.rfft3d(
input_tensor, fft_length=None, name=None
)
Computes the 3-dimensional discrete Fourier transform of a real-valued signal over the inner-most 3 dimensions of input. Since the DFT of a real signal is Hermitian-symmetric, RFFT3D only returns the fft_length / 2 + 1 unique components of the FFT for the inner-most dimension of output: the zero-frequency term, followed by the fft_length / 2 positive-frequency terms. Along each axis RFFT3D is computed on, if fft_length is smaller than the corresponding dimension of input, the dimension is cropped. If it is larger, the dimension is padded with zeros.
Args
input A Tensor. Must be one of the following types: float32, float64. A float32 tensor.
fft_length A Tensor of type int32. An int32 tensor of shape [3]. The FFT length for each dimension.
Tcomplex An optional tf.DType from: tf.complex64, tf.complex128. Defaults to tf.complex64.
name A name for the operation (optional).
Returns A Tensor of type Tcomplex. | tensorflow.signal.rfft3d |
tf.signal.stft View source on GitHub Computes the Short-time Fourier Transform of signals. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.stft
tf.signal.stft(
signals, frame_length, frame_step, fft_length=None,
window_fn=tf.signal.hann_window, pad_end=False, name=None
)
Implemented with TPU/GPU-compatible ops and supports gradients.
Args
signals A [..., samples] float32/float64 Tensor of real-valued signals.
frame_length An integer scalar Tensor. The window length in samples.
frame_step An integer scalar Tensor. The number of samples to step.
fft_length An integer scalar Tensor. The size of the FFT to apply. If not provided, uses the smallest power of 2 enclosing frame_length.
window_fn A callable that takes a window length and a dtype keyword argument and returns a [window_length] Tensor of samples in the provided datatype. If set to None, no windowing is used.
pad_end Whether to pad the end of signals with zeros when the provided frame length and step produces a frame that lies partially past its end.
name An optional name for the operation.
Returns A [..., frames, fft_unique_bins] Tensor of complex64/complex128 STFT values where fft_unique_bins is fft_length // 2 + 1 (the unique components of the FFT).
Raises
ValueError If signals is not at least rank 1, frame_length is not scalar, or frame_step is not scalar. | tensorflow.signal.stft |
tf.signal.vorbis_window Generate a Vorbis power complementary window. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.signal.vorbis_window
tf.signal.vorbis_window(
window_length, dtype=tf.dtypes.float32, name=None
)
Args
window_length A scalar Tensor indicating the window length to generate.
dtype The data type to produce. Must be a floating point type.
name An optional name for the operation.
Returns A Tensor of shape [window_length] of type dtype. | tensorflow.signal.vorbis_window |
tf.size View source on GitHub Returns the size of a tensor.
tf.size(
input, out_type=tf.dtypes.int32, name=None
)
See also tf.shape. Returns a 0-D Tensor representing the number of elements in input of type out_type. Defaults to tf.int32. For example:
t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]])
tf.size(t)
<tf.Tensor: shape=(), dtype=int32, numpy=12>
Args
input A Tensor or SparseTensor.
name A name for the operation (optional).
out_type (Optional) The specified non-quantized numeric output type of the operation. Defaults to tf.int32.
Returns A Tensor of type out_type. Defaults to tf.int32.
Numpy Compatibility Equivalent to np.size() | tensorflow.size |
tf.slice View source on GitHub Extracts a slice from a tensor. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.slice
tf.slice(
input_, begin, size, name=None
)
See also tf.strided_slice. This operation extracts a slice of size size from a tensor input_ starting at the location specified by begin. The slice size is represented as a tensor shape, where size[i] is the number of elements of the 'i'th dimension of input_ that you want to slice. The starting location (begin) for the slice is represented as an offset in each dimension of input_. In other words, begin[i] is the offset into the i'th dimension of input_ that you want to slice from. Note that tf.Tensor.getitem is typically a more pythonic way to perform slices, as it allows you to write foo[3:7, :-2] instead of tf.slice(foo, [3, 0], [4, foo.get_shape()[1]-2]). begin is zero-based; size is one-based. If size[i] is -1, all remaining elements in dimension i are included in the slice. In other words, this is equivalent to setting: size[i] = input_.dim_size(i) - begin[i] This operation requires that: 0 <= begin[i] <= begin[i] + size[i] <= Di for i in [0, n] For example: t = tf.constant([[[1, 1, 1], [2, 2, 2]],
[[3, 3, 3], [4, 4, 4]],
[[5, 5, 5], [6, 6, 6]]])
tf.slice(t, [1, 0, 0], [1, 1, 3]) # [[[3, 3, 3]]]
tf.slice(t, [1, 0, 0], [1, 2, 3]) # [[[3, 3, 3],
# [4, 4, 4]]]
tf.slice(t, [1, 0, 0], [2, 1, 3]) # [[[3, 3, 3]],
# [[5, 5, 5]]]
Args
input_ A Tensor.
begin An int32 or int64 Tensor.
size An int32 or int64 Tensor.
name A name for the operation (optional).
Returns A Tensor the same type as input_. | tensorflow.slice |
tf.sort View source on GitHub Sorts a tensor. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.sort
tf.sort(
values, axis=-1, direction='ASCENDING', name=None
)
Usage: import tensorflow as tf
a = [1, 10, 26.9, 2.8, 166.32, 62.3]
b = tf.sort(a,axis=-1,direction='ASCENDING',name=None)
c = tf.keras.backend.eval(b)
# Here, c = [ 1. 2.8 10. 26.9 62.3 166.32]
Args
values 1-D or higher numeric Tensor.
axis The axis along which to sort. The default is -1, which sorts the last axis.
direction The direction in which to sort the values ('ASCENDING' or 'DESCENDING').
name Optional name for the operation.
Returns A Tensor with the same dtype and shape as values, with the elements sorted along the given axis.
Raises
ValueError If axis is not a constant scalar, or the direction is invalid. | tensorflow.sort |
tf.space_to_batch SpaceToBatch for N-D tensors of type T. View aliases Main aliases
tf.nn.space_to_batch
tf.space_to_batch(
input, block_shape, paddings, name=None
)
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.
Args
input A Tensor. N-D with shape input_shape = [batch] + spatial_shape + remaining_shape, where spatial_shape has M dimensions.
block_shape A Tensor. Must be one of the following types: int32, int64. 1-D with shape [M], all values must be >= 1.
paddings A Tensor. Must be one of the following types: int32, int64. 2-D with shape [M, 2], all values must be >= 0. paddings[i] = [pad_start, pad_end] specifies the padding for input dimension i + 1, which corresponds to spatial dimension i. It is required that block_shape[i] divides input_shape[i + 1] + pad_start + pad_end. 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 Permute dimensions of reshaped_padded to produce permuted_reshaped_padded of shape: block_shape + [batch] + [padded_shape[1] / block_shape[0], ..., padded_shape[M] / block_shape[M-1]] + remaining_shape Reshape permuted_reshaped_padded to flatten block_shape into the batch dimension, producing an output tensor of 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]]: x = [[[[1], [2]], [[3], [4]]]]
The output tensor has shape [4, 1, 1, 1] and value: [[[[1]]], [[[2]]], [[[3]]], [[[4]]]]
(2) For the following input of shape [1, 2, 2, 3], block_shape = [2, 2], and paddings = [[0, 0], [0, 0]]: x = [[[[1, 2, 3], [4, 5, 6]],
[[7, 8, 9], [10, 11, 12]]]]
The output tensor has shape [4, 1, 1, 3] and value: [[[[1, 2, 3]]], [[[4, 5, 6]]], [[[7, 8, 9]]], [[[10, 11, 12]]]]
(3) For the following input of shape [1, 4, 4, 1], block_shape = [2, 2], and paddings = [[0, 0], [0, 0]]: x = [[[[1], [2], [3], [4]],
[[5], [6], [7], [8]],
[[9], [10], [11], [12]],
[[13], [14], [15], [16]]]]
The output tensor has shape [4, 2, 2, 1] and value: x = [[[[1], [3]], [[9], [11]]],
[[[2], [4]], [[10], [12]]],
[[[5], [7]], [[13], [15]]],
[[[6], [8]], [[14], [16]]]]
(4) For the following input of shape [2, 2, 4, 1], block_shape = [2, 2], and paddings = [[0, 0], [2, 0]]: x = [[[[1], [2], [3], [4]],
[[5], [6], [7], [8]]],
[[[9], [10], [11], [12]],
[[13], [14], [15], [16]]]]
The output tensor has shape [8, 1, 3, 1] and value: x = [[[[0], [1], [3]]], [[[0], [9], [11]]],
[[[0], [2], [4]]], [[[0], [10], [12]]],
[[[0], [5], [7]]], [[[0], [13], [15]]],
[[[0], [6], [8]]], [[[0], [14], [16]]]]
Among others, this operation is useful for reducing atrous convolution into regular convolution.
name A name for the operation (optional).
Returns A Tensor. Has the same type as input. | tensorflow.space_to_batch |
tf.space_to_batch_nd SpaceToBatch for N-D tensors of type T. View aliases 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
tf.space_to_batch_nd(
input, block_shape, paddings, name=None
)
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.
Args
input A Tensor. N-D with shape input_shape = [batch] + spatial_shape + remaining_shape, where spatial_shape has M dimensions.
block_shape A Tensor. Must be one of the following types: int32, int64. 1-D with shape [M], all values must be >= 1.
paddings A Tensor. Must be one of the following types: int32, int64. 2-D with shape [M, 2], all values must be >= 0. paddings[i] = [pad_start, pad_end] specifies the padding for input dimension i + 1, which corresponds to spatial dimension i. It is required that block_shape[i] divides input_shape[i + 1] + pad_start + pad_end. 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 Permute dimensions of reshaped_padded to produce permuted_reshaped_padded of shape: block_shape + [batch] + [padded_shape[1] / block_shape[0], ..., padded_shape[M] / block_shape[M-1]] + remaining_shape Reshape permuted_reshaped_padded to flatten block_shape into the batch dimension, producing an output tensor of 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]]: x = [[[[1], [2]], [[3], [4]]]]
The output tensor has shape [4, 1, 1, 1] and value: [[[[1]]], [[[2]]], [[[3]]], [[[4]]]]
(2) For the following input of shape [1, 2, 2, 3], block_shape = [2, 2], and paddings = [[0, 0], [0, 0]]: x = [[[[1, 2, 3], [4, 5, 6]],
[[7, 8, 9], [10, 11, 12]]]]
The output tensor has shape [4, 1, 1, 3] and value: [[[[1, 2, 3]]], [[[4, 5, 6]]], [[[7, 8, 9]]], [[[10, 11, 12]]]]
(3) For the following input of shape [1, 4, 4, 1], block_shape = [2, 2], and paddings = [[0, 0], [0, 0]]: x = [[[[1], [2], [3], [4]],
[[5], [6], [7], [8]],
[[9], [10], [11], [12]],
[[13], [14], [15], [16]]]]
The output tensor has shape [4, 2, 2, 1] and value: x = [[[[1], [3]], [[9], [11]]],
[[[2], [4]], [[10], [12]]],
[[[5], [7]], [[13], [15]]],
[[[6], [8]], [[14], [16]]]]
(4) For the following input of shape [2, 2, 4, 1], block_shape = [2, 2], and paddings = [[0, 0], [2, 0]]: x = [[[[1], [2], [3], [4]],
[[5], [6], [7], [8]]],
[[[9], [10], [11], [12]],
[[13], [14], [15], [16]]]]
The output tensor has shape [8, 1, 3, 1] and value: x = [[[[0], [1], [3]]], [[[0], [9], [11]]],
[[[0], [2], [4]]], [[[0], [10], [12]]],
[[[0], [5], [7]]], [[[0], [13], [15]]],
[[[0], [6], [8]]], [[[0], [14], [16]]]]
Among others, this operation is useful for reducing atrous convolution into regular convolution.
name A name for the operation (optional).
Returns A Tensor. Has the same type as input. | tensorflow.space_to_batch_nd |
Module: tf.sparse Sparse Tensor Representation. See also tf.sparse.SparseTensor. Classes class SparseTensor: Represents a sparse tensor. Functions 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 | tensorflow.sparse |
tf.sparse.add View source on GitHub Adds two tensors, at least one of each is a SparseTensor.
tf.sparse.add(
a, b, threshold=0
)
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): [ 2]
[.1 0]
[ 6 -.2]
Then,
threshold == 0 (the default): all 5 index/value pairs will be returned.
threshold == 0.11: only .1 and 0 will vanish, and the remaining three index/value pairs will be returned.
threshold == 0.21: .1, 0, and -.2 will vanish.
Args
a The first operand; SparseTensor or Tensor.
b The second operand; SparseTensor or Tensor. At least one operand must be sparse.
threshold A 0-D Tensor. The magnitude threshold that determines if an output value/index pair takes space. Its dtype should match that of the values if they are real; if the latter are complex64/complex128, then the dtype should be float32/float64, correspondingly.
Returns A SparseTensor or a Tensor, representing the sum.
Raises
TypeError If both a and b are Tensors. Use tf.add() instead. | tensorflow.sparse.add |
tf.sparse.bincount Count the number of times an integer value appears in a tensor. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.sparse.bincount
tf.sparse.bincount(
values, weights=None, axis=0, minlength=None, maxlength=None,
binary_output=False, name=None
)
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.
Args
values A Tensor, RaggedTensor, or SparseTensor whose values should be counted. These tensors must have a rank of 2 if axis=-1.
weights If non-None, must be the same shape as arr. For each value in value, the bin will be incremented by the corresponding weight instead of 1.
axis The axis to slice over. Axes at and below axis will be flattened before bin counting. Currently, only 0, and -1 are supported. If None, all axes will be flattened (identical to passing 0).
minlength If given, ensures the output has length at least minlength, padding with zeros at the end if necessary.
maxlength If given, skips values in values that are equal or greater than maxlength, ensuring that the output has length at most maxlength.
binary_output If True, this op will output 1 instead of the number of times a token appears (equivalent to one_hot + reduce_any instead of one_hot + reduce_add). Defaults to False.
name A name for this op.
Returns A SparseTensor with output.shape = values.shape[:axis] + [N], where N is
maxlength (if set);
minlength (if set, and minlength > reduce_max(values));
0 (if values is empty);
reduce_max(values) + 1 otherwise.
Examples: 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.
data = np.array([[10, 20, 30, 20], [11, 101, 11, 10001]], dtype=np.int64)
output = tf.sparse.bincount(data, axis=-1)
print(output)
SparseTensor(indices=tf.Tensor(
[[ 0 10]
[ 0 20]
[ 0 30]
[ 1 11]
[ 1 101]
[ 1 10001]], shape=(6, 2), dtype=int64),
values=tf.Tensor([1 2 1 2 1 1], shape=(6,), dtype=int64),
dense_shape=tf.Tensor([ 2 10002], shape=(2,), dtype=int64))
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].
minlength = maxlength = 500
data = np.array([[10, 20, 30, 20], [11, 101, 11, 10001]], dtype=np.int64)
output = tf.sparse.bincount(
data, axis=-1, minlength=minlength, maxlength=maxlength)
print(output)
SparseTensor(indices=tf.Tensor(
[[ 0 10]
[ 0 20]
[ 0 30]
[ 1 11]
[ 1 101]], shape=(5, 2), dtype=int64),
values=tf.Tensor([1 2 1 2 1], shape=(5,), dtype=int64),
dense_shape=tf.Tensor([ 2 500], shape=(2,), dtype=int64))
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.
data = np.array([[10, 20, 30, 20], [11, 101, 11, 10001]], dtype=np.int64)
output = tf.sparse.bincount(data, binary_output=True, axis=-1)
print(output)
SparseTensor(indices=tf.Tensor(
[[ 0 10]
[ 0 20]
[ 0 30]
[ 1 11]
[ 1 101]
[ 1 10001]], shape=(6, 2), dtype=int64),
values=tf.Tensor([1 1 1 1 1 1], shape=(6,), dtype=int64),
dense_shape=tf.Tensor([ 2 10002], shape=(2,), dtype=int64))
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.
data = np.array([[10, 20, 30, 20], [11, 101, 11, 10001]], dtype=np.int64)
weights = [[2, 0.25, 15, 0.5], [2, 17, 3, 0.9]]
output = tf.sparse.bincount(data, weights=weights, axis=-1)
print(output)
SparseTensor(indices=tf.Tensor(
[[ 0 10]
[ 0 20]
[ 0 30]
[ 1 11]
[ 1 101]
[ 1 10001]], shape=(6, 2), dtype=int64),
values=tf.Tensor([2. 0.75 15. 5. 17. 0.9], shape=(6,), dtype=float32),
dense_shape=tf.Tensor([ 2 10002], shape=(2,), dtype=int64)) | tensorflow.sparse.bincount |
tf.sparse.concat View source on GitHub Concatenates a list of SparseTensor along the specified dimension. (deprecated arguments)
tf.sparse.concat(
axis, sp_inputs, expand_nonconcat_dims=False, name=None
)
Warning: SOME ARGUMENTS ARE DEPRECATED: (concat_dim). They will be removed in a future version. Instructions for updating: concat_dim is deprecated, use axis instead 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 sp_inputs[0]: shape = [2, 3]
[0, 2]: "a"
[1, 0]: "b"
[1, 1]: "c"
sp_inputs[1]: shape = [2, 4]
[0, 1]: "d"
[0, 2]: "e"
then the output will be shape = [2, 7]
[0, 2]: "a"
[0, 4]: "d"
[0, 5]: "e"
[1, 0]: "b"
[1, 1]: "c"
Graphically this is equivalent to doing [ a] concat [ d e ] = [ a d e ]
[b c ] [ ] [b c ]
Another example, if 'axis = 1' and the inputs are sp_inputs[0]: shape = [3, 3]
[0, 2]: "a"
[1, 0]: "b"
[2, 1]: "c"
sp_inputs[1]: shape = [2, 4]
[0, 1]: "d"
[0, 2]: "e"
if expand_nonconcat_dim = False, this will result in an error. But if expand_nonconcat_dim = True, this will result in: shape = [3, 7]
[0, 2]: "a"
[0, 4]: "d"
[0, 5]: "e"
[1, 0]: "b"
[2, 1]: "c"
Graphically this is equivalent to doing [ a] concat [ d e ] = [ a d e ]
[b ] [ ] [b ]
[ c ] [ c ]
Args
axis Dimension to concatenate along. Must be in range [-rank, rank), where rank is the number of dimensions in each input SparseTensor.
sp_inputs List of SparseTensor to concatenate.
name A name prefix for the returned tensors (optional).
expand_nonconcat_dim Whether to allow the expansion in the non-concat dimensions. Defaulted to False.
concat_dim The old (deprecated) name for axis.
expand_nonconcat_dims alias for expand_nonconcat_dim
Returns A SparseTensor with the concatenated output.
Raises
TypeError If sp_inputs is not a list of SparseTensor. | tensorflow.sparse.concat |
tf.sparse.cross View source on GitHub Generates sparse cross from a list of sparse and dense tensors. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.sparse.cross
tf.sparse.cross(
inputs, name=None, separator=None
)
For example, if the inputs are * inputs[0]: SparseTensor with shape = [2, 2]
[0, 0]: "a"
[1, 0]: "b"
[1, 1]: "c"
* inputs[1]: SparseTensor with shape = [2, 1]
[0, 0]: "d"
[1, 0]: "e"
* inputs[2]: Tensor [["f"], ["g"]]
then the output will be: shape = [2, 2]
[0, 0]: "a_X_d_X_f"
[1, 0]: "b_X_e_X_g"
[1, 1]: "c_X_e_X_g"
Customized separator "Y":
inp_0 = tf.constant([['a'], ['b']])
inp_1 = tf.constant([['c'], ['d']])
output = tf.sparse.cross([inp_0, inp_1], separator='_Y_')
output.values
<tf.Tensor: shape=(2,), dtype=string, numpy=array([b'a_Y_c', b'b_Y_d'],
dtype=object)>
Args
inputs An iterable of Tensor or SparseTensor.
name Optional name for the op.
separator A string added between each string being joined. Defaults to 'X'.
Returns A SparseTensor of type string. | tensorflow.sparse.cross |
tf.sparse.cross_hashed View source on GitHub Generates hashed sparse cross from a list of sparse and dense tensors. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.sparse.cross_hashed
tf.sparse.cross_hashed(
inputs, num_buckets=0, hash_key=None, name=None
)
For example, if the inputs are * inputs[0]: SparseTensor with shape = [2, 2]
[0, 0]: "a"
[1, 0]: "b"
[1, 1]: "c"
* inputs[1]: SparseTensor with shape = [2, 1]
[0, 0]: "d"
[1, 0]: "e"
* inputs[2]: Tensor [["f"], ["g"]]
then the output will be: shape = [2, 2]
[0, 0]: FingerprintCat64(
Fingerprint64("f"), FingerprintCat64(
Fingerprint64("d"), Fingerprint64("a")))
[1, 0]: FingerprintCat64(
Fingerprint64("g"), FingerprintCat64(
Fingerprint64("e"), Fingerprint64("b")))
[1, 1]: FingerprintCat64(
Fingerprint64("g"), FingerprintCat64(
Fingerprint64("e"), Fingerprint64("c")))
Args
inputs An iterable of Tensor or SparseTensor.
num_buckets An int that is >= 0. output = hashed_value%num_buckets if num_buckets > 0 else hashed_value.
hash_key Integer hash_key that will be used by the FingerprintCat64 function. If not given, will use a default key.
name Optional name for the op.
Returns A SparseTensor of type int64. | tensorflow.sparse.cross_hashed |
tf.sparse.expand_dims View source on GitHub Returns a tensor with an length 1 axis inserted at index axis. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.sparse.expand_dims
tf.sparse.expand_dims(
sp_input, axis=None, name=None
)
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: Add an outer "batch" dimension to a single element. Align axes for broadcasting. To add an inner vector length axis to a tensor of scalars. For example: If you have a sparse tensor with shape [height, width, depth]:
sp = tf.sparse.SparseTensor(indices=[[3,4,1]], values=[7,],
dense_shape=[10,10,3])
You can add an outer batch axis by passing axis=0:
tf.sparse.expand_dims(sp, axis=0).shape.as_list()
[1, 10, 10, 3]
The new axis location matches Python list.insert(axis, 1):
tf.sparse.expand_dims(sp, axis=1).shape.as_list()
[10, 1, 10, 3]
Following standard python indexing rules, a negative axis counts from the end so axis=-1 adds an inner most dimension:
tf.sparse.expand_dims(sp, axis=-1).shape.as_list()
[10, 10, 3, 1]
Note: Unlike tf.expand_dims this function includes a default value for the axis: -1. So if `axis is not specified, an inner dimension is added.
sp.shape.as_list()
[10, 10, 3]
tf.sparse.expand_dims(sp).shape.as_list()
[10, 10, 3, 1]
This operation requires that axis is a valid index for input.shape, following python indexing rules: -1-tf.rank(input) <= axis <= tf.rank(input)
This operation is related to:
tf.expand_dims, which provides this functionality for dense tensors.
tf.squeeze, which removes dimensions of size 1, from dense tensors.
tf.sparse.reshape, which provides more flexible reshaping capability.
Args
sp_input A SparseTensor.
axis 0-D (scalar). Specifies the dimension index at which to expand the shape of input. Must be in the range [-rank(sp_input) - 1, rank(sp_input)]. Defaults to -1.
name The name of the output SparseTensor.
Returns A SparseTensor with the same data as sp_input, but its shape has an additional dimension of size 1 added. | tensorflow.sparse.expand_dims |
tf.sparse.eye View source on GitHub Creates a two-dimensional sparse tensor with ones along the diagonal. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.sparse.eye
tf.sparse.eye(
num_rows, num_columns=None, dtype=tf.dtypes.float32, name=None
)
Args
num_rows Non-negative integer or int32 scalar tensor giving the number of rows in the resulting matrix.
num_columns Optional non-negative integer or int32 scalar tensor giving the number of columns in the resulting matrix. Defaults to num_rows.
dtype The type of element in the resulting Tensor.
name A name for this Op. Defaults to "eye".
Returns A SparseTensor of shape [num_rows, num_columns] with ones along the diagonal. | tensorflow.sparse.eye |
tf.sparse.fill_empty_rows View source on GitHub Fills empty rows in the input 2-D SparseTensor with a default value. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.sparse.fill_empty_rows, tf.compat.v1.sparse_fill_empty_rows
tf.sparse.fill_empty_rows(
sp_input, default_value, name=None
)
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: [0, 1]: a
[0, 3]: b
[2, 0]: c
[3, 1]: d
Rows 1 and 4 are empty, so the output will be of shape [5, 6] with values: [0, 1]: a
[0, 3]: b
[1, 0]: default_value
[2, 0]: c
[3, 1]: d
[4, 0]: default_value
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 empty_row_indicator[i] = True iff row i was an empty row.
Args
sp_input A SparseTensor with shape [N, M].
default_value The value to fill for empty rows, with the same type as sp_input.
name A name prefix for the returned tensors (optional)
Returns
sp_ordered_output A SparseTensor with shape [N, M], and with all empty rows filled in with default_value.
empty_row_indicator A bool vector of length N indicating whether each input row was empty.
Raises
TypeError If sp_input is not a SparseTensor. | tensorflow.sparse.fill_empty_rows |
tf.sparse.from_dense View source on GitHub Converts a dense tensor into a sparse tensor. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.sparse.from_dense
tf.sparse.from_dense(
tensor, name=None
)
Only elements not equal to zero will be present in the result. The resulting SparseTensor has the same dtype and shape as the input.
Args
tensor A dense Tensor to be converted to a SparseTensor.
name Optional name for the op.
Returns The SparseTensor. | tensorflow.sparse.from_dense |
tf.sparse.map_values Applies op to the .values tensor of one or more SparseTensors.
tf.sparse.map_values(
op, *args, **kwargs
)
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. Examples:
s = tf.sparse.from_dense([[1, 2, 0],
[0, 4, 0],
[1, 0, 0]])
tf.sparse.to_dense(tf.sparse.map_values(tf.ones_like, s)).numpy()
array([[1, 1, 0],
[0, 1, 0],
[1, 0, 0]], dtype=int32)
tf.sparse.to_dense(tf.sparse.map_values(tf.multiply, s, s)).numpy()
array([[ 1, 4, 0],
[ 0, 16, 0],
[ 1, 0, 0]], dtype=int32)
tf.sparse.to_dense(tf.sparse.map_values(tf.add, s, 5)).numpy()
array([[6, 7, 0],
[0, 9, 0],
[6, 0, 0]], dtype=int32)
Note: even though tf.add(0, 5) != 0, implicit zeros will remain unchanged. However, if the sparse tensor contains any explict zeros, these will be affected by the mapping!
Args
op The operation that should be applied to the SparseTensor values. op is typically an element-wise operation (such as math_ops.add), but any operation that preserves the shape can be used.
*args Arguments for op.
**kwargs Keyword arguments for op.
Returns A SparseTensor whose indices and dense_shape matches the indices and dense_shape of all input SparseTensors.
Raises
ValueError If args contains no SparseTensor, or if the indices or dense_shapes of the input SparseTensors are not equal. | tensorflow.sparse.map_values |
tf.sparse.mask View source on GitHub Masks elements of IndexedSlices. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.sparse.mask, tf.compat.v1.sparse_mask
tf.sparse.mask(
a, mask_indices, name=None
)
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. For example: # `a` contains slices at indices [12, 26, 37, 45] from a large tensor
# with shape [1000, 10]
a.indices # [12, 26, 37, 45]
tf.shape(a.values) # [4, 10]
# `b` will be the subset of `a` slices at its second and third indices, so
# we want to mask its first and last indices (which are at absolute
# indices 12, 45)
b = tf.sparse.mask(a, [12, 45])
b.indices # [26, 37]
tf.shape(b.values) # [2, 10]
Args
a An IndexedSlices instance.
mask_indices Indices of elements to mask.
name A name for the operation (optional).
Returns The masked IndexedSlices instance. | tensorflow.sparse.mask |
tf.sparse.maximum View source on GitHub Returns the element-wise max of two SparseTensors. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.sparse.maximum, tf.compat.v1.sparse_maximum
tf.sparse.maximum(
sp_a, sp_b, name=None
)
Assumes the two SparseTensors have the same shape, i.e., no broadcasting. Example: sp_zero = sparse_tensor.SparseTensor([[0]], [0], [7])
sp_one = sparse_tensor.SparseTensor([[1]], [1], [7])
res = tf.sparse.maximum(sp_zero, sp_one).eval()
# "res" should be equal to SparseTensor([[0], [1]], [0, 1], [7]).
Args
sp_a a SparseTensor operand whose dtype is real, and indices lexicographically ordered.
sp_b the other SparseTensor operand with the same requirements (and the same shape).
name optional name of the operation.
Returns
output the output SparseTensor. | tensorflow.sparse.maximum |
tf.sparse.minimum View source on GitHub Returns the element-wise min of two SparseTensors. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.sparse.minimum, tf.compat.v1.sparse_minimum
tf.sparse.minimum(
sp_a, sp_b, name=None
)
Assumes the two SparseTensors have the same shape, i.e., no broadcasting. Example: sp_zero = sparse_tensor.SparseTensor([[0]], [0], [7])
sp_one = sparse_tensor.SparseTensor([[1]], [1], [7])
res = tf.sparse.minimum(sp_zero, sp_one).eval()
# "res" should be equal to SparseTensor([[0], [1]], [0, 0], [7]).
Args
sp_a a SparseTensor operand whose dtype is real, and indices lexicographically ordered.
sp_b the other SparseTensor operand with the same requirements (and the same shape).
name optional name of the operation.
Returns
output the output SparseTensor. | tensorflow.sparse.minimum |
tf.sparse.reduce_max View source on GitHub Computes the max of elements across dimensions of a SparseTensor.
tf.sparse.reduce_max(
sp_input, axis=None, keepdims=None, output_is_sparse=False, name=None
)
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.
Note: A gradient is not defined for this function, so it can't be used in training models that need gradient descent.
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. For example: # 'x' represents [[1, ?, 2]
# [?, 3, ?]]
# where ? is implicitly-zero.
tf.sparse.reduce_max(x) ==> 3
tf.sparse.reduce_max(x, 0) ==> [1, 3, 2]
tf.sparse.reduce_max(x, 1) ==> [2, 3] # Can also use -1 as the axis.
tf.sparse.reduce_max(x, 1, keepdims=True) ==> [[2], [3]]
tf.sparse.reduce_max(x, [0, 1]) ==> 3
# 'y' represents [[-7, ?]
# [ 4, 3]
# [ ?, ?]
tf.sparse.reduce_max(x, 1) ==> [-7, 4, 0]
Args
sp_input The SparseTensor to reduce. Should have numeric type.
axis The dimensions to reduce; list or scalar. If None (the default), reduces all dimensions.
keepdims If true, retain reduced dimensions with length 1.
output_is_sparse If true, returns a SparseTensor instead of a dense Tensor (the default).
name A name for the operation (optional).
Returns The reduced Tensor or the reduced SparseTensor if output_is_sparse is True. | tensorflow.sparse.reduce_max |
tf.sparse.reduce_sum View source on GitHub Computes the sum of elements across dimensions of a SparseTensor.
tf.sparse.reduce_sum(
sp_input, axis=None, keepdims=None, output_is_sparse=False, name=None
)
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.
Note: if output_is_sparse is True, a gradient is not defined for this function, so it can't be used in training models that need gradient descent.
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. For example: # 'x' represents [[1, ?, 1]
# [?, 1, ?]]
# where ? is implicitly-zero.
tf.sparse.reduce_sum(x) ==> 3
tf.sparse.reduce_sum(x, 0) ==> [1, 1, 1]
tf.sparse.reduce_sum(x, 1) ==> [2, 1] # Can also use -1 as the axis.
tf.sparse.reduce_sum(x, 1, keepdims=True) ==> [[2], [1]]
tf.sparse.reduce_sum(x, [0, 1]) ==> 3
Args
sp_input The SparseTensor to reduce. Should have numeric type.
axis The dimensions to reduce; list or scalar. If None (the default), reduces all dimensions.
keepdims If true, retain reduced dimensions with length 1.
output_is_sparse If true, returns a SparseTensor instead of a dense Tensor (the default).
name A name for the operation (optional).
Returns The reduced Tensor or the reduced SparseTensor if output_is_sparse is True. | tensorflow.sparse.reduce_sum |
tf.sparse.reorder View source on GitHub Reorders a SparseTensor into the canonical, row-major ordering. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.sparse.reorder, tf.compat.v1.sparse_reorder
tf.sparse.reorder(
sp_input, name=None
)
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: [0, 3]: b
[0, 1]: a
[3, 1]: d
[2, 0]: c
then the output will be a SparseTensor of shape [4, 5] and indices / values: [0, 1]: a
[0, 3]: b
[2, 0]: c
[3, 1]: d
Args
sp_input The input SparseTensor.
name A name prefix for the returned tensors (optional)
Returns A SparseTensor with the same shape and non-empty values, but in canonical ordering.
Raises
TypeError If sp_input is not a SparseTensor. | tensorflow.sparse.reorder |
tf.sparse.reset_shape View source on GitHub Resets the shape of a SparseTensor with indices and values unchanged. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.sparse.reset_shape, tf.compat.v1.sparse_reset_shape
tf.sparse.reset_shape(
sp_input, new_shape=None
)
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. For example: 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.
Args
sp_input The input SparseTensor.
new_shape None or a vector representing the new shape for the returned SparseTensor.
Returns A SparseTensor indices and values unchanged from input_sp. Its shape is new_shape if that is set. Otherwise it is the tight bounding box of input_sp
Raises
TypeError If sp_input is not a SparseTensor.
ValueError If new_shape represents a tensor with a different rank from that of sp_input (if shapes are known when graph is constructed).
ValueError If new_shape is determined during graph build to have dimension sizes that are too small.
OpError If new_shape has dimension sizes that are too small. If shapes are not known during graph construction time, and during run time it is found out that the ranks do not match. | tensorflow.sparse.reset_shape |
tf.sparse.reshape View source on GitHub Reshapes a SparseTensor to represent values in a new dense shape. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.sparse.reshape, tf.compat.v1.sparse_reshape
tf.sparse.reshape(
sp_input, shape, name=None
)
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: [0, 0, 0]: a
[0, 0, 1]: b
[0, 1, 0]: c
[1, 0, 0]: d
[1, 2, 3]: e
and shape is [9, -1], then the output will be a SparseTensor of shape [9, 4] and indices / values: [0, 0]: a
[0, 1]: b
[1, 2]: c
[4, 2]: d
[8, 1]: e
Args
sp_input The input SparseTensor.
shape A 1-D (vector) int64 Tensor specifying the new dense shape of the represented SparseTensor.
name A name prefix for the returned tensors (optional)
Returns A SparseTensor with the same non-empty values but with indices calculated by the new dense shape.
Raises
TypeError If sp_input is not a SparseTensor.
ValueError If argument shape requests a SparseTensor with a different number of elements than sp_input.
ValueError If shape has more than one inferred (== -1) dimension. | tensorflow.sparse.reshape |
tf.sparse.retain View source on GitHub Retains specified non-empty values within a SparseTensor. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.sparse.retain, tf.compat.v1.sparse_retain
tf.sparse.retain(
sp_input, to_retain
)
For example, if sp_input has shape [4, 5] and 4 non-empty string values: [0, 1]: a
[0, 3]: b
[2, 0]: c
[3, 1]: d
and to_retain = [True, False, False, True], then the output will be a SparseTensor of shape [4, 5] with 2 non-empty values: [0, 1]: a
[3, 1]: d
Args
sp_input The input SparseTensor with N non-empty elements.
to_retain A bool vector of length N with M true values.
Returns A SparseTensor with the same shape as the input and M non-empty elements corresponding to the true positions in to_retain.
Raises
TypeError If sp_input is not a SparseTensor. | tensorflow.sparse.retain |
tf.sparse.segment_mean View source on GitHub Computes the mean along sparse segments of a tensor.
tf.sparse.segment_mean(
data, indices, segment_ids, num_segments=None, name=None
)
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.
Args
data A Tensor with data that will be assembled in the output.
indices A 1-D Tensor with indices into data. Has same rank as segment_ids.
segment_ids A 1-D Tensor with indices into the output Tensor. Values should be sorted and can be repeated.
num_segments An optional int32 scalar. Indicates the size of the output Tensor.
name A name for the operation (optional).
Returns A tensor of the shape as data, except for dimension 0 which has size k, the number of segments specified via num_segments or inferred for the last element in segments_ids. | tensorflow.sparse.segment_mean |
tf.sparse.segment_sqrt_n View source on GitHub Computes the sum along sparse segments of a tensor divided by the sqrt(N).
tf.sparse.segment_sqrt_n(
data, indices, segment_ids, num_segments=None, name=None
)
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.
Args
data A Tensor with data that will be assembled in the output.
indices A 1-D Tensor with indices into data. Has same rank as segment_ids.
segment_ids A 1-D Tensor with indices into the output Tensor. Values should be sorted and can be repeated.
num_segments An optional int32 scalar. Indicates the size of the output Tensor.
name A name for the operation (optional).
Returns A tensor of the shape as data, except for dimension 0 which has size k, the number of segments specified via num_segments or inferred for the last element in segments_ids. | tensorflow.sparse.segment_sqrt_n |
tf.sparse.segment_sum View source on GitHub Computes the sum along sparse segments of a tensor.
tf.sparse.segment_sum(
data, indices, segment_ids, num_segments=None, name=None
)
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. For example: c = tf.constant([[1,2,3,4], [-1,-2,-3,-4], [5,6,7,8]])
# Select two rows, one segment.
tf.sparse.segment_sum(c, tf.constant([0, 1]), tf.constant([0, 0]))
# => [[0 0 0 0]]
# Select two rows, two segment.
tf.sparse.segment_sum(c, tf.constant([0, 1]), tf.constant([0, 1]))
# => [[ 1 2 3 4]
# [-1 -2 -3 -4]]
# With missing segment ids.
tf.sparse.segment_sum(c, tf.constant([0, 1]), tf.constant([0, 2]),
num_segments=4)
# => [[ 1 2 3 4]
# [ 0 0 0 0]
# [-1 -2 -3 -4]
# [ 0 0 0 0]]
# Select all rows, two segments.
tf.sparse.segment_sum(c, tf.constant([0, 1, 2]), tf.constant([0, 0, 1]))
# => [[0 0 0 0]
# [5 6 7 8]]
# Which is equivalent to:
tf.math.segment_sum(c, tf.constant([0, 0, 1]))
Args
data A Tensor with data that will be assembled in the output.
indices A 1-D Tensor with indices into data. Has same rank as segment_ids.
segment_ids A 1-D Tensor with indices into the output Tensor. Values should be sorted and can be repeated.
num_segments An optional int32 scalar. Indicates the size of the output Tensor.
name A name for the operation (optional).
Returns A tensor of the shape as data, except for dimension 0 which has size k, the number of segments specified via num_segments or inferred for the last element in segments_ids. | tensorflow.sparse.segment_sum |
tf.sparse.slice View source on GitHub Slice a SparseTensor based on the start and `size. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.sparse.slice, tf.compat.v1.sparse_slice
tf.sparse.slice(
sp_input, start, size, name=None
)
For example, if the input is input_tensor = shape = [2, 7]
[ a d e ]
[b c ]
Graphically the output tensors are: sparse.slice([0, 0], [2, 4]) = shape = [2, 4]
[ a ]
[b c ]
sparse.slice([0, 4], [2, 3]) = shape = [2, 3]
[ d e ]
[ ]
Args
sp_input The SparseTensor to split.
start 1-D. tensor represents the start of the slice.
size 1-D. tensor represents the size of the slice.
name A name for the operation (optional).
Returns A SparseTensor objects resulting from splicing.
Raises
TypeError If sp_input is not a SparseTensor. | tensorflow.sparse.slice |
tf.sparse.softmax View source on GitHub Applies softmax to a batched N-D SparseTensor. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.sparse.softmax, tf.compat.v1.sparse_softmax
tf.sparse.softmax(
sp_input, name=None
)
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. Example: # First batch:
# [? e.]
# [1. ? ]
# Second batch:
# [e ? ]
# [e e ]
shape = [2, 2, 2] # 3-D SparseTensor
values = np.asarray([[[0., np.e], [1., 0.]], [[np.e, 0.], [np.e, np.e]]])
indices = np.vstack(np.where(values)).astype(np.int64).T
result = tf.sparse.softmax(tf.sparse.SparseTensor(indices, values, shape))
# ...returning a 3-D SparseTensor, equivalent to:
# [? 1.] [1 ?]
# [1. ? ] and [.5 .5]
# where ? means implicitly zero.
Args
sp_input N-D SparseTensor, where N >= 2.
name optional name of the operation.
Returns
output N-D SparseTensor representing the results. | tensorflow.sparse.softmax |
tf.sparse.SparseTensor View source on GitHub Represents a sparse tensor. View aliases Main aliases
tf.SparseTensor Compat aliases for migration See Migration guide for more details. tf.compat.v1.SparseTensor, tf.compat.v1.sparse.SparseTensor
tf.sparse.SparseTensor(
indices, values, dense_shape
)
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: dense.shape = dense_shape
dense[tuple(indices[i])] = values[i]
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 SparseTensor(indices=[[0, 0], [1, 2]], values=[1, 2], dense_shape=[3, 4])
represents the dense tensor [[1, 0, 0, 0]
[0, 0, 2, 0]
[0, 0, 0, 0]]
Args
indices A 2-D int64 tensor of shape [N, ndims].
values A 1-D tensor of any type and shape [N].
dense_shape A 1-D int64 tensor of shape [ndims].
Raises
ValueError When building an eager SparseTensor if dense_shape is unknown or contains unknown elements (None or -1).
Attributes
dense_shape A 1-D Tensor of int64 representing the shape of the dense tensor.
dtype The DType of elements in this tensor.
graph The Graph that contains the index, value, and dense_shape tensors.
indices The indices of non-zero values in the represented dense tensor.
op The Operation that produces values as an output.
shape Get the TensorShape representing the shape of the dense tensor.
values The non-zero values in the represented dense tensor. Methods consumers View source
consumers()
eval View source
eval(
feed_dict=None, session=None
)
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.
Note: Before invoking SparseTensor.eval(), its graph must have been launched in a session, and either a default session must be available, or session must be specified explicitly.
Args
feed_dict A dictionary that maps Tensor objects to feed values. See tf.Session.run for a description of the valid feed values.
session (Optional.) The Session to be used to evaluate this sparse tensor. If none, the default session will be used.
Returns A SparseTensorValue object.
from_value View source
@classmethod
from_value(
sparse_tensor_value
)
get_shape View source
get_shape()
Get the TensorShape representing the shape of the dense tensor.
Returns A TensorShape object.
with_values View source
with_values(
new_values
)
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.
Args
new_values The values of the new SparseTensor. Needs to have the same shape as the current .values Tensor. May have a different type than the current values.
Returns A SparseTensor with identical indices and shape but updated values.
Example usage:
st = tf.sparse.from_dense([[1, 0, 2, 0], [3, 0, 0, 4]])
tf.sparse.to_dense(st.with_values([10, 20, 30, 40])) # 4 nonzero values
<tf.Tensor: shape=(2, 4), dtype=int32, numpy=
array([[10, 0, 20, 0],
[30, 0, 0, 40]], dtype=int32)>
__div__ View source
__div__(
sp_x, y
)
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.
Args
sp_indices A Tensor of type int64. 2-D. N x R matrix with the indices of non-empty values in a SparseTensor, possibly not in canonical ordering.
sp_values A Tensor. Must be one of the following types: float32, float64, int32, uint8, int16, int8, complex64, int64, qint8, quint8, qint32, bfloat16, uint16, complex128, half, uint32, uint64. 1-D. N non-empty values corresponding to sp_indices.
sp_shape A Tensor of type int64. 1-D. Shape of the input SparseTensor.
dense A Tensor. Must have the same type as sp_values. R-D. The dense Tensor operand.
name A name for the operation (optional).
Returns A Tensor. Has the same type as sp_values.
__mul__ View source
__mul__(
sp_x, y
)
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.
Args
sp_indices A Tensor of type int64. 2-D. N x R matrix with the indices of non-empty values in a SparseTensor, possibly not in canonical ordering.
sp_values A Tensor. Must be one of the following types: float32, float64, int32, uint8, int16, int8, complex64, int64, qint8, quint8, qint32, bfloat16, uint16, complex128, half, uint32, uint64. 1-D. N non-empty values corresponding to sp_indices.
sp_shape A Tensor of type int64. 1-D. Shape of the input SparseTensor.
dense A Tensor. Must have the same type as sp_values. R-D. The dense Tensor operand.
name A name for the operation (optional).
Returns A Tensor. Has the same type as sp_values.
__truediv__ View source
__truediv__(
sp_x, y
)
Internal helper function for 'sp_t / dense_t'. | tensorflow.sparse.sparsetensor |
tf.sparse.sparse_dense_matmul View source on GitHub Multiply SparseTensor (or dense Matrix) (of rank 2) "A" by dense matrix View aliases 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
tf.sparse.sparse_dense_matmul(
sp_a, b, adjoint_a=False, adjoint_b=False, name=None
)
(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: If adjoint_a == false: A should be sorted in lexicographically increasing order. Use sparse.reorder if you're not sure. If adjoint_a == true: A should be sorted in order of increasing dimension 1 (i.e., "column major" order instead of "row major" order). 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: [[ a ]
[b c]
[ d ]]
SparseTensor format expected by sparse_tensor_dense_matmul: sp_a (indices, values): [0, 1]: a
[1, 0]: b
[1, 4]: c
[2, 2]: d
SparseTensor format expected by embedding_lookup_sparse: sp_ids sp_weights [0, 0]: 1 [0, 0]: a
[1, 0]: 0 [1, 0]: b
[1, 1]: 4 [1, 1]: c
[2, 0]: 2 [2, 0]: d
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: Will the SparseTensor A fit in memory if densified? Is the column count of the product large (>> 1)? Is the density of A larger than approximately 15%? 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. Benchmark system: CPU: Intel Ivybridge with HyperThreading (6 cores) dL1:32KB dL2:256KB dL3:12MB GPU: NVidia Tesla k40c Compiled with: -c opt --config=cuda --copt=-mavx tensorflow/python/sparse_tensor_dense_matmul_op_test --benchmarks
A sparse [m, k] with % nonzero values between 1% and 80%
B dense [k, n]
% nnz n gpu m k dt(dense) dt(sparse) dt(sparse)/dt(dense)
0.01 1 True 100 100 0.000221166 0.00010154 0.459112
0.01 1 True 100 1000 0.00033858 0.000109275 0.322745
0.01 1 True 1000 100 0.000310557 9.85661e-05 0.317385
0.01 1 True 1000 1000 0.0008721 0.000100875 0.115669
0.01 1 False 100 100 0.000208085 0.000107603 0.51711
0.01 1 False 100 1000 0.000327112 9.51118e-05 0.290762
0.01 1 False 1000 100 0.000308222 0.00010345 0.335635
0.01 1 False 1000 1000 0.000865721 0.000101397 0.117124
0.01 10 True 100 100 0.000218522 0.000105537 0.482958
0.01 10 True 100 1000 0.000340882 0.000111641 0.327506
0.01 10 True 1000 100 0.000315472 0.000117376 0.372064
0.01 10 True 1000 1000 0.000905493 0.000123263 0.136128
0.01 10 False 100 100 0.000221529 9.82571e-05 0.44354
0.01 10 False 100 1000 0.000330552 0.000112615 0.340687
0.01 10 False 1000 100 0.000341277 0.000114097 0.334324
0.01 10 False 1000 1000 0.000819944 0.000120982 0.147549
0.01 25 True 100 100 0.000207806 0.000105977 0.509981
0.01 25 True 100 1000 0.000322879 0.00012921 0.400181
0.01 25 True 1000 100 0.00038262 0.00014158 0.370035
0.01 25 True 1000 1000 0.000865438 0.000202083 0.233504
0.01 25 False 100 100 0.000209401 0.000104696 0.499979
0.01 25 False 100 1000 0.000321161 0.000130737 0.407076
0.01 25 False 1000 100 0.000377012 0.000136801 0.362856
0.01 25 False 1000 1000 0.000861125 0.00020272 0.235413
0.2 1 True 100 100 0.000206952 9.69219e-05 0.46833
0.2 1 True 100 1000 0.000348674 0.000147475 0.422959
0.2 1 True 1000 100 0.000336908 0.00010122 0.300439
0.2 1 True 1000 1000 0.001022 0.000203274 0.198898
0.2 1 False 100 100 0.000207532 9.5412e-05 0.459746
0.2 1 False 100 1000 0.000356127 0.000146824 0.41228
0.2 1 False 1000 100 0.000322664 0.000100918 0.312764
0.2 1 False 1000 1000 0.000998987 0.000203442 0.203648
0.2 10 True 100 100 0.000211692 0.000109903 0.519165
0.2 10 True 100 1000 0.000372819 0.000164321 0.440753
0.2 10 True 1000 100 0.000338651 0.000144806 0.427596
0.2 10 True 1000 1000 0.00108312 0.000758876 0.70064
0.2 10 False 100 100 0.000215727 0.000110502 0.512231
0.2 10 False 100 1000 0.000375419 0.0001613 0.429653
0.2 10 False 1000 100 0.000336999 0.000145628 0.432132
0.2 10 False 1000 1000 0.00110502 0.000762043 0.689618
0.2 25 True 100 100 0.000218705 0.000129913 0.594009
0.2 25 True 100 1000 0.000394794 0.00029428 0.745402
0.2 25 True 1000 100 0.000404483 0.0002693 0.665788
0.2 25 True 1000 1000 0.0012002 0.00194494 1.62052
0.2 25 False 100 100 0.000221494 0.0001306 0.589632
0.2 25 False 100 1000 0.000396436 0.000297204 0.74969
0.2 25 False 1000 100 0.000409346 0.000270068 0.659754
0.2 25 False 1000 1000 0.00121051 0.00193737 1.60046
0.5 1 True 100 100 0.000214981 9.82111e-05 0.456836
0.5 1 True 100 1000 0.000415328 0.000223073 0.537101
0.5 1 True 1000 100 0.000358324 0.00011269 0.314492
0.5 1 True 1000 1000 0.00137612 0.000437401 0.317851
0.5 1 False 100 100 0.000224196 0.000101423 0.452386
0.5 1 False 100 1000 0.000400987 0.000223286 0.556841
0.5 1 False 1000 100 0.000368825 0.00011224 0.304318
0.5 1 False 1000 1000 0.00136036 0.000429369 0.31563
0.5 10 True 100 100 0.000222125 0.000112308 0.505608
0.5 10 True 100 1000 0.000461088 0.00032357 0.701753
0.5 10 True 1000 100 0.000394624 0.000225497 0.571422
0.5 10 True 1000 1000 0.00158027 0.00190898 1.20801
0.5 10 False 100 100 0.000232083 0.000114978 0.495418
0.5 10 False 100 1000 0.000454574 0.000324632 0.714146
0.5 10 False 1000 100 0.000379097 0.000227768 0.600817
0.5 10 False 1000 1000 0.00160292 0.00190168 1.18638
0.5 25 True 100 100 0.00023429 0.000151703 0.647501
0.5 25 True 100 1000 0.000497462 0.000598873 1.20386
0.5 25 True 1000 100 0.000460778 0.000557038 1.20891
0.5 25 True 1000 1000 0.00170036 0.00467336 2.74845
0.5 25 False 100 100 0.000228981 0.000155334 0.678371
0.5 25 False 100 1000 0.000496139 0.000620789 1.25124
0.5 25 False 1000 100 0.00045473 0.000551528 1.21287
0.5 25 False 1000 1000 0.00171793 0.00467152 2.71927
0.8 1 True 100 100 0.000222037 0.000105301 0.47425
0.8 1 True 100 1000 0.000410804 0.000329327 0.801664
0.8 1 True 1000 100 0.000349735 0.000131225 0.375212
0.8 1 True 1000 1000 0.00139219 0.000677065 0.48633
0.8 1 False 100 100 0.000214079 0.000107486 0.502085
0.8 1 False 100 1000 0.000413746 0.000323244 0.781261
0.8 1 False 1000 100 0.000348983 0.000131983 0.378193
0.8 1 False 1000 1000 0.00136296 0.000685325 0.50282
0.8 10 True 100 100 0.000229159 0.00011825 0.516017
0.8 10 True 100 1000 0.000498845 0.000532618 1.0677
0.8 10 True 1000 100 0.000383126 0.00029935 0.781336
0.8 10 True 1000 1000 0.00162866 0.00307312 1.88689
0.8 10 False 100 100 0.000230783 0.000124958 0.541452
0.8 10 False 100 1000 0.000493393 0.000550654 1.11606
0.8 10 False 1000 100 0.000377167 0.000298581 0.791642
0.8 10 False 1000 1000 0.00165795 0.00305103 1.84024
0.8 25 True 100 100 0.000233496 0.000175241 0.75051
0.8 25 True 100 1000 0.00055654 0.00102658 1.84458
0.8 25 True 1000 100 0.000463814 0.000783267 1.68875
0.8 25 True 1000 1000 0.00186905 0.00755344 4.04132
0.8 25 False 100 100 0.000240243 0.000175047 0.728625
0.8 25 False 100 1000 0.000578102 0.00104499 1.80763
0.8 25 False 1000 100 0.000485113 0.000776849 1.60138
0.8 25 False 1000 1000 0.00211448 0.00752736 3.55992
Args
sp_a SparseTensor (or dense Matrix) A, of rank 2.
b dense Matrix (or SparseTensor) B, with the same dtype as sp_a.
adjoint_a Use the adjoint of A in the matrix multiply. If A is complex, this is transpose(conj(A)). Otherwise it's transpose(A).
adjoint_b Use the adjoint of B in the matrix multiply. If B is complex, this is transpose(conj(B)). Otherwise it's transpose(B).
name A name prefix for the returned tensors (optional)
Returns A dense matrix (pseudo-code in dense np.matrix notation): A = A.H if adjoint_a else A B = B.H if adjoint_b else B return A*B | tensorflow.sparse.sparse_dense_matmul |
tf.sparse.split View source on GitHub Split a SparseTensor into num_split tensors along axis.
tf.sparse.split(
sp_input=None, num_split=None, axis=None, name=None
)
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:
indices = [[0, 2], [0, 4], [0, 5], [1, 0], [1, 1]]
values = [1, 2, 3, 4, 5]
t = tf.SparseTensor(indices=indices, values=values, dense_shape=[2, 7])
tf.sparse.to_dense(t)
<tf.Tensor: shape=(2, 7), dtype=int32, numpy=
array([[0, 0, 1, 0, 2, 3, 0],
[4, 5, 0, 0, 0, 0, 0]], dtype=int32)>
output = tf.sparse.split(sp_input=t, num_split=2, axis=1)
tf.sparse.to_dense(output[0])
<tf.Tensor: shape=(2, 4), dtype=int32, numpy=
array([[0, 0, 1, 0],
[4, 5, 0, 0]], dtype=int32)>
tf.sparse.to_dense(output[1])
<tf.Tensor: shape=(2, 3), dtype=int32, numpy=
array([[2, 3, 0],
[0, 0, 0]], dtype=int32)>
output = tf.sparse.split(sp_input=t, num_split=2, axis=0)
tf.sparse.to_dense(output[0])
<tf.Tensor: shape=(1, 7), dtype=int32, numpy=array([[0, 0, 1, 0, 2, 3, 0]],
dtype=int32)>
tf.sparse.to_dense(output[1])
<tf.Tensor: shape=(1, 7), dtype=int32, numpy=array([[4, 5, 0, 0, 0, 0, 0]],
dtype=int32)>
output = tf.sparse.split(sp_input=t, num_split=2, axis=-1)
tf.sparse.to_dense(output[0])
<tf.Tensor: shape=(2, 4), dtype=int32, numpy=
array([[0, 0, 1, 0],
[4, 5, 0, 0]], dtype=int32)>
tf.sparse.to_dense(output[1])
<tf.Tensor: shape=(2, 3), dtype=int32, numpy=
array([[2, 3, 0],
[0, 0, 0]], dtype=int32)>
Args
sp_input The SparseTensor to split.
num_split A Python integer. The number of ways to split.
axis A 0-D int32 Tensor. The dimension along which to split. Must be in range [-rank, rank), where rank is the number of dimensions in the input SparseTensor.
name A name for the operation (optional).
Returns num_split SparseTensor objects resulting from splitting value.
Raises
TypeError If sp_input is not a SparseTensor. | tensorflow.sparse.split |
tf.sparse.to_dense View source on GitHub Converts a SparseTensor into a dense tensor. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.sparse.to_dense, tf.compat.v1.sparse_tensor_to_dense
tf.sparse.to_dense(
sp_input, default_value=None, validate_indices=True, name=None
)
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: [0, 1]: a
[0, 3]: b
[2, 0]: c
and default_value is x, then the output will be a dense [3, 5] string tensor with values: [[x a x b x]
[x x x x x]
[c x x x x]]
Indices must be without repeats. This is only tested if validate_indices is True.
Args
sp_input The input SparseTensor.
default_value Scalar value to set for indices not specified in sp_input. Defaults to zero.
validate_indices A boolean value. If True, indices are checked to make sure they are sorted in lexicographic order and that there are no repeats.
name A name prefix for the returned tensors (optional).
Returns A dense tensor with shape sp_input.dense_shape and values specified by the non-empty values in sp_input. Indices not in sp_input are assigned default_value.
Raises
TypeError If sp_input is not a SparseTensor. | tensorflow.sparse.to_dense |
tf.sparse.to_indicator View source on GitHub Converts a SparseTensor of ids into a dense bool indicator tensor. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.sparse.to_indicator, tf.compat.v1.sparse_to_indicator
tf.sparse.to_indicator(
sp_input, vocab_size, name=None
)
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 output[d_0, d_1, ..., d_n, sp_input[d_0, d_1, ..., d_n, k]] = True
and False elsewhere in output. For example, if sp_input.dense_shape = [2, 3, 4] with non-empty values: [0, 0, 0]: 0
[0, 1, 0]: 10
[1, 0, 3]: 103
[1, 1, 1]: 150
[1, 1, 2]: 149
[1, 1, 3]: 150
[1, 2, 1]: 121
and vocab_size = 200, then the output will be a [2, 3, 200] dense bool tensor with False everywhere except at positions (0, 0, 0), (0, 1, 10), (1, 0, 103), (1, 1, 149), (1, 1, 150),
(1, 2, 121).
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.
Args
sp_input A SparseTensor with values property of type int32 or int64.
vocab_size A scalar int64 Tensor (or Python int) containing the new size of the last dimension, all(0 <= sp_input.values < vocab_size).
name A name prefix for the returned tensors (optional)
Returns A dense bool indicator tensor representing the indices with specified value.
Raises
TypeError If sp_input is not a SparseTensor. | tensorflow.sparse.to_indicator |
tf.sparse.transpose View source on GitHub Transposes a SparseTensor View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.sparse.transpose, tf.compat.v1.sparse_transpose
tf.sparse.transpose(
sp_input, perm=None, name=None
)
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: [0, 3]: b
[0, 1]: a
[3, 1]: d
[2, 0]: c
then the output will be a SparseTensor of shape [5, 4] and indices / values: [0, 2]: c
[1, 0]: a
[1, 3]: d
[3, 0]: b
Args
sp_input The input SparseTensor.
perm A permutation of the dimensions of sp_input.
name A name prefix for the returned tensors (optional)
Returns A transposed SparseTensor.
Raises
TypeError If sp_input is not a SparseTensor. | tensorflow.sparse.transpose |
tf.SparseTensorSpec View source on GitHub Type specification for a tf.sparse.SparseTensor. Inherits From: TypeSpec View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.SparseTensorSpec
tf.SparseTensorSpec(
shape=None, dtype=tf.dtypes.float32
)
Args
shape The dense shape of the SparseTensor, or None to allow any dense shape.
dtype tf.DType of values in the SparseTensor.
Attributes
dtype The tf.dtypes.DType specified by this type for the SparseTensor.
shape The tf.TensorShape specified by this type for the SparseTensor.
value_type
Methods from_value View source
@classmethod
from_value(
value
)
is_compatible_with View source
is_compatible_with(
spec_or_value
)
Returns true if spec_or_value is compatible with this TypeSpec. most_specific_compatible_type View source
most_specific_compatible_type(
other
)
Returns the most specific TypeSpec compatible with self and other.
Args
other A TypeSpec.
Raises
ValueError If there is no TypeSpec that is compatible with both self and other. __eq__ View source
__eq__(
other
)
Return self==value. __ne__ View source
__ne__(
other
)
Return self!=value. | tensorflow.sparsetensorspec |
tf.split View source on GitHub Splits a tensor value into a list of sub tensors. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.split
tf.split(
value, num_or_size_splits, axis=0, num=None, name='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]. For example:
x = tf.Variable(tf.random.uniform([5, 30], -1, 1))
# Split `x` into 3 tensors along dimension 1
s0, s1, s2 = tf.split(x, num_or_size_splits=3, axis=1)
tf.shape(s0).numpy()
array([ 5, 10], dtype=int32)
# Split `x` into 3 tensors with sizes [4, 15, 11] along dimension 1
split0, split1, split2 = tf.split(x, [4, 15, 11], 1)
tf.shape(split0).numpy()
array([5, 4], dtype=int32)
tf.shape(split1).numpy()
array([ 5, 15], dtype=int32)
tf.shape(split2).numpy()
array([ 5, 11], dtype=int32)
Args
value The Tensor to split.
num_or_size_splits Either an integer indicating the number of splits along axis or a 1-D integer Tensor or Python list containing the sizes of each output tensor along axis. If a scalar, then it must evenly divide value.shape[axis]; otherwise the sum of sizes along the split axis must match that of the value.
axis An integer or scalar int32 Tensor. The dimension along which to split. Must be in the range [-rank(value), rank(value)). Defaults to 0.
num Optional, used to specify the number of outputs when it cannot be inferred from the shape of size_splits.
name A name for the operation (optional).
Returns if num_or_size_splits is a scalar returns a list of num_or_size_splits Tensor objects; if num_or_size_splits is a 1-D Tensor returns num_or_size_splits.get_shape[0] Tensor objects resulting from splitting value.
Raises
ValueError If num is unspecified and cannot be inferred. | tensorflow.split |
tf.squeeze View source on GitHub Removes dimensions of size 1 from the shape of a tensor.
tf.squeeze(
input, axis=None, name=None
)
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. For example: # 't' is a tensor of shape [1, 2, 1, 3, 1, 1]
tf.shape(tf.squeeze(t)) # [2, 3]
Or, to remove specific size 1 dimensions: # 't' is a tensor of shape [1, 2, 1, 3, 1, 1]
tf.shape(tf.squeeze(t, [2, 4])) # [1, 2, 3, 1]
Unlike the older op tf.compat.v1.squeeze, this op does not accept a deprecated squeeze_dims argument.
Note: if input is a tf.RaggedTensor, then this operation takes O(N) time, where N is the number of elements in the squeezed dimensions.
Args
input A Tensor. The input to squeeze.
axis An optional list of ints. Defaults to []. If specified, only squeezes the dimensions listed. The dimension index starts at 0. It is an error to squeeze a dimension that is not 1. Must be in the range [-rank(input), rank(input)). Must be specified if input is a RaggedTensor.
name A name for the operation (optional).
Returns A Tensor. Has the same type as input. Contains the same data as input, but has one or more dimensions of size 1 removed.
Raises
ValueError The input cannot be converted to a tensor, or the specified axis cannot be squeezed. | tensorflow.squeeze |
tf.stack View source on GitHub Stacks a list of rank-R tensors into one rank-(R+1) tensor. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.stack
tf.stack(
values, axis=0, name='stack'
)
See also tf.concat, tf.tile, tf.repeat. Packs the list of tensors in values into a tensor with rank one higher than each tensor in values, by packing them along the axis dimension. Given a list of length N of tensors of shape (A, B, C); if axis == 0 then the output tensor will have the shape (N, A, B, C). if axis == 1 then the output tensor will have the shape (A, N, B, C). Etc. For example:
x = tf.constant([1, 4])
y = tf.constant([2, 5])
z = tf.constant([3, 6])
tf.stack([x, y, z])
<tf.Tensor: shape=(3, 2), dtype=int32, numpy=
array([[1, 4],
[2, 5],
[3, 6]], dtype=int32)>
tf.stack([x, y, z], axis=1)
<tf.Tensor: shape=(2, 3), dtype=int32, numpy=
array([[1, 2, 3],
[4, 5, 6]], dtype=int32)>
This is the opposite of unstack. The numpy equivalent is np.stack
np.array_equal(np.stack([x, y, z]), tf.stack([x, y, z]))
True
Args
values A list of Tensor objects with the same shape and type.
axis An int. The axis to stack along. Defaults to the first dimension. Negative values wrap around, so the valid range is [-(R+1), R+1).
name A name for this operation (optional).
Returns
output A stacked Tensor with the same type as values.
Raises
ValueError If axis is out of the range [-(R+1), R+1). | tensorflow.stack |
tf.stop_gradient Stops gradient computation. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.stop_gradient
tf.stop_gradient(
input, name=None
)
When executed in a graph, this op outputs its input tensor as-is. When building ops to compute gradients, this op prevents the contribution of its inputs to be taken into account. Normally, the gradient generator adds ops to a graph to compute the derivatives of a specified 'loss' by recursively finding out inputs that contributed to its computation. If you insert this op in the graph it inputs are masked from the gradient generator. They are not taken into account for computing gradients. This is useful any time you want to compute a value with TensorFlow but need to pretend that the value was a constant. Some examples include: The EM algorithm where the M-step should not involve backpropagation through the output of the E-step. Contrastive divergence training of Boltzmann machines where, when differentiating the energy function, the training must not backpropagate through the graph that generated the samples from the model. Adversarial training, where no backprop should happen through the adversarial example generation process.
Args
input A Tensor.
name A name for the operation (optional).
Returns A Tensor. Has the same type as input. | tensorflow.stop_gradient |
tf.strided_slice View source on GitHub Extracts a strided slice of a tensor (generalized Python array indexing). View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.strided_slice
tf.strided_slice(
input_, begin, end, strides=None, begin_mask=0, end_mask=0, ellipsis_mask=0,
new_axis_mask=0, shrink_axis_mask=0, var=None, name=None
)
See also tf.slice. Instead of calling this op directly most users will want to use the NumPy-style slicing syntax (e.g. tensor[..., 3:4:-1, tf.newaxis, 3]), which is supported via tf.Tensor.getitem and tf.Variable.getitem. The interface of this op is a low-level encoding of the slicing syntax. Roughly speaking, this op extracts a slice of size (end-begin)/stride from the given input_ tensor. Starting at the location specified by begin the slice continues by adding stride to the index until all dimensions are not less than end. Note that a stride can be negative, which causes a reverse slice. Given a Python slice input[spec0, spec1, ..., specn], this function will be called as follows. begin, end, and strides will be vectors of length n. n in general is not equal to the rank of the input_ tensor. In each mask field (begin_mask, end_mask, ellipsis_mask, new_axis_mask, shrink_axis_mask) the ith bit will correspond to the ith spec. If the ith bit of begin_mask is set, begin[i] is ignored and the fullest possible range in that dimension is used instead. end_mask works analogously, except with the end range. foo[5:,:,:3] on a 7x8x9 tensor is equivalent to foo[5:7,0:8,0:3]. foo[::-1] reverses a tensor with shape 8. If the ith bit of ellipsis_mask is set, as many unspecified dimensions as needed will be inserted between other dimensions. Only one non-zero bit is allowed in ellipsis_mask. For example foo[3:5,...,4:5] on a shape 10x3x3x10 tensor is equivalent to foo[3:5,:,:,4:5] and foo[3:5,...] is equivalent to foo[3:5,:,:,:]. If the ith bit of new_axis_mask is set, then begin, end, and stride are ignored and a new length 1 dimension is added at this point in the output tensor. For example, foo[:4, tf.newaxis, :2] would produce a shape (4, 1, 2) tensor. If the ith bit of shrink_axis_mask is set, it implies that the ith specification shrinks the dimensionality by 1, taking on the value at index begin[i]. end[i] and strides[i] are ignored in this case. For example in Python one might do foo[:, 3, :] which would result in shrink_axis_mask equal to 2.
Note: begin and end are zero-indexed. strides entries must be non-zero.
t = tf.constant([[[1, 1, 1], [2, 2, 2]],
[[3, 3, 3], [4, 4, 4]],
[[5, 5, 5], [6, 6, 6]]])
tf.strided_slice(t, [1, 0, 0], [2, 1, 3], [1, 1, 1]) # [[[3, 3, 3]]]
tf.strided_slice(t, [1, 0, 0], [2, 2, 3], [1, 1, 1]) # [[[3, 3, 3],
# [4, 4, 4]]]
tf.strided_slice(t, [1, -1, 0], [2, -3, 3], [1, -1, 1]) # [[[4, 4, 4],
# [3, 3, 3]]]
Args
input_ A Tensor.
begin An int32 or int64 Tensor.
end An int32 or int64 Tensor.
strides An int32 or int64 Tensor.
begin_mask An int32 mask.
end_mask An int32 mask.
ellipsis_mask An int32 mask.
new_axis_mask An int32 mask.
shrink_axis_mask An int32 mask.
var The variable corresponding to input_ or None
name A name for the operation (optional).
Returns A Tensor the same type as input. | tensorflow.strided_slice |
Module: tf.strings Operations for working with string Tensors. Functions as_string(...): Converts each entry in the given tensor to strings. bytes_split(...): Split string elements of input into bytes. format(...): Formats a string template using a list of tensors. join(...): Perform element-wise concatenation of a list of string tensors. length(...): String lengths of input. lower(...): Converts all uppercase characters into their respective lowercase replacements. ngrams(...): Create a tensor of n-grams based on data. reduce_join(...): Joins all strings into a single string, or joins along an axis. regex_full_match(...): Check if the input matches the regex pattern. regex_replace(...): Replace elements of input matching regex pattern with rewrite. split(...): Split elements of input based on sep into a RaggedTensor. strip(...): Strip leading and trailing whitespaces from the Tensor. substr(...): Return substrings from Tensor of strings. to_hash_bucket(...): Converts each string in the input Tensor to its hash mod by a number of buckets. to_hash_bucket_fast(...): Converts each string in the input Tensor to its hash mod by a number of buckets. to_hash_bucket_strong(...): Converts each string in the input Tensor to its hash mod by a number of buckets. to_number(...): Converts each string in the input Tensor to the specified numeric type. unicode_decode(...): Decodes each string in input into a sequence of Unicode code points. unicode_decode_with_offsets(...): Decodes each string into a sequence of code points with start offsets. unicode_encode(...): Encodes each sequence of Unicode code points in input into a string. unicode_script(...): Determine the script codes of a given tensor of Unicode integer code points. unicode_split(...): Splits each string in input into a sequence of Unicode code points. unicode_split_with_offsets(...): Splits each string into a sequence of code points with start offsets. unicode_transcode(...): Transcode the input text from a source encoding to a destination encoding. unsorted_segment_join(...): Joins the elements of inputs based on segment_ids. upper(...): Converts all lowercase characters into their respective uppercase replacements. | tensorflow.strings |
tf.strings.as_string Converts each entry in the given tensor to strings. View aliases Main aliases
tf.as_string Compat aliases for migration See Migration guide for more details. tf.compat.v1.as_string, tf.compat.v1.dtypes.as_string, tf.compat.v1.strings.as_string
tf.strings.as_string(
input, precision=-1, scientific=False, shortest=False, width=-1,
fill='', name=None
)
Supports many numeric types and boolean. For Unicode, see the https://www.tensorflow.org/tutorials/representation/unicode tutorial. Examples:
tf.strings.as_string([3, 2])
<tf.Tensor: shape=(2,), dtype=string, numpy=array([b'3', b'2'], dtype=object)>
tf.strings.as_string([3.1415926, 2.71828], precision=2).numpy()
array([b'3.14', b'2.72'], dtype=object)
Args
input A Tensor. Must be one of the following types: int8, int16, int32, int64, complex64, complex128, float32, float64, bool.
precision An optional int. Defaults to -1. The post-decimal precision to use for floating point numbers. Only used if precision > -1.
scientific An optional bool. Defaults to False. Use scientific notation for floating point numbers.
shortest An optional bool. Defaults to False. Use shortest representation (either scientific or standard) for floating point numbers.
width An optional int. Defaults to -1. Pad pre-decimal numbers to this width. Applies to both floating point and integer numbers. Only used if width > -1.
fill An optional string. Defaults to "". The value to pad if width > -1. If empty, pads with spaces. Another typical value is '0'. String cannot be longer than 1 character.
name A name for the operation (optional).
Returns A Tensor of type string. | tensorflow.strings.as_string |
tf.strings.bytes_split View source on GitHub Split string elements of input into bytes. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.strings.bytes_split
tf.strings.bytes_split(
input, name=None
)
Examples:
tf.strings.bytes_split('hello').numpy()
array([b'h', b'e', b'l', b'l', b'o'], dtype=object)
tf.strings.bytes_split(['hello', '123'])
<tf.RaggedTensor [[b'h', b'e', b'l', b'l', b'o'], [b'1', b'2', b'3']]>
Note that this op splits strings into bytes, not unicode characters. To split strings into unicode characters, use tf.strings.unicode_split. See also: tf.io.decode_raw, tf.strings.split, tf.strings.unicode_split.
Args
input A string Tensor or RaggedTensor: the strings to split. Must have a statically known rank (N).
name A name for the operation (optional).
Returns A RaggedTensor of rank N+1: the bytes that make up the source strings. | tensorflow.strings.bytes_split |
tf.strings.format View source on GitHub Formats a string template using a list of tensors. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.strings.format
tf.strings.format(
template, inputs, placeholder='{}', summarize=3, name=None
)
Formats a string template using a list of tensors, abbreviating tensors by only printing the first and last summarize elements of each dimension (recursively). If formatting only one tensor into a template, the tensor does not have to be wrapped in a list. Example: Formatting a single-tensor template:
tensor = tf.range(5)
tf.strings.format("tensor: {}, suffix", tensor)
<tf.Tensor: shape=(), dtype=string, numpy=b'tensor: [0 1 2 3 4], suffix'>
Formatting a multi-tensor template:
tensor_a = tf.range(2)
tensor_b = tf.range(1, 4, 2)
tf.strings.format("a: {}, b: {}, suffix", (tensor_a, tensor_b))
<tf.Tensor: shape=(), dtype=string, numpy=b'a: [0 1], b: [1 3], suffix'>
Args
template A string template to format tensor values into.
inputs A list of Tensor objects, or a single Tensor. The list of tensors to format into the template string. If a solitary tensor is passed in, the input tensor will automatically be wrapped as a list.
placeholder An optional string. Defaults to {}. At each placeholder occurring in the template, a subsequent tensor will be inserted.
summarize An optional int. Defaults to 3. When formatting the tensors, show the first and last summarize entries of each tensor dimension (recursively). If set to -1, all elements of the tensor will be shown.
name A name for the operation (optional).
Returns A scalar Tensor of type string.
Raises
ValueError if the number of placeholders does not match the number of inputs. | tensorflow.strings.format |
tf.strings.join View source on GitHub Perform element-wise concatenation of a list of string tensors. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.string_join, tf.compat.v1.strings.join
tf.strings.join(
inputs, separator='', name=None
)
Given a list of string tensors of same shape, performs element-wise concatenation of the strings of the same index in all tensors.
tf.strings.join(['abc','def']).numpy()
b'abcdef'
tf.strings.join([['abc','123'],
['def','456'],
['ghi','789']]).numpy()
array([b'abcdefghi', b'123456789'], dtype=object)
tf.strings.join([['abc','123'],
['def','456']],
separator=" ").numpy()
array([b'abc def', b'123 456'], dtype=object)
Args
inputs A list of tf.Tensor objects of same size and tf.string dtype.
separator A string added between each string being joined.
name A name for the operation (optional).
Returns A tf.string tensor. | tensorflow.strings.join |
tf.strings.length View source on GitHub String lengths of input.
tf.strings.length(
input, unit='BYTE', name=None
)
Computes the length of each string given in the input tensor.
strings = tf.constant(['Hello','TensorFlow', '\U0001F642'])
tf.strings.length(strings).numpy() # default counts bytes
array([ 5, 10, 4], dtype=int32)
tf.strings.length(strings, unit="UTF8_CHAR").numpy()
array([ 5, 10, 1], dtype=int32)
Args
input A Tensor of type string. The strings for which to compute the length for each element.
unit An optional string from: "BYTE", "UTF8_CHAR". Defaults to "BYTE". The unit that is counted to compute string length. One of: "BYTE" (for the number of bytes in each string) or "UTF8_CHAR" (for the number of UTF-8 encoded Unicode code points in each string). Results are undefined if unit=UTF8_CHAR and the input strings do not contain structurally valid UTF-8.
name A name for the operation (optional).
Returns A Tensor of type int32. | tensorflow.strings.length |
tf.strings.lower Converts all uppercase characters into their respective lowercase replacements. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.strings.lower
tf.strings.lower(
input, encoding='', name=None
)
Example:
tf.strings.lower("CamelCase string and ALL CAPS")
<tf.Tensor: shape=(), dtype=string, numpy=b'camelcase string and all caps'>
Args
input A Tensor of type string.
encoding An optional string. Defaults to "".
name A name for the operation (optional).
Returns A Tensor of type string. | tensorflow.strings.lower |
tf.strings.ngrams View source on GitHub Create a tensor of n-grams based on data. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.strings.ngrams
tf.strings.ngrams(
data, ngram_width, separator=' ', pad_values=None, padding_width=None,
preserve_short_sequences=False, name=None
)
Creates a tensor of n-grams based on data. The n-grams are created by joining windows of width adjacent strings from the inner axis of data using separator. The input data can be padded on both the start and end of the sequence, if desired, using the pad_values argument. If set, pad_values should contain either a tuple of strings or a single string; the 0th element of the tuple will be used to pad the left side of the sequence and the 1st element of the tuple will be used to pad the right side of the sequence. The padding_width arg controls how many padding values are added to each side; it defaults to ngram_width-1. If this op is configured to not have padding, or if it is configured to add padding with padding_width set to less than ngram_width-1, it is possible that a sequence, or a sequence plus padding, is smaller than the ngram width. In that case, no ngrams will be generated for that sequence. This can be prevented by setting preserve_short_sequences, which will cause the op to always generate at least one ngram per non-empty sequence. Examples:
tf.strings.ngrams(["A", "B", "C", "D"], 2).numpy()
array([b'A B', b'B C', b'C D'], dtype=object)
tf.strings.ngrams(["TF", "and", "keras"], 1).numpy()
array([b'TF', b'and', b'keras'], dtype=object)
Args
data A Tensor or RaggedTensor containing the source data for the ngrams.
ngram_width The width(s) of the ngrams to create. If this is a list or tuple, the op will return ngrams of all specified arities in list order. Values must be non-Tensor integers greater than 0.
separator The separator string used between ngram elements. Must be a string constant, not a Tensor.
pad_values A tuple of (left_pad_value, right_pad_value), a single string, or None. If None, no padding will be added; if a single string, then that string will be used for both left and right padding. Values must be Python strings.
padding_width If set, padding_width pad values will be added to both sides of each sequence. Defaults to ngram_width-1. Must be greater than (Note that 1-grams are never padded, regardless of this value.)
preserve_short_sequences If true, then ensure that at least one ngram is generated for each input sequence. In particular, if an input sequence is shorter than min(ngram_width) + 2*pad_width, then generate a single ngram containing the entire sequence. If false, then no ngrams are generated for these short input sequences.
name The op name.
Returns A RaggedTensor of ngrams. If data.shape=[D1...DN, S], then output.shape=[D1...DN, NUM_NGRAMS], where NUM_NGRAMS=S-ngram_width+1+2*padding_width.
Raises
TypeError if pad_values is set to an invalid type.
ValueError if pad_values, padding_width, or ngram_width is set to an invalid value. | tensorflow.strings.ngrams |
tf.strings.reduce_join View source on GitHub Joins all strings into a single string, or joins along an axis.
tf.strings.reduce_join(
inputs, axis=None, keepdims=False, separator='', name=None
)
tf.strings.reduce_join([['abc','123'],
['def','456']]).numpy()
b'abc123def456'
tf.strings.reduce_join([['abc','123'],
['def','456']], axis=-1).numpy()
array([b'abc123', b'def456'], dtype=object)
tf.strings.reduce_join([['abc','123'],
['def','456']],
axis=-1,
separator=" ").numpy()
array([b'abc 123', b'def 456'], dtype=object)
Args
inputs A tf.string tensor.
axis Which axis to join along. The default behavior is to join all elements, producing a scalar.
keepdims If true, retains reduced dimensions with length 1.
separator a string added between each string being joined.
name A name for the operation (optional).
Returns A tf.string tensor. | tensorflow.strings.reduce_join |
tf.strings.regex_full_match View source on GitHub Check if the input matches the regex pattern. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.strings.regex_full_match
tf.strings.regex_full_match(
input, pattern, name=None
)
The input is a string tensor of any shape. The pattern is a scalar string tensor which is applied to every element of the input tensor. The boolean values (True or False) of the output tensor indicate if the input matches the regex pattern provided. The pattern follows the re2 syntax (https://github.com/google/re2/wiki/Syntax) Examples:
tf.strings.regex_full_match(["TF lib", "lib TF"], ".*lib$")
<tf.Tensor: shape=(2,), dtype=bool, numpy=array([ True, False])>
tf.strings.regex_full_match(["TF lib", "lib TF"], ".*TF$")
<tf.Tensor: shape=(2,), dtype=bool, numpy=array([False, True])>
Args
input A Tensor of type string. A string tensor of the text to be processed.
pattern A Tensor of type string. A scalar string tensor containing the regular expression to match the input.
name A name for the operation (optional).
Returns A Tensor of type bool. | tensorflow.strings.regex_full_match |
tf.strings.regex_replace View source on GitHub Replace elements of input matching regex pattern with rewrite. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.regex_replace, tf.compat.v1.strings.regex_replace
tf.strings.regex_replace(
input, pattern, rewrite, replace_global=True, name=None
)
tf.strings.regex_replace("Text with tags.<br /><b>contains html</b>",
"<[^>]+>", " ")
<tf.Tensor: shape=(), dtype=string, numpy=b'Text with tags. contains html '>
Args
input string Tensor, the source strings to process.
pattern string or scalar string Tensor, regular expression to use, see more details at https://github.com/google/re2/wiki/Syntax
rewrite string or scalar string Tensor, value to use in match replacement, supports backslash-escaped digits (\1 to \9) can be to insert text matching corresponding parenthesized group.
replace_global bool, if True replace all non-overlapping matches, else replace only the first match.
name A name for the operation (optional).
Returns string Tensor of the same shape as input with specified replacements. | tensorflow.strings.regex_replace |
tf.strings.split View source on GitHub Split elements of input based on sep into a RaggedTensor.
tf.strings.split(
input, sep=None, maxsplit=-1, name=None
)
Let N be the size of input (typically N will be the batch size). Split each element of input based on sep and return a RaggedTensor containing the split tokens. Empty tokens are ignored. Example:
tf.strings.split('hello world').numpy()
array([b'hello', b'world'], dtype=object)
tf.strings.split(['hello world', 'a b c'])
<tf.RaggedTensor [[b'hello', b'world'], [b'a', b'b', b'c']]>
If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings. For example, input of "1<>2<><>3" and sep of "<>" returns ["1", "2", "", "3"]. If sep is None or an empty string, consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Note that the above mentioned behavior matches python's str.split.
Args
input A string Tensor of rank N, the strings to split. If rank(input) is not known statically, then it is assumed to be 1.
sep 0-D string Tensor, the delimiter string.
maxsplit An int. If maxsplit > 0, limit of the split of the result.
name A name for the operation (optional).
Raises
ValueError If sep is not a string.
Returns A RaggedTensor of rank N+1, the strings split according to the delimiter. | tensorflow.strings.split |
tf.strings.strip Strip leading and trailing whitespaces from the Tensor. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.string_strip, tf.compat.v1.strings.strip
tf.strings.strip(
input, name=None
)
Args
input A Tensor of type string. A string Tensor of any shape.
name A name for the operation (optional).
Returns A Tensor of type string. | tensorflow.strings.strip |
tf.strings.substr View source on GitHub Return substrings from Tensor of strings.
tf.strings.substr(
input, pos, len, unit='BYTE', name=None
)
For each string in the input Tensor, creates a substring starting at index pos with a total length of len. If len defines a substring that would extend beyond the length of the input string, or if len is negative, then as many characters as possible are used. A negative pos indicates distance within the string backwards from the end. If pos specifies an index which is out of range for any of the input strings, then an InvalidArgumentError is thrown. pos and len must have the same shape, otherwise a ValueError is thrown on Op creation.
Note: Substr supports broadcasting up to two dimensions. More about broadcasting here
Examples Using scalar pos and len: input = [b'Hello', b'World']
position = 1
length = 3
output = [b'ell', b'orl']
Using pos and len with same shape as input: input = [[b'ten', b'eleven', b'twelve'],
[b'thirteen', b'fourteen', b'fifteen'],
[b'sixteen', b'seventeen', b'eighteen']]
position = [[1, 2, 3],
[1, 2, 3],
[1, 2, 3]]
length = [[2, 3, 4],
[4, 3, 2],
[5, 5, 5]]
output = [[b'en', b'eve', b'lve'],
[b'hirt', b'urt', b'te'],
[b'ixtee', b'vente', b'hteen']]
Broadcasting pos and len onto input: input = [[b'ten', b'eleven', b'twelve'],
[b'thirteen', b'fourteen', b'fifteen'],
[b'sixteen', b'seventeen', b'eighteen'],
[b'nineteen', b'twenty', b'twentyone']]
position = [1, 2, 3]
length = [1, 2, 3]
output = [[b'e', b'ev', b'lve'],
[b'h', b'ur', b'tee'],
[b'i', b've', b'hte'],
[b'i', b'en', b'nty']]
Broadcasting input onto pos and len: input = b'thirteen'
position = [1, 5, 7]
length = [3, 2, 1]
output = [b'hir', b'ee', b'n']
Raises
ValueError: If the first argument cannot be converted to a Tensor of dtype string.
InvalidArgumentError: If indices are out of range.
ValueError: If pos and len are not the same shape.
Args
input A Tensor of type string. Tensor of strings
pos A Tensor. Must be one of the following types: int32, int64. Scalar defining the position of first character in each substring
len A Tensor. Must have the same type as pos. Scalar defining the number of characters to include in each substring
unit An optional string from: "BYTE", "UTF8_CHAR". Defaults to "BYTE". The unit that is used to create the substring. One of: "BYTE" (for defining position and length by bytes) or "UTF8_CHAR" (for the UTF-8 encoded Unicode code points). The default is "BYTE". Results are undefined if unit=UTF8_CHAR and the input strings do not contain structurally valid UTF-8.
name A name for the operation (optional).
Returns A Tensor of type string. | tensorflow.strings.substr |
tf.strings.to_hash_bucket View source on GitHub Converts each string in the input Tensor to its hash mod by a number of buckets.
tf.strings.to_hash_bucket(
input, num_buckets, name=None
)
The hash function is deterministic on the content of the string within the process. Note that the hash function may change from time to time. This functionality will be deprecated and it's recommended to use tf.strings.to_hash_bucket_fast() or tf.strings.to_hash_bucket_strong(). Examples:
tf.strings.to_hash_bucket(["Hello", "TensorFlow", "2.x"], 3)
<tf.Tensor: shape=(3,), dtype=int64, numpy=array([2, 0, 1])>
Args
input A Tensor of type string.
num_buckets An int that is >= 1. The number of buckets.
name A name for the operation (optional).
Returns A Tensor of type int64. | tensorflow.strings.to_hash_bucket |
tf.strings.to_hash_bucket_fast Converts each string in the input Tensor to its hash mod by a number of buckets. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.string_to_hash_bucket_fast, tf.compat.v1.strings.to_hash_bucket_fast
tf.strings.to_hash_bucket_fast(
input, num_buckets, name=None
)
The hash function is deterministic on the content of the string within the process and will never change. However, it is not suitable for cryptography. This function may be used when CPU time is scarce and inputs are trusted or unimportant. There is a risk of adversaries constructing inputs that all hash to the same bucket. To prevent this problem, use a strong hash function with tf.string_to_hash_bucket_strong. Examples:
tf.strings.to_hash_bucket_fast(["Hello", "TensorFlow", "2.x"], 3).numpy()
array([0, 2, 2])
Args
input A Tensor of type string. The strings to assign a hash bucket.
num_buckets An int that is >= 1. The number of buckets.
name A name for the operation (optional).
Returns A Tensor of type int64. | tensorflow.strings.to_hash_bucket_fast |
tf.strings.to_hash_bucket_strong Converts each string in the input Tensor to its hash mod by a number of buckets. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.string_to_hash_bucket_strong, tf.compat.v1.strings.to_hash_bucket_strong
tf.strings.to_hash_bucket_strong(
input, num_buckets, key, name=None
)
The hash function is deterministic on the content of the string within the process. The hash function is a keyed hash function, where attribute key defines the key of the hash function. key is an array of 2 elements. A strong hash is important when inputs may be malicious, e.g. URLs with additional components. Adversaries could try to make their inputs hash to the same bucket for a denial-of-service attack or to skew the results. A strong hash can be used to make it difficult to find inputs with a skewed hash value distribution over buckets. This requires that the hash function is seeded by a high-entropy (random) "key" unknown to the adversary. The additional robustness comes at a cost of roughly 4x higher compute time than tf.string_to_hash_bucket_fast. Examples:
tf.strings.to_hash_bucket_strong(["Hello", "TF"], 3, [1, 2]).numpy()
array([2, 0])
Args
input A Tensor of type string. The strings to assign a hash bucket.
num_buckets An int that is >= 1. The number of buckets.
key A list of ints. The key used to seed the hash function, passed as a list of two uint64 elements.
name A name for the operation (optional).
Returns A Tensor of type int64. | tensorflow.strings.to_hash_bucket_strong |
tf.strings.to_number View source on GitHub Converts each string in the input Tensor to the specified numeric type.
tf.strings.to_number(
input, out_type=tf.dtypes.float32, name=None
)
(Note that int32 overflow results in an error while float overflow results in a rounded value.) Examples:
tf.strings.to_number("1.55")
<tf.Tensor: shape=(), dtype=float32, numpy=1.55>
tf.strings.to_number("3", tf.int32)
<tf.Tensor: shape=(), dtype=int32, numpy=3>
Args
input A Tensor of type string.
out_type An optional tf.DType from: tf.float32, tf.float64, tf.int32, tf.int64. Defaults to tf.float32. The numeric type to interpret each string in string_tensor as.
name A name for the operation (optional).
Returns A Tensor of type out_type. | tensorflow.strings.to_number |
tf.strings.unicode_decode View source on GitHub Decodes each string in input into a sequence of Unicode code points. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.strings.unicode_decode
tf.strings.unicode_decode(
input, input_encoding, errors='replace', replacement_char=65533,
replace_control_characters=False, name=None
)
result[i1...iN, j] is the Unicode codepoint for the jth character in input[i1...iN], when decoded using input_encoding.
Args
input An N dimensional potentially ragged string tensor with shape [D1...DN]. N must be statically known.
input_encoding String name for the unicode encoding that should be used to decode each string.
errors Specifies the response when an input string can't be converted using the indicated encoding. One of:
'strict': Raise an exception for any illegal substrings.
'replace': Replace illegal substrings with replacement_char.
'ignore': Skip illegal substrings.
replacement_char The replacement codepoint to be used in place of invalid substrings in input when errors='replace'; and in place of C0 control characters in input when replace_control_characters=True.
replace_control_characters Whether to replace the C0 control characters (U+0000 - U+001F) with the replacement_char.
name A name for the operation (optional).
Returns A N+1 dimensional int32 tensor with shape [D1...DN, (num_chars)]. The returned tensor is a tf.Tensor if input is a scalar, or a tf.RaggedTensor otherwise.
Example:
input = [s.encode('utf8') for s in (u'G\xf6\xf6dnight', u'\U0001f60a')]
tf.strings.unicode_decode(input, 'UTF-8').to_list()
[[71, 246, 246, 100, 110, 105, 103, 104, 116], [128522]] | tensorflow.strings.unicode_decode |
tf.strings.unicode_decode_with_offsets View source on GitHub Decodes each string into a sequence of code points with start offsets. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.strings.unicode_decode_with_offsets
tf.strings.unicode_decode_with_offsets(
input, input_encoding, errors='replace', replacement_char=65533,
replace_control_characters=False, name=None
)
This op is similar to tf.strings.decode(...), but it also returns the start offset for each character in its respective string. This information can be used to align the characters with the original byte sequence. Returns a tuple (codepoints, start_offsets) where:
codepoints[i1...iN, j] is the Unicode codepoint for the jth character in input[i1...iN], when decoded using input_encoding.
start_offsets[i1...iN, j] is the start byte offset for the jth character in input[i1...iN], when decoded using input_encoding.
Args
input An N dimensional potentially ragged string tensor with shape [D1...DN]. N must be statically known.
input_encoding String name for the unicode encoding that should be used to decode each string.
errors Specifies the response when an input string can't be converted using the indicated encoding. One of:
'strict': Raise an exception for any illegal substrings.
'replace': Replace illegal substrings with replacement_char.
'ignore': Skip illegal substrings.
replacement_char The replacement codepoint to be used in place of invalid substrings in input when errors='replace'; and in place of C0 control characters in input when replace_control_characters=True.
replace_control_characters Whether to replace the C0 control characters (U+0000 - U+001F) with the replacement_char.
name A name for the operation (optional).
Returns A tuple of N+1 dimensional tensors (codepoints, start_offsets).
codepoints is an int32 tensor with shape [D1...DN, (num_chars)].
offsets is an int64 tensor with shape [D1...DN, (num_chars)]. The returned tensors are tf.Tensors if input is a scalar, or tf.RaggedTensors otherwise.
Example:
input = [s.encode('utf8') for s in (u'G\xf6\xf6dnight', u'\U0001f60a')]
result = tf.strings.unicode_decode_with_offsets(input, 'UTF-8')
result[0].to_list() # codepoints
[[71, 246, 246, 100, 110, 105, 103, 104, 116], [128522]]
result[1].to_list() # offsets
[[0, 1, 3, 5, 6, 7, 8, 9, 10], [0]] | tensorflow.strings.unicode_decode_with_offsets |
tf.strings.unicode_encode View source on GitHub Encodes each sequence of Unicode code points in input into a string. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.strings.unicode_encode
tf.strings.unicode_encode(
input, output_encoding, errors='replace', replacement_char=65533,
name=None
)
result[i1...iN] is the string formed by concatenating the Unicode codepoints input[1...iN, :], encoded using output_encoding.
Args
input An N+1 dimensional potentially ragged integer tensor with shape [D1...DN, num_chars].
output_encoding Unicode encoding that should be used to encode each codepoint sequence. Can be "UTF-8", "UTF-16-BE", or "UTF-32-BE".
errors Specifies the response when an invalid codepoint is encountered (optional). One of:
'replace': Replace invalid codepoint with the replacement_char. (default)
'ignore': Skip invalid codepoints.
'strict': Raise an exception for any invalid codepoint.
replacement_char The replacement character codepoint to be used in place of any invalid input when errors='replace'. Any valid unicode codepoint may be used. The default value is the default unicode replacement character which is 0xFFFD (U+65533).
name A name for the operation (optional).
Returns A N dimensional string tensor with shape [D1...DN].
Example:
input = tf.ragged.constant(
[[71, 246, 246, 100, 110, 105, 103, 104, 116], [128522]])
print(unicode_encode(input, 'UTF-8'))
tf.Tensor([b'G\xc3\xb6\xc3\xb6dnight' b'\xf0\x9f\x98\x8a'],
shape=(2,), dtype=string) | tensorflow.strings.unicode_encode |
tf.strings.unicode_script Determine the script codes of a given tensor of Unicode integer code points. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.strings.unicode_script
tf.strings.unicode_script(
input, name=None
)
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. Examples:
tf.strings.unicode_script([1, 31, 38])
<tf.Tensor: shape=(3,), dtype=int32, numpy=array([0, 0, 0], dtype=int32)>
Args
input A Tensor of type int32. A Tensor of int32 Unicode code points.
name A name for the operation (optional).
Returns A Tensor of type int32. | tensorflow.strings.unicode_script |
tf.strings.unicode_split View source on GitHub Splits each string in input into a sequence of Unicode code points. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.strings.unicode_split
tf.strings.unicode_split(
input, input_encoding, errors='replace', replacement_char=65533,
name=None
)
result[i1...iN, j] is the substring of input[i1...iN] that encodes its jth character, when decoded using input_encoding.
Args
input An N dimensional potentially ragged string tensor with shape [D1...DN]. N must be statically known.
input_encoding String name for the unicode encoding that should be used to decode each string.
errors Specifies the response when an input string can't be converted using the indicated encoding. One of:
'strict': Raise an exception for any illegal substrings.
'replace': Replace illegal substrings with replacement_char.
'ignore': Skip illegal substrings.
replacement_char The replacement codepoint to be used in place of invalid substrings in input when errors='replace'.
name A name for the operation (optional).
Returns A N+1 dimensional int32 tensor with shape [D1...DN, (num_chars)]. The returned tensor is a tf.Tensor if input is a scalar, or a tf.RaggedTensor otherwise.
Example:
input = [s.encode('utf8') for s in (u'G\xf6\xf6dnight', u'\U0001f60a')]
tf.strings.unicode_split(input, 'UTF-8').to_list()
[[b'G', b'\xc3\xb6', b'\xc3\xb6', b'd', b'n', b'i', b'g', b'h', b't'],
[b'\xf0\x9f\x98\x8a']] | tensorflow.strings.unicode_split |
tf.strings.unicode_split_with_offsets View source on GitHub Splits each string into a sequence of code points with start offsets. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.strings.unicode_split_with_offsets
tf.strings.unicode_split_with_offsets(
input, input_encoding, errors='replace', replacement_char=65533,
name=None
)
This op is similar to tf.strings.decode(...), but it also returns the start offset for each character in its respective string. This information can be used to align the characters with the original byte sequence. Returns a tuple (chars, start_offsets) where:
chars[i1...iN, j] is the substring of input[i1...iN] that encodes its jth character, when decoded using input_encoding.
start_offsets[i1...iN, j] is the start byte offset for the jth character in input[i1...iN], when decoded using input_encoding.
Args
input An N dimensional potentially ragged string tensor with shape [D1...DN]. N must be statically known.
input_encoding String name for the unicode encoding that should be used to decode each string.
errors Specifies the response when an input string can't be converted using the indicated encoding. One of:
'strict': Raise an exception for any illegal substrings.
'replace': Replace illegal substrings with replacement_char.
'ignore': Skip illegal substrings.
replacement_char The replacement codepoint to be used in place of invalid substrings in input when errors='replace'.
name A name for the operation (optional).
Returns A tuple of N+1 dimensional tensors (codepoints, start_offsets).
codepoints is an int32 tensor with shape [D1...DN, (num_chars)].
offsets is an int64 tensor with shape [D1...DN, (num_chars)]. The returned tensors are tf.Tensors if input is a scalar, or tf.RaggedTensors otherwise.
Example:
input = [s.encode('utf8') for s in (u'G\xf6\xf6dnight', u'\U0001f60a')]
result = tf.strings.unicode_split_with_offsets(input, 'UTF-8')
result[0].to_list() # character substrings
[[b'G', b'\xc3\xb6', b'\xc3\xb6', b'd', b'n', b'i', b'g', b'h', b't'],
[b'\xf0\x9f\x98\x8a']]
result[1].to_list() # offsets
[[0, 1, 3, 5, 6, 7, 8, 9, 10], [0]] | tensorflow.strings.unicode_split_with_offsets |
tf.strings.unicode_transcode Transcode the input text from a source encoding to a destination encoding. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.strings.unicode_transcode
tf.strings.unicode_transcode(
input, input_encoding, output_encoding, errors='replace',
replacement_char=65533, replace_control_characters=False, name=None
)
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. Examples:
tf.strings.unicode_transcode(["Hello", "TensorFlow", "2.x"], "UTF-8", "UTF-16-BE")
<tf.Tensor: shape=(3,), dtype=string, numpy=
array([b'\x00H\x00e\x00l\x00l\x00o',
b'\x00T\x00e\x00n\x00s\x00o\x00r\x00F\x00l\x00o\x00w',
b'\x002\x00.\x00x'], dtype=object)>
tf.strings.unicode_transcode(["A", "B", "C"], "US ASCII", "UTF-8").numpy()
array([b'A', b'B', b'C'], dtype=object)
Args
input A Tensor of type string. The text to be processed. Can have any shape.
input_encoding A string. Text encoding of the input strings. This is any of the encodings supported by ICU ucnv algorithmic converters. Examples: "UTF-16", "US ASCII", "UTF-8".
output_encoding A string from: "UTF-8", "UTF-16-BE", "UTF-32-BE". The unicode encoding to use in the output. Must be one of "UTF-8", "UTF-16-BE", "UTF-32-BE". Multi-byte encodings will be big-endian.
errors An optional string from: "strict", "replace", "ignore". Defaults to "replace". Error handling policy when there is invalid formatting found in the input. The value of 'strict' will cause the operation to produce a InvalidArgument error on any invalid input formatting. A value of 'replace' (the default) will cause the operation to replace any invalid formatting in the input with the replacement_char codepoint. A value of 'ignore' will cause the operation to skip any invalid formatting in the input and produce no corresponding output character.
replacement_char An optional int. Defaults to 65533. The replacement character codepoint to be used in place of any invalid formatting in the input when errors='replace'. Any valid unicode codepoint may be used. The default value is the default unicode replacement character is 0xFFFD or U+65533.) 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.
replace_control_characters An optional bool. Defaults to False. Whether to replace the C0 control characters (00-1F) with the replacement_char. Default is false.
name A name for the operation (optional).
Returns A Tensor of type string. | tensorflow.strings.unicode_transcode |
tf.strings.unsorted_segment_join Joins the elements of inputs based on segment_ids. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.strings.unsorted_segment_join
tf.strings.unsorted_segment_join(
inputs, segment_ids, num_segments, separator='', name=None
)
Computes the string join along segments of a tensor. Given segment_ids with rank N and data with rank N+M: `output[i, k1...kM] = strings.join([data[j1...jN, k1...kM])`
where the join is over all [j1...jN] such that segment_ids[j1...jN] = i. Strings are joined in row-major order. For example: inputs = [['Y', 'q', 'c'], ['Y', '6', '6'], ['p', 'G', 'a']]
output_array = string_ops.unsorted_segment_join(inputs=inputs,
segment_ids=[1, 0, 1],
num_segments=2,
separator=':'))
# output_array ==> [['Y', '6', '6'], ['Y:p', 'q:G', 'c:a']]
inputs = ['this', 'is', 'a', 'test']
output_array = string_ops.unsorted_segment_join(inputs=inputs,
segment_ids=[0, 0, 0, 0],
num_segments=1,
separator=':'))
# output_array ==> ['this:is:a:test']
Args
inputs A Tensor of type string. The input to be joined.
segment_ids A Tensor. Must be one of the following types: int32, int64. A tensor whose shape is a prefix of data.shape. Negative segment ids are not supported.
num_segments A Tensor. Must be one of the following types: int32, int64. A scalar.
separator An optional string. Defaults to "". The separator to use when joining.
name A name for the operation (optional).
Returns A Tensor of type string. | tensorflow.strings.unsorted_segment_join |
tf.strings.upper Converts all lowercase characters into their respective uppercase replacements. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.strings.upper
tf.strings.upper(
input, encoding='', name=None
)
Example:
tf.strings.upper("CamelCase string and ALL CAPS")
<tf.Tensor: shape=(), dtype=string, numpy=b'CAMELCASE STRING AND ALL CAPS'>
Args
input A Tensor of type string.
encoding An optional string. Defaults to "".
name A name for the operation (optional).
Returns A Tensor of type string. | tensorflow.strings.upper |
Module: tf.summary View source on GitHub Operations for writing summary data, for use in analysis and visualization. The tf.summary module provides APIs for writing summary data. This data can be visualized in TensorBoard, the visualization toolkit that comes with TensorFlow. See the TensorBoard website for more detailed tutorials about how to use these APIs, or some quick examples below. Example usage with eager execution, the default in TF 2.0: writer = tf.summary.create_file_writer("/tmp/mylogs")
with writer.as_default():
for step in range(100):
# other model code would go here
tf.summary.scalar("my_metric", 0.5, step=step)
writer.flush()
Example usage with tf.function graph execution: writer = tf.summary.create_file_writer("/tmp/mylogs")
@tf.function
def my_func(step):
# other model code would go here
with writer.as_default():
tf.summary.scalar("my_metric", 0.5, step=step)
for step in range(100):
my_func(step)
writer.flush()
Example usage with legacy TF 1.x graph execution: with tf.compat.v1.Graph().as_default():
step = tf.Variable(0, dtype=tf.int64)
step_update = step.assign_add(1)
writer = tf.summary.create_file_writer("/tmp/mylogs")
with writer.as_default():
tf.summary.scalar("my_metric", 0.5, step=step)
all_summary_ops = tf.compat.v1.summary.all_v2_summary_ops()
writer_flush = writer.flush()
sess = tf.compat.v1.Session()
sess.run([writer.init(), step.initializer])
for i in range(100):
sess.run(all_summary_ops)
sess.run(step_update)
sess.run(writer_flush)
Modules experimental module: Public API for tf.summary.experimental namespace. Classes class SummaryWriter: Interface representing a stateful summary writer object. Functions audio(...): Write an audio summary. create_file_writer(...): Creates a summary file writer for the given log directory. create_noop_writer(...): Returns a summary writer that does nothing. flush(...): Forces summary writer to send any buffered data to storage. histogram(...): Write a histogram summary. image(...): Write an image summary. record_if(...): Sets summary recording on or off per the provided boolean value. scalar(...): Write a scalar summary. should_record_summaries(...): Returns boolean Tensor which is true if summaries should be recorded. text(...): Write a text summary. trace_export(...): Stops and exports the active trace as a Summary and/or profile file. trace_off(...): Stops the current trace and discards any collected information. trace_on(...): Starts a trace to record computation graphs and profiling information. write(...): Writes a generic summary to the default SummaryWriter if one exists. | tensorflow.summary |
tf.summary.audio View source on GitHub Write an audio summary.
tf.summary.audio(
name, data, sample_rate, step=None, max_outputs=3, encoding=None,
description=None
)
Arguments
name A name for this summary. The summary tag used for TensorBoard will be this name prefixed by any active name scopes.
data A Tensor representing audio data with shape [k, t, c], where k is the number of audio clips, t is the number of frames, and c is the number of channels. Elements should be floating-point values in [-1.0, 1.0]. Any of the dimensions may be statically unknown (i.e., None).
sample_rate An int or rank-0 int32 Tensor that represents the sample rate, in Hz. Must be positive.
step Explicit int64-castable monotonic step value for this summary. If omitted, this defaults to tf.summary.experimental.get_step(), which must not be None.
max_outputs Optional int or rank-0 integer Tensor. At most this many audio clips will be emitted at each step. When more than max_outputs many clips are provided, the first max_outputs many clips will be used and the rest silently discarded.
encoding Optional constant str for the desired encoding. Only "wav" is currently supported, but this is not guaranteed to remain the default, so if you want "wav" in particular, set this explicitly.
description Optional long-form description for this summary, as a constant str. Markdown is supported. Defaults to empty.
Returns True on success, or false if no summary was emitted because no default summary writer was available.
Raises
ValueError if a default writer exists, but no step was provided and tf.summary.experimental.get_step() is None. | tensorflow.summary.audio |
tf.summary.create_file_writer Creates a summary file writer for the given log directory.
tf.summary.create_file_writer(
logdir, max_queue=None, flush_millis=None, filename_suffix=None, name=None
)
Args
logdir a string specifying the directory in which to write an event file.
max_queue the largest number of summaries to keep in a queue; will flush once the queue gets bigger than this. Defaults to 10.
flush_millis the largest interval between flushes. Defaults to 120,000.
filename_suffix optional suffix for the event file name. Defaults to .v2.
name a name for the op that creates the writer.
Returns A SummaryWriter object. | tensorflow.summary.create_file_writer |
tf.summary.create_noop_writer Returns a summary writer that does nothing.
tf.summary.create_noop_writer()
This is useful as a placeholder in code that expects a context manager. | tensorflow.summary.create_noop_writer |
Module: tf.summary.experimental Public API for tf.summary.experimental namespace. Functions get_step(...): Returns the default summary step for the current thread. set_step(...): Sets the default summary step for the current thread. summary_scope(...): Experimental context manager for use when defining a custom summary op. write_raw_pb(...): Writes a summary using raw tf.compat.v1.Summary protocol buffers. | tensorflow.summary.experimental |
tf.summary.experimental.get_step Returns the default summary step for the current thread.
tf.summary.experimental.get_step()
Returns The step set by tf.summary.experimental.set_step() if one has been set, otherwise None. | tensorflow.summary.experimental.get_step |
tf.summary.experimental.set_step Sets the default summary step for the current thread.
tf.summary.experimental.set_step(
step
)
For convenience, this function sets a default value for the step parameter used in summary-writing functions elsewhere in the API so that it need not be explicitly passed in every such invocation. The value can be a constant or a variable, and can be retrieved via tf.summary.experimental.get_step().
Note: when using this with @tf.functions, the step value will be captured at the time the function is traced, so changes to the step outside the function will not be reflected inside the function unless using a tf.Variable step.
Args
step An int64-castable default step value, or None to unset. | tensorflow.summary.experimental.set_step |
tf.summary.experimental.summary_scope Experimental context manager for use when defining a custom summary op.
@tf_contextlib.contextmanager
tf.summary.experimental.summary_scope(
name, default_name='summary', values=None
)
This behaves similarly to tf.name_scope, except that it returns a generated summary tag in addition to the scope name. The tag is structurally similar to the scope name - derived from the user-provided name, prefixed with enclosing name scopes if any - but we relax the constraint that it be uniquified, as well as the character set limitation (so the user-provided name can contain characters not legal for scope names; in the scope name these are removed). This makes the summary tag more predictable and consistent for the user. For example, to define a new summary op called my_op: def my_op(name, my_value, step):
with tf.summary.summary_scope(name, "MyOp", [my_value]) as (tag, scope):
my_value = tf.convert_to_tensor(my_value)
return tf.summary.write(tag, my_value, step=step)
Args
name string name for the summary.
default_name Optional; if provided, used as default name of the summary.
values Optional; passed as values parameter to name_scope.
Yields A tuple (tag, scope) as described above. | tensorflow.summary.experimental.summary_scope |
tf.summary.experimental.write_raw_pb Writes a summary using raw tf.compat.v1.Summary protocol buffers.
tf.summary.experimental.write_raw_pb(
tensor, step=None, name=None
)
Experimental: this exists to support the usage of V1-style manual summary writing (via the construction of a tf.compat.v1.Summary protocol buffer) with the V2 summary writing API.
Args
tensor the string Tensor holding one or more serialized Summary protobufs
step Explicit int64-castable monotonic step value for this summary. If omitted, this defaults to tf.summary.experimental.get_step(), which must not be None.
name Optional string name for this op.
Returns True on success, or false if no summary was written because no default summary writer was available.
Raises
ValueError if a default writer exists, but no step was provided and tf.summary.experimental.get_step() is None. | tensorflow.summary.experimental.write_raw_pb |
tf.summary.flush Forces summary writer to send any buffered data to storage.
tf.summary.flush(
writer=None, name=None
)
This operation blocks until that finishes.
Args
writer The tf.summary.SummaryWriter resource to flush. The thread default will be used if this parameter is None. Otherwise a tf.no_op is returned.
name A name for the operation (optional).
Returns The created tf.Operation. | tensorflow.summary.flush |
tf.summary.histogram View source on GitHub Write a histogram summary.
tf.summary.histogram(
name, data, step=None, buckets=None, description=None
)
Arguments
name A name for this summary. The summary tag used for TensorBoard will be this name prefixed by any active name scopes.
data A Tensor of any shape. Must be castable to float64.
step Explicit int64-castable monotonic step value for this summary. If omitted, this defaults to tf.summary.experimental.get_step(), which must not be None.
buckets Optional positive int. The output will have this many buckets, except in two edge cases. If there is no data, then there are no buckets. If there is data but all points have the same value, then there is one bucket whose left and right endpoints are the same.
description Optional long-form description for this summary, as a constant str. Markdown is supported. Defaults to empty.
Returns True on success, or false if no summary was emitted because no default summary writer was available.
Raises
ValueError if a default writer exists, but no step was provided and tf.summary.experimental.get_step() is None. | tensorflow.summary.histogram |
tf.summary.image View source on GitHub Write an image summary.
tf.summary.image(
name, data, step=None, max_outputs=3, description=None
)
Arguments
name A name for this summary. The summary tag used for TensorBoard will be this name prefixed by any active name scopes.
data A Tensor representing pixel data with shape [k, h, w, c], where k is the number of images, h and w are the height and width of the images, and c is the number of channels, which should be 1, 2, 3, or 4 (grayscale, grayscale with alpha, RGB, RGBA). Any of the dimensions may be statically unknown (i.e., None). Floating point data will be clipped to the range [0,1).
step Explicit int64-castable monotonic step value for this summary. If omitted, this defaults to tf.summary.experimental.get_step(), which must not be None.
max_outputs Optional int or rank-0 integer Tensor. At most this many images will be emitted at each step. When more than max_outputs many images are provided, the first max_outputs many images will be used and the rest silently discarded.
description Optional long-form description for this summary, as a constant str. Markdown is supported. Defaults to empty.
Returns True on success, or false if no summary was emitted because no default summary writer was available.
Raises
ValueError if a default writer exists, but no step was provided and tf.summary.experimental.get_step() is None. | tensorflow.summary.image |
tf.summary.record_if Sets summary recording on or off per the provided boolean value.
@tf_contextlib.contextmanager
tf.summary.record_if(
condition
)
The provided value can be a python boolean, a scalar boolean Tensor, or or a callable providing such a value; if a callable is passed it will be invoked on-demand to determine whether summary writing will occur.
Args
condition can be True, False, a bool Tensor, or a callable providing such.
Yields Returns a context manager that sets this value on enter and restores the previous value on exit. | tensorflow.summary.record_if |
tf.summary.scalar View source on GitHub Write a scalar summary.
tf.summary.scalar(
name, data, step=None, description=None
)
Arguments
name A name for this summary. The summary tag used for TensorBoard will be this name prefixed by any active name scopes.
data A real numeric scalar value, convertible to a float32 Tensor.
step Explicit int64-castable monotonic step value for this summary. If omitted, this defaults to tf.summary.experimental.get_step(), which must not be None.
description Optional long-form description for this summary, as a constant str. Markdown is supported. Defaults to empty.
Returns True on success, or false if no summary was written because no default summary writer was available.
Raises
ValueError if a default writer exists, but no step was provided and tf.summary.experimental.get_step() is None. | tensorflow.summary.scalar |
tf.summary.should_record_summaries Returns boolean Tensor which is true if summaries should be recorded.
tf.summary.should_record_summaries() | tensorflow.summary.should_record_summaries |
tf.summary.SummaryWriter Interface representing a stateful summary writer object. Methods as_default View source
@abc.abstractmethod
@tf_contextlib.contextmanager
as_default(
step=None
)
Returns a context manager that enables summary writing. For convenience, if step is not None, this function also sets a default value for the step parameter used in summary-writing functions elsewhere in the API so that it need not be explicitly passed in every such invocation. The value can be a constant or a variable.
Note: when setting step in a @tf.function, the step value will be captured at the time the function is traced, so changes to the step outside the function will not be reflected inside the function unless using a tf.Variable step.
For example, step can be used as: with writer_a.as_default(step=10):
tf.summary.scalar(tag, value) # Logged to writer_a with step 10
with writer_b.as_default(step=20):
tf.summary.scalar(tag, value) # Logged to writer_b with step 20
tf.summary.scalar(tag, value) # Logged to writer_a with step 10
Args
step An int64-castable default step value, or None. When not None, the current step is captured, replaced by a given one, and the original one is restored when the context manager exits. When None, the current step is not modified (and not restored when the context manager exits). close View source
close()
Flushes and closes the summary writer. flush View source
flush()
Flushes any buffered data. init View source
init()
Initializes the summary writer. set_as_default View source
@abc.abstractmethod
set_as_default(
step=None
)
Enables this summary writer for the current thread. For convenience, if step is not None, this function also sets a default value for the step parameter used in summary-writing functions elsewhere in the API so that it need not be explicitly passed in every such invocation. The value can be a constant or a variable.
Note: when setting step in a @tf.function, the step value will be captured at the time the function is traced, so changes to the step outside the function will not be reflected inside the function unless using a tf.Variable step.
Args
step An int64-castable default step value, or None. When not None, the current step is modified to the given value. When None, the current step is not modified. | tensorflow.summary.summarywriter |
tf.summary.text View source on GitHub Write a text summary.
tf.summary.text(
name, data, step=None, description=None
)
Arguments
name A name for this summary. The summary tag used for TensorBoard will be this name prefixed by any active name scopes.
data A UTF-8 string tensor value.
step Explicit int64-castable monotonic step value for this summary. If omitted, this defaults to tf.summary.experimental.get_step(), which must not be None.
description Optional long-form description for this summary, as a constant str. Markdown is supported. Defaults to empty.
Returns True on success, or false if no summary was emitted because no default summary writer was available.
Raises
ValueError if a default writer exists, but no step was provided and tf.summary.experimental.get_step() is None. | tensorflow.summary.text |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.