doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
tf.nn.nce_loss View source on GitHub Computes and returns the noise-contrastive estimation training loss. tf.nn.nce_loss( weights, biases, labels, inputs, num_sampled, num_classes, num_true=1, sampled_values=None, remove_accidental_hits=False, name='nce_loss' ) See Noise-contrastive estimation: A new estimation principle for unnormalized statistical models. Also see our Candidate Sampling Algorithms Reference A common use case is to use this method for training, and calculate the full sigmoid loss for evaluation or inference as in the following example: if mode == "train": loss = tf.nn.nce_loss( weights=weights, biases=biases, labels=labels, inputs=inputs, ...) elif mode == "eval": logits = tf.matmul(inputs, tf.transpose(weights)) logits = tf.nn.bias_add(logits, biases) labels_one_hot = tf.one_hot(labels, n_classes) loss = tf.nn.sigmoid_cross_entropy_with_logits( labels=labels_one_hot, logits=logits) loss = tf.reduce_sum(loss, axis=1) Note: when doing embedding lookup on weights and bias, "div" partition strategy will be used. Support for other partition strategy will be added later. Note: By default this uses a log-uniform (Zipfian) distribution for sampling, so your labels must be sorted in order of decreasing frequency to achieve good results. For more details, see tf.random.log_uniform_candidate_sampler. Note: In the case where num_true > 1, we assign to each target class the target probability 1 / num_true so that the target probabilities sum to 1 per-example. Note: It would be useful to allow a variable number of target classes per example. We hope to provide this functionality in a future release. For now, if you have a variable number of target classes, you can pad them out to a constant number by either repeating them or by padding with an otherwise unused class. Args weights A Tensor of shape [num_classes, dim], or a list of Tensor objects whose concatenation along dimension 0 has shape [num_classes, dim]. The (possibly-partitioned) class embeddings. biases A Tensor of shape [num_classes]. The class biases. labels A Tensor of type int64 and shape [batch_size, num_true]. The target classes. inputs A Tensor of shape [batch_size, dim]. The forward activations of the input network. num_sampled An int. The number of negative classes to randomly sample per batch. This single sample of negative classes is evaluated for each element in the batch. num_classes An int. The number of possible classes. num_true An int. The number of target classes per training example. sampled_values a tuple of (sampled_candidates, true_expected_count, sampled_expected_count) returned by a *_candidate_sampler function. (if None, we default to log_uniform_candidate_sampler) remove_accidental_hits A bool. Whether to remove "accidental hits" where a sampled class equals one of the target classes. If set to True, this is a "Sampled Logistic" loss instead of NCE, and we are learning to generate log-odds instead of log probabilities. See our Candidate Sampling Algorithms Reference. Default is False. name A name for the operation (optional). Returns A batch_size 1-D tensor of per-example NCE losses.
tensorflow.nn.nce_loss
tf.nn.normalize_moments View source on GitHub Calculate the mean and variance of based on the sufficient statistics. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.nn.normalize_moments tf.nn.normalize_moments( counts, mean_ss, variance_ss, shift, name=None ) Args counts A Tensor containing the total count of the data (one value). mean_ss A Tensor containing the mean sufficient statistics: the (possibly shifted) sum of the elements to average over. variance_ss A Tensor containing the variance sufficient statistics: the (possibly shifted) squared sum of the data to compute the variance over. shift A Tensor containing the value by which the data is shifted for numerical stability, or None if no shift was performed. name Name used to scope the operations that compute the moments. Returns Two Tensor objects: mean and variance.
tensorflow.nn.normalize_moments
tf.nn.pool View source on GitHub Performs an N-D pooling operation. tf.nn.pool( input, window_shape, pooling_type, strides=None, padding='VALID', data_format=None, dilations=None, name=None ) In the case that data_format does not start with "NC", computes for 0 <= b < batch_size, 0 <= x[i] < output_spatial_shape[i], 0 <= c < num_channels: output[b, x[0], ..., x[N-1], c] = REDUCE_{z[0], ..., z[N-1]} input[b, x[0] * strides[0] - pad_before[0] + dilation_rate[0]*z[0], ... x[N-1]*strides[N-1] - pad_before[N-1] + dilation_rate[N-1]*z[N-1], c], where the reduction function REDUCE depends on the value of pooling_type, and pad_before is defined based on the value of padding as described in the "returns" section of tf.nn.convolution for details. The reduction never includes out-of-bounds positions. In the case that data_format starts with "NC", the input and output are simply transposed as follows: pool(input, data_format, **kwargs) = tf.transpose(pool(tf.transpose(input, [0] + range(2,N+2) + [1]), **kwargs), [0, N+1] + range(1, N+1)) Args input Tensor of rank N+2, of shape [batch_size] + input_spatial_shape + [num_channels] if data_format does not start with "NC" (default), or [batch_size, num_channels] + input_spatial_shape if data_format starts with "NC". Pooling happens over the spatial dimensions only. window_shape Sequence of N ints >= 1. pooling_type Specifies pooling operation, must be "AVG" or "MAX". strides Optional. Sequence of N ints >= 1. Defaults to [1]N. If any value of strides is > 1, then all values of dilation_rate must be 1. padding The padding algorithm, must be "SAME" or "VALID". Defaults to "SAME". See the "returns" section of tf.nn.convolution for details. data_format A string or None. Specifies whether the channel dimension of the input and output is the last dimension (default, or if data_format does not start with "NC"), or the second dimension (if data_format starts with "NC"). For N=1, the valid values are "NWC" (default) and "NCW". For N=2, the valid values are "NHWC" (default) and "NCHW". For N=3, the valid values are "NDHWC" (default) and "NCDHW". dilations Optional. Dilation rate. List of N ints >= 1. Defaults to [1]N. If any value of dilation_rate is > 1, then all values of strides must be 1. name Optional. Name of the op. Returns Tensor of rank N+2, of shape [batch_size] + output_spatial_shape + [num_channels] if data_format is None or does not start with "NC", or [batch_size, num_channels] + output_spatial_shape if data_format starts with "NC", where output_spatial_shape depends on the value of padding: If padding = "SAME": output_spatial_shape[i] = ceil(input_spatial_shape[i] / strides[i]) If padding = "VALID": output_spatial_shape[i] = ceil((input_spatial_shape[i] - (window_shape[i] - 1) * dilation_rate[i]) / strides[i]). Raises ValueError if arguments are invalid.
tensorflow.nn.pool
tf.nn.relu Computes rectified linear: max(features, 0). View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.nn.relu tf.nn.relu( features, name=None ) See: https://en.wikipedia.org/wiki/Rectifier_(neural_networks) Example usage: >>> tf.nn.relu([-2., 0., -0., 3.]).numpy() array([ 0., 0., -0., 3.], dtype=float32) Args features A Tensor. Must be one of the following types: float32, float64, int32, uint8, int16, int8, int64, bfloat16, uint16, half, uint32, uint64, qint8. name A name for the operation (optional). Returns A Tensor. Has the same type as features.
tensorflow.nn.relu
tf.nn.relu6 View source on GitHub Computes Rectified Linear 6: min(max(features, 0), 6). View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.nn.relu6 tf.nn.relu6( features, name=None ) Args features A Tensor with type float, double, int32, int64, uint8, int16, or int8. name A name for the operation (optional). Returns A Tensor with the same type as features. References: Convolutional Deep Belief Networks on CIFAR-10: Krizhevsky et al., 2010 (pdf)
tensorflow.nn.relu6
tf.nn.RNNCellDeviceWrapper Operator that ensures an RNNCell runs on a particular device. Inherits From: AbstractRNNCell, Layer, Module tf.nn.RNNCellDeviceWrapper( *args, **kwargs ) Args cell An instance of RNNCell. device A device string or function, for passing to tf.device. **kwargs dict of keyword arguments for base layer. Attributes output_size state_size Methods get_initial_state View source get_initial_state( inputs=None, batch_size=None, dtype=None ) zero_state View source zero_state( batch_size, dtype )
tensorflow.nn.rnncelldevicewrapper
tf.nn.RNNCellDropoutWrapper Operator adding dropout to inputs and outputs of the given cell. Inherits From: AbstractRNNCell, Layer, Module tf.nn.RNNCellDropoutWrapper( *args, **kwargs ) Args cell an RNNCell, a projection to output_size is added to it. input_keep_prob unit Tensor or float between 0 and 1, input keep probability; if it is constant and 1, no input dropout will be added. output_keep_prob unit Tensor or float between 0 and 1, output keep probability; if it is constant and 1, no output dropout will be added. state_keep_prob unit Tensor or float between 0 and 1, output keep probability; if it is constant and 1, no output dropout will be added. State dropout is performed on the outgoing states of the cell. Note the state components to which dropout is applied when state_keep_prob is in (0, 1) are also determined by the argument dropout_state_filter_visitor (e.g. by default dropout is never applied to the c component of an LSTMStateTuple). variational_recurrent Python bool. If True, then the same dropout pattern is applied across all time steps per run call. If this parameter is set, input_size must be provided. input_size (optional) (possibly nested tuple of) TensorShape objects containing the depth(s) of the input tensors expected to be passed in to the DropoutWrapper. Required and used iff variational_recurrent = True and input_keep_prob < 1. dtype (optional) The dtype of the input, state, and output tensors. Required and used iff variational_recurrent = True. seed (optional) integer, the randomness seed. dropout_state_filter_visitor (optional), default: (see below). Function that takes any hierarchical level of the state and returns a scalar or depth=1 structure of Python booleans describing which terms in the state should be dropped out. In addition, if the function returns True, dropout is applied across this sublevel. If the function returns False, dropout is not applied across this entire sublevel. Default behavior: perform dropout on all terms except the memory (c) state of LSTMCellState objects, and don't try to apply dropout to TensorArray objects: def dropout_state_filter_visitor(s): if isinstance(s, LSTMCellState): # Never perform dropout on the c state. return LSTMCellState(c=False, h=True) elif isinstance(s, TensorArray): return False return True **kwargs dict of keyword arguments for base layer. Raises TypeError if cell is not an RNNCell, or keep_state_fn is provided but not callable. ValueError if any of the keep_probs are not between 0 and 1. Attributes output_size state_size wrapped_cell Methods get_initial_state View source get_initial_state( inputs=None, batch_size=None, dtype=None ) zero_state View source zero_state( batch_size, dtype )
tensorflow.nn.rnncelldropoutwrapper
tf.nn.RNNCellResidualWrapper RNNCell wrapper that ensures cell inputs are added to the outputs. Inherits From: AbstractRNNCell, Layer, Module tf.nn.RNNCellResidualWrapper( *args, **kwargs ) Args cell An instance of RNNCell. residual_fn (Optional) The function to map raw cell inputs and raw cell outputs to the actual cell outputs of the residual network. Defaults to calling nest.map_structure on (lambda i, o: i + o), inputs and outputs. **kwargs dict of keyword arguments for base layer. Attributes output_size state_size Methods get_initial_state View source get_initial_state( inputs=None, batch_size=None, dtype=None ) zero_state View source zero_state( batch_size, dtype )
tensorflow.nn.rnncellresidualwrapper
tf.nn.safe_embedding_lookup_sparse View source on GitHub Lookup embedding results, accounting for invalid IDs and empty features. tf.nn.safe_embedding_lookup_sparse( embedding_weights, sparse_ids, sparse_weights=None, combiner='mean', default_id=None, max_norm=None, name=None ) The partitioned embedding in embedding_weights must all be the same shape except for the first dimension. The first dimension is allowed to vary as the vocabulary size is not necessarily a multiple of num of shards. Invalid IDs (< 0) are pruned from input IDs and weights, as well as any IDs with non-positive weight. For an entry with no features, the embedding vector for default_id is returned, or the 0-vector if default_id is not supplied. The ids and weights may be multi-dimensional. Embeddings are always aggregated along the last dimension. If len(embedding_weights) > 1, each element id of ids is partitioned between the elements of embedding_weights according to the "div" partition strategy, which means we assign ids to partitions in a contiguous manner. For instance, 13 ids are split across 5 partitions as: [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10], [11, 12]]. If the id space does not evenly divide the number of partitions, each of the first (max_id + 1) % len(embedding_weights) partitions will be assigned one more id. Args embedding_weights A single tensor representing the complete embedding tensor, or a list of tensors all of same shape except for the first dimension, representing sharded embedding tensors following "div" partition strategy. sparse_ids SparseTensor of shape [d_0, d_1, ..., d_n] containing the ids. d_0 is typically batch size. sparse_weights SparseTensor of same shape as sparse_ids, containing float weights corresponding to sparse_ids, or None if all weights are be assumed to be 1.0. combiner A string specifying how to combine embedding results for each entry. Currently "mean", "sqrtn" and "sum" are supported, with "mean" the default. default_id The id to use for an entry with no features. Defaults to 0-vector. max_norm If not None, all embeddings are l2-normalized to max_norm before combining. name A name for this operation (optional). Returns A dense tensor representing the combined embeddings for the sparse ids. For each row in the dense tensor represented by sparse_ids, the op looks up the embeddings for all ids in that row, multiplies them by the corresponding weight, and combines these embeddings as specified. In other words, if shape(combined embedding_weights) = [p0, p1, ..., pm] and shape(sparse_ids) = shape(sparse_weights) = [d0, d1, ..., dn] then shape(output) = [d0, d1, ... dn-1, p1, ..., pm]. For instance, if params is a 10x20 matrix, and sp_ids / sp_weights are [0, 0]: id 1, weight 2.0 [0, 1]: id 3, weight 0.5 [1, 0]: id -1, weight 1.0 [2, 3]: id 1, weight 3.0 default_id is 0. with combiner="mean", then the output will be a 3x20 matrix where output[0, :] = (params[1, :] * 2.0 + params[3, :] * 0.5) / (2.0 + 0.5) output[1, :] = (params[0, :] * 1.0) / 1.0 output[2, :] = (params[1, :] * 3.0) / 3.0 Raises ValueError if embedding_weights is empty.
tensorflow.nn.safe_embedding_lookup_sparse
tf.nn.sampled_softmax_loss View source on GitHub Computes and returns the sampled softmax training loss. tf.nn.sampled_softmax_loss( weights, biases, labels, inputs, num_sampled, num_classes, num_true=1, sampled_values=None, remove_accidental_hits=True, seed=None, name='sampled_softmax_loss' ) This is a faster way to train a softmax classifier over a huge number of classes. This operation is for training only. It is generally an underestimate of the full softmax loss. A common use case is to use this method for training, and calculate the full sigmoid loss for evaluation or inference as in the following example: if mode == "train": loss = tf.nn.sampled_softmax_loss( weights=weights, biases=biases, labels=labels, inputs=inputs, ...) elif mode == "eval": logits = tf.matmul(inputs, tf.transpose(weights)) logits = tf.nn.bias_add(logits, biases) labels_one_hot = tf.one_hot(labels, n_classes) loss = tf.nn.softmax_cross_entropy_with_logits( labels=labels_one_hot, logits=logits) See our Candidate Sampling Algorithms Reference Also see Section 3 of Jean et al., 2014 (pdf) for the math. Note: when doing embedding lookup on weights and bias, "div" partition strategy will be used. Support for other partition strategy will be added later. Args weights A Tensor of shape [num_classes, dim], or a list of Tensor objects whose concatenation along dimension 0 has shape [num_classes, dim]. The (possibly-sharded) class embeddings. biases A Tensor of shape [num_classes]. The class biases. labels A Tensor of type int64 and shape [batch_size, num_true]. The target classes. Note that this format differs from the labels argument of nn.softmax_cross_entropy_with_logits. inputs A Tensor of shape [batch_size, dim]. The forward activations of the input network. num_sampled An int. The number of classes to randomly sample per batch. num_classes An int. The number of possible classes. num_true An int. The number of target classes per training example. sampled_values a tuple of (sampled_candidates, true_expected_count, sampled_expected_count) returned by a *_candidate_sampler function. (if None, we default to log_uniform_candidate_sampler) remove_accidental_hits A bool. whether to remove "accidental hits" where a sampled class equals one of the target classes. Default is True. seed random seed for candidate sampling. Default to None, which doesn't set the op-level random seed for candidate sampling. name A name for the operation (optional). Returns A batch_size 1-D tensor of per-example sampled softmax losses.
tensorflow.nn.sampled_softmax_loss
tf.nn.scale_regularization_loss View source on GitHub Scales the sum of the given regularization losses by number of replicas. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.nn.scale_regularization_loss tf.nn.scale_regularization_loss( regularization_loss ) Usage with distribution strategy and custom training loop: with strategy.scope(): def compute_loss(self, label, predictions): per_example_loss = tf.keras.losses.sparse_categorical_crossentropy( labels, predictions) # Compute loss that is scaled by sample_weight and by global batch size. loss = tf.nn.compute_average_loss( per_example_loss, sample_weight=sample_weight, global_batch_size=GLOBAL_BATCH_SIZE) # Add scaled regularization losses. loss += tf.nn.scale_regularization_loss(tf.nn.l2_loss(weights)) return loss Args regularization_loss Regularization loss. Returns Scalar loss value.
tensorflow.nn.scale_regularization_loss
tf.nn.selu Computes scaled exponential linear: scale * alpha * (exp(features) - 1) View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.nn.selu tf.nn.selu( features, name=None ) if < 0, scale * features otherwise. To be used together with initializer = tf.variance_scaling_initializer(factor=1.0, mode='FAN_IN'). For correct dropout, use tf.contrib.nn.alpha_dropout. See Self-Normalizing Neural Networks Args features A Tensor. Must be one of the following types: half, bfloat16, float32, float64. name A name for the operation (optional). Returns A Tensor. Has the same type as features.
tensorflow.nn.selu
tf.nn.separable_conv2d View source on GitHub 2-D convolution with separable filters. tf.nn.separable_conv2d( input, depthwise_filter, pointwise_filter, strides, padding, data_format=None, dilations=None, name=None ) Performs a depthwise convolution that acts separately on channels followed by a pointwise convolution that mixes channels. Note that this is separability between dimensions [1, 2] and 3, not spatial separability between dimensions 1 and 2. In detail, with the default NHWC format, output[b, i, j, k] = sum_{di, dj, q, r} input[b, strides[1] * i + di, strides[2] * j + dj, q] * depthwise_filter[di, dj, q, r] * pointwise_filter[0, 0, q * channel_multiplier + r, k] strides controls the strides for the depthwise convolution only, since the pointwise convolution has implicit strides of [1, 1, 1, 1]. Must have strides[0] = strides[3] = 1. For the most common case of the same horizontal and vertical strides, strides = [1, stride, stride, 1]. If any value in rate is greater than 1, we perform atrous depthwise convolution, in which case all values in the strides tensor must be equal to 1. Args input 4-D Tensor with shape according to data_format. depthwise_filter 4-D Tensor with shape [filter_height, filter_width, in_channels, channel_multiplier]. Contains in_channels convolutional filters of depth 1. pointwise_filter 4-D Tensor with shape [1, 1, channel_multiplier * in_channels, out_channels]. Pointwise filter to mix channels after depthwise_filter has convolved spatially. strides 1-D of size 4. The strides for the depthwise convolution for each dimension of input. padding Controls how to pad the image before applying the depthwise convolution. Can be the string "SAME" or "VALID" indicating the type of padding algorithm to use, or a Python list indicating the explicit paddings at the start and end of each dimension. When explicit padding is used and data_format is "NHWC", this should be in the form [[0, 0], [pad_top, pad_bottom], [pad_left, pad_right], [0, 0]]. When explicit padding used and data_format is "NCHW", this should be in the form [[0, 0], [0, 0], [pad_top, pad_bottom], [pad_left, pad_right]]. data_format The data format for input. Either "NHWC" (default) or "NCHW". dilations 1-D of size 2. The dilation rate in which we sample input values across the height and width dimensions in atrous convolution. If it is greater than 1, then all values of strides must be 1. name A name for this operation (optional). Returns A 4-D Tensor with shape according to 'data_format'. For example, with data_format="NHWC", shape is [batch, out_height, out_width, out_channels].
tensorflow.nn.separable_conv2d
tf.nn.sigmoid_cross_entropy_with_logits View source on GitHub Computes sigmoid cross entropy given logits. tf.nn.sigmoid_cross_entropy_with_logits( labels=None, logits=None, name=None ) Measures the probability error in discrete classification tasks in which each class is independent and not mutually exclusive. For instance, one could perform multilabel classification where a picture can contain both an elephant and a dog at the same time. For brevity, let x = logits, z = labels. The logistic loss is z * -log(sigmoid(x)) + (1 - z) * -log(1 - sigmoid(x)) = z * -log(1 / (1 + exp(-x))) + (1 - z) * -log(exp(-x) / (1 + exp(-x))) = z * log(1 + exp(-x)) + (1 - z) * (-log(exp(-x)) + log(1 + exp(-x))) = z * log(1 + exp(-x)) + (1 - z) * (x + log(1 + exp(-x)) = (1 - z) * x + log(1 + exp(-x)) = x - x * z + log(1 + exp(-x)) For x < 0, to avoid overflow in exp(-x), we reformulate the above x - x * z + log(1 + exp(-x)) = log(exp(x)) - x * z + log(1 + exp(-x)) = - x * z + log(1 + exp(x)) Hence, to ensure stability and avoid overflow, the implementation uses this equivalent formulation max(x, 0) - x * z + log(1 + exp(-abs(x))) logits and labels must have the same type and shape. Args labels A Tensor of the same type and shape as logits. logits A Tensor of type float32 or float64. name A name for the operation (optional). Returns A Tensor of the same shape as logits with the componentwise logistic losses. Raises ValueError If logits and labels do not have the same shape.
tensorflow.nn.sigmoid_cross_entropy_with_logits
tf.nn.silu Computes the SiLU or Swish activation function: x * sigmoid(x). View aliases Main aliases tf.nn.swish Compat aliases for migration See Migration guide for more details. tf.compat.v1.nn.silu, tf.compat.v1.nn.swish tf.nn.silu( features ) The SiLU activation function was introduced in "Gaussian Error Linear Units (GELUs)" Hendrycks et al. 2016 and "Sigmoid-Weighted Linear Units for Neural Network Function Approximation in Reinforcement Learning" Elfwing et al. 2017 and was independently discovered (and called swish) in "Searching for Activation Functions" Ramachandran et al. 2017 Args features A Tensor representing preactivation values. name A name for the operation (optional). Returns The activation value.
tensorflow.nn.silu
tf.nn.softmax View source on GitHub Computes softmax activations. View aliases Main aliases tf.math.softmax tf.nn.softmax( logits, axis=None, name=None ) This function performs the equivalent of softmax = tf.exp(logits) / tf.reduce_sum(tf.exp(logits), axis) Args logits A non-empty Tensor. Must be one of the following types: half, float32, float64. axis The dimension softmax would be performed on. The default is -1 which indicates the last dimension. name A name for the operation (optional). Returns A Tensor. Has the same type and shape as logits. Raises InvalidArgumentError if logits is empty or axis is beyond the last dimension of logits.
tensorflow.nn.softmax
tf.nn.softmax_cross_entropy_with_logits View source on GitHub Computes softmax cross entropy between logits and labels. tf.nn.softmax_cross_entropy_with_logits( labels, logits, axis=-1, name=None ) Measures the probability error in discrete classification tasks in which the classes are mutually exclusive (each entry is in exactly one class). For example, each CIFAR-10 image is labeled with one and only one label: an image can be a dog or a truck, but not both. Note: While the classes are mutually exclusive, their probabilities need not be. All that is required is that each row of labels is a valid probability distribution. If they are not, the computation of the gradient will be incorrect. If using exclusive labels (wherein one and only one class is true at a time), see sparse_softmax_cross_entropy_with_logits. Usage: logits = [[4.0, 2.0, 1.0], [0.0, 5.0, 1.0]] labels = [[1.0, 0.0, 0.0], [0.0, 0.8, 0.2]] tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits) <tf.Tensor: shape=(2,), dtype=float32, numpy=array([0.16984604, 0.82474494], dtype=float32)> Warning: This op expects unscaled logits, since it performs a softmax on logits internally for efficiency. Do not call this op with the output of softmax, as it will produce incorrect results. A common use case is to have logits and labels of shape [batch_size, num_classes], but higher dimensions are supported, with the axis argument specifying the class dimension. logits and labels must have the same dtype (either float16, float32, or float64). Backpropagation will happen into both logits and labels. To disallow backpropagation into labels, pass label tensors through tf.stop_gradient before feeding it to this function. Note that to avoid confusion, it is required to pass only named arguments to this function. Args labels Each vector along the class dimension should hold a valid probability distribution e.g. for the case in which labels are of shape [batch_size, num_classes], each row of labels[i] must be a valid probability distribution. logits Per-label activations, typically a linear output. These activation energies are interpreted as unnormalized log probabilities. axis The class dimension. Defaulted to -1 which is the last dimension. name A name for the operation (optional). Returns A Tensor that contains the softmax cross entropy loss. Its type is the same as logits and its shape is the same as labels except that it does not have the last dimension of labels.
tensorflow.nn.softmax_cross_entropy_with_logits
tf.nn.softsign Computes softsign: features / (abs(features) + 1). View aliases Main aliases tf.math.softsign Compat aliases for migration See Migration guide for more details. tf.compat.v1.math.softsign, tf.compat.v1.nn.softsign tf.nn.softsign( features, name=None ) Args features A Tensor. Must be one of the following types: half, bfloat16, float32, float64. name A name for the operation (optional). Returns A Tensor. Has the same type as features.
tensorflow.nn.softsign
tf.nn.space_to_depth View source on GitHub SpaceToDepth for tensors of type T. tf.nn.space_to_depth( input, block_size, data_format='NHWC', name=None ) Rearranges blocks of spatial data, into depth. More specifically, this op outputs a copy of the input tensor where values from the height and width dimensions are moved to the depth dimension. The attr block_size indicates the input block size. Non-overlapping blocks of size block_size x block size are rearranged into depth at each location. The depth of the output tensor is block_size * block_size * input_depth. The Y, X coordinates within each block of the input become the high order component of the output channel index. The input tensor's height and width must be divisible by block_size. The data_format attr specifies the layout of the input and output tensors with the following options: "NHWC": [ batch, height, width, channels ] "NCHW": [ batch, channels, height, width ] "NCHW_VECT_C": qint8 [ batch, channels / 4, height, width, 4 ] It is useful to consider the operation as transforming a 6-D Tensor. e.g. for data_format = NHWC, Each element in the input tensor can be specified via 6 coordinates, ordered by decreasing memory layout significance as: n,oY,bY,oX,bX,iC (where n=batch index, oX, oY means X or Y coordinates within the output image, bX, bY means coordinates within the input block, iC means input channels). The output would be a transpose to the following layout: n,oY,oX,bY,bX,iC This operation is useful for resizing the activations between convolutions (but keeping all data), e.g. instead of pooling. It is also useful for training purely convolutional models. For example, given an input of shape [1, 2, 2, 1], data_format = "NHWC" and block_size = 2: x = [[[[1], [2]], [[3], [4]]]] This operation will output a tensor of shape [1, 1, 1, 4]: [[[[1, 2, 3, 4]]]] Here, the input has a batch of 1 and each batch element has shape [2, 2, 1], the corresponding output will have a single element (i.e. width and height are both 1) and will have a depth of 4 channels (1 * block_size * block_size). The output element shape is [1, 1, 4]. For an input tensor with larger depth, here of shape [1, 2, 2, 3], e.g. x = [[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]] This operation, for block_size of 2, will return the following tensor of shape [1, 1, 1, 12] [[[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]]] Similarly, for the following input of shape [1 4 4 1], and a block size of 2: x = [[[[1], [2], [5], [6]], [[3], [4], [7], [8]], [[9], [10], [13], [14]], [[11], [12], [15], [16]]]] the operator will return the following tensor of shape [1 2 2 4]: x = [[[[1, 2, 3, 4], [5, 6, 7, 8]], [[9, 10, 11, 12], [13, 14, 15, 16]]]] Args input A Tensor. block_size An int that is >= 2. The size of the spatial block. data_format An optional string from: "NHWC", "NCHW", "NCHW_VECT_C". Defaults to "NHWC". name A name for the operation (optional). Returns A Tensor. Has the same type as input.
tensorflow.nn.space_to_depth
tf.nn.sparse_softmax_cross_entropy_with_logits View source on GitHub Computes sparse softmax cross entropy between logits and labels. tf.nn.sparse_softmax_cross_entropy_with_logits( labels, logits, name=None ) Measures the probability error in discrete classification tasks in which the classes are mutually exclusive (each entry is in exactly one class). For example, each CIFAR-10 image is labeled with one and only one label: an image can be a dog or a truck, but not both. Note: For this operation, the probability of a given label is considered exclusive. That is, soft classes are not allowed, and the labels vector must provide a single specific index for the true class for each row of logits (each minibatch entry). For soft softmax classification with a probability distribution for each entry, see softmax_cross_entropy_with_logits_v2. Warning: This op expects unscaled logits, since it performs a softmax on logits internally for efficiency. Do not call this op with the output of softmax, as it will produce incorrect results. A common use case is to have logits of shape [batch_size, num_classes] and have labels of shape [batch_size], but higher dimensions are supported, in which case the dim-th dimension is assumed to be of size num_classes. logits must have the dtype of float16, float32, or float64, and labels must have the dtype of int32 or int64. Note that to avoid confusion, it is required to pass only named arguments to this function. Args labels Tensor of shape [d_0, d_1, ..., d_{r-1}] (where r is rank of labels and result) and dtype int32 or int64. Each entry in labels must be an index in [0, num_classes). Other values will raise an exception when this op is run on CPU, and return NaN for corresponding loss and gradient rows on GPU. logits Unscaled log probabilities of shape [d_0, d_1, ..., d_{r-1}, num_classes] and dtype float16, float32, or float64. name A name for the operation (optional). Returns A Tensor of the same shape as labels and of the same type as logits with the softmax cross entropy loss. Raises ValueError If logits are scalars (need to have rank >= 1) or if the rank of the labels is not equal to the rank of the logits minus one.
tensorflow.nn.sparse_softmax_cross_entropy_with_logits
tf.nn.sufficient_statistics View source on GitHub Calculate the sufficient statistics for the mean and variance of x. tf.nn.sufficient_statistics( x, axes, shift=None, keepdims=False, name=None ) These sufficient statistics are computed using the one pass algorithm on an input that's optionally shifted. See: https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Computing_shifted_data Args x A Tensor. axes Array of ints. Axes along which to compute mean and variance. shift A Tensor containing the value by which to shift the data for numerical stability, or None if no shift is to be performed. A shift close to the true mean provides the most numerically stable results. keepdims produce statistics with the same dimensionality as the input. name Name used to scope the operations that compute the sufficient stats. Returns Four Tensor objects of the same type as x: the count (number of elements to average over). the (possibly shifted) sum of the elements in the array. the (possibly shifted) sum of squares of the elements in the array. the shift by which the mean must be corrected or None if shift is None.
tensorflow.nn.sufficient_statistics
tf.nn.weighted_cross_entropy_with_logits View source on GitHub Computes a weighted cross entropy. tf.nn.weighted_cross_entropy_with_logits( labels, logits, pos_weight, name=None ) This is like sigmoid_cross_entropy_with_logits() except that pos_weight, allows one to trade off recall and precision by up- or down-weighting the cost of a positive error relative to a negative error. The usual cross-entropy cost is defined as: labels * -log(sigmoid(logits)) + (1 - labels) * -log(1 - sigmoid(logits)) A value pos_weight > 1 decreases the false negative count, hence increasing the recall. Conversely setting pos_weight < 1 decreases the false positive count and increases the precision. This can be seen from the fact that pos_weight is introduced as a multiplicative coefficient for the positive labels term in the loss expression: labels * -log(sigmoid(logits)) * pos_weight + (1 - labels) * -log(1 - sigmoid(logits)) For brevity, let x = logits, z = labels, q = pos_weight. The loss is: qz * -log(sigmoid(x)) + (1 - z) * -log(1 - sigmoid(x)) = qz * -log(1 / (1 + exp(-x))) + (1 - z) * -log(exp(-x) / (1 + exp(-x))) = qz * log(1 + exp(-x)) + (1 - z) * (-log(exp(-x)) + log(1 + exp(-x))) = qz * log(1 + exp(-x)) + (1 - z) * (x + log(1 + exp(-x)) = (1 - z) * x + (qz + 1 - z) * log(1 + exp(-x)) = (1 - z) * x + (1 + (q - 1) * z) * log(1 + exp(-x)) Setting l = (1 + (q - 1) * z), to ensure stability and avoid overflow, the implementation uses (1 - z) * x + l * (log(1 + exp(-abs(x))) + max(-x, 0)) logits and labels must have the same type and shape. Args labels A Tensor of the same type and shape as logits. logits A Tensor of type float32 or float64. pos_weight A coefficient to use on the positive examples. name A name for the operation (optional). Returns A Tensor of the same shape as logits with the componentwise weighted logistic losses. Raises ValueError If logits and labels do not have the same shape.
tensorflow.nn.weighted_cross_entropy_with_logits
tf.nn.weighted_moments View source on GitHub Returns the frequency-weighted mean and variance of x. tf.nn.weighted_moments( x, axes, frequency_weights, keepdims=False, name=None ) Args x A tensor. axes 1-d tensor of int32 values; these are the axes along which to compute mean and variance. frequency_weights A tensor of positive weights which can be broadcast with x. keepdims Produce moments with the same dimensionality as the input. name Name used to scope the operation. Returns Two tensors: weighted_mean and weighted_variance.
tensorflow.nn.weighted_moments
tf.nn.with_space_to_batch View source on GitHub Performs op on the space-to-batch representation of input. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.nn.with_space_to_batch tf.nn.with_space_to_batch( input, dilation_rate, padding, op, filter_shape=None, spatial_dims=None, data_format=None ) This has the effect of transforming sliding window operations into the corresponding "atrous" operation in which the input is sampled at the specified dilation_rate. In the special case that dilation_rate is uniformly 1, this simply returns: op(input, num_spatial_dims, padding) Otherwise, it returns: batch_to_space_nd( op(space_to_batch_nd(input, adjusted_dilation_rate, adjusted_paddings), num_spatial_dims, "VALID") adjusted_dilation_rate, adjusted_crops), where: adjusted_dilation_rate is an int64 tensor of shape [max(spatialdims)], adjusted{paddings,crops} are int64 tensors of shape [max(spatial_dims), 2] defined as follows: We first define two int64 tensors paddings and crops of shape [num_spatial_dims, 2] based on the value of padding and the spatial dimensions of the input: If padding = "VALID", then: paddings, crops = required_space_to_batch_paddings( input_shape[spatial_dims], dilation_rate) If padding = "SAME", then: dilated_filter_shape = filter_shape + (filter_shape - 1) * (dilation_rate - 1) paddings, crops = required_space_to_batch_paddings( input_shape[spatial_dims], dilation_rate, [(dilated_filter_shape - 1) // 2, dilated_filter_shape - 1 - (dilated_filter_shape - 1) // 2]) Because space_to_batch_nd and batch_to_space_nd assume that the spatial dimensions are contiguous starting at the second dimension, but the specified spatial_dims may not be, we must adjust dilation_rate, paddings and crops in order to be usable with these operations. For a given dimension, if the block size is 1, and both the starting and ending padding and crop amounts are 0, then space_to_batch_nd effectively leaves that dimension alone, which is what is needed for dimensions not part of spatial_dims. Furthermore, space_to_batch_nd and batch_to_space_nd handle this case efficiently for any number of leading and trailing dimensions. For 0 <= i < len(spatial_dims), we assign: adjusted_dilation_rate[spatial_dims[i] - 1] = dilation_rate[i] adjusted_paddings[spatial_dims[i] - 1, :] = paddings[i, :] adjusted_crops[spatial_dims[i] - 1, :] = crops[i, :] All unassigned values of adjusted_dilation_rate default to 1, while all unassigned values of adjusted_paddings and adjusted_crops default to 0. Note in the case that dilation_rate is not uniformly 1, specifying "VALID" padding is equivalent to specifying padding = "SAME" with a filter_shape of [1]*N. Advanced usage. Note the following optimization: A sequence of with_space_to_batch operations with identical (not uniformly 1) dilation_rate parameters and "VALID" padding net = with_space_to_batch(net, dilation_rate, "VALID", op_1) ... net = with_space_to_batch(net, dilation_rate, "VALID", op_k) can be combined into a single with_space_to_batch operation as follows: def combined_op(converted_input, num_spatial_dims, _): result = op_1(converted_input, num_spatial_dims, "VALID") ... result = op_k(result, num_spatial_dims, "VALID") net = with_space_to_batch(net, dilation_rate, "VALID", combined_op) This eliminates the overhead of k-1 calls to space_to_batch_nd and batch_to_space_nd. Similarly, a sequence of with_space_to_batch operations with identical (not uniformly 1) dilation_rate parameters, "SAME" padding, and odd filter dimensions net = with_space_to_batch(net, dilation_rate, "SAME", op_1, filter_shape_1) ... net = with_space_to_batch(net, dilation_rate, "SAME", op_k, filter_shape_k) can be combined into a single with_space_to_batch operation as follows: def combined_op(converted_input, num_spatial_dims, _): result = op_1(converted_input, num_spatial_dims, "SAME") ... result = op_k(result, num_spatial_dims, "SAME") net = with_space_to_batch(net, dilation_rate, "VALID", combined_op) Args input Tensor of rank > max(spatial_dims). dilation_rate int32 Tensor of known shape [num_spatial_dims]. padding str constant equal to "VALID" or "SAME" op Function that maps (input, num_spatial_dims, padding) -> output filter_shape If padding = "SAME", specifies the shape of the convolution kernel/pooling window as an integer Tensor of shape [>=num_spatial_dims]. If padding = "VALID", filter_shape is ignored and need not be specified. spatial_dims Monotonically increasing sequence of num_spatial_dims integers (which are >= 1) specifying the spatial dimensions of input and output. Defaults to: range(1, num_spatial_dims+1). data_format A string or None. Specifies whether the channel dimension of the input and output is the last dimension (default, or if data_format does not start with "NC"), or the second dimension (if data_format starts with "NC"). For N=1, the valid values are "NWC" (default) and "NCW". For N=2, the valid values are "NHWC" (default) and "NCHW". For N=3, the valid values are "NDHWC" (default) and "NCDHW". Returns The output Tensor as described above, dimensions will vary based on the op provided. Raises ValueError if padding is invalid or the arguments are incompatible. ValueError if spatial_dims are invalid.
tensorflow.nn.with_space_to_batch
tf.nondifferentiable_batch_function View source on GitHub Batches the computation done by the decorated function. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.nondifferentiable_batch_function tf.nondifferentiable_batch_function( num_batch_threads, max_batch_size, batch_timeout_micros, allowed_batch_sizes=None, max_enqueued_batches=10, autograph=True, enable_large_batch_splitting=True ) So, for example, in the following code @batch_function(1, 2, 3) def layer(a): return tf.matmul(a, a) b = layer(w) if more than one session.run call is simultaneously trying to compute b the values of w will be gathered, non-deterministically concatenated along the first axis, and only one thread will run the computation. See the documentation of the Batch op for more details. Assumes that all arguments of the decorated function are Tensors which will be batched along their first dimension. SparseTensor is not supported. The return value of the decorated function must be a Tensor or a list/tuple of Tensors. Args num_batch_threads Number of scheduling threads for processing batches of work. Determines the number of batches processed in parallel. max_batch_size Batch sizes will never be bigger than this. batch_timeout_micros Maximum number of microseconds to wait before outputting an incomplete batch. allowed_batch_sizes Optional list of allowed batch sizes. If left empty, does nothing. Otherwise, supplies a list of batch sizes, causing the op to pad batches up to one of those sizes. The entries must increase monotonically, and the final entry must equal max_batch_size. max_enqueued_batches The maximum depth of the batch queue. Defaults to 10. autograph Whether to use autograph to compile python and eager style code for efficient graph-mode execution. enable_large_batch_splitting The value of this option doesn't affect processing output given the same input; it affects implementation details as stated below: 1. Improve batching efficiency by eliminating unnecessary adding. 2.max_batch_size specifies the limit of input and allowed_batch_sizes specifies the limit of a task to be processed. API user can give an input of size 128 when 'max_execution_batch_size' is 32 -> implementation can split input of 128 into 4 x 32, schedule concurrent processing, and then return concatenated results corresponding to 128. Returns The decorated function will return the unbatched computation output Tensors.
tensorflow.nondifferentiable_batch_function
tf.norm View source on GitHub Computes the norm of vectors, matrices, and tensors. View aliases Main aliases tf.linalg.norm tf.norm( tensor, ord='euclidean', axis=None, keepdims=None, name=None ) This function can compute several different vector norms (the 1-norm, the Euclidean or 2-norm, the inf-norm, and in general the p-norm for p > 0) and matrix norms (Frobenius, 1-norm, 2-norm and inf-norm). Args tensor Tensor of types float32, float64, complex64, complex128 ord Order of the norm. Supported values are 'fro', 'euclidean', 1, 2, np.inf and any positive real number yielding the corresponding p-norm. Default is 'euclidean' which is equivalent to Frobenius norm if tensor is a matrix and equivalent to 2-norm for vectors. Some restrictions apply: a) The Frobenius norm 'fro' is not defined for vectors, b) If axis is a 2-tuple (matrix norm), only 'euclidean', 'fro', 1, 2, np.inf are supported. See the description of axis on how to compute norms for a batch of vectors or matrices stored in a tensor. axis If axis is None (the default), the input is considered a vector and a single vector norm is computed over the entire set of values in the tensor, i.e. norm(tensor, ord=ord) is equivalent to norm(reshape(tensor, [-1]), ord=ord). If axis is a Python integer, the input is considered a batch of vectors, and axis determines the axis in tensor over which to compute vector norms. If axis is a 2-tuple of Python integers it is considered a batch of matrices and axis determines the axes in tensor over which to compute a matrix norm. Negative indices are supported. Example: If you are passing a tensor that can be either a matrix or a batch of matrices at runtime, pass axis=[-2,-1] instead of axis=None to make sure that matrix norms are computed. keepdims If True, the axis indicated in axis are kept with size 1. Otherwise, the dimensions in axis are removed from the output shape. name The name of the op. Returns output A Tensor of the same type as tensor, containing the vector or matrix norms. If keepdims is True then the rank of output is equal to the rank of tensor. Otherwise, if axis is none the output is a scalar, if axis is an integer, the rank of output is one less than the rank of tensor, if axis is a 2-tuple the rank of output is two less than the rank of tensor. Raises ValueError If ord or axis is invalid. Numpy Compatibility Mostly equivalent to numpy.linalg.norm. Not supported: ord <= 0, 2-norm for matrices, nuclear norm. Other differences: a) If axis is None, treats the flattened tensor as a vector regardless of rank. b) Explicitly supports 'euclidean' norm as the default, including for higher order tensors.
tensorflow.norm
tf.no_gradient View source on GitHub Specifies that ops of type op_type is not differentiable. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.NoGradient, tf.compat.v1.NotDifferentiable, tf.compat.v1.no_gradient tf.no_gradient( op_type ) This function should not be used for operations that have a well-defined gradient that is not yet implemented. This function is only used when defining a new op type. It may be used for ops such as tf.size() that are not differentiable. For example: tf.no_gradient("Size") The gradient computed for 'op_type' will then propagate zeros. For ops that have a well-defined gradient but are not yet implemented, no declaration should be made, and an error must be thrown if an attempt to request its gradient is made. Args op_type The string type of an operation. This corresponds to the OpDef.name field for the proto that defines the operation. Raises TypeError If op_type is not a string.
tensorflow.no_gradient
tf.no_op Does nothing. Only useful as a placeholder for control edges. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.no_op tf.no_op( name=None ) Args name A name for the operation (optional). Returns The created Operation.
tensorflow.no_op
tf.numpy_function View source on GitHub Wraps a python function and uses it as a TensorFlow op. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.numpy_function tf.numpy_function( func, inp, Tout, name=None ) Given a python function func wrap this function as an operation in a TensorFlow function. func must take numpy arrays as its arguments and return numpy arrays as its outputs. The following example creates a TensorFlow graph with np.sinh() as an operation in the graph: def my_numpy_func(x): # x will be a numpy array with the contents of the input to the # tf.function return np.sinh(x) @tf.function(input_signature=[tf.TensorSpec(None, tf.float32)]) def tf_function(input): y = tf.numpy_function(my_numpy_func, [input], tf.float32) return y * y tf_function(tf.constant(1.)) <tf.Tensor: shape=(), dtype=float32, numpy=1.3810978> Comparison to tf.py_function: tf.py_function and tf.numpy_function are very similar, except that tf.numpy_function takes numpy arrays, and not tf.Tensors. If you want the function to contain tf.Tensors, and have any TensorFlow operations executed in the function be differentiable, please use tf.py_function. Note: The tf.numpy_function operation has the following known limitations: The body of the function (i.e. func) will not be serialized in a tf.SavedModel. Therefore, you should not use this function if you need to serialize your model and restore it in a different environment. The operation must run in the same address space as the Python program that calls tf.numpy_function(). If you are using distributed TensorFlow, you must run a tf.distribute.Server in the same process as the program that calls tf.numpy_function you must pin the created operation to a device in that server (e.g. using with tf.device():). Since the function takes numpy arrays, you cannot take gradients through a numpy_function. If you require something that is differentiable, please consider using tf.py_function. The resulting function is assumed stateful and will never be optimized. Args func A Python function, which accepts numpy.ndarray objects as arguments and returns a list of numpy.ndarray objects (or a single numpy.ndarray). This function must accept as many arguments as there are tensors in inp, and these argument types will match the corresponding tf.Tensor objects in inp. The returns numpy.ndarrays must match the number and types defined Tout. Important Note: Input and output numpy.ndarrays of func are not guaranteed to be copies. In some cases their underlying memory will be shared with the corresponding TensorFlow tensors. In-place modification or storing func input or return values in python datastructures without explicit (np.)copy can have non-deterministic consequences. inp A list of tf.Tensor objects. Tout A list or tuple of tensorflow data types or a single tensorflow data type if there is only one, indicating what func returns. name (Optional) A name for the operation. Returns Single or list of tf.Tensor which func computes.
tensorflow.numpy_function
tf.ones View source on GitHub Creates a tensor with all elements set to one (1). View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.ones tf.ones( shape, dtype=tf.dtypes.float32, name=None ) See also tf.ones_like, tf.zeros, tf.fill, tf.eye. This operation returns a tensor of type dtype with shape shape and all elements set to one. tf.ones([3, 4], tf.int32) <tf.Tensor: shape=(3, 4), dtype=int32, numpy= array([[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], dtype=int32)> Args shape A list of integers, a tuple of integers, or a 1-D Tensor of type int32. dtype Optional DType of an element in the resulting Tensor. Default is tf.float32. name Optional string. A name for the operation. Returns A Tensor with all elements set to one (1).
tensorflow.ones
tf.ones_initializer Initializer that generates tensors initialized to 1. Initializers allow you to pre-specify an initialization strategy, encoded in the Initializer object, without knowing the shape and dtype of the variable being initialized. Examples: def make_variables(k, initializer): return (tf.Variable(initializer(shape=[k], dtype=tf.float32)), tf.Variable(initializer(shape=[k, k], dtype=tf.float32))) v1, v2 = make_variables(3, tf.ones_initializer()) v1 <tf.Variable ... shape=(3,) ... numpy=array([1., 1., 1.], dtype=float32)> v2 <tf.Variable ... shape=(3, 3) ... numpy= array([[1., 1., 1.], [1., 1., 1.], [1., 1., 1.]], dtype=float32)> make_variables(4, tf.random_uniform_initializer(minval=-1., maxval=1.)) (<tf.Variable...shape=(4,) dtype=float32...>, <tf.Variable...shape=(4, 4) ... Methods from_config View source @classmethod from_config( config ) Instantiates an initializer from a configuration dictionary. Example: initializer = RandomUniform(-1, 1) config = initializer.get_config() initializer = RandomUniform.from_config(config) Args config A Python dictionary. It will typically be the output of get_config. Returns An Initializer instance. get_config View source get_config() Returns the configuration of the initializer as a JSON-serializable dict. Returns A JSON-serializable Python dict. __call__ View source __call__( shape, dtype=tf.dtypes.float32, **kwargs ) Returns a tensor object initialized as specified by the initializer. Args shape Shape of the tensor. dtype Optional dtype of the tensor. Only numeric or boolean dtypes are supported. **kwargs Additional keyword arguments. Raises ValuesError If the dtype is not numeric or boolean.
tensorflow.ones_initializer
tf.ones_like View source on GitHub Creates a tensor of all ones that has the same shape as the input. tf.ones_like( input, dtype=None, name=None ) See also tf.ones. Given a single tensor (tensor), this operation returns a tensor of the same type and shape as tensor with all elements set to 1. Optionally, you can use dtype to specify a new type for the returned tensor. For example: tensor = tf.constant([[1, 2, 3], [4, 5, 6]]) tf.ones_like(tensor) <tf.Tensor: shape=(2, 3), dtype=int32, numpy= array([[1, 1, 1], [1, 1, 1]], dtype=int32)> Args input A Tensor. dtype A type for the returned Tensor. Must be float16, float32, float64, int8, uint8, int16, uint16, int32, int64, complex64, complex128, bool or string. name A name for the operation (optional). Returns A Tensor with all elements set to one.
tensorflow.ones_like
tf.one_hot View source on GitHub Returns a one-hot tensor. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.one_hot tf.one_hot( indices, depth, on_value=None, off_value=None, axis=None, dtype=None, name=None ) See also tf.fill, tf.eye. The locations represented by indices in indices take value on_value, while all other locations take value off_value. on_value and off_value must have matching data types. If dtype is also provided, they must be the same data type as specified by dtype. If on_value is not provided, it will default to the value 1 with type dtype If off_value is not provided, it will default to the value 0 with type dtype If the input indices is rank N, the output will have rank N+1. The new axis is created at dimension axis (default: the new axis is appended at the end). If indices is a scalar the output shape will be a vector of length depth If indices is a vector of length features, the output shape will be: features x depth if axis == -1 depth x features if axis == 0 If indices is a matrix (batch) with shape [batch, features], the output shape will be: batch x features x depth if axis == -1 batch x depth x features if axis == 1 depth x batch x features if axis == 0 If indices is a RaggedTensor, the 'axis' argument must be positive and refer to a non-ragged axis. The output will be equivalent to applying 'one_hot' on the values of the RaggedTensor, and creating a new RaggedTensor from the result. If dtype is not provided, it will attempt to assume the data type of on_value or off_value, if one or both are passed in. If none of on_value, off_value, or dtype are provided, dtype will default to the value tf.float32. Note: If a non-numeric data type output is desired (tf.string, tf.bool, etc.), both on_value and off_value must be provided to one_hot. For example: indices = [0, 1, 2] depth = 3 tf.one_hot(indices, depth) # output: [3 x 3] # [[1., 0., 0.], # [0., 1., 0.], # [0., 0., 1.]] indices = [0, 2, -1, 1] depth = 3 tf.one_hot(indices, depth, on_value=5.0, off_value=0.0, axis=-1) # output: [4 x 3] # [[5.0, 0.0, 0.0], # one_hot(0) # [0.0, 0.0, 5.0], # one_hot(2) # [0.0, 0.0, 0.0], # one_hot(-1) # [0.0, 5.0, 0.0]] # one_hot(1) indices = [[0, 2], [1, -1]] depth = 3 tf.one_hot(indices, depth, on_value=1.0, off_value=0.0, axis=-1) # output: [2 x 2 x 3] # [[[1.0, 0.0, 0.0], # one_hot(0) # [0.0, 0.0, 1.0]], # one_hot(2) # [[0.0, 1.0, 0.0], # one_hot(1) # [0.0, 0.0, 0.0]]] # one_hot(-1) indices = tf.ragged.constant([[0, 1], [2]]) depth = 3 tf.one_hot(indices, depth) # output: [2 x None x 3] # [[[1., 0., 0.], # [0., 1., 0.]], # [[0., 0., 1.]]] Args indices A Tensor of indices. depth A scalar defining the depth of the one hot dimension. on_value A scalar defining the value to fill in output when indices[j] = i. (default: 1) off_value A scalar defining the value to fill in output when indices[j] != i. (default: 0) axis The axis to fill (default: -1, a new inner-most axis). dtype The data type of the output tensor. name A name for the operation (optional). Returns output The one-hot tensor. Raises TypeError If dtype of either on_value or off_value don't match dtype TypeError If dtype of on_value and off_value don't match one another
tensorflow.one_hot
tf.Operation View source on GitHub Represents a graph node that performs computation on tensors. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.Operation tf.Operation( node_def, g, inputs=None, output_types=None, control_inputs=None, input_types=None, original_op=None, op_def=None ) An Operation is a node in a tf.Graph that takes zero or more Tensor objects as input, and produces zero or more Tensor objects as output. Objects of type Operation are created by calling a Python op constructor (such as tf.matmul) within a tf.function or under a tf.Graph.as_default context manager. For example, within a tf.function, c = tf.matmul(a, b) creates an Operation of type "MatMul" that takes tensors a and b as input, and produces c as output. If a tf.compat.v1.Session is used, an Operation of a tf.Graph can be executed by passing it to tf.Session.run. op.run() is a shortcut for calling tf.compat.v1.get_default_session().run(op). Args node_def node_def_pb2.NodeDef. NodeDef for the Operation. Used for attributes of node_def_pb2.NodeDef, typically name, op, and device. The input attribute is irrelevant here as it will be computed when generating the model. g Graph. The parent graph. inputs list of Tensor objects. The inputs to this Operation. output_types list of DType objects. List of the types of the Tensors computed by this operation. The length of this list indicates the number of output endpoints of the Operation. control_inputs list of operations or tensors from which to have a control dependency. input_types List of DType objects representing the types of the tensors accepted by the Operation. By default uses [x.dtype.base_dtype for x in inputs]. Operations that expect reference-typed inputs must specify these explicitly. original_op Optional. Used to associate the new Operation with an existing Operation (for example, a replica with the op that was replicated). op_def Optional. The op_def_pb2.OpDef proto that describes the op type that this Operation represents. Raises TypeError if control inputs are not Operations or Tensors, or if node_def is not a NodeDef, or if g is not a Graph, or if inputs are not tensors, or if inputs and input_types are incompatible. ValueError if the node_def name is not valid. Attributes control_inputs The Operation objects on which this op has a control dependency. Before this op is executed, TensorFlow will ensure that the operations in self.control_inputs have finished executing. This mechanism can be used to run ops sequentially for performance reasons, or to ensure that the side effects of an op are observed in the correct order. device The name of the device to which this op has been assigned, if any. graph The Graph that contains this operation. inputs The sequence of Tensor objects representing the data inputs of this op. name The full name of this operation. node_def Returns the NodeDef representation of this operation. op_def Returns the OpDef proto that represents the type of this op. outputs The list of Tensor objects representing the outputs of this op. traceback Returns the call stack from when this operation was constructed. type The type of the op (e.g. "MatMul"). Methods colocation_groups View source colocation_groups() Returns the list of colocation groups of the op. get_attr View source get_attr( name ) Returns the value of the attr of this op with the given name. Args name The name of the attr to fetch. Returns The value of the attr, as a Python object. Raises ValueError If this op does not have an attr with the given name. run View source run( feed_dict=None, session=None ) Runs this operation in a Session. Calling this method will execute all preceding operations that produce the inputs needed for this operation. Note: Before invoking Operation.run(), its graph must have been launched in a session, and either a default session must be available, or session must be specified explicitly. 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 run to this operation. If none, the default session will be used. values View source values() DEPRECATED: Use outputs.
tensorflow.operation
tf.OptionalSpec View source on GitHub Type specification for tf.experimental.Optional. Inherits From: TypeSpec View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.OptionalSpec, tf.compat.v1.data.experimental.OptionalStructure tf.OptionalSpec( element_spec ) For instance, tf.OptionalSpec can be used to define a tf.function that takes tf.experimental.Optional as an input argument: @tf.function(input_signature=[tf.OptionalSpec( tf.TensorSpec(shape=(), dtype=tf.int32, name=None))]) def maybe_square(optional): if optional.has_value(): x = optional.get_value() return x * x return -1 optional = tf.experimental.Optional.from_value(5) print(maybe_square(optional)) tf.Tensor(25, shape=(), dtype=int32) Attributes element_spec A nested structure of TypeSpec objects that represents the type specification of the optional element. value_type The Python type for values that are compatible with this TypeSpec. In particular, all values that are compatible with this TypeSpec must be an instance of this type. Methods from_value View source @staticmethod 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.optionalspec
tf.pad View source on GitHub Pads a tensor. tf.pad( tensor, paddings, mode='CONSTANT', constant_values=0, name=None ) This operation pads a tensor according to the paddings you specify. paddings is an integer tensor with shape [n, 2], where n is the rank of tensor. For each dimension D of input, paddings[D, 0] indicates how many values to add before the contents of tensor in that dimension, and paddings[D, 1] indicates how many values to add after the contents of tensor in that dimension. If mode is "REFLECT" then both paddings[D, 0] and paddings[D, 1] must be no greater than tensor.dim_size(D) - 1. If mode is "SYMMETRIC" then both paddings[D, 0] and paddings[D, 1] must be no greater than tensor.dim_size(D). The padded size of each dimension D of the output is: paddings[D, 0] + tensor.dim_size(D) + paddings[D, 1] For example: t = tf.constant([[1, 2, 3], [4, 5, 6]]) paddings = tf.constant([[1, 1,], [2, 2]]) # 'constant_values' is 0. # rank of 't' is 2. tf.pad(t, paddings, "CONSTANT") # [[0, 0, 0, 0, 0, 0, 0], # [0, 0, 1, 2, 3, 0, 0], # [0, 0, 4, 5, 6, 0, 0], # [0, 0, 0, 0, 0, 0, 0]] tf.pad(t, paddings, "REFLECT") # [[6, 5, 4, 5, 6, 5, 4], # [3, 2, 1, 2, 3, 2, 1], # [6, 5, 4, 5, 6, 5, 4], # [3, 2, 1, 2, 3, 2, 1]] tf.pad(t, paddings, "SYMMETRIC") # [[2, 1, 1, 2, 3, 3, 2], # [2, 1, 1, 2, 3, 3, 2], # [5, 4, 4, 5, 6, 6, 5], # [5, 4, 4, 5, 6, 6, 5]] Args tensor A Tensor. paddings A Tensor of type int32. mode One of "CONSTANT", "REFLECT", or "SYMMETRIC" (case-insensitive) constant_values In "CONSTANT" mode, the scalar pad value to use. Must be same type as tensor. name A name for the operation (optional). Returns A Tensor. Has the same type as tensor. Raises ValueError When mode is not one of "CONSTANT", "REFLECT", or "SYMMETRIC".
tensorflow.pad
tf.parallel_stack View source on GitHub Stacks a list of rank-R tensors into one rank-(R+1) tensor in parallel. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.parallel_stack tf.parallel_stack( values, name='parallel_stack' ) Requires that the shape of inputs be known at graph construction time. Packs the list of tensors in values into a tensor with rank one higher than each tensor in values, by packing them along the first dimension. Given a list of length N of tensors of shape (A, B, C); the output tensor will have the shape (N, A, B, C). For example: x = tf.constant([1, 4]) y = tf.constant([2, 5]) z = tf.constant([3, 6]) tf.parallel_stack([x, y, z]) # [[1, 4], [2, 5], [3, 6]] The difference between stack and parallel_stack is that stack requires all the inputs be computed before the operation will begin but doesn't require that the input shapes be known during graph construction. parallel_stack will copy pieces of the input into the output as they become available, in some situations this can provide a performance benefit. Unlike stack, parallel_stack does NOT support backpropagation. This is the opposite of unstack. The numpy equivalent is tf.parallel_stack([x, y, z]) = np.asarray([x, y, z]) Args values A list of Tensor objects with the same shape and type. name A name for this operation (optional). Returns output A stacked Tensor with the same type as values.
tensorflow.parallel_stack
tf.print View source on GitHub Print the specified inputs. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.print tf.print( *inputs, **kwargs ) A TensorFlow operator that prints the specified inputs to a desired output stream or logging level. The inputs may be dense or sparse Tensors, primitive python objects, data structures that contain tensors, and printable Python objects. Printed tensors will recursively show the first and last elements of each dimension to summarize. Example: Single-input usage: tensor = tf.range(10) tf.print(tensor, output_stream=sys.stderr) (This prints "[0 1 2 ... 7 8 9]" to sys.stderr) Multi-input usage: tensor = tf.range(10) tf.print("tensors:", tensor, {2: tensor * 2}, output_stream=sys.stdout) (This prints "tensors: [0 1 2 ... 7 8 9] {2: [0 2 4 ... 14 16 18]}" to sys.stdout) Changing the input separator: tensor_a = tf.range(2) tensor_b = tensor_a * 2 tf.print(tensor_a, tensor_b, output_stream=sys.stderr, sep=',') (This prints "[0 1],[0 2]" to sys.stderr) Usage in a tf.function: @tf.function def f(): tensor = tf.range(10) tf.print(tensor, output_stream=sys.stderr) return tensor range_tensor = f() (This prints "[0 1 2 ... 7 8 9]" to sys.stderr) @compatibility(TF 1.x Graphs and Sessions) In graphs manually created outside of tf.function, this method returns the created TF operator that prints the data. To make sure the operator runs, users need to pass the produced op to tf.compat.v1.Session's run method, or to use the op as a control dependency for executed ops by specifying with tf.compat.v1.control_dependencies([print_op]). @end_compatibility Compatibility usage in TF 1.x graphs: sess = tf.compat.v1.Session() with sess.as_default(): tensor = tf.range(10) print_op = tf.print("tensors:", tensor, {2: tensor * 2}, output_stream=sys.stdout) with tf.control_dependencies([print_op]): tripled_tensor = tensor * 3 sess.run(tripled_tensor) (This prints "tensors: [0 1 2 ... 7 8 9] {2: [0 2 4 ... 14 16 18]}" to sys.stdout) Note: In Jupyter notebooks and colabs, tf.print prints to the notebook cell outputs. It will not write to the notebook kernel's console logs. Args *inputs Positional arguments that are the inputs to print. Inputs in the printed output will be separated by spaces. Inputs may be python primitives, tensors, data structures such as dicts and lists that may contain tensors (with the data structures possibly nested in arbitrary ways), and printable python objects. output_stream The output stream, logging level, or file to print to. Defaults to sys.stderr, but sys.stdout, tf.compat.v1.logging.info, tf.compat.v1.logging.warning, tf.compat.v1.logging.error, absl.logging.info, absl.logging.warning and absl.logging.error are also supported. To print to a file, pass a string started with "file://" followed by the file path, e.g., "file:///tmp/foo.out". summarize The first and last summarize elements within each dimension are recursively printed per Tensor. If None, then the first 3 and last 3 elements of each dimension are printed for each tensor. If set to -1, it will print all elements of every tensor. sep The string to use to separate the inputs. Defaults to " ". end End character that is appended at the end the printed string. Defaults to the newline character. name A name for the operation (optional). Returns None when executing eagerly. During graph tracing this returns a TF operator that prints the specified inputs in the specified output stream or logging level. This operator will be automatically executed except inside of tf.compat.v1 graphs and sessions. Raises ValueError If an unsupported output stream is specified.
tensorflow.print
Module: tf.profiler Public API for tf.profiler namespace. Modules experimental module: Public API for tf.profiler.experimental namespace.
tensorflow.profiler
Module: tf.profiler.experimental Public API for tf.profiler.experimental namespace. Modules client module: Public API for tf.profiler.experimental.client namespace. server module: Public API for tf.profiler.experimental.server namespace. Classes class Profile: Context-manager profile API. class ProfilerOptions: Options for finer control over the profiler. class Trace: Context manager that generates a trace event in the profiler. Functions start(...): Start profiling TensorFlow performance. stop(...): Stops the current profiling session.
tensorflow.profiler.experimental
Module: tf.profiler.experimental.client Public API for tf.profiler.experimental.client namespace. Functions monitor(...): Sends grpc requests to profiler server to perform on-demand monitoring. trace(...): Sends gRPC requests to one or more profiler servers to perform on-demand profiling.
tensorflow.profiler.experimental.client
tf.profiler.experimental.client.monitor Sends grpc requests to profiler server to perform on-demand monitoring. tf.profiler.experimental.client.monitor( service_addr, duration_ms, level=1 ) The monitoring result is a light weight performance summary of your model execution. This method will block the caller thread until it receives the monitoring result. This method currently supports Cloud TPU only. Args service_addr gRPC address of profiler service e.g. grpc://10.0.0.2:8466. duration_ms Duration of monitoring in ms. level Choose a monitoring level between 1 and 2 to monitor your job. Level 2 is more verbose than level 1 and shows more metrics. Returns A string of monitoring output. Example usage: # Continuously send gRPC requests to the Cloud TPU to monitor the model # execution. for query in range(0, 100): print( tf.profiler.experimental.client.monitor('grpc://10.0.0.2:8466', 1000))
tensorflow.profiler.experimental.client.monitor
tf.profiler.experimental.client.trace Sends gRPC requests to one or more profiler servers to perform on-demand profiling. tf.profiler.experimental.client.trace( service_addr, logdir, duration_ms, worker_list='', num_tracing_attempts=3, options=None ) This method will block the calling thread until it receives responses from all servers or until deadline expiration. Both single host and multiple host profiling are supported on CPU, GPU, and TPU. The profiled results will be saved by each server to the specified TensorBoard log directory (i.e. the directory you save your model checkpoints). Use the TensorBoard profile plugin to view the visualization and analysis results. Args service_addr A comma delimited string of gRPC addresses of the workers to profile. e.g. service_addr='grpc://localhost:6009' service_addr='grpc://10.0.0.2:8466,grpc://10.0.0.3:8466' service_addr='grpc://localhost:12345,grpc://localhost:23456' logdir Path to save profile data to, typically a TensorBoard log directory. This path must be accessible to both the client and server. e.g. logdir='gs://your_tb_dir' duration_ms Duration of tracing or monitoring in milliseconds. Must be greater than zero. worker_list An optional TPU only configuration. The list of workers to profile in the current session. num_tracing_attempts Optional. Automatically retry N times when no trace event is collected (default 3). options profiler.experimental.ProfilerOptions namedtuple for miscellaneous profiler options. Raises InvalidArgumentError For when arguments fail validation checks. UnavailableError If no trace event was collected. Example usage (CPU/GPU): # Start a profiler server before your model runs. tf.profiler.experimental.server.start(6009) # (Model code goes here). # Send gRPC request to the profiler server to collect a trace of your model. tf.profiler.experimental.client.trace('grpc://localhost:6009', '/nfs/tb_log', 2000) Example usage (Multiple GPUs): # E.g. your worker IP addresses are 10.0.0.2, 10.0.0.3, 10.0.0.4, and you # would like to schedule start of profiling 1 second from now, for a # duration of 2 seconds. options['delay_ms'] = 1000 tf.profiler.experimental.client.trace( 'grpc://10.0.0.2:8466,grpc://10.0.0.3:8466,grpc://10.0.0.4:8466', 'gs://your_tb_dir', 2000, options=options) Example usage (TPU): # Send gRPC request to a TPU worker to collect a trace of your model. A # profiler service has been started in the TPU worker at port 8466. # E.g. your TPU IP address is 10.0.0.2 and you want to profile for 2 seconds # . tf.profiler.experimental.client.trace('grpc://10.0.0.2:8466', 'gs://your_tb_dir', 2000) Example usage (Multiple TPUs): # Send gRPC request to a TPU pod to collect a trace of your model on # multipleTPUs. A profiler service has been started in all the TPU workers # at theport 8466. # E.g. your TPU IP addresses are 10.0.0.2, 10.0.0.3, 10.0.0.4, and you want # to profile for 2 seconds. tf.profiler.experimental.client.trace('grpc://10.0.0.2:8466', 'gs://your_tb_dir', 2000, '10.0.0.2,10.0.0.3,10.0.0.4') Launch TensorBoard and point it to the same logdir you provided to this API. # logdir can be gs://your_tb_dir as in the above examples. $ tensorboard --logdir=/tmp/tb_log Open your browser and go to localhost:6006/#profile to view profiling results.
tensorflow.profiler.experimental.client.trace
tf.profiler.experimental.Profile Context-manager profile API. tf.profiler.experimental.Profile( logdir, options=None ) Profiling will start when entering the scope, and stop and save the results to the logdir when exits the scope. Open TensorBoard profile tab to view results. Example usage: with tf.profiler.experimental.Profile("/path/to/logdir"): # do some work Args logdir profile data will save to this directory. options An optional tf.profiler.ProfilerOptions can be provided to fine tune the profiler's behavior. Methods __enter__ View source __enter__() __exit__ View source __exit__( typ, value, tb )
tensorflow.profiler.experimental.profile
tf.profiler.experimental.ProfilerOptions Options for finer control over the profiler. tf.profiler.experimental.ProfilerOptions( host_tracer_level=2, python_tracer_level=0, device_tracer_level=1, delay_ms=None ) Use tf.profiler.ProfilerOptions to control tf.profiler behavior. Fields: host_tracer_level: Adjust CPU tracing level. Values are: 1 - critical info only, 2 - info, 3 - verbose. [default value is 2] python_tracer_level: Toggle tracing of Python function calls. Values are: 1 enabled, 0 - disabled [default value is 0] device_tracer_level: Adjust device (TPU/GPU) tracing level. Values are: 1 - enabled, 0 - disabled [default value is 1] delay_ms: Requests for all hosts to start profiling at a timestamp that is delay_ms away from the current time. delay_ms is in milliseconds. If zero, each host will start profiling immediately upon receiving the request. Default value is None, allowing the profiler guess the best value. Attributes host_tracer_level python_tracer_level device_tracer_level delay_ms
tensorflow.profiler.experimental.profileroptions
Module: tf.profiler.experimental.server Public API for tf.profiler.experimental.server namespace. Functions start(...): Start a profiler grpc server that listens to given port.
tensorflow.profiler.experimental.server
tf.profiler.experimental.server.start Start a profiler grpc server that listens to given port. tf.profiler.experimental.server.start( port ) The profiler server will exit when the process finishes. The service is defined in tensorflow/core/profiler/profiler_service.proto. Args port port profiler server listens to. Example usage: ```python tf.profiler.experimental.server.start('6009') # do your training here.
tensorflow.profiler.experimental.server.start
tf.profiler.experimental.start Start profiling TensorFlow performance. tf.profiler.experimental.start( logdir, options=None ) Args logdir Profiling results log directory. options ProfilerOptions namedtuple to specify miscellaneous profiler options. See example usage below. Raises AlreadyExistsError If a profiling session is already running. Example usage: options = tf.profiler.experimental.ProfilerOptions(host_tracer_level = 3, python_tracer_level = 1, device_tracer_level = 1) tf.profiler.experimental.start('logdir_path', options = options) # Training code here tf.profiler.experimental.stop() To view the profiling results, launch TensorBoard and point it to logdir. Open your browser and go to localhost:6006/#profile to view profiling results.
tensorflow.profiler.experimental.start
tf.profiler.experimental.stop Stops the current profiling session. tf.profiler.experimental.stop( save=True ) The profiler session will be stopped and profile results can be saved. Args save An optional variable to save the results to TensorBoard. Default True. Raises UnavailableError If there is no active profiling session.
tensorflow.profiler.experimental.stop
tf.profiler.experimental.Trace Context manager that generates a trace event in the profiler. tf.profiler.experimental.Trace( name, **kwargs ) A trace event will start when entering the context, and stop and save the result to the profiler when exiting the context. Open TensorBoard Profile tab and choose trace viewer to view the trace event in the timeline. Trace events are created only when the profiler is enabled. More information on how to use the profiler can be found at https://tensorflow.org/guide/profiler Example usage: tf.profiler.experimental.start('logdir') for step in range(num_steps): # Creates a trace event for each training step with the step number. with tf.profiler.experimental.Trace("Train", step_num=step): train_fn() tf.profiler.experimental.stop() Args name The name of the trace event. **kwargs Keyword arguments added to the trace event. Both the key and value are of types that can be converted to strings, which will be interpreted by the profiler according to the traceme name. Example usage: tf.profiler.experimental.start('logdir') for step in range(num_steps): # Creates a trace event for each training step with the # step number. with tf.profiler.experimental.Trace("Train", step_num=step): train_fn() tf.profiler.experimental.stop() The example above uses the keyword argument "step_num" to specify the training step being traced. Methods set_metadata View source set_metadata( **kwargs ) Sets metadata in this trace event. Args **kwargs metadata in key-value pairs. This method enables setting metadata in a trace event after it is created. Example usage: def call(function): with tf.profiler.experimental.Trace("call", function_name=function.name) as tm: binary, in_cache = jit_compile(function) tm.set_metadata(in_cache=in_cache) execute(binary) In this example, we want to trace how much time spent on calling a function, which includes compilation and execution. The compilation can be either getting a cached copy of the binary or actually generating the binary, which is indicated by the boolean "in_cache" returned by jit_compile(). We need to use set_metadata() to pass in_cache because we did not know the in_cache value when the trace was created (and we cannot create the trace after jit_compile(), because we want to measure the entire duration of call()). __enter__ View source __enter__() __exit__ View source __exit__( exc_type, exc_val, exc_tb )
tensorflow.profiler.experimental.trace
tf.py_function View source on GitHub Wraps a python function into a TensorFlow op that executes it eagerly. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.py_function tf.py_function( func, inp, Tout, name=None ) This function allows expressing computations in a TensorFlow graph as Python functions. In particular, it wraps a Python function func in a once-differentiable TensorFlow operation that executes it with eager execution enabled. As a consequence, tf.py_function makes it possible to express control flow using Python constructs (if, while, for, etc.), instead of TensorFlow control flow constructs (tf.cond, tf.while_loop). For example, you might use tf.py_function to implement the log huber function: def log_huber(x, m): if tf.abs(x) <= m: return x**2 else: return m**2 * (1 - 2 * tf.math.log(m) + tf.math.log(x**2)) x = tf.compat.v1.placeholder(tf.float32) m = tf.compat.v1.placeholder(tf.float32) y = tf.py_function(func=log_huber, inp=[x, m], Tout=tf.float32) dy_dx = tf.gradients(y, x)[0] with tf.compat.v1.Session() as sess: # The session executes `log_huber` eagerly. Given the feed values below, # it will take the first branch, so `y` evaluates to 1.0 and # `dy_dx` evaluates to 2.0. y, dy_dx = sess.run([y, dy_dx], feed_dict={x: 1.0, m: 2.0}) You can also use tf.py_function to debug your models at runtime using Python tools, i.e., you can isolate portions of your code that you want to debug, wrap them in Python functions and insert pdb tracepoints or print statements as desired, and wrap those functions in tf.py_function. For more information on eager execution, see the Eager guide. tf.py_function is similar in spirit to tf.compat.v1.py_func, but unlike the latter, the former lets you use TensorFlow operations in the wrapped Python function. In particular, while tf.compat.v1.py_func only runs on CPUs and wraps functions that take NumPy arrays as inputs and return NumPy arrays as outputs, tf.py_function can be placed on GPUs and wraps functions that take Tensors as inputs, execute TensorFlow operations in their bodies, and return Tensors as outputs. Like tf.compat.v1.py_func, tf.py_function has the following limitations with respect to serialization and distribution: The body of the function (i.e. func) will not be serialized in a GraphDef. Therefore, you should not use this function if you need to serialize your model and restore it in a different environment. The operation must run in the same address space as the Python program that calls tf.py_function(). If you are using distributed TensorFlow, you must run a tf.distribute.Server in the same process as the program that calls tf.py_function() and you must pin the created operation to a device in that server (e.g. using with tf.device():). Args func A Python function which accepts a list of Tensor objects having element types that match the corresponding tf.Tensor objects in inp and returns a list of Tensor objects (or a single Tensor, or None) having element types that match the corresponding values in Tout. inp A list of Tensor objects. Tout A list or tuple of tensorflow data types or a single tensorflow data type if there is only one, indicating what func returns; an empty list if no value is returned (i.e., if the return value is None). name A name for the operation (optional). Returns A list of Tensor or a single Tensor which func computes; an empty list if func returns None.
tensorflow.py_function
Module: tf.quantization Public API for tf.quantization namespace. Functions dequantize(...): Dequantize the 'input' tensor into a float or bfloat16 Tensor. fake_quant_with_min_max_args(...): Fake-quantize the 'inputs' tensor, type float to 'outputs' tensor of same type. fake_quant_with_min_max_args_gradient(...): Compute gradients for a FakeQuantWithMinMaxArgs operation. fake_quant_with_min_max_vars(...): Fake-quantize the 'inputs' tensor of type float via global float scalars fake_quant_with_min_max_vars_gradient(...): Compute gradients for a FakeQuantWithMinMaxVars operation. fake_quant_with_min_max_vars_per_channel(...): Fake-quantize the 'inputs' tensor of type float via per-channel floats fake_quant_with_min_max_vars_per_channel_gradient(...): Compute gradients for a FakeQuantWithMinMaxVarsPerChannel operation. quantize(...): Quantize the 'input' tensor of type float to 'output' tensor of type 'T'. quantize_and_dequantize(...): Quantizes then dequantizes a tensor. (deprecated) quantize_and_dequantize_v2(...): Quantizes then dequantizes a tensor. quantized_concat(...): Concatenates quantized tensors along one dimension.
tensorflow.quantization
tf.quantization.dequantize View source on GitHub Dequantize the 'input' tensor into a float or bfloat16 Tensor. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.dequantize, tf.compat.v1.quantization.dequantize tf.quantization.dequantize( input, min_range, max_range, mode='MIN_COMBINED', name=None, axis=None, narrow_range=False, dtype=tf.dtypes.float32 ) [min_range, max_range] are scalar floats that specify the range for the output. The 'mode' attribute controls exactly which calculations are used to convert the float values to their quantized equivalents. In 'MIN_COMBINED' mode, each value of the tensor will undergo the following: if T == qint8: in[i] += (range(T) + 1)/ 2.0 out[i] = min_range + (in[i]* (max_range - min_range) / range(T)) here range(T) = numeric_limits<T>::max() - numeric_limits<T>::min() MIN_COMBINED Mode Example If the input comes from a QuantizedRelu6, the output type is quint8 (range of 0-255) but the possible range of QuantizedRelu6 is 0-6. The min_range and max_range values are therefore 0.0 and 6.0. Dequantize on quint8 will take each value, cast to float, and multiply by 6 / 255. Note that if quantizedtype is qint8, the operation will additionally add each value by 128 prior to casting. If the mode is 'MIN_FIRST', then this approach is used: num_discrete_values = 1 << (# of bits in T) range_adjust = num_discrete_values / (num_discrete_values - 1) range = (range_max - range_min) * range_adjust range_scale = range / num_discrete_values const double offset_input = static_cast<double>(input) - lowest_quantized; result = range_min + ((input - numeric_limits<T>::min()) * range_scale) If the mode is SCALED, dequantization is performed by multiplying each input value by a scaling_factor. (Thus an input of 0 always maps to 0.0). The scaling_factor is determined from min_range, max_range, and narrow_range in a way that is compatible with QuantizeAndDequantize{V2|V3} and QuantizeV2, using the following algorithm: const int min_expected_T = std::numeric_limits<T>::min() + (narrow_range ? 1 : 0); const int max_expected_T = std::numeric_limits<T>::max(); const float max_expected_T = std::numeric_limits<float>::max(); const float scale_factor = (std::numeric_limits<T>::min() == 0) ? (max_range / max_expected_T) : std::max(min_range / min_expected_T, max_range / max_expected_T); Args input A Tensor. Must be one of the following types: qint8, quint8, qint32, qint16, quint16. min_range A Tensor of type float32. The minimum scalar value possibly produced for the input. max_range A Tensor of type float32. The maximum scalar value possibly produced for the input. mode An optional string from: "MIN_COMBINED", "MIN_FIRST", "SCALED". Defaults to "MIN_COMBINED". narrow_range An optional bool. Defaults to False. axis An optional int. Defaults to -1. dtype An optional tf.DType from: tf.bfloat16, tf.float32. Defaults to tf.float32. Type of the output tensor. Currently Dequantize supports float and bfloat16. If 'dtype' is 'bfloat16', it only supports 'MIN_COMBINED' mode. name A name for the operation (optional). Returns A Tensor of type dtype.
tensorflow.quantization.dequantize
tf.quantization.fake_quant_with_min_max_args Fake-quantize the 'inputs' tensor, type float to 'outputs' tensor of same type. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.fake_quant_with_min_max_args, tf.compat.v1.quantization.fake_quant_with_min_max_args tf.quantization.fake_quant_with_min_max_args( inputs, min=-6, max=6, num_bits=8, narrow_range=False, name=None ) Attributes [min; max] define the clamping range for the inputs data. inputs values are quantized into the quantization range ( [0; 2^num_bits - 1] when narrow_range is false and [1; 2^num_bits - 1] when it is true) and then de-quantized and output as floats in [min; max] interval. num_bits is the bitwidth of the quantization; between 2 and 16, inclusive. Before quantization, min and max values are adjusted with the following logic. It is suggested to have min <= 0 <= max. If 0 is not in the range of values, the behavior can be unexpected: If 0 < min < max: min_adj = 0 and max_adj = max - min. If min < max < 0: min_adj = min - max and max_adj = 0. If min <= 0 <= max: scale = (max - min) / (2^num_bits - 1), min_adj = scale * round(min / scale) and max_adj = max + min_adj - min. Quantization is called fake since the output is still in floating point. Args inputs A Tensor of type float32. min An optional float. Defaults to -6. max An optional float. Defaults to 6. num_bits An optional int. Defaults to 8. narrow_range An optional bool. Defaults to False. name A name for the operation (optional). Returns A Tensor of type float32.
tensorflow.quantization.fake_quant_with_min_max_args
tf.quantization.fake_quant_with_min_max_args_gradient Compute gradients for a FakeQuantWithMinMaxArgs operation. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.fake_quant_with_min_max_args_gradient, tf.compat.v1.quantization.fake_quant_with_min_max_args_gradient tf.quantization.fake_quant_with_min_max_args_gradient( gradients, inputs, min=-6, max=6, num_bits=8, narrow_range=False, name=None ) Args gradients A Tensor of type float32. Backpropagated gradients above the FakeQuantWithMinMaxArgs operation. inputs A Tensor of type float32. Values passed as inputs to the FakeQuantWithMinMaxArgs operation. min An optional float. Defaults to -6. max An optional float. Defaults to 6. num_bits An optional int. Defaults to 8. narrow_range An optional bool. Defaults to False. name A name for the operation (optional). Returns A Tensor of type float32.
tensorflow.quantization.fake_quant_with_min_max_args_gradient
tf.quantization.fake_quant_with_min_max_vars Fake-quantize the 'inputs' tensor of type float via global float scalars View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.fake_quant_with_min_max_vars, tf.compat.v1.quantization.fake_quant_with_min_max_vars tf.quantization.fake_quant_with_min_max_vars( inputs, min, max, num_bits=8, narrow_range=False, name=None ) Fake-quantize the inputs tensor of type float via global float scalars min and max to outputs tensor of same shape as inputs. Attributes [min; max] define the clamping range for the inputs data. inputs values are quantized into the quantization range ( [0; 2^num_bits - 1] when narrow_range is false and [1; 2^num_bits - 1] when it is true) and then de-quantized and output as floats in [min; max] interval. num_bits is the bitwidth of the quantization; between 2 and 16, inclusive. Before quantization, min and max values are adjusted with the following logic. It is suggested to have min <= 0 <= max. If 0 is not in the range of values, the behavior can be unexpected: If 0 < min < max: min_adj = 0 and max_adj = max - min. If min < max < 0: min_adj = min - max and max_adj = 0. If min <= 0 <= max: scale = (max - min) / (2^num_bits - 1), min_adj = scale * round(min / scale) and max_adj = max + min_adj - min. This operation has a gradient and thus allows for training min and max values. Args inputs A Tensor of type float32. min A Tensor of type float32. max A Tensor of type float32. num_bits An optional int. Defaults to 8. narrow_range An optional bool. Defaults to False. name A name for the operation (optional). Returns A Tensor of type float32.
tensorflow.quantization.fake_quant_with_min_max_vars
tf.quantization.fake_quant_with_min_max_vars_gradient Compute gradients for a FakeQuantWithMinMaxVars operation. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.fake_quant_with_min_max_vars_gradient, tf.compat.v1.quantization.fake_quant_with_min_max_vars_gradient tf.quantization.fake_quant_with_min_max_vars_gradient( gradients, inputs, min, max, num_bits=8, narrow_range=False, name=None ) Args gradients A Tensor of type float32. Backpropagated gradients above the FakeQuantWithMinMaxVars operation. inputs A Tensor of type float32. Values passed as inputs to the FakeQuantWithMinMaxVars operation. min, max: Quantization interval, scalar floats. min A Tensor of type float32. max A Tensor of type float32. num_bits An optional int. Defaults to 8. The bitwidth of the quantization; between 2 and 8, inclusive. narrow_range An optional bool. Defaults to False. Whether to quantize into 2^num_bits - 1 distinct values. name A name for the operation (optional). Returns A tuple of Tensor objects (backprops_wrt_input, backprop_wrt_min, backprop_wrt_max). backprops_wrt_input A Tensor of type float32. backprop_wrt_min A Tensor of type float32. backprop_wrt_max A Tensor of type float32.
tensorflow.quantization.fake_quant_with_min_max_vars_gradient
tf.quantization.fake_quant_with_min_max_vars_per_channel Fake-quantize the 'inputs' tensor of type float via per-channel floats View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.fake_quant_with_min_max_vars_per_channel, tf.compat.v1.quantization.fake_quant_with_min_max_vars_per_channel tf.quantization.fake_quant_with_min_max_vars_per_channel( inputs, min, max, num_bits=8, narrow_range=False, name=None ) Fake-quantize the inputs tensor of type float per-channel and one of the shapes: [d], [b, d] [b, h, w, d] via per-channel floats min and max of shape [d] to outputs tensor of same shape as inputs. Attributes [min; max] define the clamping range for the inputs data. inputs values are quantized into the quantization range ( [0; 2^num_bits - 1] when narrow_range is false and [1; 2^num_bits - 1] when it is true) and then de-quantized and output as floats in [min; max] interval. num_bits is the bitwidth of the quantization; between 2 and 16, inclusive. Before quantization, min and max values are adjusted with the following logic. It is suggested to have min <= 0 <= max. If 0 is not in the range of values, the behavior can be unexpected: If 0 < min < max: min_adj = 0 and max_adj = max - min. If min < max < 0: min_adj = min - max and max_adj = 0. If min <= 0 <= max: scale = (max - min) / (2^num_bits - 1), min_adj = scale * round(min / scale) and max_adj = max + min_adj - min. This operation has a gradient and thus allows for training min and max values. Args inputs A Tensor of type float32. min A Tensor of type float32. max A Tensor of type float32. num_bits An optional int. Defaults to 8. narrow_range An optional bool. Defaults to False. name A name for the operation (optional). Returns A Tensor of type float32.
tensorflow.quantization.fake_quant_with_min_max_vars_per_channel
tf.quantization.fake_quant_with_min_max_vars_per_channel_gradient Compute gradients for a FakeQuantWithMinMaxVarsPerChannel operation. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.fake_quant_with_min_max_vars_per_channel_gradient, tf.compat.v1.quantization.fake_quant_with_min_max_vars_per_channel_gradient tf.quantization.fake_quant_with_min_max_vars_per_channel_gradient( gradients, inputs, min, max, num_bits=8, narrow_range=False, name=None ) Args gradients A Tensor of type float32. Backpropagated gradients above the FakeQuantWithMinMaxVars operation, shape one of: [d], [b, d], [b, h, w, d]. inputs A Tensor of type float32. Values passed as inputs to the FakeQuantWithMinMaxVars operation, shape same as gradients. min, max: Quantization interval, floats of shape [d]. min A Tensor of type float32. max A Tensor of type float32. num_bits An optional int. Defaults to 8. The bitwidth of the quantization; between 2 and 16, inclusive. narrow_range An optional bool. Defaults to False. Whether to quantize into 2^num_bits - 1 distinct values. name A name for the operation (optional). Returns A tuple of Tensor objects (backprops_wrt_input, backprop_wrt_min, backprop_wrt_max). backprops_wrt_input A Tensor of type float32. backprop_wrt_min A Tensor of type float32. backprop_wrt_max A Tensor of type float32.
tensorflow.quantization.fake_quant_with_min_max_vars_per_channel_gradient
tf.quantization.quantize View source on GitHub Quantize the 'input' tensor of type float to 'output' tensor of type 'T'. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.quantization.quantize, tf.compat.v1.quantize tf.quantization.quantize( input, min_range, max_range, T, mode='MIN_COMBINED', round_mode='HALF_AWAY_FROM_ZERO', name=None, narrow_range=False, axis=None, ensure_minimum_range=0.01 ) [min_range, max_range] are scalar floats that specify the range for the 'input' data. The 'mode' attribute controls exactly which calculations are used to convert the float values to their quantized equivalents. The 'round_mode' attribute controls which rounding tie-breaking algorithm is used when rounding float values to their quantized equivalents. In 'MIN_COMBINED' mode, each value of the tensor will undergo the following: out[i] = (in[i] - min_range) * range(T) / (max_range - min_range) if T == qint8: out[i] -= (range(T) + 1) / 2.0 here range(T) = numeric_limits<T>::max() - numeric_limits<T>::min() MIN_COMBINED Mode Example Assume the input is type float and has a possible range of [0.0, 6.0] and the output type is quint8 ([0, 255]). The min_range and max_range values should be specified as 0.0 and 6.0. Quantizing from float to quint8 will multiply each value of the input by 255/6 and cast to quint8. If the output type was qint8 ([-128, 127]), the operation will additionally subtract each value by 128 prior to casting, so that the range of values aligns with the range of qint8. If the mode is 'MIN_FIRST', then this approach is used: num_discrete_values = 1 << (# of bits in T) range_adjust = num_discrete_values / (num_discrete_values - 1) range = (range_max - range_min) * range_adjust range_scale = num_discrete_values / range quantized = round(input * range_scale) - round(range_min * range_scale) + numeric_limits<T>::min() quantized = max(quantized, numeric_limits<T>::min()) quantized = min(quantized, numeric_limits<T>::max()) The biggest difference between this and MIN_COMBINED is that the minimum range is rounded first, before it's subtracted from the rounded value. With MIN_COMBINED, a small bias is introduced where repeated iterations of quantizing and dequantizing will introduce a larger and larger error. SCALED mode Example SCALED mode matches the quantization approach used in QuantizeAndDequantize{V2|V3}. If the mode is SCALED, the quantization is performed by multiplying each input value by a scaling_factor. The scaling_factor is determined from min_range and max_range to be as large as possible such that the range from min_range to max_range is representable within values of type T. const int min_T = std::numeric_limits<T>::min(); const int max_T = std::numeric_limits<T>::max(); const float max_float = std::numeric_limits<float>::max(); const float scale_factor_from_min_side = (min_T * min_range > 0) ? min_T / min_range : max_float; const float scale_factor_from_max_side = (max_T * max_range > 0) ? max_T / max_range : max_float; const float scale_factor = std::min(scale_factor_from_min_side, scale_factor_from_max_side); We next use the scale_factor to adjust min_range and max_range as follows: min_range = min_T / scale_factor; max_range = max_T / scale_factor; e.g. if T = qint8, and initially min_range = -10, and max_range = 9, we would compare -128/-10.0 = 12.8 to 127/9.0 = 14.11, and set scaling_factor = 12.8 In this case, min_range would remain -10, but max_range would be adjusted to 127 / 12.8 = 9.921875 So we will quantize input values in the range (-10, 9.921875) to (-128, 127). The input tensor can now be quantized by clipping values to the range min_range to max_range, then multiplying by scale_factor as follows: result = round(min(max_range, max(min_range, input)) * scale_factor) The adjusted min_range and max_range are returned as outputs 2 and 3 of this operation. These outputs should be used as the range for any further calculations. narrow_range (bool) attribute If true, we do not use the minimum quantized value. i.e. for int8 the quantized output, it would be restricted to the range -127..127 instead of the full -128..127 range. This is provided for compatibility with certain inference backends. (Only applies to SCALED mode) axis (int) attribute An optional axis attribute can specify a dimension index of the input tensor, such that quantization ranges will be calculated and applied separately for each slice of the tensor along that dimension. This is useful for per-channel quantization. If axis is specified, min_range and max_range if axis=None, per-tensor quantization is performed as normal. ensure_minimum_range (float) attribute Ensures the minimum quantization range is at least this value. The legacy default value for this is 0.01, but it is strongly suggested to set it to 0 for new uses. Args input A Tensor of type float32. min_range A Tensor of type float32. The minimum value of the quantization range. This value may be adjusted by the op depending on other parameters. The adjusted value is written to output_min. If the axis attribute is specified, this must be a 1-D tensor whose size matches the axis dimension of the input and output tensors. max_range A Tensor of type float32. The maximum value of the quantization range. This value may be adjusted by the op depending on other parameters. The adjusted value is written to output_max. If the axis attribute is specified, this must be a 1-D tensor whose size matches the axis dimension of the input and output tensors. T A tf.DType from: tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16. mode An optional string from: "MIN_COMBINED", "MIN_FIRST", "SCALED". Defaults to "MIN_COMBINED". round_mode An optional string from: "HALF_AWAY_FROM_ZERO", "HALF_TO_EVEN". Defaults to "HALF_AWAY_FROM_ZERO". narrow_range An optional bool. Defaults to False. axis An optional int. Defaults to -1. ensure_minimum_range An optional float. Defaults to 0.01. name A name for the operation (optional). Returns A tuple of Tensor objects (output, output_min, output_max). output A Tensor of type T. output_min A Tensor of type float32. output_max A Tensor of type float32.
tensorflow.quantization.quantize
tf.quantization.quantized_concat Concatenates quantized tensors along one dimension. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.quantization.quantized_concat, tf.compat.v1.quantized_concat tf.quantization.quantized_concat( concat_dim, values, input_mins, input_maxes, name=None ) Args concat_dim A Tensor of type int32. 0-D. The dimension along which to concatenate. Must be in the range [0, rank(values)). values A list of at least 2 Tensor objects with the same type. The N Tensors to concatenate. Their ranks and types must match, and their sizes must match in all dimensions except concat_dim. input_mins A list with the same length as values of Tensor objects with type float32. The minimum scalar values for each of the input tensors. input_maxes A list with the same length as values of Tensor objects with type float32. The maximum scalar values for each of the input tensors. name A name for the operation (optional). Returns A tuple of Tensor objects (output, output_min, output_max). output A Tensor. Has the same type as values. output_min A Tensor of type float32. output_max A Tensor of type float32.
tensorflow.quantization.quantized_concat
tf.quantization.quantize_and_dequantize View source on GitHub Quantizes then dequantizes a tensor. (deprecated) View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.quantization.quantize_and_dequantize tf.quantization.quantize_and_dequantize( input, input_min, input_max, signed_input=True, num_bits=8, range_given=False, round_mode='HALF_TO_EVEN', name=None, narrow_range=False, axis=None ) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: This Op has been deprecated, usequantize_and_dequantize_v2 instead. To To simulate the V1 the behavior of tf.quantization.quantize_and_dequantize(...) use tf.grad_pass_through(tf.quantization.quantize_and_dequantize_v2)(...). Args input A Tensor to quantize and dequantize. input_min If range_given=True, the minimum input value, that needs to be represented in the quantized representation. If axis is specified, this should be a vector of minimum values for each slice along axis. input_max If range_given=True, the maximum input value that needs to be represented in the quantized representation. If axis is specified, this should be a vector of maximum values for each slice along axis. signed_input True if the quantization is signed or unsigned. num_bits The bitwidth of the quantization. range_given If true use input_min and input_max for the range of the input, otherwise determine min and max from the input Tensor. round_mode Rounding mode when rounding from float values to quantized ones. one of ['HALF_TO_EVEN', 'HALF_UP'] name Optional name for the operation. narrow_range If true, then the absolute value of the quantized minimum value is the same as the quantized maximum value, instead of 1 greater. i.e. for 8 bit quantization, the minimum value is -127 instead of -128. axis Integer. If specified, refers to a dimension of the input tensor, such that quantization will be per slice along that dimension. Returns A Tensor. Each element is the result of quantizing and dequantizing the corresponding element of input.
tensorflow.quantization.quantize_and_dequantize
tf.quantization.quantize_and_dequantize_v2 Quantizes then dequantizes a tensor. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.quantization.quantize_and_dequantize_v2 tf.quantization.quantize_and_dequantize_v2( input, input_min, input_max, signed_input=True, num_bits=8, range_given=False, round_mode='HALF_TO_EVEN', name=None, narrow_range=False, axis=None ) Updates the gradient definition for quantization that is outside the range to be 0.To simulate the V1 the behavior of tf.quantization.quantize_and_dequantize(...) use tf.grad_pass_through(tf.quantization.quantize_and_dequantize_v2)(...). Example usage: def getQuantizeOp(input): input_tensor = tf.placeholder(tf.float32, shape=[4, 4]) net = tf.quantization.quantize_and_dequantize(input, input_min=min_threshold, input_max=max_threshold, range_given=True) To simulate v1 behavior: def testDecomposeQuantizeDequantize(self): def f(input_tensor): return tf.quantization.quantize_and_dequantize_v2(input_tensor, input_min = 5.0, input_max= -10.0, range_given=True) input_tensor = tf.placeholder(tf.float32, shape=[4, 4]) net = tf.grad_pass_through(f)(input_tensor) Args input A Tensor to quantize and dequantize. input_min If range_given=True, the minimum input value, that needs to be represented in the quantized representation. If axis is specified, this should be a vector of minimum values for each slice along axis. input_max If range_given=True, the maximum input value that needs to be represented in the quantized representation. If axis is specified, this should be a vector of maximum values for each slice along axis. signed_input True if the quantization is signed or unsigned. num_bits The bitwidth of the quantization. range_given If true use input_min and input_max for the range of the input, otherwise determine min and max from the input Tensor. round_mode Rounding mode when rounding from float values to quantized ones. one of ['HALF_TO_EVEN', 'HALF_UP'] name Optional name for the operation. narrow_range If true, then the absolute value of the quantized minimum value is the same as the quantized maximum value, instead of 1 greater. i.e. for 8 bit quantization, the minimum value is -127 instead of -128. axis Integer. If specified, refers to a dimension of the input tensor, such that quantization will be per slice along that dimension. Returns A Tensor. Each element is the result of quantizing and dequantizing the corresponding element of input.
tensorflow.quantization.quantize_and_dequantize_v2
tf.quantize_and_dequantize_v4 Returns the gradient of QuantizeAndDequantizeV4. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.quantize_and_dequantize_v4 tf.quantize_and_dequantize_v4( input, input_min, input_max, signed_input=True, num_bits=8, range_given=False, round_mode='HALF_TO_EVEN', narrow_range=False, axis=-1, name=None ) This is almost identical to QuantizeAndDequantizeV2, except that it returns a gradient of 1 for inputs that are within the quantization range, or 0 otherwise. Args input A Tensor. Must be one of the following types: bfloat16, half, float32, float64. input_min A Tensor. Must have the same type as input. input_max A Tensor. Must have the same type as input. signed_input An optional bool. Defaults to True. num_bits An optional int. Defaults to 8. range_given An optional bool. Defaults to False. round_mode An optional string from: "HALF_TO_EVEN", "HALF_UP". Defaults to "HALF_TO_EVEN". narrow_range An optional bool. Defaults to False. axis An optional int. Defaults to -1. name A name for the operation (optional). Returns A Tensor. Has the same type as input.
tensorflow.quantize_and_dequantize_v4
Module: tf.queue Public API for tf.queue namespace. Classes class FIFOQueue: A queue implementation that dequeues elements in first-in first-out order. class PaddingFIFOQueue: A FIFOQueue that supports batching variable-sized tensors by padding. class PriorityQueue: A queue implementation that dequeues elements in prioritized order. class QueueBase: Base class for queue implementations. class RandomShuffleQueue: A queue implementation that dequeues elements in a random order.
tensorflow.queue
tf.queue.FIFOQueue View source on GitHub A queue implementation that dequeues elements in first-in first-out order. Inherits From: QueueBase View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.FIFOQueue, tf.compat.v1.queue.FIFOQueue tf.queue.FIFOQueue( capacity, dtypes, shapes=None, names=None, shared_name=None, name='fifo_queue' ) See tf.queue.QueueBase for a description of the methods on this class. Args capacity An integer. The upper bound on the number of elements that may be stored in this queue. dtypes A list of DType objects. The length of dtypes must equal the number of tensors in each queue element. shapes (Optional.) A list of fully-defined TensorShape objects with the same length as dtypes, or None. names (Optional.) A list of string naming the components in the queue with the same length as dtypes, or None. If specified the dequeue methods return a dictionary with the names as keys. shared_name (Optional.) If non-empty, this queue will be shared under the given name across multiple sessions. name Optional name for the queue operation. Attributes dtypes The list of dtypes for each component of a queue element. name The name of the underlying queue. names The list of names for each component of a queue element. queue_ref The underlying queue reference. shapes The list of shapes for each component of a queue element. Methods close View source close( cancel_pending_enqueues=False, name=None ) Closes this queue. This operation signals that no more elements will be enqueued in the given queue. Subsequent enqueue and enqueue_many operations will fail. Subsequent dequeue and dequeue_many operations will continue to succeed if sufficient elements remain in the queue. Subsequently dequeue and dequeue_many operations that would otherwise block waiting for more elements (if close hadn't been called) will now fail immediately. If cancel_pending_enqueues is True, all pending requests will also be canceled. Args cancel_pending_enqueues (Optional.) A boolean, defaulting to False (described above). name A name for the operation (optional). Returns The operation that closes the queue. dequeue View source dequeue( name=None ) Dequeues one element from this queue. If the queue is empty when this operation executes, it will block until there is an element to dequeue. At runtime, this operation may raise an error if the queue is tf.QueueBase.close before or during its execution. If the queue is closed, the queue is empty, and there are no pending enqueue operations that can fulfill this request, tf.errors.OutOfRangeError will be raised. If the session is tf.Session.close, tf.errors.CancelledError will be raised. Args name A name for the operation (optional). Returns The tuple of tensors that was dequeued. dequeue_many View source dequeue_many( n, name=None ) Dequeues and concatenates n elements from this queue. This operation concatenates queue-element component tensors along the 0th dimension to make a single component tensor. All of the components in the dequeued tuple will have size n in the 0th dimension. If the queue is closed and there are less than n elements left, then an OutOfRange exception is raised. At runtime, this operation may raise an error if the queue is tf.QueueBase.close before or during its execution. If the queue is closed, the queue contains fewer than n elements, and there are no pending enqueue operations that can fulfill this request, tf.errors.OutOfRangeError will be raised. If the session is tf.Session.close, tf.errors.CancelledError will be raised. Args n A scalar Tensor containing the number of elements to dequeue. name A name for the operation (optional). Returns The list of concatenated tensors that was dequeued. dequeue_up_to View source dequeue_up_to( n, name=None ) Dequeues and concatenates n elements from this queue. Note: This operation is not supported by all queues. If a queue does not support DequeueUpTo, then a tf.errors.UnimplementedError is raised. This operation concatenates queue-element component tensors along the 0th dimension to make a single component tensor. If the queue has not been closed, all of the components in the dequeued tuple will have size n in the 0th dimension. If the queue is closed and there are more than 0 but fewer than n elements remaining, then instead of raising a tf.errors.OutOfRangeError like tf.QueueBase.dequeue_many, less than n elements are returned immediately. If the queue is closed and there are 0 elements left in the queue, then a tf.errors.OutOfRangeError is raised just like in dequeue_many. Otherwise the behavior is identical to dequeue_many. Args n A scalar Tensor containing the number of elements to dequeue. name A name for the operation (optional). Returns The tuple of concatenated tensors that was dequeued. enqueue View source enqueue( vals, name=None ) Enqueues one element to this queue. If the queue is full when this operation executes, it will block until the element has been enqueued. At runtime, this operation may raise an error if the queue is tf.QueueBase.close before or during its execution. If the queue is closed before this operation runs, tf.errors.CancelledError will be raised. If this operation is blocked, and either (i) the queue is closed by a close operation with cancel_pending_enqueues=True, or (ii) the session is tf.Session.close, tf.errors.CancelledError will be raised. Args vals A tensor, a list or tuple of tensors, or a dictionary containing the values to enqueue. name A name for the operation (optional). Returns The operation that enqueues a new tuple of tensors to the queue. enqueue_many View source enqueue_many( vals, name=None ) Enqueues zero or more elements to this queue. This operation slices each component tensor along the 0th dimension to make multiple queue elements. All of the tensors in vals must have the same size in the 0th dimension. If the queue is full when this operation executes, it will block until all of the elements have been enqueued. At runtime, this operation may raise an error if the queue is tf.QueueBase.close before or during its execution. If the queue is closed before this operation runs, tf.errors.CancelledError will be raised. If this operation is blocked, and either (i) the queue is closed by a close operation with cancel_pending_enqueues=True, or (ii) the session is tf.Session.close, tf.errors.CancelledError will be raised. Args vals A tensor, a list or tuple of tensors, or a dictionary from which the queue elements are taken. name A name for the operation (optional). Returns The operation that enqueues a batch of tuples of tensors to the queue. from_list View source @staticmethod from_list( index, queues ) Create a queue using the queue reference from queues[index]. Args index An integer scalar tensor that determines the input that gets selected. queues A list of QueueBase objects. Returns A QueueBase object. Raises TypeError When queues is not a list of QueueBase objects, or when the data types of queues are not all the same. is_closed View source is_closed( name=None ) Returns true if queue is closed. This operation returns true if the queue is closed and false if the queue is open. Args name A name for the operation (optional). Returns True if the queue is closed and false if the queue is open. size View source size( name=None ) Compute the number of elements in this queue. Args name A name for the operation (optional). Returns A scalar tensor containing the number of elements in this queue.
tensorflow.queue.fifoqueue
tf.queue.PaddingFIFOQueue View source on GitHub A FIFOQueue that supports batching variable-sized tensors by padding. Inherits From: QueueBase View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.PaddingFIFOQueue, tf.compat.v1.io.PaddingFIFOQueue, tf.compat.v1.queue.PaddingFIFOQueue tf.queue.PaddingFIFOQueue( capacity, dtypes, shapes, names=None, shared_name=None, name='padding_fifo_queue' ) A PaddingFIFOQueue may contain components with dynamic shape, while also supporting dequeue_many. See the constructor for more details. See tf.queue.QueueBase for a description of the methods on this class. Args capacity An integer. The upper bound on the number of elements that may be stored in this queue. dtypes A list of DType objects. The length of dtypes must equal the number of tensors in each queue element. shapes A list of TensorShape objects, with the same length as dtypes. Any dimension in the TensorShape containing value None is dynamic and allows values to be enqueued with variable size in that dimension. names (Optional.) A list of string naming the components in the queue with the same length as dtypes, or None. If specified the dequeue methods return a dictionary with the names as keys. shared_name (Optional.) If non-empty, this queue will be shared under the given name across multiple sessions. name Optional name for the queue operation. Raises ValueError If shapes is not a list of shapes, or the lengths of dtypes and shapes do not match, or if names is specified and the lengths of dtypes and names do not match. Attributes dtypes The list of dtypes for each component of a queue element. name The name of the underlying queue. names The list of names for each component of a queue element. queue_ref The underlying queue reference. shapes The list of shapes for each component of a queue element. Methods close View source close( cancel_pending_enqueues=False, name=None ) Closes this queue. This operation signals that no more elements will be enqueued in the given queue. Subsequent enqueue and enqueue_many operations will fail. Subsequent dequeue and dequeue_many operations will continue to succeed if sufficient elements remain in the queue. Subsequently dequeue and dequeue_many operations that would otherwise block waiting for more elements (if close hadn't been called) will now fail immediately. If cancel_pending_enqueues is True, all pending requests will also be canceled. Args cancel_pending_enqueues (Optional.) A boolean, defaulting to False (described above). name A name for the operation (optional). Returns The operation that closes the queue. dequeue View source dequeue( name=None ) Dequeues one element from this queue. If the queue is empty when this operation executes, it will block until there is an element to dequeue. At runtime, this operation may raise an error if the queue is tf.QueueBase.close before or during its execution. If the queue is closed, the queue is empty, and there are no pending enqueue operations that can fulfill this request, tf.errors.OutOfRangeError will be raised. If the session is tf.Session.close, tf.errors.CancelledError will be raised. Args name A name for the operation (optional). Returns The tuple of tensors that was dequeued. dequeue_many View source dequeue_many( n, name=None ) Dequeues and concatenates n elements from this queue. This operation concatenates queue-element component tensors along the 0th dimension to make a single component tensor. All of the components in the dequeued tuple will have size n in the 0th dimension. If the queue is closed and there are less than n elements left, then an OutOfRange exception is raised. At runtime, this operation may raise an error if the queue is tf.QueueBase.close before or during its execution. If the queue is closed, the queue contains fewer than n elements, and there are no pending enqueue operations that can fulfill this request, tf.errors.OutOfRangeError will be raised. If the session is tf.Session.close, tf.errors.CancelledError will be raised. Args n A scalar Tensor containing the number of elements to dequeue. name A name for the operation (optional). Returns The list of concatenated tensors that was dequeued. dequeue_up_to View source dequeue_up_to( n, name=None ) Dequeues and concatenates n elements from this queue. Note: This operation is not supported by all queues. If a queue does not support DequeueUpTo, then a tf.errors.UnimplementedError is raised. This operation concatenates queue-element component tensors along the 0th dimension to make a single component tensor. If the queue has not been closed, all of the components in the dequeued tuple will have size n in the 0th dimension. If the queue is closed and there are more than 0 but fewer than n elements remaining, then instead of raising a tf.errors.OutOfRangeError like tf.QueueBase.dequeue_many, less than n elements are returned immediately. If the queue is closed and there are 0 elements left in the queue, then a tf.errors.OutOfRangeError is raised just like in dequeue_many. Otherwise the behavior is identical to dequeue_many. Args n A scalar Tensor containing the number of elements to dequeue. name A name for the operation (optional). Returns The tuple of concatenated tensors that was dequeued. enqueue View source enqueue( vals, name=None ) Enqueues one element to this queue. If the queue is full when this operation executes, it will block until the element has been enqueued. At runtime, this operation may raise an error if the queue is tf.QueueBase.close before or during its execution. If the queue is closed before this operation runs, tf.errors.CancelledError will be raised. If this operation is blocked, and either (i) the queue is closed by a close operation with cancel_pending_enqueues=True, or (ii) the session is tf.Session.close, tf.errors.CancelledError will be raised. Args vals A tensor, a list or tuple of tensors, or a dictionary containing the values to enqueue. name A name for the operation (optional). Returns The operation that enqueues a new tuple of tensors to the queue. enqueue_many View source enqueue_many( vals, name=None ) Enqueues zero or more elements to this queue. This operation slices each component tensor along the 0th dimension to make multiple queue elements. All of the tensors in vals must have the same size in the 0th dimension. If the queue is full when this operation executes, it will block until all of the elements have been enqueued. At runtime, this operation may raise an error if the queue is tf.QueueBase.close before or during its execution. If the queue is closed before this operation runs, tf.errors.CancelledError will be raised. If this operation is blocked, and either (i) the queue is closed by a close operation with cancel_pending_enqueues=True, or (ii) the session is tf.Session.close, tf.errors.CancelledError will be raised. Args vals A tensor, a list or tuple of tensors, or a dictionary from which the queue elements are taken. name A name for the operation (optional). Returns The operation that enqueues a batch of tuples of tensors to the queue. from_list View source @staticmethod from_list( index, queues ) Create a queue using the queue reference from queues[index]. Args index An integer scalar tensor that determines the input that gets selected. queues A list of QueueBase objects. Returns A QueueBase object. Raises TypeError When queues is not a list of QueueBase objects, or when the data types of queues are not all the same. is_closed View source is_closed( name=None ) Returns true if queue is closed. This operation returns true if the queue is closed and false if the queue is open. Args name A name for the operation (optional). Returns True if the queue is closed and false if the queue is open. size View source size( name=None ) Compute the number of elements in this queue. Args name A name for the operation (optional). Returns A scalar tensor containing the number of elements in this queue.
tensorflow.queue.paddingfifoqueue
tf.queue.PriorityQueue View source on GitHub A queue implementation that dequeues elements in prioritized order. Inherits From: QueueBase View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.PriorityQueue, tf.compat.v1.io.PriorityQueue, tf.compat.v1.queue.PriorityQueue tf.queue.PriorityQueue( capacity, types, shapes=None, names=None, shared_name=None, name='priority_queue' ) See tf.queue.QueueBase for a description of the methods on this class. Args capacity An integer. The upper bound on the number of elements that may be stored in this queue. types A list of DType objects. The length of types must equal the number of tensors in each queue element, except the first priority element. The first tensor in each element is the priority, which must be type int64. shapes (Optional.) A list of fully-defined TensorShape objects, with the same length as types, or None. names (Optional.) A list of strings naming the components in the queue with the same length as dtypes, or None. If specified, the dequeue methods return a dictionary with the names as keys. shared_name (Optional.) If non-empty, this queue will be shared under the given name across multiple sessions. name Optional name for the queue operation. Attributes dtypes The list of dtypes for each component of a queue element. name The name of the underlying queue. names The list of names for each component of a queue element. queue_ref The underlying queue reference. shapes The list of shapes for each component of a queue element. Methods close View source close( cancel_pending_enqueues=False, name=None ) Closes this queue. This operation signals that no more elements will be enqueued in the given queue. Subsequent enqueue and enqueue_many operations will fail. Subsequent dequeue and dequeue_many operations will continue to succeed if sufficient elements remain in the queue. Subsequently dequeue and dequeue_many operations that would otherwise block waiting for more elements (if close hadn't been called) will now fail immediately. If cancel_pending_enqueues is True, all pending requests will also be canceled. Args cancel_pending_enqueues (Optional.) A boolean, defaulting to False (described above). name A name for the operation (optional). Returns The operation that closes the queue. dequeue View source dequeue( name=None ) Dequeues one element from this queue. If the queue is empty when this operation executes, it will block until there is an element to dequeue. At runtime, this operation may raise an error if the queue is tf.QueueBase.close before or during its execution. If the queue is closed, the queue is empty, and there are no pending enqueue operations that can fulfill this request, tf.errors.OutOfRangeError will be raised. If the session is tf.Session.close, tf.errors.CancelledError will be raised. Args name A name for the operation (optional). Returns The tuple of tensors that was dequeued. dequeue_many View source dequeue_many( n, name=None ) Dequeues and concatenates n elements from this queue. This operation concatenates queue-element component tensors along the 0th dimension to make a single component tensor. All of the components in the dequeued tuple will have size n in the 0th dimension. If the queue is closed and there are less than n elements left, then an OutOfRange exception is raised. At runtime, this operation may raise an error if the queue is tf.QueueBase.close before or during its execution. If the queue is closed, the queue contains fewer than n elements, and there are no pending enqueue operations that can fulfill this request, tf.errors.OutOfRangeError will be raised. If the session is tf.Session.close, tf.errors.CancelledError will be raised. Args n A scalar Tensor containing the number of elements to dequeue. name A name for the operation (optional). Returns The list of concatenated tensors that was dequeued. dequeue_up_to View source dequeue_up_to( n, name=None ) Dequeues and concatenates n elements from this queue. Note: This operation is not supported by all queues. If a queue does not support DequeueUpTo, then a tf.errors.UnimplementedError is raised. This operation concatenates queue-element component tensors along the 0th dimension to make a single component tensor. If the queue has not been closed, all of the components in the dequeued tuple will have size n in the 0th dimension. If the queue is closed and there are more than 0 but fewer than n elements remaining, then instead of raising a tf.errors.OutOfRangeError like tf.QueueBase.dequeue_many, less than n elements are returned immediately. If the queue is closed and there are 0 elements left in the queue, then a tf.errors.OutOfRangeError is raised just like in dequeue_many. Otherwise the behavior is identical to dequeue_many. Args n A scalar Tensor containing the number of elements to dequeue. name A name for the operation (optional). Returns The tuple of concatenated tensors that was dequeued. enqueue View source enqueue( vals, name=None ) Enqueues one element to this queue. If the queue is full when this operation executes, it will block until the element has been enqueued. At runtime, this operation may raise an error if the queue is tf.QueueBase.close before or during its execution. If the queue is closed before this operation runs, tf.errors.CancelledError will be raised. If this operation is blocked, and either (i) the queue is closed by a close operation with cancel_pending_enqueues=True, or (ii) the session is tf.Session.close, tf.errors.CancelledError will be raised. Args vals A tensor, a list or tuple of tensors, or a dictionary containing the values to enqueue. name A name for the operation (optional). Returns The operation that enqueues a new tuple of tensors to the queue. enqueue_many View source enqueue_many( vals, name=None ) Enqueues zero or more elements to this queue. This operation slices each component tensor along the 0th dimension to make multiple queue elements. All of the tensors in vals must have the same size in the 0th dimension. If the queue is full when this operation executes, it will block until all of the elements have been enqueued. At runtime, this operation may raise an error if the queue is tf.QueueBase.close before or during its execution. If the queue is closed before this operation runs, tf.errors.CancelledError will be raised. If this operation is blocked, and either (i) the queue is closed by a close operation with cancel_pending_enqueues=True, or (ii) the session is tf.Session.close, tf.errors.CancelledError will be raised. Args vals A tensor, a list or tuple of tensors, or a dictionary from which the queue elements are taken. name A name for the operation (optional). Returns The operation that enqueues a batch of tuples of tensors to the queue. from_list View source @staticmethod from_list( index, queues ) Create a queue using the queue reference from queues[index]. Args index An integer scalar tensor that determines the input that gets selected. queues A list of QueueBase objects. Returns A QueueBase object. Raises TypeError When queues is not a list of QueueBase objects, or when the data types of queues are not all the same. is_closed View source is_closed( name=None ) Returns true if queue is closed. This operation returns true if the queue is closed and false if the queue is open. Args name A name for the operation (optional). Returns True if the queue is closed and false if the queue is open. size View source size( name=None ) Compute the number of elements in this queue. Args name A name for the operation (optional). Returns A scalar tensor containing the number of elements in this queue.
tensorflow.queue.priorityqueue
tf.queue.QueueBase View source on GitHub Base class for queue implementations. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.QueueBase, tf.compat.v1.io.QueueBase, tf.compat.v1.queue.QueueBase tf.queue.QueueBase( dtypes, shapes, names, queue_ref ) A queue is a TensorFlow data structure that stores tensors across multiple steps, and exposes operations that enqueue and dequeue tensors. Each queue element is a tuple of one or more tensors, where each tuple component has a static dtype, and may have a static shape. The queue implementations support versions of enqueue and dequeue that handle single elements, versions that support enqueuing and dequeuing a batch of elements at once. See tf.queue.FIFOQueue and tf.queue.RandomShuffleQueue for concrete implementations of this class, and instructions on how to create them. Args dtypes A list of types. The length of dtypes must equal the number of tensors in each element. shapes Constraints on the shapes of tensors in an element: A list of shape tuples or None. This list is the same length as dtypes. If the shape of any tensors in the element are constrained, all must be; shapes can be None if the shapes should not be constrained. names Optional list of names. If provided, the enqueue() and dequeue() methods will use dictionaries with these names as keys. Must be None or a list or tuple of the same length as dtypes. queue_ref The queue reference, i.e. the output of the queue op. Raises ValueError If one of the arguments is invalid. Attributes dtypes The list of dtypes for each component of a queue element. name The name of the underlying queue. names The list of names for each component of a queue element. queue_ref The underlying queue reference. shapes The list of shapes for each component of a queue element. Methods close View source close( cancel_pending_enqueues=False, name=None ) Closes this queue. This operation signals that no more elements will be enqueued in the given queue. Subsequent enqueue and enqueue_many operations will fail. Subsequent dequeue and dequeue_many operations will continue to succeed if sufficient elements remain in the queue. Subsequently dequeue and dequeue_many operations that would otherwise block waiting for more elements (if close hadn't been called) will now fail immediately. If cancel_pending_enqueues is True, all pending requests will also be canceled. Args cancel_pending_enqueues (Optional.) A boolean, defaulting to False (described above). name A name for the operation (optional). Returns The operation that closes the queue. dequeue View source dequeue( name=None ) Dequeues one element from this queue. If the queue is empty when this operation executes, it will block until there is an element to dequeue. At runtime, this operation may raise an error if the queue is tf.QueueBase.close before or during its execution. If the queue is closed, the queue is empty, and there are no pending enqueue operations that can fulfill this request, tf.errors.OutOfRangeError will be raised. If the session is tf.Session.close, tf.errors.CancelledError will be raised. Args name A name for the operation (optional). Returns The tuple of tensors that was dequeued. dequeue_many View source dequeue_many( n, name=None ) Dequeues and concatenates n elements from this queue. This operation concatenates queue-element component tensors along the 0th dimension to make a single component tensor. All of the components in the dequeued tuple will have size n in the 0th dimension. If the queue is closed and there are less than n elements left, then an OutOfRange exception is raised. At runtime, this operation may raise an error if the queue is tf.QueueBase.close before or during its execution. If the queue is closed, the queue contains fewer than n elements, and there are no pending enqueue operations that can fulfill this request, tf.errors.OutOfRangeError will be raised. If the session is tf.Session.close, tf.errors.CancelledError will be raised. Args n A scalar Tensor containing the number of elements to dequeue. name A name for the operation (optional). Returns The list of concatenated tensors that was dequeued. dequeue_up_to View source dequeue_up_to( n, name=None ) Dequeues and concatenates n elements from this queue. Note: This operation is not supported by all queues. If a queue does not support DequeueUpTo, then a tf.errors.UnimplementedError is raised. This operation concatenates queue-element component tensors along the 0th dimension to make a single component tensor. If the queue has not been closed, all of the components in the dequeued tuple will have size n in the 0th dimension. If the queue is closed and there are more than 0 but fewer than n elements remaining, then instead of raising a tf.errors.OutOfRangeError like tf.QueueBase.dequeue_many, less than n elements are returned immediately. If the queue is closed and there are 0 elements left in the queue, then a tf.errors.OutOfRangeError is raised just like in dequeue_many. Otherwise the behavior is identical to dequeue_many. Args n A scalar Tensor containing the number of elements to dequeue. name A name for the operation (optional). Returns The tuple of concatenated tensors that was dequeued. enqueue View source enqueue( vals, name=None ) Enqueues one element to this queue. If the queue is full when this operation executes, it will block until the element has been enqueued. At runtime, this operation may raise an error if the queue is tf.QueueBase.close before or during its execution. If the queue is closed before this operation runs, tf.errors.CancelledError will be raised. If this operation is blocked, and either (i) the queue is closed by a close operation with cancel_pending_enqueues=True, or (ii) the session is tf.Session.close, tf.errors.CancelledError will be raised. Args vals A tensor, a list or tuple of tensors, or a dictionary containing the values to enqueue. name A name for the operation (optional). Returns The operation that enqueues a new tuple of tensors to the queue. enqueue_many View source enqueue_many( vals, name=None ) Enqueues zero or more elements to this queue. This operation slices each component tensor along the 0th dimension to make multiple queue elements. All of the tensors in vals must have the same size in the 0th dimension. If the queue is full when this operation executes, it will block until all of the elements have been enqueued. At runtime, this operation may raise an error if the queue is tf.QueueBase.close before or during its execution. If the queue is closed before this operation runs, tf.errors.CancelledError will be raised. If this operation is blocked, and either (i) the queue is closed by a close operation with cancel_pending_enqueues=True, or (ii) the session is tf.Session.close, tf.errors.CancelledError will be raised. Args vals A tensor, a list or tuple of tensors, or a dictionary from which the queue elements are taken. name A name for the operation (optional). Returns The operation that enqueues a batch of tuples of tensors to the queue. from_list View source @staticmethod from_list( index, queues ) Create a queue using the queue reference from queues[index]. Args index An integer scalar tensor that determines the input that gets selected. queues A list of QueueBase objects. Returns A QueueBase object. Raises TypeError When queues is not a list of QueueBase objects, or when the data types of queues are not all the same. is_closed View source is_closed( name=None ) Returns true if queue is closed. This operation returns true if the queue is closed and false if the queue is open. Args name A name for the operation (optional). Returns True if the queue is closed and false if the queue is open. size View source size( name=None ) Compute the number of elements in this queue. Args name A name for the operation (optional). Returns A scalar tensor containing the number of elements in this queue.
tensorflow.queue.queuebase
tf.queue.RandomShuffleQueue View source on GitHub A queue implementation that dequeues elements in a random order. Inherits From: QueueBase View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.RandomShuffleQueue, tf.compat.v1.io.RandomShuffleQueue, tf.compat.v1.queue.RandomShuffleQueue tf.queue.RandomShuffleQueue( capacity, min_after_dequeue, dtypes, shapes=None, names=None, seed=None, shared_name=None, name='random_shuffle_queue' ) See tf.queue.QueueBase for a description of the methods on this class. Args capacity An integer. The upper bound on the number of elements that may be stored in this queue. min_after_dequeue An integer (described above). dtypes A list of DType objects. The length of dtypes must equal the number of tensors in each queue element. shapes (Optional.) A list of fully-defined TensorShape objects with the same length as dtypes, or None. names (Optional.) A list of string naming the components in the queue with the same length as dtypes, or None. If specified the dequeue methods return a dictionary with the names as keys. seed A Python integer. Used to create a random seed. See tf.compat.v1.set_random_seed for behavior. shared_name (Optional.) If non-empty, this queue will be shared under the given name across multiple sessions. name Optional name for the queue operation. Attributes dtypes The list of dtypes for each component of a queue element. name The name of the underlying queue. names The list of names for each component of a queue element. queue_ref The underlying queue reference. shapes The list of shapes for each component of a queue element. Methods close View source close( cancel_pending_enqueues=False, name=None ) Closes this queue. This operation signals that no more elements will be enqueued in the given queue. Subsequent enqueue and enqueue_many operations will fail. Subsequent dequeue and dequeue_many operations will continue to succeed if sufficient elements remain in the queue. Subsequently dequeue and dequeue_many operations that would otherwise block waiting for more elements (if close hadn't been called) will now fail immediately. If cancel_pending_enqueues is True, all pending requests will also be canceled. Args cancel_pending_enqueues (Optional.) A boolean, defaulting to False (described above). name A name for the operation (optional). Returns The operation that closes the queue. dequeue View source dequeue( name=None ) Dequeues one element from this queue. If the queue is empty when this operation executes, it will block until there is an element to dequeue. At runtime, this operation may raise an error if the queue is tf.QueueBase.close before or during its execution. If the queue is closed, the queue is empty, and there are no pending enqueue operations that can fulfill this request, tf.errors.OutOfRangeError will be raised. If the session is tf.Session.close, tf.errors.CancelledError will be raised. Args name A name for the operation (optional). Returns The tuple of tensors that was dequeued. dequeue_many View source dequeue_many( n, name=None ) Dequeues and concatenates n elements from this queue. This operation concatenates queue-element component tensors along the 0th dimension to make a single component tensor. All of the components in the dequeued tuple will have size n in the 0th dimension. If the queue is closed and there are less than n elements left, then an OutOfRange exception is raised. At runtime, this operation may raise an error if the queue is tf.QueueBase.close before or during its execution. If the queue is closed, the queue contains fewer than n elements, and there are no pending enqueue operations that can fulfill this request, tf.errors.OutOfRangeError will be raised. If the session is tf.Session.close, tf.errors.CancelledError will be raised. Args n A scalar Tensor containing the number of elements to dequeue. name A name for the operation (optional). Returns The list of concatenated tensors that was dequeued. dequeue_up_to View source dequeue_up_to( n, name=None ) Dequeues and concatenates n elements from this queue. Note: This operation is not supported by all queues. If a queue does not support DequeueUpTo, then a tf.errors.UnimplementedError is raised. This operation concatenates queue-element component tensors along the 0th dimension to make a single component tensor. If the queue has not been closed, all of the components in the dequeued tuple will have size n in the 0th dimension. If the queue is closed and there are more than 0 but fewer than n elements remaining, then instead of raising a tf.errors.OutOfRangeError like tf.QueueBase.dequeue_many, less than n elements are returned immediately. If the queue is closed and there are 0 elements left in the queue, then a tf.errors.OutOfRangeError is raised just like in dequeue_many. Otherwise the behavior is identical to dequeue_many. Args n A scalar Tensor containing the number of elements to dequeue. name A name for the operation (optional). Returns The tuple of concatenated tensors that was dequeued. enqueue View source enqueue( vals, name=None ) Enqueues one element to this queue. If the queue is full when this operation executes, it will block until the element has been enqueued. At runtime, this operation may raise an error if the queue is tf.QueueBase.close before or during its execution. If the queue is closed before this operation runs, tf.errors.CancelledError will be raised. If this operation is blocked, and either (i) the queue is closed by a close operation with cancel_pending_enqueues=True, or (ii) the session is tf.Session.close, tf.errors.CancelledError will be raised. Args vals A tensor, a list or tuple of tensors, or a dictionary containing the values to enqueue. name A name for the operation (optional). Returns The operation that enqueues a new tuple of tensors to the queue. enqueue_many View source enqueue_many( vals, name=None ) Enqueues zero or more elements to this queue. This operation slices each component tensor along the 0th dimension to make multiple queue elements. All of the tensors in vals must have the same size in the 0th dimension. If the queue is full when this operation executes, it will block until all of the elements have been enqueued. At runtime, this operation may raise an error if the queue is tf.QueueBase.close before or during its execution. If the queue is closed before this operation runs, tf.errors.CancelledError will be raised. If this operation is blocked, and either (i) the queue is closed by a close operation with cancel_pending_enqueues=True, or (ii) the session is tf.Session.close, tf.errors.CancelledError will be raised. Args vals A tensor, a list or tuple of tensors, or a dictionary from which the queue elements are taken. name A name for the operation (optional). Returns The operation that enqueues a batch of tuples of tensors to the queue. from_list View source @staticmethod from_list( index, queues ) Create a queue using the queue reference from queues[index]. Args index An integer scalar tensor that determines the input that gets selected. queues A list of QueueBase objects. Returns A QueueBase object. Raises TypeError When queues is not a list of QueueBase objects, or when the data types of queues are not all the same. is_closed View source is_closed( name=None ) Returns true if queue is closed. This operation returns true if the queue is closed and false if the queue is open. Args name A name for the operation (optional). Returns True if the queue is closed and false if the queue is open. size View source size( name=None ) Compute the number of elements in this queue. Args name A name for the operation (optional). Returns A scalar tensor containing the number of elements in this queue.
tensorflow.queue.randomshufflequeue
Module: tf.ragged Ragged Tensors. This package defines ops for manipulating ragged tensors (tf.RaggedTensor), which are tensors with non-uniform shapes. In particular, each RaggedTensor has one or more ragged dimensions, which are dimensions whose slices may have different lengths. For example, the inner (column) dimension of rt=[[3, 1, 4, 1], [], [5, 9, 2], [6], []] is ragged, since the column slices (rt[0, :], ..., rt[4, :]) have different lengths. For a more detailed description of ragged tensors, see the tf.RaggedTensor class documentation and the Ragged Tensor Guide. Additional ops that support RaggedTensor Arguments that accept RaggedTensors are marked in bold. tf.batch_gather(params, indices, name=None) tf.bitwise.bitwise_and(x, y, name=None) tf.bitwise.bitwise_or(x, y, name=None) tf.bitwise.bitwise_xor(x, y, name=None) tf.bitwise.invert(x, name=None) tf.bitwise.left_shift(x, y, name=None) tf.bitwise.right_shift(x, y, name=None) tf.cast(x, dtype, name=None) tf.clip_by_value(t, clip_value_min, clip_value_max, name=None) tf.concat(values, axis, name='concat') tf.debugging.check_numerics(tensor, message, name=None) tf.dtypes.complex(real, imag, name=None) tf.dtypes.saturate_cast(value, dtype, name=None) tf.dynamic_partition(data, partitions, num_partitions, name=None) tf.expand_dims(input, axis=None, name=None, dim=None) tf.gather_nd(params, indices, name=None, batch_dims=0) tf.gather(params, indices, validate_indices=None, name=None, axis=None, batch_dims=0) tf.identity(input, name=None) tf.io.decode_base64(input, name=None) tf.io.decode_compressed(bytes, compression_type='', name=None) tf.io.encode_base64(input, pad=False, name=None) tf.math.abs(x, name=None) tf.math.acos(x, name=None) tf.math.acosh(x, name=None) tf.math.add_n(inputs, name=None) tf.math.add(x, y, name=None) tf.math.angle(input, name=None) tf.math.asin(x, name=None) tf.math.asinh(x, name=None) tf.math.atan2(y, x, name=None) tf.math.atan(x, name=None) tf.math.atanh(x, name=None) tf.math.ceil(x, name=None) tf.math.conj(x, name=None) tf.math.cos(x, name=None) tf.math.cosh(x, name=None) tf.math.digamma(x, name=None) tf.math.divide_no_nan(x, y, name=None) tf.math.divide(x, y, name=None) tf.math.equal(x, y, name=None) tf.math.erf(x, name=None) tf.math.erfc(x, name=None) tf.math.erfinv(x, name=None) tf.math.exp(x, name=None) tf.math.expm1(x, name=None) tf.math.floor(x, name=None) tf.math.floordiv(x, y, name=None) tf.math.floormod(x, y, name=None) tf.math.greater_equal(x, y, name=None) tf.math.greater(x, y, name=None) tf.math.imag(input, name=None) tf.math.is_finite(x, name=None) tf.math.is_inf(x, name=None) tf.math.is_nan(x, name=None) tf.math.less_equal(x, y, name=None) tf.math.less(x, y, name=None) tf.math.lgamma(x, name=None) tf.math.log1p(x, name=None) tf.math.log_sigmoid(x, name=None) tf.math.log(x, name=None) tf.math.logical_and(x, y, name=None) tf.math.logical_not(x, name=None) tf.math.logical_or(x, y, name=None) tf.math.logical_xor(x, y, name='LogicalXor') tf.math.maximum(x, y, name=None) tf.math.minimum(x, y, name=None) tf.math.multiply(x, y, name=None) tf.math.ndtri(x, name=None) tf.math.negative(x, name=None) tf.math.not_equal(x, y, name=None) tf.math.pow(x, y, name=None) tf.math.real(input, name=None) tf.math.reciprocal(x, name=None) tf.math.reduce_all(input_tensor, axis=None, keepdims=False, name=None) tf.math.reduce_any(input_tensor, axis=None, keepdims=False, name=None) tf.math.reduce_max(input_tensor, axis=None, keepdims=False, name=None) tf.math.reduce_mean(input_tensor, axis=None, keepdims=False, name=None) tf.math.reduce_min(input_tensor, axis=None, keepdims=False, name=None) tf.math.reduce_prod(input_tensor, axis=None, keepdims=False, name=None) tf.math.reduce_sum(input_tensor, axis=None, keepdims=False, name=None) tf.math.rint(x, name=None) tf.math.round(x, name=None) tf.math.rsqrt(x, name=None) tf.math.sign(x, name=None) tf.math.sin(x, name=None) tf.math.sinh(x, name=None) tf.math.sqrt(x, name=None) tf.math.square(x, name=None) tf.math.squared_difference(x, y, name=None) tf.math.subtract(x, y, name=None) tf.math.tan(x, name=None) tf.math.truediv(x, y, name=None) tf.math.unsorted_segment_max(data, segment_ids, num_segments, name=None) tf.math.unsorted_segment_mean(data, segment_ids, num_segments, name=None) tf.math.unsorted_segment_min(data, segment_ids, num_segments, name=None) tf.math.unsorted_segment_prod(data, segment_ids, num_segments, name=None) tf.math.unsorted_segment_sqrt_n(data, segment_ids, num_segments, name=None) tf.math.unsorted_segment_sum(data, segment_ids, num_segments, name=None) tf.nn.dropout(x, keep_prob=None, noise_shape=None, seed=None, name=None, rate=None) tf.one_hot(indices, depth, on_value=None, off_value=None, axis=None, dtype=None, name=None) tf.ones_like(tensor, dtype=None, name=None, optimize=True) tf.print(*inputs, **kwargs) tf.rank(input, name=None) tf.realdiv(x, y, name=None) tf.reverse(tensor, axis, name=None) tf.size(input, name=None, out_type=tf.int32) tf.squeeze(input, axis=None, name=None, squeeze_dims=None) tf.stack(values, axis=0, name='stack') tf.strings.as_string(input, precision=-1, scientific=False, shortest=False, width=-1, fill='', name=None) tf.strings.format(template, inputs, placeholder='{}', summarize=3, name=None) tf.strings.join(inputs, separator='', name=None) tf.strings.length(input, name=None, unit='BYTE') tf.strings.reduce_join(inputs, axis=None, keepdims=False, separator='', name=None) tf.strings.regex_full_match(input, pattern, name=None) tf.strings.regex_replace(input, pattern, rewrite, replace_global=True, name=None) tf.strings.strip(input, name=None) tf.strings.substr(input, pos, len, name=None, unit='BYTE') tf.strings.to_hash_bucket_fast(input, num_buckets, name=None) tf.strings.to_hash_bucket_strong(input, num_buckets, key, name=None) tf.strings.to_hash_bucket(input, num_buckets, name=None) tf.strings.to_hash_bucket(input, num_buckets, name=None) tf.strings.to_number(input, out_type=tf.float32, name=None) tf.strings.unicode_script(input, name=None) tf.tile(input, multiples, name=None) tf.truncatediv(x, y, name=None) tf.truncatemod(x, y, name=None) tf.where(condition, x=None, y=None, name=None) tf.where(condition, x=None, y=None, name=None) tf.zeros_like(tensor, dtype=None, name=None, optimize=True)n Functions boolean_mask(...): Applies a boolean mask to data without flattening the mask dimensions. constant(...): Constructs a constant RaggedTensor from a nested Python list. cross(...): Generates feature cross from a list of tensors. cross_hashed(...): Generates hashed feature cross from a list of tensors. map_flat_values(...): Applies op to the values of one or more RaggedTensors. range(...): Returns a RaggedTensor containing the specified sequences of numbers. row_splits_to_segment_ids(...): Generates the segmentation corresponding to a RaggedTensor row_splits. segment_ids_to_row_splits(...): Generates the RaggedTensor row_splits corresponding to a segmentation. stack(...): Stacks a list of rank-R tensors into one rank-(R+1) RaggedTensor. stack_dynamic_partitions(...): Stacks dynamic partitions of a Tensor or RaggedTensor.
tensorflow.ragged
tf.ragged.boolean_mask View source on GitHub Applies a boolean mask to data without flattening the mask dimensions. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.ragged.boolean_mask tf.ragged.boolean_mask( data, mask, name=None ) Returns a potentially ragged tensor that is formed by retaining the elements in data where the corresponding value in mask is True. output[a1...aA, i, b1...bB] = data[a1...aA, j, b1...bB] Where j is the ith True entry of mask[a1...aA]. Note that output preserves the mask dimensions a1...aA; this differs from tf.boolean_mask, which flattens those dimensions. Args data A potentially ragged tensor. mask A potentially ragged boolean tensor. mask's shape must be a prefix of data's shape. rank(mask) must be known statically. name A name prefix for the returned tensor (optional). Returns A potentially ragged tensor that is formed by retaining the elements in data where the corresponding value in mask is True. rank(output) = rank(data). output.ragged_rank = max(data.ragged_rank, rank(mask) - 1). Raises ValueError if rank(mask) is not known statically; or if mask.shape is not a prefix of data.shape. Examples: # Aliases for True & False so data and mask line up. T, F = (True, False) tf.ragged.boolean_mask( # Mask a 2D Tensor. data=[[1, 2, 3], [4, 5, 6], [7, 8, 9]], mask=[[T, F, T], [F, F, F], [T, F, F]]).to_list() [[1, 3], [], [7]] tf.ragged.boolean_mask( # Mask a 2D RaggedTensor. tf.ragged.constant([[1, 2, 3], [4], [5, 6]]), tf.ragged.constant([[F, F, T], [F], [T, T]])).to_list() [[3], [], [5, 6]] tf.ragged.boolean_mask( # Mask rows of a 2D RaggedTensor. tf.ragged.constant([[1, 2, 3], [4], [5, 6]]), tf.ragged.constant([True, False, True])).to_list() [[1, 2, 3], [5, 6]]
tensorflow.ragged.boolean_mask
tf.ragged.constant View source on GitHub Constructs a constant RaggedTensor from a nested Python list. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.ragged.constant tf.ragged.constant( pylist, dtype=None, ragged_rank=None, inner_shape=None, name=None, row_splits_dtype=tf.dtypes.int64 ) Example: tf.ragged.constant([[1, 2], [3], [4, 5, 6]]) <tf.RaggedTensor [[1, 2], [3], [4, 5, 6]]> All scalar values in pylist must have the same nesting depth K, and the returned RaggedTensor will have rank K. If pylist contains no scalar values, then K is one greater than the maximum depth of empty lists in pylist. All scalar values in pylist must be compatible with dtype. Args pylist A nested list, tuple or np.ndarray. Any nested element that is not a list, tuple or np.ndarray must be a scalar value compatible with dtype. dtype The type of elements for the returned RaggedTensor. If not specified, then a default is chosen based on the scalar values in pylist. ragged_rank An integer specifying the ragged rank of the returned RaggedTensor. Must be nonnegative and less than K. Defaults to max(0, K - 1) if inner_shape is not specified. Defaults to max(0, K - 1 - len(inner_shape)) if inner_shape is specified. inner_shape A tuple of integers specifying the shape for individual inner values in the returned RaggedTensor. Defaults to () if ragged_rank is not specified. If ragged_rank is specified, then a default is chosen based on the contents of pylist. name A name prefix for the returned tensor (optional). row_splits_dtype data type for the constructed RaggedTensor's row_splits. One of tf.int32 or tf.int64. Returns A potentially ragged tensor with rank K and the specified ragged_rank, containing the values from pylist. Raises ValueError If the scalar values in pylist have inconsistent nesting depth; or if ragged_rank or inner_shape are incompatible with pylist.
tensorflow.compat.v1.ragged.constant
tf.ragged.constant View source on GitHub Constructs a constant RaggedTensor from a nested Python list. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.ragged.constant tf.ragged.constant( pylist, dtype=None, ragged_rank=None, inner_shape=None, name=None, row_splits_dtype=tf.dtypes.int64 ) Example: tf.ragged.constant([[1, 2], [3], [4, 5, 6]]) <tf.RaggedTensor [[1, 2], [3], [4, 5, 6]]> All scalar values in pylist must have the same nesting depth K, and the returned RaggedTensor will have rank K. If pylist contains no scalar values, then K is one greater than the maximum depth of empty lists in pylist. All scalar values in pylist must be compatible with dtype. Args pylist A nested list, tuple or np.ndarray. Any nested element that is not a list, tuple or np.ndarray must be a scalar value compatible with dtype. dtype The type of elements for the returned RaggedTensor. If not specified, then a default is chosen based on the scalar values in pylist. ragged_rank An integer specifying the ragged rank of the returned RaggedTensor. Must be nonnegative and less than K. Defaults to max(0, K - 1) if inner_shape is not specified. Defaults to max(0, K - 1 - len(inner_shape)) if inner_shape is specified. inner_shape A tuple of integers specifying the shape for individual inner values in the returned RaggedTensor. Defaults to () if ragged_rank is not specified. If ragged_rank is specified, then a default is chosen based on the contents of pylist. name A name prefix for the returned tensor (optional). row_splits_dtype data type for the constructed RaggedTensor's row_splits. One of tf.int32 or tf.int64. Returns A potentially ragged tensor with rank K and the specified ragged_rank, containing the values from pylist. Raises ValueError If the scalar values in pylist have inconsistent nesting depth; or if ragged_rank or inner_shape are incompatible with pylist.
tensorflow.ragged.constant
tf.ragged.cross Generates feature cross from a list of tensors. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.ragged.cross tf.ragged.cross( inputs, name=None ) The input tensors must have rank=2, and must all have the same number of rows. The result is a RaggedTensor with the same number of rows as the inputs, where result[row] contains a list of all combinations of values formed by taking a single value from each input's corresponding row (inputs[i][row]). Values are combined by joining their strings with 'X'. E.g.: tf.ragged.cross([tf.ragged.constant([['a'], ['b', 'c']]), tf.ragged.constant([['d'], ['e']]), tf.ragged.constant([['f'], ['g']])]) <tf.RaggedTensor [[b'a_X_d_X_f'], [b'b_X_e_X_g', b'c_X_e_X_g']]> Args inputs A list of RaggedTensor or Tensor or SparseTensor. name Optional name for the op. Returns A 2D RaggedTensor of type string.
tensorflow.ragged.cross
tf.ragged.cross_hashed Generates hashed feature cross from a list of tensors. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.ragged.cross_hashed tf.ragged.cross_hashed( inputs, num_buckets=0, hash_key=None, name=None ) The input tensors must have rank=2, and must all have the same number of rows. The result is a RaggedTensor with the same number of rows as the inputs, where result[row] contains a list of all combinations of values formed by taking a single value from each input's corresponding row (inputs[i][row]). Values are combined by hashing together their fingerprints. E.g.: tf.ragged.cross_hashed([tf.ragged.constant([['a'], ['b', 'c']]), tf.ragged.constant([['d'], ['e']]), tf.ragged.constant([['f'], ['g']])], num_buckets=100) <tf.RaggedTensor [[78], [66, 74]]> Args inputs A list of RaggedTensor or Tensor or SparseTensor. num_buckets A non-negative int that used to bucket the hashed values. If num_buckets != 0, then output = hashed_value % num_buckets. hash_key Integer hash_key that will be used by the FingerprintCat64 function. If not given, a default key is used. name Optional name for the op. Returns A 2D RaggedTensor of type int64.
tensorflow.ragged.cross_hashed
tf.ragged.map_flat_values View source on GitHub Applies op to the values of one or more RaggedTensors. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.ragged.map_flat_values tf.ragged.map_flat_values( op, *args, **kwargs ) Replaces any RaggedTensor in args or kwargs with its flat_values tensor, and then calls op. Returns a RaggedTensor that is constructed from the input RaggedTensors' nested_row_splits and the value returned by the op. If the input arguments contain multiple RaggedTensors, then they must have identical nested_row_splits. Examples: rt = tf.ragged.constant([[1, 2, 3], [], [4, 5], [6]]) map_flat_values(tf.ones_like, rt).to_list() [[1, 1, 1], [], [1, 1], [1]] map_flat_values(tf.multiply, rt, rt).to_list() [[1, 4, 9], [], [16, 25], [36]] map_flat_values(tf.add, rt, 5).to_list() [[6, 7, 8], [], [9, 10], [11]] Args op The operation that should be applied to the RaggedTensor flat_values. op is typically an element-wise operation (such as math_ops.add), but any operation that preserves the size of the outermost dimension can be used. I.e., shape[0] of the value returned by op must match shape[0] of the RaggedTensors' flat_values tensors. *args Arguments for op. **kwargs Keyword arguments for op. Returns A RaggedTensor whose ragged_rank matches the ragged_rank of all input RaggedTensors. Raises ValueError If args contains no RaggedTensors, or if the nested_splits of the input RaggedTensors are not identical.
tensorflow.ragged.map_flat_values
tf.ragged.range View source on GitHub Returns a RaggedTensor containing the specified sequences of numbers. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.ragged.range tf.ragged.range( starts, limits=None, deltas=1, dtype=None, name=None, row_splits_dtype=tf.dtypes.int64 ) Each row of the returned RaggedTensor contains a single sequence: ragged.range(starts, limits, deltas)[i] == tf.range(starts[i], limits[i], deltas[i]) If start[i] < limits[i] and deltas[i] > 0, then output[i] will be an empty list. Similarly, if start[i] > limits[i] and deltas[i] < 0, then output[i] will be an empty list. This behavior is consistent with the Python range function, but differs from the tf.range op, which returns an error for these cases. Examples: tf.ragged.range([3, 5, 2]).to_list() [[0, 1, 2], [0, 1, 2, 3, 4], [0, 1]] tf.ragged.range([0, 5, 8], [3, 3, 12]).to_list() [[0, 1, 2], [], [8, 9, 10, 11]] tf.ragged.range([0, 5, 8], [3, 3, 12], 2).to_list() [[0, 2], [], [8, 10]] The input tensors starts, limits, and deltas may be scalars or vectors. The vector inputs must all have the same size. Scalar inputs are broadcast to match the size of the vector inputs. Args starts Vector or scalar Tensor. Specifies the first entry for each range if limits is not None; otherwise, specifies the range limits, and the first entries default to 0. limits Vector or scalar Tensor. Specifies the exclusive upper limits for each range. deltas Vector or scalar Tensor. Specifies the increment for each range. Defaults to 1. dtype The type of the elements of the resulting tensor. If not specified, then a value is chosen based on the other args. name A name for the operation. row_splits_dtype dtype for the returned RaggedTensor's row_splits tensor. One of tf.int32 or tf.int64. Returns A RaggedTensor of type dtype with ragged_rank=1.
tensorflow.ragged.range
tf.ragged.row_splits_to_segment_ids View source on GitHub Generates the segmentation corresponding to a RaggedTensor row_splits. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.ragged.row_splits_to_segment_ids tf.ragged.row_splits_to_segment_ids( splits, name=None, out_type=None ) Returns an integer vector segment_ids, where segment_ids[i] == j if splits[j] <= i < splits[j+1]. Example: print(tf.ragged.row_splits_to_segment_ids([0, 3, 3, 5, 6, 9])) tf.Tensor([0 0 0 2 2 3 4 4 4], shape=(9,), dtype=int64) Args splits A sorted 1-D integer Tensor. splits[0] must be zero. name A name prefix for the returned tensor (optional). out_type The dtype for the return value. Defaults to splits.dtype, or tf.int64 if splits does not have a dtype. Returns A sorted 1-D integer Tensor, with shape=[splits[-1]] Raises ValueError If splits is invalid.
tensorflow.ragged.row_splits_to_segment_ids
tf.ragged.segment_ids_to_row_splits View source on GitHub Generates the RaggedTensor row_splits corresponding to a segmentation. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.ragged.segment_ids_to_row_splits tf.ragged.segment_ids_to_row_splits( segment_ids, num_segments=None, out_type=None, name=None ) Returns an integer vector splits, where splits[0] = 0 and splits[i] = splits[i-1] + count(segment_ids==i). Example: print(tf.ragged.segment_ids_to_row_splits([0, 0, 0, 2, 2, 3, 4, 4, 4])) tf.Tensor([0 3 3 5 6 9], shape=(6,), dtype=int64) Args segment_ids A 1-D integer Tensor. num_segments A scalar integer indicating the number of segments. Defaults to max(segment_ids) + 1 (or zero if segment_ids is empty). out_type The dtype for the return value. Defaults to segment_ids.dtype, or tf.int64 if segment_ids does not have a dtype. name A name prefix for the returned tensor (optional). Returns A sorted 1-D integer Tensor, with shape=[num_segments + 1].
tensorflow.ragged.segment_ids_to_row_splits
tf.ragged.stack View source on GitHub Stacks a list of rank-R tensors into one rank-(R+1) RaggedTensor. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.ragged.stack tf.ragged.stack( values, axis=0, name=None ) Given a list of tensors or ragged tensors with the same rank R (R >= axis), returns a rank-R+1 RaggedTensor result such that result[i0...iaxis] is [value[i0...iaxis] for value in values]. Examples: # Stacking two ragged tensors. t1 = tf.ragged.constant([[1, 2], [3, 4, 5]]) t2 = tf.ragged.constant([[6], [7, 8, 9]]) tf.ragged.stack([t1, t2], axis=0) <tf.RaggedTensor [[[1, 2], [3, 4, 5]], [[6], [7, 8, 9]]]> tf.ragged.stack([t1, t2], axis=1) <tf.RaggedTensor [[[1, 2], [6]], [[3, 4, 5], [7, 8, 9]]]> # Stacking two dense tensors with different sizes. t3 = tf.constant([[1, 2, 3], [4, 5, 6]]) t4 = tf.constant([[5], [6], [7]]) tf.ragged.stack([t3, t4], axis=0) <tf.RaggedTensor [[[1, 2, 3], [4, 5, 6]], [[5], [6], [7]]]> Args values A list of tf.Tensor or tf.RaggedTensor. May not be empty. All values must have the same rank and the same dtype; but unlike tf.stack, they can have arbitrary dimension sizes. axis A python integer, indicating the dimension along which to stack. (Note: Unlike tf.stack, the axis parameter must be statically known.) Negative values are supported only if the rank of at least one values value is statically known. name A name prefix for the returned tensor (optional). Returns A RaggedTensor with rank R+1. result.ragged_rank=1+max(axis, max(rt.ragged_rank for rt in values])). Raises ValueError If values is empty, if axis is out of bounds or if the input tensors have different ranks.
tensorflow.ragged.stack
tf.ragged.stack_dynamic_partitions View source on GitHub Stacks dynamic partitions of a Tensor or RaggedTensor. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.ragged.stack_dynamic_partitions tf.ragged.stack_dynamic_partitions( data, partitions, num_partitions, name=None ) Returns a RaggedTensor output with num_partitions rows, where the row output[i] is formed by stacking all slices data[j1...jN] such that partitions[j1...jN] = i. Slices of data are stacked in row-major order. If num_partitions is an int (not a Tensor), then this is equivalent to tf.ragged.stack(tf.dynamic_partition(data, partitions, num_partitions)). Example: data = ['a', 'b', 'c', 'd', 'e'] partitions = [ 3, 0, 2, 2, 3] num_partitions = 5 tf.ragged.stack_dynamic_partitions(data, partitions, num_partitions) <tf.RaggedTensor [[b'b'], [], [b'c', b'd'], [b'a', b'e'], []]> Args data A Tensor or RaggedTensor containing the values to stack. partitions An int32 or int64 Tensor or RaggedTensor specifying the partition that each slice of data should be added to. partitions.shape must be a prefix of data.shape. Values must be greater than or equal to zero, and less than num_partitions. partitions is not required to be sorted. num_partitions An int32 or int64 scalar specifying the number of partitions to output. This determines the number of rows in output. name A name prefix for the returned tensor (optional). Returns A RaggedTensor containing the stacked partitions. The returned tensor has the same dtype as data, and its shape is [num_partitions, (D)] + data.shape[partitions.rank:], where (D) is a ragged dimension whose length is the number of data slices stacked for each partition.
tensorflow.ragged.stack_dynamic_partitions
tf.RaggedTensor View source on GitHub Represents a ragged tensor. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.RaggedTensor A RaggedTensor is a tensor with one or more ragged dimensions, which are dimensions whose slices may have different lengths. For example, the inner (column) dimension of rt=[[3, 1, 4, 1], [], [5, 9, 2], [6], []] is ragged, since the column slices (rt[0, :], ..., rt[4, :]) have different lengths. Dimensions whose slices all have the same length are called uniform dimensions. The outermost dimension of a RaggedTensor is always uniform, since it consists of a single slice (and so there is no possibility for differing slice lengths). The total number of dimensions in a RaggedTensor is called its rank, and the number of ragged dimensions in a RaggedTensor is called its ragged-rank. A RaggedTensor's ragged-rank is fixed at graph creation time: it can't depend on the runtime values of Tensors, and can't vary dynamically for different session runs. Note that the __init__ constructor is private. Please use one of the following methods to construct a RaggedTensor: * <a href="../tf/RaggedTensor#from_row_lengths"><code>tf.RaggedTensor.from_row_lengths</code></a> * <a href="../tf/RaggedTensor#from_value_rowids"><code>tf.RaggedTensor.from_value_rowids</code></a> * <a href="../tf/RaggedTensor#from_row_splits"><code>tf.RaggedTensor.from_row_splits</code></a> * <a href="../tf/RaggedTensor#from_row_starts"><code>tf.RaggedTensor.from_row_starts</code></a> * <a href="../tf/RaggedTensor#from_row_limits"><code>tf.RaggedTensor.from_row_limits</code></a> * <a href="../tf/RaggedTensor#from_nested_row_splits"><code>tf.RaggedTensor.from_nested_row_splits</code></a> * <a href="../tf/RaggedTensor#from_nested_row_lengths"><code>tf.RaggedTensor.from_nested_row_lengths</code></a> * <a href="../tf/RaggedTensor#from_nested_value_rowids"><code>tf.RaggedTensor.from_nested_value_rowids</code></a> Potentially Ragged Tensors Many ops support both Tensors and RaggedTensors. The term "potentially ragged tensor" may be used to refer to a tensor that might be either a Tensor or a RaggedTensor. The ragged-rank of a Tensor is zero. Documenting RaggedTensor Shapes When documenting the shape of a RaggedTensor, ragged dimensions can be indicated by enclosing them in parentheses. For example, the shape of a 3-D RaggedTensor that stores the fixed-size word embedding for each word in a sentence, for each sentence in a batch, could be written as [num_sentences, (num_words), embedding_size]. The parentheses around (num_words) indicate that dimension is ragged, and that the length of each element list in that dimension may vary for each item. Component Tensors Internally, a RaggedTensor consists of a concatenated list of values that are partitioned into variable-length rows. In particular, each RaggedTensor consists of: A values tensor, which concatenates the variable-length rows into a flattened list. For example, the values tensor for [[3, 1, 4, 1], [], [5, 9, 2], [6], []] is [3, 1, 4, 1, 5, 9, 2, 6]. A row_splits vector, which indicates how those flattened values are divided into rows. In particular, the values for row rt[i] are stored in the slice rt.values[rt.row_splits[i]:rt.row_splits[i+1]]. Example: print(tf.RaggedTensor.from_row_splits( values=[3, 1, 4, 1, 5, 9, 2, 6], row_splits=[0, 4, 4, 7, 8, 8])) <tf.RaggedTensor [[3, 1, 4, 1], [], [5, 9, 2], [6], []]> Alternative Row-Partitioning Schemes In addition to row_splits, ragged tensors provide support for five other row-partitioning schemes: row_lengths: a vector with shape [nrows], which specifies the length of each row. value_rowids and nrows: value_rowids is a vector with shape [nvals], corresponding one-to-one with values, which specifies each value's row index. In particular, the row rt[row] consists of the values rt.values[j] where value_rowids[j]==row. nrows is an integer scalar that specifies the number of rows in the RaggedTensor. (nrows is used to indicate trailing empty rows.) row_starts: a vector with shape [nrows], which specifies the start offset of each row. Equivalent to row_splits[:-1]. row_limits: a vector with shape [nrows], which specifies the stop offset of each row. Equivalent to row_splits[1:]. uniform_row_length: A scalar tensor, specifying the length of every row. This row-partitioning scheme may only be used if all rows have the same length. Example: The following ragged tensors are equivalent, and all represent the nested list [[3, 1, 4, 1], [], [5, 9, 2], [6], []]. values = [3, 1, 4, 1, 5, 9, 2, 6] rt1 = RaggedTensor.from_row_splits(values, row_splits=[0, 4, 4, 7, 8, 8]) rt2 = RaggedTensor.from_row_lengths(values, row_lengths=[4, 0, 3, 1, 0]) rt3 = RaggedTensor.from_value_rowids( values, value_rowids=[0, 0, 0, 0, 2, 2, 2, 3], nrows=5) rt4 = RaggedTensor.from_row_starts(values, row_starts=[0, 4, 4, 7, 8]) rt5 = RaggedTensor.from_row_limits(values, row_limits=[4, 4, 7, 8, 8]) Multiple Ragged Dimensions RaggedTensors with multiple ragged dimensions can be defined by using a nested RaggedTensor for the values tensor. Each nested RaggedTensor adds a single ragged dimension. inner_rt = RaggedTensor.from_row_splits( # =rt1 from above values=[3, 1, 4, 1, 5, 9, 2, 6], row_splits=[0, 4, 4, 7, 8, 8]) outer_rt = RaggedTensor.from_row_splits( values=inner_rt, row_splits=[0, 3, 3, 5]) print(outer_rt.to_list()) [[[3, 1, 4, 1], [], [5, 9, 2]], [], [[6], []]] print(outer_rt.ragged_rank) 2 The factory function RaggedTensor.from_nested_row_splits may be used to construct a RaggedTensor with multiple ragged dimensions directly, by providing a list of row_splits tensors: RaggedTensor.from_nested_row_splits( flat_values=[3, 1, 4, 1, 5, 9, 2, 6], nested_row_splits=([0, 3, 3, 5], [0, 4, 4, 7, 8, 8])).to_list() [[[3, 1, 4, 1], [], [5, 9, 2]], [], [[6], []]] Uniform Inner Dimensions RaggedTensors with uniform inner dimensions can be defined by using a multidimensional Tensor for values. rt = RaggedTensor.from_row_splits(values=tf.ones([5, 3], tf.int32), row_splits=[0, 2, 5]) print(rt.to_list()) [[[1, 1, 1], [1, 1, 1]], [[1, 1, 1], [1, 1, 1], [1, 1, 1]]] print(rt.shape) (2, None, 3) Uniform Outer Dimensions RaggedTensors with uniform outer dimensions can be defined by using one or more RaggedTensor with a uniform_row_length row-partitioning tensor. For example, a RaggedTensor with shape [2, 2, None] can be constructed with this method from a RaggedTensor values with shape [4, None]: values = tf.ragged.constant([[1, 2, 3], [4], [5, 6], [7, 8, 9, 10]]) print(values.shape) (4, None) rt6 = tf.RaggedTensor.from_uniform_row_length(values, 2) print(rt6) <tf.RaggedTensor [[[1, 2, 3], [4]], [[5, 6], [7, 8, 9, 10]]]> print(rt6.shape) (2, 2, None) Note that rt6 only contains one ragged dimension (the innermost dimension). In contrast, if from_row_splits is used to construct a similar RaggedTensor, then that RaggedTensor will have two ragged dimensions: rt7 = tf.RaggedTensor.from_row_splits(values, [0, 2, 4]) print(rt7.shape) (2, None, None) Uniform and ragged outer dimensions may be interleaved, meaning that a tensor with any combination of ragged and uniform dimensions may be created. For example, a RaggedTensor t4 with shape [3, None, 4, 8, None, 2] could be constructed as follows: t0 = tf.zeros([1000, 2]) # Shape: [1000, 2] t1 = RaggedTensor.from_row_lengths(t0, [...]) # [160, None, 2] t2 = RaggedTensor.from_uniform_row_length(t1, 8) # [20, 8, None, 2] t3 = RaggedTensor.from_uniform_row_length(t2, 4) # [5, 4, 8, None, 2] t4 = RaggedTensor.from_row_lengths(t3, [...]) # [3, None, 4, 8, None, 2] Attributes dtype The DType of values in this tensor. flat_values The innermost values tensor for this ragged tensor. Concretely, if rt.values is a Tensor, then rt.flat_values is rt.values; otherwise, rt.flat_values is rt.values.flat_values. Conceptually, flat_values is the tensor formed by flattening the outermost dimension and all of the ragged dimensions into a single dimension. rt.flat_values.shape = [nvals] + rt.shape[rt.ragged_rank + 1:] (where nvals is the number of items in the flattened dimensions). Example: rt = tf.ragged.constant([[[3, 1, 4, 1], [], [5, 9, 2]], [], [[6], []]]) print(rt.flat_values) tf.Tensor([3 1 4 1 5 9 2 6], shape=(8,), dtype=int32) nested_row_splits A tuple containing the row_splits for all ragged dimensions. rt.nested_row_splits is a tuple containing the row_splits tensors for all ragged dimensions in rt, ordered from outermost to innermost. In particular, rt.nested_row_splits = (rt.row_splits,) + value_splits where: value_splits = () if rt.values is a Tensor. value_splits = rt.values.nested_row_splits otherwise. Example: rt = tf.ragged.constant( [[[[3, 1, 4, 1], [], [5, 9, 2]], [], [[6], []]]]) for i, splits in enumerate(rt.nested_row_splits): print('Splits for dimension %d: %s' % (i+1, splits.numpy())) Splits for dimension 1: [0 3] Splits for dimension 2: [0 3 3 5] Splits for dimension 3: [0 4 4 7 8 8] ragged_rank The number of times the RaggedTensor's flat_values is partitioned. values = tf.ragged.constant([[1, 2, 3], [4], [5, 6], [7, 8, 9, 10]]) values.ragged_rank 1 rt = tf.RaggedTensor.from_uniform_row_length(values, 2) rt.ragged_rank 2 row_splits The row-split indices for this ragged tensor's values. rt.row_splits specifies where the values for each row begin and end in rt.values. In particular, the values for row rt[i] are stored in the slice rt.values[rt.row_splits[i]:rt.row_splits[i+1]]. Example: rt = tf.ragged.constant([[3, 1, 4, 1], [], [5, 9, 2], [6], []]) print(rt.row_splits) # indices of row splits in rt.values tf.Tensor([0 4 4 7 8 8], shape=(6,), dtype=int64) shape The statically known shape of this ragged tensor. tf.ragged.constant([[0], [1, 2]]).shape TensorShape([2, None]) tf.ragged.constant([[[0, 1]], [[1, 2], [3, 4]]], ragged_rank=1).shape TensorShape([2, None, 2]) uniform_row_length The length of each row in this ragged tensor, or None if rows are ragged. rt1 = tf.ragged.constant([[1, 2, 3], [4], [5, 6], [7, 8, 9, 10]]) print(rt1.uniform_row_length) # rows are ragged. None rt2 = tf.RaggedTensor.from_uniform_row_length( values=rt1, uniform_row_length=2) print(rt2) <tf.RaggedTensor [[[1, 2, 3], [4]], [[5, 6], [7, 8, 9, 10]]]> print(rt2.uniform_row_length) # rows are not ragged (all have size 2). tf.Tensor(2, shape=(), dtype=int64) A RaggedTensor's rows are only considered to be uniform (i.e. non-ragged) if it can be determined statically (at graph construction time) that the rows all have the same length. values The concatenated rows for this ragged tensor. rt.values is a potentially ragged tensor formed by flattening the two outermost dimensions of rt into a single dimension. rt.values.shape = [nvals] + rt.shape[2:] (where nvals is the number of items in the outer two dimensions of rt). rt.ragged_rank = self.ragged_rank - 1 Example: rt = tf.ragged.constant([[3, 1, 4, 1], [], [5, 9, 2], [6], []]) print(rt.values) tf.Tensor([3 1 4 1 5 9 2 6], shape=(8,), dtype=int32) Methods bounding_shape View source bounding_shape( axis=None, name=None, out_type=None ) Returns the tight bounding box shape for this RaggedTensor. Args axis An integer scalar or vector indicating which axes to return the bounding box for. If not specified, then the full bounding box is returned. name A name prefix for the returned tensor (optional). out_type dtype for the returned tensor. Defaults to self.row_splits.dtype. Returns An integer Tensor (dtype=self.row_splits.dtype). If axis is not specified, then output is a vector with output.shape=[self.shape.ndims]. If axis is a scalar, then the output is a scalar. If axis is a vector, then output is a vector, where output[i] is the bounding size for dimension axis[i]. Example: rt = tf.ragged.constant([[1, 2, 3, 4], [5], [], [6, 7, 8, 9], [10]]) rt.bounding_shape().numpy() array([5, 4]) consumers View source consumers() from_nested_row_lengths View source @classmethod from_nested_row_lengths( flat_values, nested_row_lengths, name=None, validate=True ) Creates a RaggedTensor from a nested list of row_lengths tensors. Equivalent to: result = flat_values for row_lengths in reversed(nested_row_lengths): result = from_row_lengths(result, row_lengths) Args flat_values A potentially ragged tensor. nested_row_lengths A list of 1-D integer tensors. The ith tensor is used as the row_lengths for the ith ragged dimension. name A name prefix for the RaggedTensor (optional). validate If true, then use assertions to check that the arguments form a valid RaggedTensor. Note: these assertions incur a runtime cost, since they must be checked for each tensor value. Returns A RaggedTensor (or flat_values if nested_row_lengths is empty). from_nested_row_splits View source @classmethod from_nested_row_splits( flat_values, nested_row_splits, name=None, validate=True ) Creates a RaggedTensor from a nested list of row_splits tensors. Equivalent to: result = flat_values for row_splits in reversed(nested_row_splits): result = from_row_splits(result, row_splits) Args flat_values A potentially ragged tensor. nested_row_splits A list of 1-D integer tensors. The ith tensor is used as the row_splits for the ith ragged dimension. name A name prefix for the RaggedTensor (optional). validate If true, then use assertions to check that the arguments form a valid RaggedTensor. Note: these assertions incur a runtime cost, since they must be checked for each tensor value. Returns A RaggedTensor (or flat_values if nested_row_splits is empty). from_nested_value_rowids View source @classmethod from_nested_value_rowids( flat_values, nested_value_rowids, nested_nrows=None, name=None, validate=True ) Creates a RaggedTensor from a nested list of value_rowids tensors. Equivalent to: result = flat_values for (rowids, nrows) in reversed(zip(nested_value_rowids, nested_nrows)): result = from_value_rowids(result, rowids, nrows) Args flat_values A potentially ragged tensor. nested_value_rowids A list of 1-D integer tensors. The ith tensor is used as the value_rowids for the ith ragged dimension. nested_nrows A list of integer scalars. The ith scalar is used as the nrows for the ith ragged dimension. name A name prefix for the RaggedTensor (optional). validate If true, then use assertions to check that the arguments form a valid RaggedTensor. Note: these assertions incur a runtime cost, since they must be checked for each tensor value. Returns A RaggedTensor (or flat_values if nested_value_rowids is empty). Raises ValueError If len(nested_values_rowids) != len(nested_nrows). from_row_lengths View source @classmethod from_row_lengths( values, row_lengths, name=None, validate=True ) Creates a RaggedTensor with rows partitioned by row_lengths. The returned RaggedTensor corresponds with the python list defined by: result = [[values.pop(0) for i in range(length)] for length in row_lengths] Args values A potentially ragged tensor with shape [nvals, ...]. row_lengths A 1-D integer tensor with shape [nrows]. Must be nonnegative. sum(row_lengths) must be nvals. name A name prefix for the RaggedTensor (optional). validate If true, then use assertions to check that the arguments form a valid RaggedTensor. Note: these assertions incur a runtime cost, since they must be checked for each tensor value. Returns A RaggedTensor. result.rank = values.rank + 1. result.ragged_rank = values.ragged_rank + 1. Example: print(tf.RaggedTensor.from_row_lengths( values=[3, 1, 4, 1, 5, 9, 2, 6], row_lengths=[4, 0, 3, 1, 0])) <tf.RaggedTensor [[3, 1, 4, 1], [], [5, 9, 2], [6], []]> from_row_limits View source @classmethod from_row_limits( values, row_limits, name=None, validate=True ) Creates a RaggedTensor with rows partitioned by row_limits. Equivalent to: from_row_splits(values, concat([0, row_limits])). Args values A potentially ragged tensor with shape [nvals, ...]. row_limits A 1-D integer tensor with shape [nrows]. Must be sorted in ascending order. If nrows>0, then row_limits[-1] must be nvals. name A name prefix for the RaggedTensor (optional). validate If true, then use assertions to check that the arguments form a valid RaggedTensor. Note: these assertions incur a runtime cost, since they must be checked for each tensor value. Returns A RaggedTensor. result.rank = values.rank + 1. result.ragged_rank = values.ragged_rank + 1. Example: print(tf.RaggedTensor.from_row_limits( values=[3, 1, 4, 1, 5, 9, 2, 6], row_limits=[4, 4, 7, 8, 8])) <tf.RaggedTensor [[3, 1, 4, 1], [], [5, 9, 2], [6], []]> from_row_splits View source @classmethod from_row_splits( values, row_splits, name=None, validate=True ) Creates a RaggedTensor with rows partitioned by row_splits. The returned RaggedTensor corresponds with the python list defined by: result = [values[row_splits[i]:row_splits[i + 1]] for i in range(len(row_splits) - 1)] Args values A potentially ragged tensor with shape [nvals, ...]. row_splits A 1-D integer tensor with shape [nrows+1]. Must not be empty, and must be sorted in ascending order. row_splits[0] must be zero and row_splits[-1] must be nvals. name A name prefix for the RaggedTensor (optional). validate If true, then use assertions to check that the arguments form a valid RaggedTensor. Note: these assertions incur a runtime cost, since they must be checked for each tensor value. Returns A RaggedTensor. result.rank = values.rank + 1. result.ragged_rank = values.ragged_rank + 1. Raises ValueError If row_splits is an empty list. Example: print(tf.RaggedTensor.from_row_splits( values=[3, 1, 4, 1, 5, 9, 2, 6], row_splits=[0, 4, 4, 7, 8, 8])) <tf.RaggedTensor [[3, 1, 4, 1], [], [5, 9, 2], [6], []]> from_row_starts View source @classmethod from_row_starts( values, row_starts, name=None, validate=True ) Creates a RaggedTensor with rows partitioned by row_starts. Equivalent to: from_row_splits(values, concat([row_starts, nvals])). Args values A potentially ragged tensor with shape [nvals, ...]. row_starts A 1-D integer tensor with shape [nrows]. Must be nonnegative and sorted in ascending order. If nrows>0, then row_starts[0] must be zero. name A name prefix for the RaggedTensor (optional). validate If true, then use assertions to check that the arguments form a valid RaggedTensor. Note: these assertions incur a runtime cost, since they must be checked for each tensor value. Returns A RaggedTensor. result.rank = values.rank + 1. result.ragged_rank = values.ragged_rank + 1. Example: print(tf.RaggedTensor.from_row_starts( values=[3, 1, 4, 1, 5, 9, 2, 6], row_starts=[0, 4, 4, 7, 8])) <tf.RaggedTensor [[3, 1, 4, 1], [], [5, 9, 2], [6], []]> from_sparse View source @classmethod from_sparse( st_input, name=None, row_splits_dtype=tf.dtypes.int64 ) Converts a 2D tf.sparse.SparseTensor to a RaggedTensor. Each row of the output RaggedTensor will contain the explicit values from the same row in st_input. st_input must be ragged-right. If not it is not ragged-right, then an error will be generated. Example: indices = [[0, 0], [0, 1], [0, 2], [1, 0], [3, 0]] st = tf.sparse.SparseTensor(indices=indices, values=[1, 2, 3, 4, 5], dense_shape=[4, 3]) tf.RaggedTensor.from_sparse(st).to_list() [[1, 2, 3], [4], [], [5]] Currently, only two-dimensional SparseTensors are supported. Args st_input The sparse tensor to convert. Must have rank 2. name A name prefix for the returned tensors (optional). row_splits_dtype dtype for the returned RaggedTensor's row_splits tensor. One of tf.int32 or tf.int64. Returns A RaggedTensor with the same values as st_input. output.ragged_rank = rank(st_input) - 1. output.shape = [st_input.dense_shape[0], None]. Raises ValueError If the number of dimensions in st_input is not known statically, or is not two. from_tensor View source @classmethod from_tensor( tensor, lengths=None, padding=None, ragged_rank=1, name=None, row_splits_dtype=tf.dtypes.int64 ) Converts a tf.Tensor into a RaggedTensor. The set of absent/default values may be specified using a vector of lengths or a padding value (but not both). If lengths is specified, then the output tensor will satisfy output[row] = tensor[row][:lengths[row]]. If 'lengths' is a list of lists or tuple of lists, those lists will be used as nested row lengths. If padding is specified, then any row suffix consisting entirely of padding will be excluded from the returned RaggedTensor. If neither lengths nor padding is specified, then the returned RaggedTensor will have no absent/default values. Examples: dt = tf.constant([[5, 7, 0], [0, 3, 0], [6, 0, 0]]) tf.RaggedTensor.from_tensor(dt) <tf.RaggedTensor [[5, 7, 0], [0, 3, 0], [6, 0, 0]]> tf.RaggedTensor.from_tensor(dt, lengths=[1, 0, 3]) <tf.RaggedTensor [[5], [], [6, 0, 0]]> tf.RaggedTensor.from_tensor(dt, padding=0) <tf.RaggedTensor [[5, 7], [0, 3], [6]]> dt = tf.constant([[[5, 0], [7, 0], [0, 0]], [[0, 0], [3, 0], [0, 0]], [[6, 0], [0, 0], [0, 0]]]) tf.RaggedTensor.from_tensor(dt, lengths=([2, 0, 3], [1, 1, 2, 0, 1])) <tf.RaggedTensor [[[5], [7]], [], [[6, 0], [], [0]]]> Args tensor The Tensor to convert. Must have rank ragged_rank + 1 or higher. lengths An optional set of row lengths, specified using a 1-D integer Tensor whose length is equal to tensor.shape[0] (the number of rows in tensor). If specified, then output[row] will contain tensor[row][:lengths[row]]. Negative lengths are treated as zero. You may optionally pass a list or tuple of lengths to this argument, which will be used as nested row lengths to construct a ragged tensor with multiple ragged dimensions. padding An optional padding value. If specified, then any row suffix consisting entirely of padding will be excluded from the returned RaggedTensor. padding is a Tensor with the same dtype as tensor and with shape=tensor.shape[ragged_rank + 1:]. ragged_rank Integer specifying the ragged rank for the returned RaggedTensor. Must be greater than zero. name A name prefix for the returned tensors (optional). row_splits_dtype dtype for the returned RaggedTensor's row_splits tensor. One of tf.int32 or tf.int64. Returns A RaggedTensor with the specified ragged_rank. The shape of the returned ragged tensor is compatible with the shape of tensor. Raises ValueError If both lengths and padding are specified. from_uniform_row_length View source @classmethod from_uniform_row_length( values, uniform_row_length, nrows=None, validate=True, name=None ) Creates a RaggedTensor with rows partitioned by uniform_row_length. This method can be used to create RaggedTensors with multiple uniform outer dimensions. For example, a RaggedTensor with shape [2, 2, None] can be constructed with this method from a RaggedTensor values with shape [4, None]: values = tf.ragged.constant([[1, 2, 3], [4], [5, 6], [7, 8, 9, 10]]) print(values.shape) (4, None) rt1 = tf.RaggedTensor.from_uniform_row_length(values, 2) print(rt1) <tf.RaggedTensor [[[1, 2, 3], [4]], [[5, 6], [7, 8, 9, 10]]]> print(rt1.shape) (2, 2, None) Note that rt1 only contains one ragged dimension (the innermost dimension). In contrast, if from_row_splits is used to construct a similar RaggedTensor, then that RaggedTensor will have two ragged dimensions: rt2 = tf.RaggedTensor.from_row_splits(values, [0, 2, 4]) print(rt2.shape) (2, None, None) Args values A potentially ragged tensor with shape [nvals, ...]. uniform_row_length A scalar integer tensor. Must be nonnegative. The size of the outer axis of values must be evenly divisible by uniform_row_length. nrows The number of rows in the constructed RaggedTensor. If not specified, then it defaults to nvals/uniform_row_length (or 0 if uniform_row_length==0). nrows only needs to be specified if uniform_row_length might be zero. uniform_row_length*nrows must be nvals. validate If true, then use assertions to check that the arguments form a valid RaggedTensor. Note: these assertions incur a runtime cost, since they must be checked for each tensor value. name A name prefix for the RaggedTensor (optional). Returns A RaggedTensor that corresponds with the python list defined by: result = [[values.pop(0) for i in range(uniform_row_length)] for _ in range(nrows)] result.rank = values.rank + 1. result.ragged_rank = values.ragged_rank + 1. from_value_rowids View source @classmethod from_value_rowids( values, value_rowids, nrows=None, name=None, validate=True ) Creates a RaggedTensor with rows partitioned by value_rowids. The returned RaggedTensor corresponds with the python list defined by: result = [[values[i] for i in range(len(values)) if value_rowids[i] == row] for row in range(nrows)] Args values A potentially ragged tensor with shape [nvals, ...]. value_rowids A 1-D integer tensor with shape [nvals], which corresponds one-to-one with values, and specifies each value's row index. Must be nonnegative, and must be sorted in ascending order. nrows An integer scalar specifying the number of rows. This should be specified if the RaggedTensor may containing empty training rows. Must be greater than value_rowids[-1] (or zero if value_rowids is empty). Defaults to value_rowids[-1] (or zero if value_rowids is empty). name A name prefix for the RaggedTensor (optional). validate If true, then use assertions to check that the arguments form a valid RaggedTensor. Note: these assertions incur a runtime cost, since they must be checked for each tensor value. Returns A RaggedTensor. result.rank = values.rank + 1. result.ragged_rank = values.ragged_rank + 1. Raises ValueError If nrows is incompatible with value_rowids. Example: print(tf.RaggedTensor.from_value_rowids( values=[3, 1, 4, 1, 5, 9, 2, 6], value_rowids=[0, 0, 0, 0, 2, 2, 2, 3], nrows=5)) <tf.RaggedTensor [[3, 1, 4, 1], [], [5, 9, 2], [6], []]> get_shape View source get_shape() The statically known shape of this ragged tensor. Returns A TensorShape containing the statically known shape of this ragged tensor. Ragged dimensions have a size of None. Alias for shape property. Examples: tf.ragged.constant([[0], [1, 2]]).get_shape() TensorShape([2, None]) tf.ragged.constant( [[[0, 1]], [[1, 2], [3, 4]]], ragged_rank=1).get_shape() TensorShape([2, None, 2]) merge_dims View source merge_dims( outer_axis, inner_axis ) Merges outer_axis...inner_axis into a single dimension. Returns a copy of this RaggedTensor with the specified range of dimensions flattened into a single dimension, with elements in row-major order. Examples: rt = tf.ragged.constant([[[1, 2], [3]], [[4, 5, 6]]]) print(rt.merge_dims(0, 1)) <tf.RaggedTensor [[1, 2], [3], [4, 5, 6]]> print(rt.merge_dims(1, 2)) <tf.RaggedTensor [[1, 2, 3], [4, 5, 6]]> print(rt.merge_dims(0, 2)) tf.Tensor([1 2 3 4 5 6], shape=(6,), dtype=int32) To mimic the behavior of np.flatten (which flattens all dimensions), use rt.merge_dims(0, -1). To mimic the behavior oftf.layers.Flatten(which flattens all dimensions except the outermost batch dimension), usert.merge_dims(1, -1)`. Args outer_axis int: The first dimension in the range of dimensions to merge. May be negative if self.shape.rank is statically known. inner_axis int: The last dimension in the range of dimensions to merge. May be negative if self.shape.rank is statically known. Returns A copy of this tensor, with the specified dimensions merged into a single dimension. The shape of the returned tensor will be self.shape[:outer_axis] + [N] + self.shape[inner_axis + 1:], where N is the total number of slices in the merged dimensions. nested_row_lengths View source nested_row_lengths( name=None ) Returns a tuple containing the row_lengths for all ragged dimensions. rt.nested_row_lengths() is a tuple containing the row_lengths tensors for all ragged dimensions in rt, ordered from outermost to innermost. Args name A name prefix for the returned tensors (optional). Returns A tuple of 1-D integer Tensors. The length of the tuple is equal to self.ragged_rank. nested_value_rowids View source nested_value_rowids( name=None ) Returns a tuple containing the value_rowids for all ragged dimensions. rt.nested_value_rowids is a tuple containing the value_rowids tensors for all ragged dimensions in rt, ordered from outermost to innermost. In particular, rt.nested_value_rowids = (rt.value_rowids(),) + value_ids where: * `value_ids = ()` if `rt.values` is a `Tensor`. * `value_ids = rt.values.nested_value_rowids` otherwise. Args name A name prefix for the returned tensors (optional). Returns A tuple of 1-D integer Tensors. Example: rt = tf.ragged.constant( [[[[3, 1, 4, 1], [], [5, 9, 2]], [], [[6], []]]]) for i, ids in enumerate(rt.nested_value_rowids()): print('row ids for dimension %d: %s' % (i+1, ids.numpy())) row ids for dimension 1: [0 0 0] row ids for dimension 2: [0 0 0 2 2] row ids for dimension 3: [0 0 0 0 2 2 2 3] nrows View source nrows( out_type=None, name=None ) Returns the number of rows in this ragged tensor. I.e., the size of the outermost dimension of the tensor. Args out_type dtype for the returned tensor. Defaults to self.row_splits.dtype. name A name prefix for the returned tensor (optional). Returns A scalar Tensor with dtype out_type. Example: rt = tf.ragged.constant([[3, 1, 4, 1], [], [5, 9, 2], [6], []]) print(rt.nrows()) # rt has 5 rows. tf.Tensor(5, shape=(), dtype=int64) numpy View source numpy() Returns a numpy array with the values for this RaggedTensor. Requires that this RaggedTensor was constructed in eager execution mode. Ragged dimensions are encoded using numpy arrays with dtype=object and rank=1, where each element is a single row. Examples In the following example, the value returned by RaggedTensor.numpy() contains three numpy array objects: one for each row (with rank=1 and dtype=int64), and one to combine them (with rank=1 and dtype=object): tf.ragged.constant([[1, 2, 3], [4, 5]], dtype=tf.int64).numpy() array([array([1, 2, 3]), array([4, 5])], dtype=object) Uniform dimensions are encoded using multidimensional numpy arrays. In the following example, the value returned by RaggedTensor.numpy() contains a single numpy array object, with rank=2 and dtype=int64: tf.ragged.constant([[1, 2, 3], [4, 5, 6]], dtype=tf.int64).numpy() array([[1, 2, 3], [4, 5, 6]]) Returns A numpy array. row_lengths View source row_lengths( axis=1, name=None ) Returns the lengths of the rows in this ragged tensor. rt.row_lengths()[i] indicates the number of values in the ith row of rt. Args axis An integer constant indicating the axis whose row lengths should be returned. name A name prefix for the returned tensor (optional). Returns A potentially ragged integer Tensor with shape self.shape[:axis]. Raises ValueError If axis is out of bounds. Example: rt = tf.ragged.constant( [[[3, 1, 4], [1]], [], [[5, 9], [2]], [[6]], []]) print(rt.row_lengths()) # lengths of rows in rt tf.Tensor([2 0 2 1 0], shape=(5,), dtype=int64) print(rt.row_lengths(axis=2)) # lengths of axis=2 rows. <tf.RaggedTensor [[3, 1], [], [2, 1], [1], []]> row_limits View source row_limits( name=None ) Returns the limit indices for rows in this ragged tensor. These indices specify where the values for each row end in self.values. rt.row_limits(self) is equal to rt.row_splits[:-1]. Args name A name prefix for the returned tensor (optional). Returns A 1-D integer Tensor with shape [nrows]. The returned tensor is nonnegative, and is sorted in ascending order. Example: rt = tf.ragged.constant([[3, 1, 4, 1], [], [5, 9, 2], [6], []]) print(rt.values) tf.Tensor([3 1 4 1 5 9 2 6], shape=(8,), dtype=int32) print(rt.row_limits()) # indices of row limits in rt.values tf.Tensor([4 4 7 8 8], shape=(5,), dtype=int64) row_starts View source row_starts( name=None ) Returns the start indices for rows in this ragged tensor. These indices specify where the values for each row begin in self.values. rt.row_starts() is equal to rt.row_splits[:-1]. Args name A name prefix for the returned tensor (optional). Returns A 1-D integer Tensor with shape [nrows]. The returned tensor is nonnegative, and is sorted in ascending order. Example: rt = tf.ragged.constant([[3, 1, 4, 1], [], [5, 9, 2], [6], []]) print(rt.values) tf.Tensor([3 1 4 1 5 9 2 6], shape=(8,), dtype=int32) print(rt.row_starts()) # indices of row starts in rt.values tf.Tensor([0 4 4 7 8], shape=(5,), dtype=int64) to_list View source to_list() Returns a nested Python list with the values for this RaggedTensor. Requires that rt was constructed in eager execution mode. Returns A nested Python list. to_sparse View source to_sparse( name=None ) Converts this RaggedTensor into a tf.sparse.SparseTensor. Example: rt = tf.ragged.constant([[1, 2, 3], [4], [], [5, 6]]) print(rt.to_sparse()) SparseTensor(indices=tf.Tensor( [[0 0] [0 1] [0 2] [1 0] [3 0] [3 1]], shape=(6, 2), dtype=int64), values=tf.Tensor([1 2 3 4 5 6], shape=(6,), dtype=int32), dense_shape=tf.Tensor([4 3], shape=(2,), dtype=int64)) Args name A name prefix for the returned tensors (optional). Returns A SparseTensor with the same values as self. to_tensor View source to_tensor( default_value=None, name=None, shape=None ) Converts this RaggedTensor into a tf.Tensor. If shape is specified, then the result is padded and/or truncated to the specified shape. Examples: rt = tf.ragged.constant([[9, 8, 7], [], [6, 5], [4]]) print(rt.to_tensor()) tf.Tensor( [[9 8 7] [0 0 0] [6 5 0] [4 0 0]], shape=(4, 3), dtype=int32) print(rt.to_tensor(shape=[5, 2])) tf.Tensor( [[9 8] [0 0] [6 5] [4 0] [0 0]], shape=(5, 2), dtype=int32) Args default_value Value to set for indices not specified in self. Defaults to zero. default_value must be broadcastable to self.shape[self.ragged_rank + 1:]. name A name prefix for the returned tensors (optional). shape The shape of the resulting dense tensor. In particular, result.shape[i] is shape[i] (if shape[i] is not None), or self.bounding_shape(i) (otherwise).shape.rank must be None or equal to self.rank. Returns A Tensor with shape ragged.bounding_shape(self) and the values specified by the non-empty values in self. Empty values are assigned default_value. value_rowids View source value_rowids( name=None ) Returns the row indices for the values in this ragged tensor. rt.value_rowids() corresponds one-to-one with the outermost dimension of rt.values, and specifies the row containing each value. In particular, the row rt[row] consists of the values rt.values[j] where rt.value_rowids()[j] == row. Args name A name prefix for the returned tensor (optional). Returns A 1-D integer Tensor with shape self.values.shape[:1]. The returned tensor is nonnegative, and is sorted in ascending order. Example: rt = tf.ragged.constant([[3, 1, 4, 1], [], [5, 9, 2], [6], []]) print(rt.values) tf.Tensor([3 1 4 1 5 9 2 6], shape=(8,), dtype=int32) print(rt.value_rowids()) # corresponds 1:1 with rt.values tf.Tensor([0 0 0 0 2 2 2 3], shape=(8,), dtype=int64) with_flat_values View source with_flat_values( new_values ) Returns a copy of self with flat_values replaced by new_value. Preserves cached row-partitioning tensors such as self.cached_nrows and self.cached_value_rowids if they have values. Args new_values Potentially ragged tensor that should replace self.flat_values. Must have rank > 0, and must have the same number of rows as self.flat_values. Returns A RaggedTensor. result.rank = self.ragged_rank + new_values.rank. result.ragged_rank = self.ragged_rank + new_values.ragged_rank. with_row_splits_dtype View source with_row_splits_dtype( dtype ) Returns a copy of this RaggedTensor with the given row_splits dtype. For RaggedTensors with multiple ragged dimensions, the row_splits for all nested RaggedTensor objects are cast to the given dtype. Args dtype The dtype for row_splits. One of tf.int32 or tf.int64. Returns A copy of this RaggedTensor, with the row_splits cast to the given type. with_values View source with_values( new_values ) Returns a copy of self with values replaced by new_value. Preserves cached row-partitioning tensors such as self.cached_nrows and self.cached_value_rowids if they have values. Args new_values Potentially ragged tensor to use as the values for the returned RaggedTensor. Must have rank > 0, and must have the same number of rows as self.values. Returns A RaggedTensor. result.rank = 1 + new_values.rank. result.ragged_rank = 1 + new_values.ragged_rank __abs__ View source __abs__( x, name=None ) Computes the absolute value of a tensor. Given a tensor of integer or floating-point values, this operation returns a tensor of the same type, where each element contains the absolute value of the corresponding element in the input. Given a tensor x of complex numbers, this operation returns a tensor of type float32 or float64 that is the absolute value of each element in x. For a complex number \(a + bj\), its absolute value is computed as \(\sqrt{a^2 + b^2}\). For example: # real number x = tf.constant([-2.25, 3.25]) tf.abs(x) <tf.Tensor: shape=(2,), dtype=float32, numpy=array([2.25, 3.25], dtype=float32)> # complex number x = tf.constant([[-2.25 + 4.75j], [-3.25 + 5.75j]]) tf.abs(x) <tf.Tensor: shape=(2, 1), dtype=float64, numpy= array([[5.25594901], [6.60492241]])> Args x A Tensor or SparseTensor of type float16, float32, float64, int32, int64, complex64 or complex128. name A name for the operation (optional). Returns A Tensor or SparseTensor of the same size, type and sparsity as x, with absolute values. Note, for complex64 or complex128 input, the returned Tensor will be of type float32 or float64, respectively. If x is a SparseTensor, returns SparseTensor(x.indices, tf.math.abs(x.values, ...), x.dense_shape) __add__ __add__( x, y, name=None ) Returns x + y element-wise. Note: math.add supports broadcasting. AddN does not. More about broadcasting here Given two input tensors, the tf.add operation computes the sum for every element in the tensor. Both input and output have a range (-inf, inf). Args x A Tensor. Must be one of the following types: bfloat16, half, float32, float64, uint8, int8, int16, int32, int64, complex64, complex128, string. y A Tensor. Must have the same type as x. name A name for the operation (optional). Returns A Tensor. Has the same type as x. __and__ View source __and__( x, y, name=None ) Logical AND function. The operation works for the following input types: Two single elements of type bool One tf.Tensor of type bool and one single bool, where the result will be calculated by applying logical AND with the single element to each element in the larger Tensor. Two tf.Tensor objects of type bool of the same shape. In this case, the result will be the element-wise logical AND of the two input tensors. Usage: a = tf.constant([True]) b = tf.constant([False]) tf.math.logical_and(a, b) <tf.Tensor: shape=(1,), dtype=bool, numpy=array([False])> c = tf.constant([True]) x = tf.constant([False, True, True, False]) tf.math.logical_and(c, x) <tf.Tensor: shape=(4,), dtype=bool, numpy=array([False, True, True, False])> y = tf.constant([False, False, True, True]) z = tf.constant([False, True, False, True]) tf.math.logical_and(y, z) <tf.Tensor: shape=(4,), dtype=bool, numpy=array([False, False, False, True])> Args x A tf.Tensor type bool. y A tf.Tensor of type bool. name A name for the operation (optional). Returns A tf.Tensor of type bool with the same size as that of x or y. __bool__ View source __bool__( _ ) Dummy method to prevent a RaggedTensor from being used as a Python bool. __div__ View source __div__( x, y, name=None ) Divides x / y elementwise (using Python 2 division operator semantics). (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Deprecated in favor of operator or tf.math.divide. Note: Prefer using the Tensor division operator or tf.divide which obey Python 3 division operator semantics. This function divides x and y, forcing Python 2 semantics. That is, if x and y are both integers then the result will be an integer. This is in contrast to Python 3, where division with / is always a float while division with // is always an integer. Args x Tensor numerator of real numeric type. y Tensor denominator of real numeric type. name A name for the operation (optional). Returns x / y returns the quotient of x and y. __eq__ View source __eq__( other ) The operation invoked by the Tensor.eq operator. Compares two tensors element-wise for equality if they are broadcast-compatible; or returns False if they are not broadcast-compatible. (Note that this behavior differs from tf.math.equal, which raises an exception if the two tensors are not broadcast-compatible.) Purpose in the API: This method is exposed in TensorFlow's API so that library developers can register dispatching for Tensor.eq to allow it to handle custom composite tensors & other custom objects. The API symbol is not intended to be called by users directly and does appear in TensorFlow's generated documentation. Args self The left-hand side of the == operator. other The right-hand side of the == operator. Returns The result of the elementwise == operation, or False if the arguments are not broadcast-compatible. __floordiv__ View source __floordiv__( x, y, name=None ) Divides x / y elementwise, rounding toward the most negative integer. The same as tf.compat.v1.div(x,y) for integers, but uses tf.floor(tf.compat.v1.div(x,y)) for floating point arguments so that the result is always an integer (though possibly an integer represented as floating point). This op is generated by x // y floor division in Python 3 and in Python 2.7 with from __future__ import division. x and y must have the same type, and the result will have the same type as well. Args x Tensor numerator of real numeric type. y Tensor denominator of real numeric type. name A name for the operation (optional). Returns x / y rounded down. Raises TypeError If the inputs are complex. __ge__ __ge__( x, y, name=None ) Returns the truth value of (x >= y) element-wise. Note: math.greater_equal supports broadcasting. More about broadcasting here Example: x = tf.constant([5, 4, 6, 7]) y = tf.constant([5, 2, 5, 10]) tf.math.greater_equal(x, y) ==> [True, True, True, False] x = tf.constant([5, 4, 6, 7]) y = tf.constant([5]) tf.math.greater_equal(x, y) ==> [True, False, True, True] Args x A Tensor. Must be one of the following types: float32, float64, int32, uint8, int16, int8, int64, bfloat16, uint16, half, uint32, uint64. y A Tensor. Must have the same type as x. name A name for the operation (optional). Returns A Tensor of type bool. __getitem__ View source __getitem__( key ) Returns the specified piece of this RaggedTensor. Supports multidimensional indexing and slicing, with one restriction: indexing into a ragged inner dimension is not allowed. This case is problematic because the indicated value may exist in some rows but not others. In such cases, it's not obvious whether we should (1) report an IndexError; (2) use a default value; or (3) skip that value and return a tensor with fewer rows than we started with. Following the guiding principles of Python ("In the face of ambiguity, refuse the temptation to guess"), we simply disallow this operation. Args self The RaggedTensor to slice. key Indicates which piece of the RaggedTensor to return, using standard Python semantics (e.g., negative values index from the end). key may have any of the following types: int constant Scalar integer Tensor slice containing integer constants and/or scalar integer Tensors Ellipsis tf.newaxis tuple containing any of the above (for multidimensional indexing) Returns A Tensor or RaggedTensor object. Values that include at least one ragged dimension are returned as RaggedTensor. Values that include no ragged dimensions are returned as Tensor. See above for examples of expressions that return Tensors vs RaggedTensors. Raises ValueError If key is out of bounds. ValueError If key is not supported. TypeError If the indices in key have an unsupported type. Examples: # A 2-D ragged tensor with 1 ragged dimension. rt = tf.ragged.constant([['a', 'b', 'c'], ['d', 'e'], ['f'], ['g']]) rt[0].numpy() # First row (1-D `Tensor`) array([b'a', b'b', b'c'], dtype=object) rt[:3].to_list() # First three rows (2-D RaggedTensor) [[b'a', b'b', b'c'], [b'd', b'e'], [b'f']] rt[3, 0].numpy() # 1st element of 4th row (scalar) b'g' # A 3-D ragged tensor with 2 ragged dimensions. rt = tf.ragged.constant([[[1, 2, 3], [4]], [[5], [], [6]], [[7]], [[8, 9], [10]]]) rt[1].to_list() # Second row (2-D RaggedTensor) [[5], [], [6]] rt[3, 0].numpy() # First element of fourth row (1-D Tensor) array([8, 9], dtype=int32) rt[:, 1:3].to_list() # Items 1-3 of each row (3-D RaggedTensor) [[[4]], [[], [6]], [], [[10]]] rt[:, -1:].to_list() # Last item of each row (3-D RaggedTensor) [[[4]], [[6]], [[7]], [[10]]] __gt__ __gt__( x, y, name=None ) Returns the truth value of (x > y) element-wise. Note: math.greater supports broadcasting. More about broadcasting here Example: x = tf.constant([5, 4, 6]) y = tf.constant([5, 2, 5]) tf.math.greater(x, y) ==> [False, True, True] x = tf.constant([5, 4, 6]) y = tf.constant([5]) tf.math.greater(x, y) ==> [False, False, True] Args x A Tensor. Must be one of the following types: float32, float64, int32, uint8, int16, int8, int64, bfloat16, uint16, half, uint32, uint64. y A Tensor. Must have the same type as x. name A name for the operation (optional). Returns A Tensor of type bool. __invert__ __invert__( x, name=None ) Returns the truth value of NOT x element-wise. Example: tf.math.logical_not(tf.constant([True, False])) <tf.Tensor: shape=(2,), dtype=bool, numpy=array([False, True])> Args x A Tensor of type bool. A Tensor of type bool. name A name for the operation (optional). Returns A Tensor of type bool. __le__ __le__( x, y, name=None ) Returns the truth value of (x <= y) element-wise. Note: math.less_equal supports broadcasting. More about broadcasting here Example: x = tf.constant([5, 4, 6]) y = tf.constant([5]) tf.math.less_equal(x, y) ==> [True, True, False] x = tf.constant([5, 4, 6]) y = tf.constant([5, 6, 6]) tf.math.less_equal(x, y) ==> [True, True, True] Args x A Tensor. Must be one of the following types: float32, float64, int32, uint8, int16, int8, int64, bfloat16, uint16, half, uint32, uint64. y A Tensor. Must have the same type as x. name A name for the operation (optional). Returns A Tensor of type bool. __lt__ __lt__( x, y, name=None ) Returns the truth value of (x < y) element-wise. Note: math.less supports broadcasting. More about broadcasting here Example: x = tf.constant([5, 4, 6]) y = tf.constant([5]) tf.math.less(x, y) ==> [False, True, False] x = tf.constant([5, 4, 6]) y = tf.constant([5, 6, 7]) tf.math.less(x, y) ==> [False, True, True] Args x A Tensor. Must be one of the following types: float32, float64, int32, uint8, int16, int8, int64, bfloat16, uint16, half, uint32, uint64. y A Tensor. Must have the same type as x. name A name for the operation (optional). Returns A Tensor of type bool. __mod__ __mod__( x, y, name=None ) Returns element-wise remainder of division. When x < 0 xor y < 0 is true, this follows Python semantics in that the result here is consistent with a flooring divide. E.g. floor(x / y) * y + mod(x, y) = x. Note: math.floormod supports broadcasting. More about broadcasting here Args x A Tensor. Must be one of the following types: int32, int64, uint64, bfloat16, half, float32, float64. y A Tensor. Must have the same type as x. name A name for the operation (optional). Returns A Tensor. Has the same type as x. __mul__ View source __mul__( x, y, name=None ) Returns an element-wise x * y. For example: x = tf.constant(([1, 2, 3, 4])) tf.math.multiply(x, x) <tf.Tensor: shape=(4,), dtype=..., numpy=array([ 1, 4, 9, 16], dtype=int32)> Since tf.math.multiply will convert its arguments to Tensors, you can also pass in non-Tensor arguments: tf.math.multiply(7,6) <tf.Tensor: shape=(), dtype=int32, numpy=42> If x.shape is not thes same as y.shape, they will be broadcast to a compatible shape. (More about broadcasting here.) For example: x = tf.ones([1, 2]); y = tf.ones([2, 1]); x * y # Taking advantage of operator overriding <tf.Tensor: shape=(2, 2), dtype=float32, numpy= array([[1., 1.], [1., 1.]], dtype=float32)> Args x A Tensor. Must be one of the following types: bfloat16, half, float32, float64, uint8, int8, uint16, int16, int32, int64, complex64, complex128. y A Tensor. Must have the same type as x. name A name for the operation (optional). Returns A Tensor. Has the same type as x. Raises InvalidArgumentError: When x and y have incomptatible shapes or types. __ne__ View source __ne__( other ) The operation invoked by the Tensor.ne operator. Compares two tensors element-wise for inequality if they are broadcast-compatible; or returns True if they are not broadcast-compatible. (Note that this behavior differs from tf.math.not_equal, which raises an exception if the two tensors are not broadcast-compatible.) Purpose in the API: This method is exposed in TensorFlow's API so that library developers can register dispatching for Tensor.ne to allow it to handle custom composite tensors & other custom objects. The API symbol is not intended to be called by users directly and does appear in TensorFlow's generated documentation. Args self The left-hand side of the != operator. other The right-hand side of the != operator. Returns The result of the elementwise != operation, or True if the arguments are not broadcast-compatible. __neg__ __neg__( x, name=None ) Computes numerical negative value element-wise. I.e., \(y = -x\). Args x A Tensor. Must be one of the following types: bfloat16, half, float32, float64, int8, int16, int32, int64, complex64, complex128. name A name for the operation (optional). Returns A Tensor. Has the same type as x. If x is a SparseTensor, returns SparseTensor(x.indices, tf.math.negative(x.values, ...), x.dense_shape) __nonzero__ View source __nonzero__( _ ) Dummy method to prevent a RaggedTensor from being used as a Python bool. __or__ __or__( x, y, name=None ) Returns the truth value of x OR y element-wise. Note: math.logical_or supports broadcasting. More about broadcasting here Args x A Tensor of type bool. y A Tensor of type bool. name A name for the operation (optional). Returns A Tensor of type bool. __pow__ View source __pow__( x, y, name=None ) Computes the power of one value to another. Given a tensor x and a tensor y, this operation computes \(x^y\) for corresponding elements in x and y. For example: x = tf.constant([[2, 2], [3, 3]]) y = tf.constant([[8, 16], [2, 3]]) tf.pow(x, y) # [[256, 65536], [9, 27]] Args x A Tensor of type float16, float32, float64, int32, int64, complex64, or complex128. y A Tensor of type float16, float32, float64, int32, int64, complex64, or complex128. name A name for the operation (optional). Returns A Tensor. __radd__ __radd__( x, y, name=None ) Returns x + y element-wise. Note: math.add supports broadcasting. AddN does not. More about broadcasting here Given two input tensors, the tf.add operation computes the sum for every element in the tensor. Both input and output have a range (-inf, inf). Args x A Tensor. Must be one of the following types: bfloat16, half, float32, float64, uint8, int8, int16, int32, int64, complex64, complex128, string. y A Tensor. Must have the same type as x. name A name for the operation (optional). Returns A Tensor. Has the same type as x. __rand__ View source __rand__( x, y, name=None ) Logical AND function. The operation works for the following input types: Two single elements of type bool One tf.Tensor of type bool and one single bool, where the result will be calculated by applying logical AND with the single element to each element in the larger Tensor. Two tf.Tensor objects of type bool of the same shape. In this case, the result will be the element-wise logical AND of the two input tensors. Usage: a = tf.constant([True]) b = tf.constant([False]) tf.math.logical_and(a, b) <tf.Tensor: shape=(1,), dtype=bool, numpy=array([False])> c = tf.constant([True]) x = tf.constant([False, True, True, False]) tf.math.logical_and(c, x) <tf.Tensor: shape=(4,), dtype=bool, numpy=array([False, True, True, False])> y = tf.constant([False, False, True, True]) z = tf.constant([False, True, False, True]) tf.math.logical_and(y, z) <tf.Tensor: shape=(4,), dtype=bool, numpy=array([False, False, False, True])> Args x A tf.Tensor type bool. y A tf.Tensor of type bool. name A name for the operation (optional). Returns A tf.Tensor of type bool with the same size as that of x or y. __rdiv__ View source __rdiv__( x, y, name=None ) Divides x / y elementwise (using Python 2 division operator semantics). (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Deprecated in favor of operator or tf.math.divide. Note: Prefer using the Tensor division operator or tf.divide which obey Python 3 division operator semantics. This function divides x and y, forcing Python 2 semantics. That is, if x and y are both integers then the result will be an integer. This is in contrast to Python 3, where division with / is always a float while division with // is always an integer. Args x Tensor numerator of real numeric type. y Tensor denominator of real numeric type. name A name for the operation (optional). Returns x / y returns the quotient of x and y. __rfloordiv__ View source __rfloordiv__( x, y, name=None ) Divides x / y elementwise, rounding toward the most negative integer. The same as tf.compat.v1.div(x,y) for integers, but uses tf.floor(tf.compat.v1.div(x,y)) for floating point arguments so that the result is always an integer (though possibly an integer represented as floating point). This op is generated by x // y floor division in Python 3 and in Python 2.7 with from __future__ import division. x and y must have the same type, and the result will have the same type as well. Args x Tensor numerator of real numeric type. y Tensor denominator of real numeric type. name A name for the operation (optional). Returns x / y rounded down. Raises TypeError If the inputs are complex. __rmod__ __rmod__( x, y, name=None ) Returns element-wise remainder of division. When x < 0 xor y < 0 is true, this follows Python semantics in that the result here is consistent with a flooring divide. E.g. floor(x / y) * y + mod(x, y) = x. Note: math.floormod supports broadcasting. More about broadcasting here Args x A Tensor. Must be one of the following types: int32, int64, uint64, bfloat16, half, float32, float64. y A Tensor. Must have the same type as x. name A name for the operation (optional). Returns A Tensor. Has the same type as x. __rmul__ View source __rmul__( x, y, name=None ) Returns an element-wise x * y. For example: x = tf.constant(([1, 2, 3, 4])) tf.math.multiply(x, x) <tf.Tensor: shape=(4,), dtype=..., numpy=array([ 1, 4, 9, 16], dtype=int32)> Since tf.math.multiply will convert its arguments to Tensors, you can also pass in non-Tensor arguments: tf.math.multiply(7,6) <tf.Tensor: shape=(), dtype=int32, numpy=42> If x.shape is not thes same as y.shape, they will be broadcast to a compatible shape. (More about broadcasting here.) For example: x = tf.ones([1, 2]); y = tf.ones([2, 1]); x * y # Taking advantage of operator overriding <tf.Tensor: shape=(2, 2), dtype=float32, numpy= array([[1., 1.], [1., 1.]], dtype=float32)> Args x A Tensor. Must be one of the following types: bfloat16, half, float32, float64, uint8, int8, uint16, int16, int32, int64, complex64, complex128. y A Tensor. Must have the same type as x. name A name for the operation (optional). Returns A Tensor. Has the same type as x. Raises InvalidArgumentError: When x and y have incomptatible shapes or types. __ror__ __ror__( x, y, name=None ) Returns the truth value of x OR y element-wise. Note: math.logical_or supports broadcasting. More about broadcasting here Args x A Tensor of type bool. y A Tensor of type bool. name A name for the operation (optional). Returns A Tensor of type bool. __rpow__ View source __rpow__( x, y, name=None ) Computes the power of one value to another. Given a tensor x and a tensor y, this operation computes \(x^y\) for corresponding elements in x and y. For example: x = tf.constant([[2, 2], [3, 3]]) y = tf.constant([[8, 16], [2, 3]]) tf.pow(x, y) # [[256, 65536], [9, 27]] Args x A Tensor of type float16, float32, float64, int32, int64, complex64, or complex128. y A Tensor of type float16, float32, float64, int32, int64, complex64, or complex128. name A name for the operation (optional). Returns A Tensor. __rsub__ View source __rsub__( x, y, name=None ) Returns x - y element-wise. Note: Subtract supports broadcasting. More about broadcasting here Args x A Tensor. Must be one of the following types: bfloat16, half, float32, float64, uint8, int8, uint16, int16, int32, int64, complex64, complex128, uint32. y A Tensor. Must have the same type as x. name A name for the operation (optional). Returns A Tensor. Has the same type as x. __rtruediv__ View source __rtruediv__( x, y, name=None ) Divides x / y elementwise (using Python 3 division operator semantics). Note: Prefer using the Tensor operator or tf.divide which obey Python division operator semantics. This function forces Python 3 division operator semantics where all integer arguments are cast to floating types first. This op is generated by normal x / y division in Python 3 and in Python 2.7 with from __future__ import division. If you want integer division that rounds down, use x // y or tf.math.floordiv. x and y must have the same numeric type. If the inputs are floating point, the output will have the same type. If the inputs are integral, the inputs are cast to float32 for int8 and int16 and float64 for int32 and int64 (matching the behavior of Numpy). Args x Tensor numerator of numeric type. y Tensor denominator of numeric type. name A name for the operation (optional). Returns x / y evaluated in floating point. Raises TypeError If x and y have different dtypes. __rxor__ View source __rxor__( x, y, name='LogicalXor' ) Logical XOR function. x ^ y = (x | y) & ~(x & y) The operation works for the following input types: Two single elements of type bool One tf.Tensor of type bool and one single bool, where the result will be calculated by applying logical XOR with the single element to each element in the larger Tensor. Two tf.Tensor objects of type bool of the same shape. In this case, the result will be the element-wise logical XOR of the two input tensors. Usage: a = tf.constant([True]) b = tf.constant([False]) tf.math.logical_xor(a, b) <tf.Tensor: shape=(1,), dtype=bool, numpy=array([ True])> c = tf.constant([True]) x = tf.constant([False, True, True, False]) tf.math.logical_xor(c, x) <tf.Tensor: shape=(4,), dtype=bool, numpy=array([ True, False, False, True])> y = tf.constant([False, False, True, True]) z = tf.constant([False, True, False, True]) tf.math.logical_xor(y, z) <tf.Tensor: shape=(4,), dtype=bool, numpy=array([False, True, True, False])> Args x A tf.Tensor type bool. y A tf.Tensor of type bool. name A name for the operation (optional). Returns A tf.Tensor of type bool with the same size as that of x or y. __sub__ View source __sub__( x, y, name=None ) Returns x - y element-wise. Note: Subtract supports broadcasting. More about broadcasting here Args x A Tensor. Must be one of the following types: bfloat16, half, float32, float64, uint8, int8, uint16, int16, int32, int64, complex64, complex128, uint32. y A Tensor. Must have the same type as x. name A name for the operation (optional). Returns A Tensor. Has the same type as x. __truediv__ View source __truediv__( x, y, name=None ) Divides x / y elementwise (using Python 3 division operator semantics). Note: Prefer using the Tensor operator or tf.divide which obey Python division operator semantics. This function forces Python 3 division operator semantics where all integer arguments are cast to floating types first. This op is generated by normal x / y division in Python 3 and in Python 2.7 with from __future__ import division. If you want integer division that rounds down, use x // y or tf.math.floordiv. x and y must have the same numeric type. If the inputs are floating point, the output will have the same type. If the inputs are integral, the inputs are cast to float32 for int8 and int16 and float64 for int32 and int64 (matching the behavior of Numpy). Args x Tensor numerator of numeric type. y Tensor denominator of numeric type. name A name for the operation (optional). Returns x / y evaluated in floating point. Raises TypeError If x and y have different dtypes. __xor__ View source __xor__( x, y, name='LogicalXor' ) Logical XOR function. x ^ y = (x | y) & ~(x & y) The operation works for the following input types: Two single elements of type bool One tf.Tensor of type bool and one single bool, where the result will be calculated by applying logical XOR with the single element to each element in the larger Tensor. Two tf.Tensor objects of type bool of the same shape. In this case, the result will be the element-wise logical XOR of the two input tensors. Usage: a = tf.constant([True]) b = tf.constant([False]) tf.math.logical_xor(a, b) <tf.Tensor: shape=(1,), dtype=bool, numpy=array([ True])> c = tf.constant([True]) x = tf.constant([False, True, True, False]) tf.math.logical_xor(c, x) <tf.Tensor: shape=(4,), dtype=bool, numpy=array([ True, False, False, True])> y = tf.constant([False, False, True, True]) z = tf.constant([False, True, False, True]) tf.math.logical_xor(y, z) <tf.Tensor: shape=(4,), dtype=bool, numpy=array([False, True, True, False])> Args x A tf.Tensor type bool. y A tf.Tensor of type bool. name A name for the operation (optional). Returns A tf.Tensor of type bool with the same size as that of x or y.
tensorflow.raggedtensor
tf.RaggedTensorSpec View source on GitHub Type specification for a tf.RaggedTensor. Inherits From: TypeSpec View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.RaggedTensorSpec tf.RaggedTensorSpec( shape=None, dtype=tf.dtypes.float32, ragged_rank=None, row_splits_dtype=tf.dtypes.int64, flat_values_spec=None ) Args shape The shape of the RaggedTensor, or None to allow any shape. If a shape is specified, then all ragged dimensions must have size None. dtype tf.DType of values in the RaggedTensor. ragged_rank Python integer, the number of times the RaggedTensor's flat_values is partitioned. Defaults to shape.ndims - 1. row_splits_dtype dtype for the RaggedTensor's row_splits tensor. One of tf.int32 or tf.int64. flat_values_spec TypeSpec for flat_value of the RaggedTensor. It shall be provided when the flat_values is a CompositeTensor rather then Tensor. If both dtype and flat_values_spec and are provided, dtype must be the same as flat_values_spec.dtype. (experimental) Attributes dtype The tf.dtypes.DType specified by this type for the RaggedTensor. rt = tf.ragged.constant([["a"], ["b", "c"]], dtype=tf.string) tf.type_spec_from_value(rt).dtype tf.string flat_values_spec The TypeSpec of the flat_values of RaggedTensor. ragged_rank The number of times the RaggedTensor's flat_values is partitioned. Defaults to shape.ndims - 1. values = tf.ragged.constant([[1, 2, 3], [4], [5, 6], [7, 8, 9, 10]]) tf.type_spec_from_value(values).ragged_rank 1 rt1 = tf.RaggedTensor.from_uniform_row_length(values, 2) tf.type_spec_from_value(rt1).ragged_rank 2 row_splits_dtype The tf.dtypes.DType of the RaggedTensor's row_splits. rt = tf.ragged.constant([[1, 2, 3], [4]], row_splits_dtype=tf.int64) tf.type_spec_from_value(rt).row_splits_dtype tf.int64 shape The statically known shape of the RaggedTensor. rt = tf.ragged.constant([[0], [1, 2]]) tf.type_spec_from_value(rt).shape TensorShape([2, None]) rt = tf.ragged.constant([[[0, 1]], [[1, 2], [3, 4]]], ragged_rank=1) tf.type_spec_from_value(rt).shape TensorShape([2, None, 2]) value_type The Python type for values that are compatible with this TypeSpec. In particular, all values that are compatible with this TypeSpec must be an instance of this 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.raggedtensorspec
Module: tf.random Public API for tf.random namespace. Modules experimental module: Public API for tf.random.experimental namespace. Classes class Algorithm: An enumeration. class Generator: Random-number generator. Functions all_candidate_sampler(...): Generate the set of all classes. categorical(...): Draws samples from a categorical distribution. create_rng_state(...): Creates a RNG state from an integer or a vector. fixed_unigram_candidate_sampler(...): Samples a set of classes using the provided (fixed) base distribution. gamma(...): Draws shape samples from each of the given Gamma distribution(s). get_global_generator(...): Retrieves the global generator. learned_unigram_candidate_sampler(...): Samples a set of classes from a distribution learned during training. log_uniform_candidate_sampler(...): Samples a set of classes using a log-uniform (Zipfian) base distribution. normal(...): Outputs random values from a normal distribution. poisson(...): Draws shape samples from each of the given Poisson distribution(s). set_global_generator(...): Replaces the global generator with another Generator object. set_seed(...): Sets the global random seed. shuffle(...): Randomly shuffles a tensor along its first dimension. stateless_binomial(...): Outputs deterministic pseudorandom values from a binomial distribution. stateless_categorical(...): Draws deterministic pseudorandom samples from a categorical distribution. stateless_gamma(...): Outputs deterministic pseudorandom values from a gamma distribution. stateless_normal(...): Outputs deterministic pseudorandom values from a normal distribution. stateless_parameterized_truncated_normal(...): Outputs random values from a truncated normal distribution. stateless_poisson(...): Outputs deterministic pseudorandom values from a Poisson distribution. stateless_truncated_normal(...): Outputs deterministic pseudorandom values, truncated normally distributed. stateless_uniform(...): Outputs deterministic pseudorandom values from a uniform distribution. truncated_normal(...): Outputs random values from a truncated normal distribution. uniform(...): Outputs random values from a uniform distribution. uniform_candidate_sampler(...): Samples a set of classes using a uniform base distribution.
tensorflow.random
tf.random.Algorithm An enumeration. View aliases Main aliases tf.random.experimental.Algorithm Compat aliases for migration See Migration guide for more details. tf.compat.v1.random.Algorithm, tf.compat.v1.random.experimental.Algorithm Class Variables PHILOX tf.random.Algorithm THREEFRY tf.random.Algorithm
tensorflow.random.algorithm
tf.random.all_candidate_sampler View source on GitHub Generate the set of all classes. View aliases Main aliases tf.nn.all_candidate_sampler Compat aliases for migration See Migration guide for more details. tf.compat.v1.nn.all_candidate_sampler, tf.compat.v1.random.all_candidate_sampler tf.random.all_candidate_sampler( true_classes, num_true, num_sampled, unique, seed=None, name=None ) Deterministically generates and returns the set of all possible classes. For testing purposes. There is no need to use this, since you might as well use full softmax or full logistic regression. Args true_classes A Tensor of type int64 and shape [batch_size, num_true]. The target classes. num_true An int. The number of target classes per training example. num_sampled An int. The number of possible classes. unique A bool. Ignored. unique. seed An int. An operation-specific seed. Default is 0. name A name for the operation (optional). Returns sampled_candidates A tensor of type int64 and shape [num_sampled]. This operation deterministically returns the entire range [0, num_sampled]. true_expected_count A tensor of type float. Same shape as true_classes. The expected counts under the sampling distribution of each of true_classes. All returned values are 1.0. sampled_expected_count A tensor of type float. Same shape as sampled_candidates. The expected counts under the sampling distribution of each of sampled_candidates. All returned values are 1.0.
tensorflow.random.all_candidate_sampler
tf.random.categorical View source on GitHub Draws samples from a categorical distribution. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.random.categorical tf.random.categorical( logits, num_samples, dtype=None, seed=None, name=None ) Example: # samples has shape [1, 5], where each value is either 0 or 1 with equal # probability. samples = tf.random.categorical(tf.math.log([[0.5, 0.5]]), 5) Args logits 2-D Tensor with shape [batch_size, num_classes]. Each slice [i, :] represents the unnormalized log-probabilities for all classes. num_samples 0-D. Number of independent samples to draw for each row slice. dtype integer type to use for the output. Defaults to int64. seed A Python integer. Used to create a random seed for the distribution. See tf.random.set_seed for behavior. name Optional name for the operation. Returns The drawn samples of shape [batch_size, num_samples].
tensorflow.random.categorical
tf.random.create_rng_state Creates a RNG state from an integer or a vector. View aliases Main aliases tf.random.experimental.create_rng_state Compat aliases for migration See Migration guide for more details. tf.compat.v1.random.create_rng_state, tf.compat.v1.random.experimental.create_rng_state tf.random.create_rng_state( seed, alg ) Example: tf.random.create_rng_state( 1234, "philox") array([1234, 0, 0]) tf.random.create_rng_state( [12, 34], "threefry") array([12, 34]) Args seed an integer or 1-D numpy array. alg the RNG algorithm. Can be a string, an Algorithm or an integer. Returns a 1-D numpy array whose size depends on the algorithm.
tensorflow.random.create_rng_state
Module: tf.random.experimental Public API for tf.random.experimental namespace. Classes class Algorithm: An enumeration. class Generator: Random-number generator. Functions create_rng_state(...): Creates a RNG state from an integer or a vector. get_global_generator(...): Retrieves the global generator. set_global_generator(...): Replaces the global generator with another Generator object. stateless_fold_in(...): Folds in data to an RNG seed to form a new RNG seed. stateless_split(...): Splits an RNG seed into num new seeds by adding a leading axis.
tensorflow.random.experimental
tf.random.experimental.stateless_fold_in Folds in data to an RNG seed to form a new RNG seed. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.random.experimental.stateless_fold_in tf.random.experimental.stateless_fold_in( seed, data ) For example, in a distributed-training setting, suppose we have a master seed and a replica ID. We want to fold the replica ID into the master seed to form a "replica seed" to be used by that replica later on, so that different replicas will generate different random numbers but the reproducibility of the whole system can still be controlled by the master seed: master_seed = [1, 2] replica_id = 3 replica_seed = tf.random.experimental.stateless_fold_in( master_seed, replica_id) print(replica_seed) tf.Tensor([1105988140 3], shape=(2,), dtype=int32) tf.random.stateless_normal(shape=[3], seed=replica_seed) <tf.Tensor: shape=(3,), dtype=float32, numpy=array([0.03197195, 0.8979765 , 0.13253039], dtype=float32)> Args seed an RNG seed (a tensor with shape [2] and dtype int32 or int64). (When using XLA, only int32 is allowed.) data an int32 or int64 scalar representing data to be folded in to the seed. Returns A new RNG seed that is a deterministic function of the inputs and is statistically safe for producing a stream of new pseudo-random values. It will have the same dtype as data (if data doesn't have an explict dtype, the dtype will be determined by tf.convert_to_tensor).
tensorflow.random.experimental.stateless_fold_in
tf.random.experimental.stateless_split Splits an RNG seed into num new seeds by adding a leading axis. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.random.experimental.stateless_split tf.random.experimental.stateless_split( seed, num=2 ) Example: seed = [1, 2] new_seeds = tf.random.experimental.stateless_split(seed, num=3) print(new_seeds) tf.Tensor( [[1105988140 1738052849] [-335576002 370444179] [ 10670227 -246211131]], shape=(3, 2), dtype=int32) tf.random.stateless_normal(shape=[3], seed=new_seeds[0, :]) <tf.Tensor: shape=(3,), dtype=float32, numpy=array([-0.59835213, -0.9578608 , 0.9002807 ], dtype=float32)> Args seed an RNG seed (a tensor with shape [2] and dtype int32 or int64). (When using XLA, only int32 is allowed.) num optional, a positive integer or scalar tensor indicating the number of seeds to produce (default 2). Returns A tensor with shape [num, 2] representing num new seeds. It will have the same dtype as seed (if seed doesn't have an explict dtype, the dtype will be determined by tf.convert_to_tensor).
tensorflow.random.experimental.stateless_split
tf.random.fixed_unigram_candidate_sampler View source on GitHub Samples a set of classes using the provided (fixed) base distribution. View aliases Main aliases tf.nn.fixed_unigram_candidate_sampler Compat aliases for migration See Migration guide for more details. tf.compat.v1.nn.fixed_unigram_candidate_sampler, tf.compat.v1.random.fixed_unigram_candidate_sampler tf.random.fixed_unigram_candidate_sampler( true_classes, num_true, num_sampled, unique, range_max, vocab_file='', distortion=1.0, num_reserved_ids=0, num_shards=1, shard=0, unigrams=(), seed=None, name=None ) This operation randomly samples a tensor of sampled classes (sampled_candidates) from the range of integers [0, range_max). The elements of sampled_candidates are drawn without replacement (if unique=True) or with replacement (if unique=False) from the base distribution. The base distribution is read from a file or passed in as an in-memory array. There is also an option to skew the distribution by applying a distortion power to the weights. In addition, this operation returns tensors true_expected_count and sampled_expected_count representing the number of times each of the target classes (true_classes) and the sampled classes (sampled_candidates) is expected to occur in an average tensor of sampled classes. These values correspond to Q(y|x) defined in this document. If unique=True, then these are post-rejection probabilities and we compute them approximately. Args true_classes A Tensor of type int64 and shape [batch_size, num_true]. The target classes. num_true An int. The number of target classes per training example. num_sampled An int. The number of classes to randomly sample. unique A bool. Determines whether all sampled classes in a batch are unique. range_max An int. The number of possible classes. vocab_file Each valid line in this file (which should have a CSV-like format) corresponds to a valid word ID. IDs are in sequential order, starting from num_reserved_ids. The last entry in each line is expected to be a value corresponding to the count or relative probability. Exactly one of vocab_file and unigrams needs to be passed to this operation. distortion The distortion is used to skew the unigram probability distribution. Each weight is first raised to the distortion's power before adding to the internal unigram distribution. As a result, distortion = 1.0 gives regular unigram sampling (as defined by the vocab file), and distortion = 0.0 gives a uniform distribution. num_reserved_ids Optionally some reserved IDs can be added in the range [0, num_reserved_ids) by the users. One use case is that a special unknown word token is used as ID 0. These IDs will have a sampling probability of 0. num_shards A sampler can be used to sample from a subset of the original range in order to speed up the whole computation through parallelism. This parameter (together with shard) indicates the number of partitions that are being used in the overall computation. shard A sampler can be used to sample from a subset of the original range in order to speed up the whole computation through parallelism. This parameter (together with num_shards) indicates the particular partition number of the operation, when partitioning is being used. unigrams A list of unigram counts or probabilities, one per ID in sequential order. Exactly one of vocab_file and unigrams should be passed to this operation. seed An int. An operation-specific seed. Default is 0. name A name for the operation (optional). Returns sampled_candidates A tensor of type int64 and shape [num_sampled]. The sampled classes. true_expected_count A tensor of type float. Same shape as true_classes. The expected counts under the sampling distribution of each of true_classes. sampled_expected_count A tensor of type float. Same shape as sampled_candidates. The expected counts under the sampling distribution of each of sampled_candidates.
tensorflow.random.fixed_unigram_candidate_sampler
tf.random.gamma View source on GitHub Draws shape samples from each of the given Gamma distribution(s). View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.random.gamma, tf.compat.v1.random_gamma tf.random.gamma( shape, alpha, beta=None, dtype=tf.dtypes.float32, seed=None, name=None ) alpha is the shape parameter describing the distribution(s), and beta is the inverse scale parameter(s). Note: Because internal calculations are done using float64 and casting has floor semantics, we must manually map zero outcomes to the smallest possible positive floating-point value, i.e., np.finfo(dtype).tiny. This means that np.finfo(dtype).tiny occurs more frequently than it otherwise should. This bias can only happen for small values of alpha, i.e., alpha << 1 or large values of beta, i.e., beta >> 1. The samples are differentiable w.r.t. alpha and beta. The derivatives are computed using the approach described in (Figurnov et al., 2018). Example: samples = tf.random.gamma([10], [0.5, 1.5]) # samples has shape [10, 2], where each slice [:, 0] and [:, 1] represents # the samples drawn from each distribution samples = tf.random.gamma([7, 5], [0.5, 1.5]) # samples has shape [7, 5, 2], where each slice [:, :, 0] and [:, :, 1] # represents the 7x5 samples drawn from each of the two distributions alpha = tf.constant([[1.],[3.],[5.]]) beta = tf.constant([[3., 4.]]) samples = tf.random.gamma([30], alpha=alpha, beta=beta) # samples has shape [30, 3, 2], with 30 samples each of 3x2 distributions. loss = tf.reduce_mean(tf.square(samples)) dloss_dalpha, dloss_dbeta = tf.gradients(loss, [alpha, beta]) # unbiased stochastic derivatives of the loss function alpha.shape == dloss_dalpha.shape # True beta.shape == dloss_dbeta.shape # True Args shape A 1-D integer Tensor or Python array. The shape of the output samples to be drawn per alpha/beta-parameterized distribution. alpha A Tensor or Python value or N-D array of type dtype. alpha provides the shape parameter(s) describing the gamma distribution(s) to sample. Must be broadcastable with beta. beta A Tensor or Python value or N-D array of type dtype. Defaults to 1. beta provides the inverse scale parameter(s) of the gamma distribution(s) to sample. Must be broadcastable with alpha. dtype The type of alpha, beta, and the output: float16, float32, or float64. seed A Python integer. Used to create a random seed for the distributions. See tf.random.set_seed for behavior. name Optional name for the operation. Returns samples a Tensor of shape tf.concat([shape, tf.shape(alpha + beta)], axis=0) with values of type dtype. References: Implicit Reparameterization Gradients: Figurnov et al., 2018 (pdf)
tensorflow.random.gamma
tf.random.Generator Random-number generator. View aliases Main aliases tf.random.experimental.Generator Compat aliases for migration See Migration guide for more details. tf.compat.v1.random.Generator, tf.compat.v1.random.experimental.Generator tf.random.Generator( copy_from=None, state=None, alg=None ) Example: Creating a generator from a seed: g = tf.random.Generator.from_seed(1234) g.normal(shape=(2, 3)) <tf.Tensor: shape=(2, 3), dtype=float32, numpy= array([[ 0.9356609 , 1.0854305 , -0.93788373], [-0.5061547 , 1.3169702 , 0.7137579 ]], dtype=float32)> Creating a generator from a non-deterministic state: g = tf.random.Generator.from_non_deterministic_state() g.normal(shape=(2, 3)) <tf.Tensor: shape=(2, 3), dtype=float32, numpy=...> All the constructors allow explicitly choosing an Random-Number-Generation (RNG) algorithm. Supported algorithms are "philox" and "threefry". For example: g = tf.random.Generator.from_seed(123, alg="philox") g.normal(shape=(2, 3)) <tf.Tensor: shape=(2, 3), dtype=float32, numpy= array([[ 0.8673864 , -0.29899067, -0.9310337 ], [-1.5828488 , 1.2481191 , -0.6770643 ]], dtype=float32)> CPU, GPU and TPU with the same algorithm and seed will generate the same integer random numbers. Float-point results (such as the output of normal) may have small numerical discrepancies between different devices. This class uses a tf.Variable to manage its internal state. Every time random numbers are generated, the state of the generator will change. For example: g = tf.random.Generator.from_seed(1234) g.state <tf.Variable ... numpy=array([1234, 0, 0])> g.normal(shape=(2, 3)) <...> g.state <tf.Variable ... numpy=array([2770, 0, 0])> The shape of the state is algorithm-specific. There is also a global generator: g = tf.random.get_global_generator() g.normal(shape=(2, 3)) <tf.Tensor: shape=(2, 3), dtype=float32, numpy=...> Args copy_from a generator to be copied from. state a vector of dtype STATE_TYPE representing the initial state of the RNG, whose length and semantics are algorithm-specific. If it's a variable, the generator will reuse it instead of creating a new variable. alg the RNG algorithm. Possible values are tf.random.Algorithm.PHILOX for the Philox algorithm and tf.random.Algorithm.THREEFRY for the ThreeFry algorithm (see paper 'Parallel Random Numbers: As Easy as 1, 2, 3' [https://www.thesalmons.org/john/random123/papers/random123sc11.pdf]). The string names "philox" and "threefry" can also be used. Note PHILOX guarantees the same numbers are produced (given the same random state) across all architectures (CPU, GPU, XLA etc). Attributes algorithm The RNG algorithm id (a Python integer or scalar integer Tensor). key The 'key' part of the state of a counter-based RNG. For a counter-base RNG algorithm such as Philox and ThreeFry (as described in paper 'Parallel Random Numbers: As Easy as 1, 2, 3' [https://www.thesalmons.org/john/random123/papers/random123sc11.pdf]), the RNG state consists of two parts: counter and key. The output is generated via the formula: output=hash(key, counter), i.e. a hashing of the counter parametrized by the key. Two RNGs with two different keys can be thought as generating two independent random-number streams (a stream is formed by increasing the counter). state The internal state of the RNG. Methods binomial View source binomial( shape, counts, probs, dtype=tf.dtypes.int32, name=None ) Outputs random values from a binomial distribution. The generated values follow a binomial distribution with specified count and probability of success parameters. Example: counts = [10., 20.] # Probability of success. probs = [0.8] rng = tf.random.Generator.from_seed(seed=234) binomial_samples = rng.binomial(shape=[2], counts=counts, probs=probs) counts = ... # Shape [3, 1, 2] probs = ... # Shape [1, 4, 2] shape = [3, 4, 3, 4, 2] rng = tf.random.Generator.from_seed(seed=1717) # Sample shape will be [3, 4, 3, 4, 2] binomial_samples = rng.binomial(shape=shape, counts=counts, probs=probs) Args shape A 1-D integer Tensor or Python array. The shape of the output tensor. counts Tensor. The counts of the binomial distribution. Must be broadcastable with probs, and broadcastable with the rightmost dimensions of shape. probs Tensor. The probability of success for the binomial distribution. Must be broadcastable with counts and broadcastable with the rightmost dimensions of shape. dtype The type of the output. Default: tf.int32 name A name for the operation (optional). Returns samples A Tensor of the specified shape filled with random binomial values. For each i, each samples[i, ...] is an independent draw from the binomial distribution on counts[i] trials with probability of success probs[i]. from_key_counter View source @classmethod from_key_counter( key, counter, alg ) Creates a generator from a key and a counter. This constructor only applies if the algorithm is a counter-based algorithm. See method key for the meaning of "key" and "counter". Args key the key for the RNG, a scalar of type STATE_TYPE. counter a vector of dtype STATE_TYPE representing the initial counter for the RNG, whose length is algorithm-specific., alg the RNG algorithm. If None, it will be auto-selected. See __init__ for its possible values. Returns The new generator. Throws: ValueError: if the generator is created inside a synchronous tf.distribute strategy such as MirroredStrategy or TPUStrategy, because there is ambiguity on how to replicate a generator (e.g. should it be copied so such each replica will get the same random numbers, or should it be "split" into different generators that generate different random numbers). from_non_deterministic_state View source @classmethod from_non_deterministic_state( alg=None ) Creates a generator by non-deterministically initializing its state. The source of the non-determinism will be platform- and time-dependent. Args alg (optional) the RNG algorithm. If None, it will be auto-selected. See __init__ for its possible values. Returns The new generator. Throws: ValueError: if the generator is created inside a synchronous tf.distribute strategy such as MirroredStrategy or TPUStrategy, because there is ambiguity on how to replicate a generator (e.g. should it be copied so such each replica will get the same random numbers, or should it be "split" into different generators that generate different random numbers). from_seed View source @classmethod from_seed( seed, alg=None ) Creates a generator from a seed. A seed is a 1024-bit unsigned integer represented either as a Python integer or a vector of integers. Seeds shorter than 1024-bit will be padded. The padding, the internal structure of a seed and the way a seed is converted to a state are all opaque (unspecified). The only semantics specification of seeds is that two different seeds are likely to produce two independent generators (but no guarantee). Args seed the seed for the RNG. alg (optional) the RNG algorithm. If None, it will be auto-selected. See __init__ for its possible values. Returns The new generator. Throws: ValueError: if the generator is created inside a synchronous tf.distribute strategy such as MirroredStrategy or TPUStrategy, because there is ambiguity on how to replicate a generator (e.g. should it be copied so such each replica will get the same random numbers, or should it be "split" into different generators that generate different random numbers). from_state View source @classmethod from_state( state, alg ) Creates a generator from a state. See __init__ for description of state and alg. Args state the new state. alg the RNG algorithm. Returns The new generator. Throws: ValueError: if the generator is created inside a synchronous tf.distribute strategy such as MirroredStrategy or TPUStrategy, because there is ambiguity on how to replicate a generator (e.g. should it be copied so such each replica will get the same random numbers, or should it be "split" into different generators that generate different random numbers). make_seeds View source make_seeds( count=1 ) Generates seeds for stateless random ops. For example: seeds = get_global_generator().make_seeds(count=10) for i in range(10): seed = seeds[:, i] numbers = stateless_random_normal(shape=[2, 3], seed=seed) ... Args count the number of seed pairs (note that stateless random ops need a pair of seeds to invoke). Returns A tensor of shape [2, count] and dtype int64. normal View source normal( shape, mean=0.0, stddev=1.0, dtype=tf.dtypes.float32, name=None ) Outputs random values from a normal distribution. Args shape A 1-D integer Tensor or Python array. The shape of the output tensor. mean A 0-D Tensor or Python value of type dtype. The mean of the normal distribution. stddev A 0-D Tensor or Python value of type dtype. The standard deviation of the normal distribution. dtype The type of the output. name A name for the operation (optional). Returns A tensor of the specified shape filled with random normal values. reset View source reset( state ) Resets the generator by a new state. See __init__ for the meaning of "state". Args state the new state. reset_from_key_counter View source reset_from_key_counter( key, counter ) Resets the generator by a new key-counter pair. See from_key_counter for the meaning of "key" and "counter". Args key the new key. counter the new counter. reset_from_seed View source reset_from_seed( seed ) Resets the generator by a new seed. See from_seed for the meaning of "seed". Args seed the new seed. skip View source skip( delta ) Advance the counter of a counter-based RNG. Args delta the amount of advancement. The state of the RNG after skip(n) will be the same as that after normal([n]) (or any other distribution). The actual increment added to the counter is an unspecified implementation detail. split View source split( count=1 ) Returns a list of independent Generator objects. Two generators are independent of each other in the sense that the random-number streams they generate don't have statistically detectable correlations. The new generators are also independent of the old one. The old generator's state will be changed (like other random-number generating methods), so two calls of split will return different new generators. For example: gens = get_global_generator().split(count=10) for gen in gens: numbers = gen.normal(shape=[2, 3]) # ... gens2 = get_global_generator().split(count=10) # gens2 will be different from gens The new generators will be put on the current device (possible different from the old generator's), for example: with tf.device("/device:CPU:0"): gen = Generator(seed=1234) # gen is on CPU with tf.device("/device:GPU:0"): gens = gen.split(count=10) # gens are on GPU Args count the number of generators to return. Returns A list (length count) of Generator objects independent of each other. The new generators have the same RNG algorithm as the old one. truncated_normal View source truncated_normal( shape, mean=0.0, stddev=1.0, dtype=tf.dtypes.float32, name=None ) Outputs random values from a truncated normal distribution. The generated values follow a normal distribution with specified mean and standard deviation, except that values whose magnitude is more than 2 standard deviations from the mean are dropped and re-picked. Args shape A 1-D integer Tensor or Python array. The shape of the output tensor. mean A 0-D Tensor or Python value of type dtype. The mean of the truncated normal distribution. stddev A 0-D Tensor or Python value of type dtype. The standard deviation of the normal distribution, before truncation. dtype The type of the output. name A name for the operation (optional). Returns A tensor of the specified shape filled with random truncated normal values. uniform View source uniform( shape, minval=0, maxval=None, dtype=tf.dtypes.float32, name=None ) Outputs random values from a uniform distribution. The generated values follow a uniform distribution in the range [minval, maxval). The lower bound minval is included in the range, while the upper bound maxval is excluded. (For float numbers especially low-precision types like bfloat16, because of rounding, the result may sometimes include maxval.) For floats, the default range is [0, 1). For ints, at least maxval must be specified explicitly. In the integer case, the random integers are slightly biased unless maxval - minval is an exact power of two. The bias is small for values of maxval - minval significantly smaller than the range of the output (either 2**32 or 2**64). For full-range random integers, pass minval=None and maxval=None with an integer dtype (for integer dtypes, minval and maxval must be both None or both not None). Args shape A 1-D integer Tensor or Python array. The shape of the output tensor. minval A Tensor or Python value of type dtype, broadcastable with shape (for integer types, broadcasting is not supported, so it needs to be a scalar). The lower bound (included) on the range of random values to generate. Pass None for full-range integers. Defaults to 0. maxval A Tensor or Python value of type dtype, broadcastable with shape (for integer types, broadcasting is not supported, so it needs to be a scalar). The upper bound (excluded) on the range of random values to generate. Pass None for full-range integers. Defaults to 1 if dtype is floating point. dtype The type of the output. name A name for the operation (optional). Returns A tensor of the specified shape filled with random uniform values. Raises ValueError If dtype is integral and maxval is not specified. uniform_full_int View source uniform_full_int( shape, dtype=tf.dtypes.uint64, name=None ) Uniform distribution on an integer type's entire range. This method is the same as setting minval and maxval to None in the uniform method. Args shape the shape of the output. dtype (optional) the integer type, default to uint64. name (optional) the name of the node. Returns A tensor of random numbers of the required shape.
tensorflow.random.generator
tf.random.get_global_generator Retrieves the global generator. View aliases Main aliases tf.random.experimental.get_global_generator Compat aliases for migration See Migration guide for more details. tf.compat.v1.random.experimental.get_global_generator, tf.compat.v1.random.get_global_generator tf.random.get_global_generator() This function will create the global generator the first time it is called, and the generator will be placed at the default device at that time, so one needs to be careful when this function is first called. Using a generator placed on a less-ideal device will incur performance regression. Returns The global tf.random.Generator object.
tensorflow.random.get_global_generator
tf.random.learned_unigram_candidate_sampler View source on GitHub Samples a set of classes from a distribution learned during training. View aliases Main aliases tf.nn.learned_unigram_candidate_sampler Compat aliases for migration See Migration guide for more details. tf.compat.v1.nn.learned_unigram_candidate_sampler, tf.compat.v1.random.learned_unigram_candidate_sampler tf.random.learned_unigram_candidate_sampler( true_classes, num_true, num_sampled, unique, range_max, seed=None, name=None ) This operation randomly samples a tensor of sampled classes (sampled_candidates) from the range of integers [0, range_max). The elements of sampled_candidates are drawn without replacement (if unique=True) or with replacement (if unique=False) from the base distribution. The base distribution for this operation is constructed on the fly during training. It is a unigram distribution over the target classes seen so far during training. Every integer in [0, range_max) begins with a weight of 1, and is incremented by 1 each time it is seen as a target class. The base distribution is not saved to checkpoints, so it is reset when the model is reloaded. In addition, this operation returns tensors true_expected_count and sampled_expected_count representing the number of times each of the target classes (true_classes) and the sampled classes (sampled_candidates) is expected to occur in an average tensor of sampled classes. These values correspond to Q(y|x) defined in this document. If unique=True, then these are post-rejection probabilities and we compute them approximately. Args true_classes A Tensor of type int64 and shape [batch_size, num_true]. The target classes. num_true An int. The number of target classes per training example. num_sampled An int. The number of classes to randomly sample. unique A bool. Determines whether all sampled classes in a batch are unique. range_max An int. The number of possible classes. seed An int. An operation-specific seed. Default is 0. name A name for the operation (optional). Returns sampled_candidates A tensor of type int64 and shape [num_sampled]. The sampled classes. true_expected_count A tensor of type float. Same shape as true_classes. The expected counts under the sampling distribution of each of true_classes. sampled_expected_count A tensor of type float. Same shape as sampled_candidates. The expected counts under the sampling distribution of each of sampled_candidates.
tensorflow.random.learned_unigram_candidate_sampler
tf.random.log_uniform_candidate_sampler View source on GitHub Samples a set of classes using a log-uniform (Zipfian) base distribution. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.nn.log_uniform_candidate_sampler, tf.compat.v1.random.log_uniform_candidate_sampler tf.random.log_uniform_candidate_sampler( true_classes, num_true, num_sampled, unique, range_max, seed=None, name=None ) This operation randomly samples a tensor of sampled classes (sampled_candidates) from the range of integers [0, range_max). The elements of sampled_candidates are drawn without replacement (if unique=True) or with replacement (if unique=False) from the base distribution. The base distribution for this operation is an approximately log-uniform or Zipfian distribution: P(class) = (log(class + 2) - log(class + 1)) / log(range_max + 1) This sampler is useful when the target classes approximately follow such a distribution - for example, if the classes represent words in a lexicon sorted in decreasing order of frequency. If your classes are not ordered by decreasing frequency, do not use this op. In addition, this operation returns tensors true_expected_count and sampled_expected_count representing the number of times each of the target classes (true_classes) and the sampled classes (sampled_candidates) is expected to occur in an average tensor of sampled classes. These values correspond to Q(y|x) defined in this document. If unique=True, then these are post-rejection probabilities and we compute them approximately. Args true_classes A Tensor of type int64 and shape [batch_size, num_true]. The target classes. num_true An int. The number of target classes per training example. num_sampled An int. The number of classes to randomly sample. unique A bool. Determines whether all sampled classes in a batch are unique. range_max An int. The number of possible classes. seed An int. An operation-specific seed. Default is 0. name A name for the operation (optional). Returns sampled_candidates A tensor of type int64 and shape [num_sampled]. The sampled classes. true_expected_count A tensor of type float. Same shape as true_classes. The expected counts under the sampling distribution of each of true_classes. sampled_expected_count A tensor of type float. Same shape as sampled_candidates. The expected counts under the sampling distribution of each of sampled_candidates.
tensorflow.random.log_uniform_candidate_sampler
tf.random.normal View source on GitHub Outputs random values from a normal distribution. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.random.normal, tf.compat.v1.random_normal tf.random.normal( shape, mean=0.0, stddev=1.0, dtype=tf.dtypes.float32, seed=None, name=None ) Example that generates a new set of random values every time: tf.random.set_seed(5); tf.random.normal([4], 0, 1, tf.float32) <tf.Tensor: shape=(4,), dtype=float32, numpy=..., dtype=float32)> Example that outputs a reproducible result: tf.random.set_seed(5); tf.random.normal([2,2], 0, 1, tf.float32, seed=1) <tf.Tensor: shape=(2, 2), dtype=float32, numpy= array([[-1.3768897 , -0.01258316], [-0.169515 , 1.0824056 ]], dtype=float32)> In this case, we are setting both the global and operation-level seed to ensure this result is reproducible. See tf.random.set_seed for more information. Args shape A 1-D integer Tensor or Python array. The shape of the output tensor. mean A Tensor or Python value of type dtype, broadcastable with stddev. The mean of the normal distribution. stddev A Tensor or Python value of type dtype, broadcastable with mean. The standard deviation of the normal distribution. dtype The type of the output. seed A Python integer. Used to create a random seed for the distribution. See tf.random.set_seed for behavior. name A name for the operation (optional). Returns A tensor of the specified shape filled with random normal values.
tensorflow.random.normal
tf.random.poisson View source on GitHub Draws shape samples from each of the given Poisson distribution(s). tf.random.poisson( shape, lam, dtype=tf.dtypes.float32, seed=None, name=None ) lam is the rate parameter describing the distribution(s). Example: samples = tf.random.poisson([10], [0.5, 1.5]) # samples has shape [10, 2], where each slice [:, 0] and [:, 1] represents # the samples drawn from each distribution samples = tf.random.poisson([7, 5], [12.2, 3.3]) # samples has shape [7, 5, 2], where each slice [:, :, 0] and [:, :, 1] # represents the 7x5 samples drawn from each of the two distributions Args shape A 1-D integer Tensor or Python array. The shape of the output samples to be drawn per "rate"-parameterized distribution. lam A Tensor or Python value or N-D array of type dtype. lam provides the rate parameter(s) describing the poisson distribution(s) to sample. dtype The type of the output: float16, float32, float64, int32 or int64. seed A Python integer. Used to create a random seed for the distributions. See tf.random.set_seed for behavior. name Optional name for the operation. Returns samples a Tensor of shape tf.concat([shape, tf.shape(lam)], axis=0) with values of type dtype.
tensorflow.random.poisson