本文档为TensorFlow参考文档,本转载已得到TensorFlow中文社区授权。
Note: Functions taking Tensor arguments can also take anything accepted by tf.convert_to_tensor.
The activation ops provide different types of nonlinearities for use in neural networks. These include smooth nonlinearities (sigmoid, tanh, and softplus), continuous but not everywhere differentiable functions (relu, relu6, and relu_x), and random regularization (dropout).
All activation ops apply componentwise, and produce a tensor of the same shape as the input tensor.
Computes rectified linear: max(features, 0).
A Tensor. Has the same type as features.
Computes Rectified Linear 6: min(max(features, 0), 6).
A Tensor with the same type as features.
Computes softplus: log(exp(features) + 1).
A Tensor. Has the same type as features.
Computes dropout.
With probability keep_prob, outputs the input element scaled up by 1 / keep_prob, otherwise outputs 0. The scaling is so that the expected sum is unchanged.
By default, each element is kept or dropped independently. If noise_shape is specified, it must bebroadcastable to the shape of x, and only dimensions with noise_shape[i] == shape(x)[i] will make independent decisions. For example, if shape(x) = [k, l, m, n] and noise_shape = [k, 1, 1, n], each batch and channel component will be kept independently and each row and column will be kept or not kept together.
A Tensor of the same shape of x.
Adds bias to value.
This is (mostly) a special case of tf.add where bias is restricted to 1-D. Broadcasting is supported, so value may have any number of dimensions. Unlike tf.add, the type of bias is allowed to differ from value in the case where both types are quantized.
A Tensor with the same type as value.
Computes sigmoid of x element-wise.
Specifically, y = 1 / (1 + exp(-x)).
A Tensor with the same type as x if x.dtype != qint32 otherwise the return type is quint8.
Computes hyperbolic tangent of x element-wise.
A Tensor with the same type as x if x.dtype != qint32 otherwise the return type is quint8.
The convolution ops sweep a 2-D filter over a batch of images, applying the filter to each window of each image of the appropriate size. The different ops trade off between generic vs. specific filters:
conv2d: Arbitrary filters that can mix channels together. depthwise_conv2d: Filters that operate on each channel independently. separable_conv2d: A depthwise spatial filter followed by a pointwise filter.Note that although these ops are called "convolution", they are strictly speaking "cross-correlation" since the filter is combined with an input window without reversing the filter. For details, see the properties of cross-correlation.
The filter is applied to image patches of the same size as the filter and strided according to the stridesargument. strides = [1, 1, 1, 1] applies the filter to a patch at every offset, strides = [1, 2, 2, 1]applies the filter to every other image patch in each dimension, etc.
Ignoring channels for the moment, the spatial semantics of the convolution ops are as follows. If the 4-D input has shape [batch, in_height, in_width, ...] and the 4-D filter has shape[filter_height, filter_width, ...], then
shape(output) = [batch, (in_height - filter_height + 1) / strides[1], (in_width - filter_width + 1) / strides[2], ...] output[b, i, j, :] = sum_{di, dj} input[b, strides[1] * i + di, strides[2] * j + dj, ...] * filter[di, dj, ...]Since input is 4-D, each input[b, i, j, :] is a vector. For conv2d, these vectors are multiplied by the filter[di, dj, :, :] matrices to produce new vectors. For depthwise_conv_2d, each scalar component input[b, i, j, k] is multiplied by a vector filter[di, dj, k], and all the vectors are concatenated.
In the formula for shape(output), the rounding direction depends on padding:
padding = 'SAME': Round down (only full size windows are considered). padding = 'VALID': Round up (partial windows are included).Computes a 2-D convolution given 4-D input and filter tensors.
Given an input tensor of shape [batch, in_height, in_width, in_channels] and a filter / kernel tensor of shape [filter_height, filter_width, in_channels, out_channels], this op performs the following:
Flattens the filter to a 2-D matrix with shape [filter_height * filter_width * in_channels, output_channels].Extracts image patches from the the input tensor to form a virtual tensor of shape [batch, out_height, out_width, filter_height * filter_width * in_channels].For each patch, right-multiplies the filter matrix and the image patch vector.In detail,
output[b, i, j, k] = sum_{di, dj, q} input[b, strides[1] * i + di, strides[2] * j + dj, q] * filter[di, dj, q, k]Must have strides[0] = strides[3] = 1. For the most common case of the same horizontal and vertices strides, strides = [1, stride, stride, 1].
A Tensor. Has the same type as input.
Depthwise 2-D convolution.
Given an input tensor of shape [batch, in_height, in_width, in_channels] and a filter tensor of shape[filter_height, filter_width, in_channels, channel_multiplier] containing in_channelsconvolutional filters of depth 1, depthwise_conv2d applies a different filter to each input channel (expanding from 1 channel to channel_multiplier channels for each), then concatenates the results together. The output has in_channels * channel_multiplier channels.
In detail,
output[b, i, j, k * channel_multiplier + q] = sum_{di, dj} input[b, strides[1] * i + di, strides[2] * j + dj, k] * filter[di, dj, k, q]Must have strides[0] = strides[3] = 1. For the most common case of the same horizontal and vertical strides, strides = [1, stride, stride, 1].
A 4-D Tensor of shape [batch, out_height, out_width, in_channels * channel_multiplier].
2-D convolution with separable filters.
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,
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].
A 4-D Tensor of shape [batch, out_height, out_width, out_channels].
The pooling ops sweep a rectangular window over the input tensor, computing a reduction operation for each window (average, max, or max with argmax). Each pooling op uses rectangular windows of size ksize separated by offset strides. For example, if strides is all ones every window is used, ifstrides is all twos every other window is used in each dimension, etc.
In detail, the output is
output[i] = reduce(value[strides * i:strides * i + ksize])for each tuple of indices i. The output shape is
shape(output) = (shape(value) - ksize + 1) / strideswhere the rounding direction depends on padding:
padding = 'SAME': Round down (only full size windows are considered). padding = 'VALID': Round up (partial windows are included).Performs the average pooling on the input.
Each entry in output is the mean of the corresponding size ksize window in value.
A Tensor with the same type as value. The average pooled output tensor.
Performs the max pooling on the input.
A Tensor with the same type as value. The max pooled output tensor.
Performs max pooling on the input and outputs both max values and indices.
The indices in argmax are flattened, so that a maximum value at position [b, y, x, c] becomes flattened index ((b * height + y) * width + x) * channels + c.
A tuple of Tensor objects (output, argmax).
output: A Tensor of type float32. The max pooled output tensor. argmax: A Tensor of type Targmax. 4-D. The flattened indices of the max values chosen for each output.Normalization is useful to prevent neurons from saturating when inputs may have varying scale, and to aid generalization.
Normalizes along dimension dim using an L2 norm.
For a 1-D tensor with dim = 0, computes
output = x / sqrt(max(sum(x**2), epsilon))For x with more dimensions, independently normalizes each 1-D slice along dimension dim.
A Tensor with the same shape as x.
Local Response Normalization.
The 4-D input tensor is treated as a 3-D array of 1-D vectors (along the last dimension), and each vector is normalized independently. Within a given vector, each component is divided by the weighted, squared sum of inputs within depth_radius. In detail,
sqr_sum[a, b, c, d] = sum(input[a, b, c, d - depth_radius : d + depth_radius + 1] ** 2) output = input / (bias + alpha * sqr_sum ** beta)For details, see [Krizhevsky et al., ImageNet classification with deep convolutional neural networks (NIPS 2012)] (http://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks).
A Tensor of type float32.
Calculate the mean and variance of x.
The mean and variance are calculated by aggregating the contents of x across axes. If x is 1-D and axes = [0] this is just the mean and variance of a vector.
For so-called "global normalization" needed for convolutional filters pass axes=[0, 1, 2] (batch, height, width). For batch normalization pass axes=[0] (batch).
Two Tensors: mean and variance.
The loss ops measure error between two tensors, or between a tensor and zero. These can be used for measuring accuracy of a network in a regression task or for regularization purposes (weight decay).
L2 Loss.
Computes half the L2 norm of a tensor without the sqrt:
output = sum(t ** 2) / 2A Tensor. Has the same type as t. 0-D.
TensorFlow provides several operations that help you perform classification.
Computes sigmoid cross entropy given logits.
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 = targets. The logistic loss is
x - x * z + log(1 + exp(-x))To ensure stability and avoid overflow, the implementation uses
max(x, 0) - x * z + log(1 + exp(-abs(x)))logits and targets must have the same type and shape.
A Tensor of the same shape as logits with the componentwise logistic losses.
Computes softmax activations.
For each batch i and class j we have
softmax[i, j] = exp(logits[i, j]) / sum(exp(logits[i]))A Tensor. Has the same type as logits. Same shape as logits.
Computes softmax cross entropy between logits and labels.
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.
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.
logits and labels must have the same shape [batch_size, num_classes] and the same dtype (either float32 or float64).
A 1-D Tensor of length batch_size of the same type as logits with the softmax cross entropy loss.
TensorFlow provides library support for looking up values in embedding tensors.
Looks up ids in a list of embedding tensors.
This function is used to perform parallel lookups on the list of tensors in params. It is a generalization oftf.gather(), where params is interpreted as a partition of a larger embedding tensor.
If len(params) > 1, each element id of ids is partitioned between the elements of params by computing p = id % len(params), and is then used to look up the slice params[p][id // len(params), ...].
The results of the lookup are then concatenated into a dense tensor. The returned tensor has shape shape(ids) + shape(params)[1:].
A Tensor with the same type as the tensors in params.
The evaluation ops are useful for measuring the performance of a network. Since they are nondifferentiable, they are typically used at evaluation time.
Returns the values and indices of the k largest elements for each row.
represents the j-th largest element in .
gives the column index of the corresponding element, such that . If two elements are equal, the lower-index element appears first.
A tuple of Tensor objects (values, indices).
values: A Tensor. Has the same type as input. A batch_size x k tensor with the k largest elements for each row, sorted in descending order indices: A Tensor of type int32. A batch_size x k tensor with the index of each value within each rowSays whether the targets are in the top K predictions.
This outputs a batch_size bool array, an entry out[i] is true if the prediction for the target class is among the top k predictions among all predictions for example i. Note that the behavior of InTopK differs from the TopK op in its handling of ties; if multiple classes have the same prediction value and straddle the top-k boundary, all of those classes are considered to be in the top k.
More formally, let
be the predictions for all classes for example i, be the target class for example i, be the output for example i,
A Tensor of type bool. Computed Precision at k as a bool Tensor
Do you want to train a multiclass or multilabel model with thousands or millions of output classes (for example, a language model with a large vocabulary)? Training with a full Softmax is slow in this case, since all of the classes are evaluated for every training example. Candidate Sampling training algorithms can speed up your step times by only considering a small randomly-chosen subset of contrastive classes (called candidates) for each batch of training examples.
See our [Candidate Sampling Algorithms Reference] (../../extras/candidate_sampling.pdf)
TensorFlow provides the following sampled loss functions for faster training.
Computes and returns the noise-contrastive estimation training loss.
See [Noise-contrastive estimation: A new estimation principle for unnormalized statistical models] (http://www.jmlr.org/proceedings/papers/v9/gutmann10a/gutmann10a.pdf). Also see our [Candidate Sampling Algorithms Reference] (http://www.tensorflow.org/extras/candidate_sampling.pdf)
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.
A batch_size 1-D tensor of per-example NCE losses.
Computes and returns the sampled softmax training 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.
At inference time, you can compute full softmax probabilities with the expression tf.nn.softmax(tf.matmul(inputs, weights) + biases).
See our [Candidate Sampling Algorithms Reference] (http://www.tensorflow.org/extras/candidate_sampling.pdf)
Also see Section 3 of http://arxiv.org/abs/1412.2007 for the math.
A batch_size 1-D tensor of per-example sampled softmax losses.
TensorFlow provides the following samplers for randomly sampling candidate classes when using one of the sampled loss functions above.
Samples a set of classes using a uniform base distribution.
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 the uniform distribution over the range of integers [0, range_max].
In addition, this operation returns tensors true_expected_count and sampled_expected_countrepresenting 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.
Samples a set of classes using a log-uniform (Zipfian) base distribution.
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_countrepresenting 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.
Samples a set of classes from a distribution learned during training.
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_countrepresenting 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.
Samples a set of classes using the provided (fixed) base distribution.
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_countrepresenting 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.
Compute the ids of positions in sampled_candidates matching true_classes.
In Candidate Sampling, this operation facilitates virtually removing sampled classes which happen to match target classes. This is done in Sampled Softmax and Sampled Logistic.
See our Candidate Sampling Algorithms Reference.
We presuppose that the sampled_candidates are unique.
We call it an 'accidental hit' when one of the target classes matches one of the sampled classes. This operation reports accidental hits as triples (index, id, weight), where index represents the row number in true_classes, id represents the position in sampled_candidates, and weight is -FLOAT_MAX.
The result of this op should be passed through a sparse_to_dense operation, then added to the logits of the sampled classes. This removes the contradictory effect of accidentally sampling the true target classes as noise classes for the same example.