doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
tf.keras.initializers.Zeros Initializer that generates tensors initialized to 0. Inherits From: zeros_initializer, Initializer View aliases Main aliases tf.initializers.Zeros, tf.initializers.zeros, tf.keras.initializers.zeros Also available via the shortcut function tf.keras.initializers.zeros. Examples: # Standalone usage: initializer = tf.keras.initializers.Zeros() values = initializer(shape=(2, 2)) # Usage in a Keras layer: initializer = tf.keras.initializers.Zeros() layer = tf.keras.layers.Dense(3, kernel_initializer=initializer) 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=None, **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. If not specified, tf.keras.backend.floatx() is used, which default to float32 unless you configured it otherwise (via tf.keras.backend.set_floatx(float_dtype)). **kwargs Additional keyword arguments.
tensorflow.keras.initializers.zeros
tf.keras.Input View source on GitHub Input() is used to instantiate a Keras tensor. View aliases Main aliases tf.keras.layers.Input Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.Input, tf.compat.v1.keras.layers.Input tf.keras.Input( shape=None, batch_size=None, name=None, dtype=None, sparse=False, tensor=None, ragged=False, **kwargs ) A Keras tensor is a TensorFlow symbolic tensor object, which we augment with certain attributes that allow us to build a Keras model just by knowing the inputs and outputs of the model. For instance, if a, b and c are Keras tensors, it becomes possible to do: model = Model(input=[a, b], output=c) Arguments shape A shape tuple (integers), not including the batch size. For instance, shape=(32,) indicates that the expected input will be batches of 32-dimensional vectors. Elements of this tuple can be None; 'None' elements represent dimensions where the shape is not known. batch_size optional static batch size (integer). name An optional name string for the layer. Should be unique in a model (do not reuse the same name twice). It will be autogenerated if it isn't provided. dtype The data type expected by the input, as a string (float32, float64, int32...) sparse A boolean specifying whether the placeholder to be created is sparse. Only one of 'ragged' and 'sparse' can be True. Note that, if sparse is False, sparse tensors can still be passed into the input - they will be densified with a default value of 0. tensor Optional existing tensor to wrap into the Input layer. If set, the layer will use the tf.TypeSpec of this tensor rather than creating a new placeholder tensor. ragged A boolean specifying whether the placeholder to be created is ragged. Only one of 'ragged' and 'sparse' can be True. In this case, values of 'None' in the 'shape' argument represent ragged dimensions. For more information about RaggedTensors, see this guide. **kwargs deprecated arguments support. Supports batch_shape and batch_input_shape. Returns A tensor. Example: # this is a logistic regression in Keras x = Input(shape=(32,)) y = Dense(16, activation='softmax')(x) model = Model(x, y) Note that even if eager execution is enabled, Input produces a symbolic tensor (i.e. a placeholder). This symbolic tensor can be used with other TensorFlow ops, as such: x = Input(shape=(32,)) y = tf.square(x) Raises ValueError If both sparse and ragged are provided. ValueError If both shape and (batch_input_shape or batch_shape) are provided. ValueError If both shape and tensor are None. ValueError if any unrecognized parameters are provided.
tensorflow.keras.input
Module: tf.keras.layers Keras layers API. Modules experimental module: Public API for tf.keras.layers.experimental namespace. Classes class AbstractRNNCell: Abstract object representing an RNN cell. class Activation: Applies an activation function to an output. class ActivityRegularization: Layer that applies an update to the cost function based input activity. class Add: Layer that adds a list of inputs. class AdditiveAttention: Additive attention layer, a.k.a. Bahdanau-style attention. class AlphaDropout: Applies Alpha Dropout to the input. class Attention: Dot-product attention layer, a.k.a. Luong-style attention. class Average: Layer that averages a list of inputs element-wise. class AveragePooling1D: Average pooling for temporal data. class AveragePooling2D: Average pooling operation for spatial data. class AveragePooling3D: Average pooling operation for 3D data (spatial or spatio-temporal). class AvgPool1D: Average pooling for temporal data. class AvgPool2D: Average pooling operation for spatial data. class AvgPool3D: Average pooling operation for 3D data (spatial or spatio-temporal). class BatchNormalization: Layer that normalizes its inputs. class Bidirectional: Bidirectional wrapper for RNNs. class Concatenate: Layer that concatenates a list of inputs. class Conv1D: 1D convolution layer (e.g. temporal convolution). class Conv1DTranspose: Transposed convolution layer (sometimes called Deconvolution). class Conv2D: 2D convolution layer (e.g. spatial convolution over images). class Conv2DTranspose: Transposed convolution layer (sometimes called Deconvolution). class Conv3D: 3D convolution layer (e.g. spatial convolution over volumes). class Conv3DTranspose: Transposed convolution layer (sometimes called Deconvolution). class ConvLSTM2D: Convolutional LSTM. class Convolution1D: 1D convolution layer (e.g. temporal convolution). class Convolution1DTranspose: Transposed convolution layer (sometimes called Deconvolution). class Convolution2D: 2D convolution layer (e.g. spatial convolution over images). class Convolution2DTranspose: Transposed convolution layer (sometimes called Deconvolution). class Convolution3D: 3D convolution layer (e.g. spatial convolution over volumes). class Convolution3DTranspose: Transposed convolution layer (sometimes called Deconvolution). class Cropping1D: Cropping layer for 1D input (e.g. temporal sequence). class Cropping2D: Cropping layer for 2D input (e.g. picture). class Cropping3D: Cropping layer for 3D data (e.g. spatial or spatio-temporal). class Dense: Just your regular densely-connected NN layer. class DenseFeatures: A layer that produces a dense Tensor based on given feature_columns. class DepthwiseConv2D: Depthwise separable 2D convolution. class Dot: Layer that computes a dot product between samples in two tensors. class Dropout: Applies Dropout to the input. class ELU: Exponential Linear Unit. class Embedding: Turns positive integers (indexes) into dense vectors of fixed size. class Flatten: Flattens the input. Does not affect the batch size. class GRU: Gated Recurrent Unit - Cho et al. 2014. class GRUCell: Cell class for the GRU layer. class GaussianDropout: Apply multiplicative 1-centered Gaussian noise. class GaussianNoise: Apply additive zero-centered Gaussian noise. class GlobalAveragePooling1D: Global average pooling operation for temporal data. class GlobalAveragePooling2D: Global average pooling operation for spatial data. class GlobalAveragePooling3D: Global Average pooling operation for 3D data. class GlobalAvgPool1D: Global average pooling operation for temporal data. class GlobalAvgPool2D: Global average pooling operation for spatial data. class GlobalAvgPool3D: Global Average pooling operation for 3D data. class GlobalMaxPool1D: Global max pooling operation for 1D temporal data. class GlobalMaxPool2D: Global max pooling operation for spatial data. class GlobalMaxPool3D: Global Max pooling operation for 3D data. class GlobalMaxPooling1D: Global max pooling operation for 1D temporal data. class GlobalMaxPooling2D: Global max pooling operation for spatial data. class GlobalMaxPooling3D: Global Max pooling operation for 3D data. class InputLayer: Layer to be used as an entry point into a Network (a graph of layers). class InputSpec: Specifies the rank, dtype and shape of every input to a layer. class LSTM: Long Short-Term Memory layer - Hochreiter 1997. class LSTMCell: Cell class for the LSTM layer. class Lambda: Wraps arbitrary expressions as a Layer object. class Layer: This is the class from which all layers inherit. class LayerNormalization: Layer normalization layer (Ba et al., 2016). class LeakyReLU: Leaky version of a Rectified Linear Unit. class LocallyConnected1D: Locally-connected layer for 1D inputs. class LocallyConnected2D: Locally-connected layer for 2D inputs. class Masking: Masks a sequence by using a mask value to skip timesteps. class MaxPool1D: Max pooling operation for 1D temporal data. class MaxPool2D: Max pooling operation for 2D spatial data. class MaxPool3D: Max pooling operation for 3D data (spatial or spatio-temporal). class MaxPooling1D: Max pooling operation for 1D temporal data. class MaxPooling2D: Max pooling operation for 2D spatial data. class MaxPooling3D: Max pooling operation for 3D data (spatial or spatio-temporal). class Maximum: Layer that computes the maximum (element-wise) a list of inputs. class Minimum: Layer that computes the minimum (element-wise) a list of inputs. class MultiHeadAttention: MultiHeadAttention layer. class Multiply: Layer that multiplies (element-wise) a list of inputs. class PReLU: Parametric Rectified Linear Unit. class Permute: Permutes the dimensions of the input according to a given pattern. class RNN: Base class for recurrent layers. class ReLU: Rectified Linear Unit activation function. class RepeatVector: Repeats the input n times. class Reshape: Layer that reshapes inputs into the given shape. class SeparableConv1D: Depthwise separable 1D convolution. class SeparableConv2D: Depthwise separable 2D convolution. class SeparableConvolution1D: Depthwise separable 1D convolution. class SeparableConvolution2D: Depthwise separable 2D convolution. class SimpleRNN: Fully-connected RNN where the output is to be fed back to input. class SimpleRNNCell: Cell class for SimpleRNN. class Softmax: Softmax activation function. class SpatialDropout1D: Spatial 1D version of Dropout. class SpatialDropout2D: Spatial 2D version of Dropout. class SpatialDropout3D: Spatial 3D version of Dropout. class StackedRNNCells: Wrapper allowing a stack of RNN cells to behave as a single cell. class Subtract: Layer that subtracts two inputs. class ThresholdedReLU: Thresholded Rectified Linear Unit. class TimeDistributed: This wrapper allows to apply a layer to every temporal slice of an input. class UpSampling1D: Upsampling layer for 1D inputs. class UpSampling2D: Upsampling layer for 2D inputs. class UpSampling3D: Upsampling layer for 3D inputs. class Wrapper: Abstract wrapper base class. class ZeroPadding1D: Zero-padding layer for 1D input (e.g. temporal sequence). class ZeroPadding2D: Zero-padding layer for 2D input (e.g. picture). class ZeroPadding3D: Zero-padding layer for 3D data (spatial or spatio-temporal). Functions Input(...): Input() is used to instantiate a Keras tensor. add(...): Functional interface to the tf.keras.layers.Add layer. average(...): Functional interface to the tf.keras.layers.Average layer. concatenate(...): Functional interface to the Concatenate layer. deserialize(...): Instantiates a layer from a config dictionary. dot(...): Functional interface to the Dot layer. maximum(...): Functional interface to compute maximum (element-wise) list of inputs. minimum(...): Functional interface to the Minimum layer. multiply(...): Functional interface to the Multiply layer. serialize(...) subtract(...): Functional interface to the Subtract layer.
tensorflow.keras.layers
tf.keras.layers.AbstractRNNCell View source on GitHub Abstract object representing an RNN cell. Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.AbstractRNNCell tf.keras.layers.AbstractRNNCell( trainable=True, name=None, dtype=None, dynamic=False, **kwargs ) See the Keras RNN API guide for details about the usage of RNN API. This is the base class for implementing RNN cells with custom behavior. Every RNNCell must have the properties below and implement call with the signature (output, next_state) = call(input, state). Examples: class MinimalRNNCell(AbstractRNNCell): def __init__(self, units, **kwargs): self.units = units super(MinimalRNNCell, self).__init__(**kwargs) @property def state_size(self): return self.units def build(self, input_shape): self.kernel = self.add_weight(shape=(input_shape[-1], self.units), initializer='uniform', name='kernel') self.recurrent_kernel = self.add_weight( shape=(self.units, self.units), initializer='uniform', name='recurrent_kernel') self.built = True def call(self, inputs, states): prev_output = states[0] h = K.dot(inputs, self.kernel) output = h + K.dot(prev_output, self.recurrent_kernel) return output, output This definition of cell differs from the definition used in the literature. In the literature, 'cell' refers to an object with a single scalar output. This definition refers to a horizontal array of such units. An RNN cell, in the most abstract setting, is anything that has a state and performs some operation that takes a matrix of inputs. This operation results in an output matrix with self.output_size columns. If self.state_size is an integer, this operation also results in a new state matrix with self.state_size columns. If self.state_size is a (possibly nested tuple of) TensorShape object(s), then it should return a matching structure of Tensors having shape [batch_size].concatenate(s) for each s in self.batch_size. Attributes output_size Integer or TensorShape: size of outputs produced by this cell. state_size size(s) of state(s) used by this cell. It can be represented by an Integer, a TensorShape or a tuple of Integers or TensorShapes. Methods get_initial_state View source get_initial_state( inputs=None, batch_size=None, dtype=None )
tensorflow.keras.layers.abstractrnncell
tf.keras.layers.Activation View source on GitHub Applies an activation function to an output. Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.Activation tf.keras.layers.Activation( activation, **kwargs ) Arguments activation Activation function, such as tf.nn.relu, or string name of built-in activation function, such as "relu". Usage: layer = tf.keras.layers.Activation('relu') output = layer([-3.0, -1.0, 0.0, 2.0]) list(output.numpy()) [0.0, 0.0, 0.0, 2.0] layer = tf.keras.layers.Activation(tf.nn.relu) output = layer([-3.0, -1.0, 0.0, 2.0]) list(output.numpy()) [0.0, 0.0, 0.0, 2.0] Input shape: Arbitrary. Use the keyword argument input_shape (tuple of integers, does not include the batch axis) when using this layer as the first layer in a model. Output shape: Same shape as input.
tensorflow.keras.layers.activation
tf.keras.layers.ActivityRegularization View source on GitHub Layer that applies an update to the cost function based input activity. Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.ActivityRegularization tf.keras.layers.ActivityRegularization( l1=0.0, l2=0.0, **kwargs ) Arguments l1 L1 regularization factor (positive float). l2 L2 regularization factor (positive float). Input shape: Arbitrary. Use the keyword argument input_shape (tuple of integers, does not include the samples axis) when using this layer as the first layer in a model. Output shape: Same shape as input.
tensorflow.keras.layers.activityregularization
tf.keras.layers.Add View source on GitHub Layer that adds a list of inputs. Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.Add tf.keras.layers.Add( **kwargs ) It takes as input a list of tensors, all of the same shape, and returns a single tensor (also of the same shape). Examples: input_shape = (2, 3, 4) x1 = tf.random.normal(input_shape) x2 = tf.random.normal(input_shape) y = tf.keras.layers.Add()([x1, x2]) print(y.shape) (2, 3, 4) Used in a functional model: input1 = tf.keras.layers.Input(shape=(16,)) x1 = tf.keras.layers.Dense(8, activation='relu')(input1) input2 = tf.keras.layers.Input(shape=(32,)) x2 = tf.keras.layers.Dense(8, activation='relu')(input2) # equivalent to `added = tf.keras.layers.add([x1, x2])` added = tf.keras.layers.Add()([x1, x2]) out = tf.keras.layers.Dense(4)(added) model = tf.keras.models.Model(inputs=[input1, input2], outputs=out) Arguments **kwargs standard layer keyword arguments.
tensorflow.keras.layers.add
tf.keras.layers.AdditiveAttention View source on GitHub Additive attention layer, a.k.a. Bahdanau-style attention. Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.AdditiveAttention tf.keras.layers.AdditiveAttention( use_scale=True, **kwargs ) Inputs are query tensor of shape [batch_size, Tq, dim], value tensor of shape [batch_size, Tv, dim] and key tensor of shape [batch_size, Tv, dim]. The calculation follows the steps: Reshape query and value into shapes [batch_size, Tq, 1, dim] and [batch_size, 1, Tv, dim] respectively. Calculate scores with shape [batch_size, Tq, Tv] as a non-linear sum: scores = tf.reduce_sum(tf.tanh(query + value), axis=-1) Use scores to calculate a distribution with shape [batch_size, Tq, Tv]: distribution = tf.nn.softmax(scores). Use distribution to create a linear combination of value with shape batch_size, Tq, dim]: return tf.matmul(distribution, value). Args use_scale If True, will create a variable to scale the attention scores. causal Boolean. Set to True for decoder self-attention. Adds a mask such that position i cannot attend to positions j > i. This prevents the flow of information from the future towards the past. dropout Float between 0 and 1. Fraction of the units to drop for the attention scores. Call Arguments: inputs: List of the following tensors: query: Query Tensor of shape [batch_size, Tq, dim]. value: Value Tensor of shape [batch_size, Tv, dim]. key: Optional key Tensor of shape [batch_size, Tv, dim]. If not given, will use value for both key and value, which is the most common case. mask: List of the following tensors: query_mask: A boolean mask Tensor of shape [batch_size, Tq]. If given, the output will be zero at the positions where mask==False. value_mask: A boolean mask Tensor of shape [batch_size, Tv]. If given, will apply the mask such that values at positions where mask==False do not contribute to the result. training: Python boolean indicating whether the layer should behave in training mode (adding dropout) or in inference mode (no dropout). return_attention_scores: bool, it True, returns the attention scores (after masking and softmax) as an additional output argument. Output: Attention outputs of shape [batch_size, Tq, dim]. [Optional] Attention scores after masking and softmax with shape [batch_size, Tq, Tv]. The meaning of query, value and key depend on the application. In the case of text similarity, for example, query is the sequence embeddings of the first piece of text and value is the sequence embeddings of the second piece of text. key is usually the same tensor as value. Here is a code example for using AdditiveAttention in a CNN+Attention network: # Variable-length int sequences. query_input = tf.keras.Input(shape=(None,), dtype='int32') value_input = tf.keras.Input(shape=(None,), dtype='int32') # Embedding lookup. token_embedding = tf.keras.layers.Embedding(max_tokens, dimension) # Query embeddings of shape [batch_size, Tq, dimension]. query_embeddings = token_embedding(query_input) # Value embeddings of shape [batch_size, Tv, dimension]. value_embeddings = token_embedding(value_input) # CNN layer. cnn_layer = tf.keras.layers.Conv1D( filters=100, kernel_size=4, # Use 'same' padding so outputs have the same shape as inputs. padding='same') # Query encoding of shape [batch_size, Tq, filters]. query_seq_encoding = cnn_layer(query_embeddings) # Value encoding of shape [batch_size, Tv, filters]. value_seq_encoding = cnn_layer(value_embeddings) # Query-value attention of shape [batch_size, Tq, filters]. query_value_attention_seq = tf.keras.layers.AdditiveAttention()( [query_seq_encoding, value_seq_encoding]) # Reduce over the sequence axis to produce encodings of shape # [batch_size, filters]. query_encoding = tf.keras.layers.GlobalAveragePooling1D()( query_seq_encoding) query_value_attention = tf.keras.layers.GlobalAveragePooling1D()( query_value_attention_seq) # Concatenate query and document encodings to produce a DNN input layer. input_layer = tf.keras.layers.Concatenate()( [query_encoding, query_value_attention]) # Add DNN layers, and create Model. # ...
tensorflow.keras.layers.additiveattention
tf.keras.layers.AlphaDropout View source on GitHub Applies Alpha Dropout to the input. Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.AlphaDropout tf.keras.layers.AlphaDropout( rate, noise_shape=None, seed=None, **kwargs ) Alpha Dropout is a Dropout that keeps mean and variance of inputs to their original values, in order to ensure the self-normalizing property even after this dropout. Alpha Dropout fits well to Scaled Exponential Linear Units by randomly setting activations to the negative saturation value. Arguments rate float, drop probability (as with Dropout). The multiplicative noise will have standard deviation sqrt(rate / (1 - rate)). seed A Python integer to use as random seed. Call arguments: inputs: Input tensor (of any rank). training: Python boolean indicating whether the layer should behave in training mode (adding dropout) or in inference mode (doing nothing). Input shape: Arbitrary. Use the keyword argument input_shape (tuple of integers, does not include the samples axis) when using this layer as the first layer in a model. Output shape: Same shape as input.
tensorflow.keras.layers.alphadropout
tf.keras.layers.Attention View source on GitHub Dot-product attention layer, a.k.a. Luong-style attention. Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.Attention tf.keras.layers.Attention( use_scale=False, **kwargs ) Inputs are query tensor of shape [batch_size, Tq, dim], value tensor of shape [batch_size, Tv, dim] and key tensor of shape [batch_size, Tv, dim]. The calculation follows the steps: Calculate scores with shape [batch_size, Tq, Tv] as a query-key dot product: scores = tf.matmul(query, key, transpose_b=True). Use scores to calculate a distribution with shape [batch_size, Tq, Tv]: distribution = tf.nn.softmax(scores). Use distribution to create a linear combination of value with shape [batch_size, Tq, dim]: return tf.matmul(distribution, value). Args use_scale If True, will create a scalar variable to scale the attention scores. causal Boolean. Set to True for decoder self-attention. Adds a mask such that position i cannot attend to positions j > i. This prevents the flow of information from the future towards the past. dropout Float between 0 and 1. Fraction of the units to drop for the attention scores. Call Arguments: inputs: List of the following tensors: query: Query Tensor of shape [batch_size, Tq, dim]. value: Value Tensor of shape [batch_size, Tv, dim]. key: Optional key Tensor of shape [batch_size, Tv, dim]. If not given, will use value for both key and value, which is the most common case. mask: List of the following tensors: query_mask: A boolean mask Tensor of shape [batch_size, Tq]. If given, the output will be zero at the positions where mask==False. value_mask: A boolean mask Tensor of shape [batch_size, Tv]. If given, will apply the mask such that values at positions where mask==False do not contribute to the result. return_attention_scores: bool, it True, returns the attention scores (after masking and softmax) as an additional output argument. training: Python boolean indicating whether the layer should behave in training mode (adding dropout) or in inference mode (no dropout). Output: Attention outputs of shape [batch_size, Tq, dim]. [Optional] Attention scores after masking and softmax with shape [batch_size, Tq, Tv]. The meaning of query, value and key depend on the application. In the case of text similarity, for example, query is the sequence embeddings of the first piece of text and value is the sequence embeddings of the second piece of text. key is usually the same tensor as value. Here is a code example for using Attention in a CNN+Attention network: # Variable-length int sequences. query_input = tf.keras.Input(shape=(None,), dtype='int32') value_input = tf.keras.Input(shape=(None,), dtype='int32') # Embedding lookup. token_embedding = tf.keras.layers.Embedding(input_dim=1000, output_dim=64) # Query embeddings of shape [batch_size, Tq, dimension]. query_embeddings = token_embedding(query_input) # Value embeddings of shape [batch_size, Tv, dimension]. value_embeddings = token_embedding(value_input) # CNN layer. cnn_layer = tf.keras.layers.Conv1D( filters=100, kernel_size=4, # Use 'same' padding so outputs have the same shape as inputs. padding='same') # Query encoding of shape [batch_size, Tq, filters]. query_seq_encoding = cnn_layer(query_embeddings) # Value encoding of shape [batch_size, Tv, filters]. value_seq_encoding = cnn_layer(value_embeddings) # Query-value attention of shape [batch_size, Tq, filters]. query_value_attention_seq = tf.keras.layers.Attention()( [query_seq_encoding, value_seq_encoding]) # Reduce over the sequence axis to produce encodings of shape # [batch_size, filters]. query_encoding = tf.keras.layers.GlobalAveragePooling1D()( query_seq_encoding) query_value_attention = tf.keras.layers.GlobalAveragePooling1D()( query_value_attention_seq) # Concatenate query and document encodings to produce a DNN input layer. input_layer = tf.keras.layers.Concatenate()( [query_encoding, query_value_attention]) # Add DNN layers, and create Model. # ...
tensorflow.keras.layers.attention
tf.keras.layers.Average View source on GitHub Layer that averages a list of inputs element-wise. Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.Average tf.keras.layers.Average( **kwargs ) It takes as input a list of tensors, all of the same shape, and returns a single tensor (also of the same shape). Example: x1 = np.ones((2, 2)) x2 = np.zeros((2, 2)) y = tf.keras.layers.Average()([x1, x2]) y.numpy().tolist() [[0.5, 0.5], [0.5, 0.5]] Usage in a functional model: input1 = tf.keras.layers.Input(shape=(16,)) x1 = tf.keras.layers.Dense(8, activation='relu')(input1) input2 = tf.keras.layers.Input(shape=(32,)) x2 = tf.keras.layers.Dense(8, activation='relu')(input2) avg = tf.keras.layers.Average()([x1, x2]) out = tf.keras.layers.Dense(4)(avg) model = tf.keras.models.Model(inputs=[input1, input2], outputs=out) Raises ValueError If there is a shape mismatch between the inputs and the shapes cannot be broadcasted to match. Arguments **kwargs standard layer keyword arguments.
tensorflow.keras.layers.average
tf.keras.layers.AveragePooling1D View source on GitHub Average pooling for temporal data. Inherits From: Layer, Module View aliases Main aliases tf.keras.layers.AvgPool1D Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.AveragePooling1D, tf.compat.v1.keras.layers.AvgPool1D tf.keras.layers.AveragePooling1D( pool_size=2, strides=None, padding='valid', data_format='channels_last', **kwargs ) Arguments pool_size Integer, size of the average pooling windows. strides Integer, or None. Factor by which to downscale. E.g. 2 will halve the input. If None, it will default to pool_size. padding One of "valid" or "same" (case-insensitive). "valid" means no padding. "same" results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. data_format A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch, steps, features) while channels_first corresponds to inputs with shape (batch, features, steps). Input shape: If data_format='channels_last': 3D tensor with shape (batch_size, steps, features). If data_format='channels_first': 3D tensor with shape (batch_size, features, steps). Output shape: If data_format='channels_last': 3D tensor with shape (batch_size, downsampled_steps, features). If data_format='channels_first': 3D tensor with shape (batch_size, features, downsampled_steps).
tensorflow.keras.layers.averagepooling1d
tf.keras.layers.AveragePooling2D View source on GitHub Average pooling operation for spatial data. Inherits From: Layer, Module View aliases Main aliases tf.keras.layers.AvgPool2D Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.AveragePooling2D, tf.compat.v1.keras.layers.AvgPool2D tf.keras.layers.AveragePooling2D( pool_size=(2, 2), strides=None, padding='valid', data_format=None, **kwargs ) Arguments pool_size integer or tuple of 2 integers, factors by which to downscale (vertical, horizontal). (2, 2) will halve the input in both spatial dimension. If only one integer is specified, the same window length will be used for both dimensions. strides Integer, tuple of 2 integers, or None. Strides values. If None, it will default to pool_size. padding One of "valid" or "same" (case-insensitive). "valid" means no padding. "same" results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. data_format A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch, height, width, channels) while channels_first corresponds to inputs with shape (batch, channels, height, width). It defaults to the image_data_format value found in your Keras config file at ~/.keras/keras.json. If you never set it, then it will be "channels_last". Input shape: If data_format='channels_last': 4D tensor with shape (batch_size, rows, cols, channels). If data_format='channels_first': 4D tensor with shape (batch_size, channels, rows, cols). Output shape: If data_format='channels_last': 4D tensor with shape (batch_size, pooled_rows, pooled_cols, channels). If data_format='channels_first': 4D tensor with shape (batch_size, channels, pooled_rows, pooled_cols).
tensorflow.keras.layers.averagepooling2d
tf.keras.layers.AveragePooling3D View source on GitHub Average pooling operation for 3D data (spatial or spatio-temporal). Inherits From: Layer, Module View aliases Main aliases tf.keras.layers.AvgPool3D Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.AveragePooling3D, tf.compat.v1.keras.layers.AvgPool3D tf.keras.layers.AveragePooling3D( pool_size=(2, 2, 2), strides=None, padding='valid', data_format=None, **kwargs ) Arguments pool_size tuple of 3 integers, factors by which to downscale (dim1, dim2, dim3). (2, 2, 2) will halve the size of the 3D input in each dimension. strides tuple of 3 integers, or None. Strides values. padding One of "valid" or "same" (case-insensitive). "valid" means no padding. "same" results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. data_format A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch, spatial_dim1, spatial_dim2, spatial_dim3, channels) while channels_first corresponds to inputs with shape (batch, channels, spatial_dim1, spatial_dim2, spatial_dim3). It defaults to the image_data_format value found in your Keras config file at ~/.keras/keras.json. If you never set it, then it will be "channels_last". Input shape: If data_format='channels_last': 5D tensor with shape: (batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels) If data_format='channels_first': 5D tensor with shape: (batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3) Output shape: If data_format='channels_last': 5D tensor with shape: (batch_size, pooled_dim1, pooled_dim2, pooled_dim3, channels) If data_format='channels_first': 5D tensor with shape: (batch_size, channels, pooled_dim1, pooled_dim2, pooled_dim3)
tensorflow.keras.layers.averagepooling3d
tf.keras.layers.BatchNormalization View source on GitHub Layer that normalizes its inputs. Inherits From: Layer, Module tf.keras.layers.BatchNormalization( axis=-1, momentum=0.99, epsilon=0.001, center=True, scale=True, beta_initializer='zeros', gamma_initializer='ones', moving_mean_initializer='zeros', moving_variance_initializer='ones', beta_regularizer=None, gamma_regularizer=None, beta_constraint=None, gamma_constraint=None, renorm=False, renorm_clipping=None, renorm_momentum=0.99, fused=None, trainable=True, virtual_batch_size=None, adjustment=None, name=None, **kwargs ) Batch normalization applies a transformation that maintains the mean output close to 0 and the output standard deviation close to 1. Importantly, batch normalization works differently during training and during inference. During training (i.e. when using fit() or when calling the layer/model with the argument training=True), the layer normalizes its output using the mean and standard deviation of the current batch of inputs. That is to say, for each channel being normalized, the layer returns (batch - mean(batch)) / (var(batch) + epsilon) * gamma + beta, where: epsilon is small constant (configurable as part of the constructor arguments) gamma is a learned scaling factor (initialized as 1), which can be disabled by passing scale=False to the constructor. beta is a learned offset factor (initialized as 0), which can be disabled by passing center=False to the constructor. During inference (i.e. when using evaluate() or predict() or when calling the layer/model with the argument training=False (which is the default), the layer normalizes its output using a moving average of the mean and standard deviation of the batches it has seen during training. That is to say, it returns (batch - self.moving_mean) / (self.moving_var + epsilon) * gamma + beta. self.moving_mean and self.moving_var are non-trainable variables that are updated each time the layer in called in training mode, as such: moving_mean = moving_mean * momentum + mean(batch) * (1 - momentum) moving_var = moving_var * momentum + var(batch) * (1 - momentum) As such, the layer will only normalize its inputs during inference after having been trained on data that has similar statistics as the inference data. Arguments axis Integer or a list of integers, the axis that should be normalized (typically the features axis). For instance, after a Conv2D layer with data_format="channels_first", set axis=1 in BatchNormalization. momentum Momentum for the moving average. epsilon Small float added to variance to avoid dividing by zero. center If True, add offset of beta to normalized tensor. If False, beta is ignored. scale If True, multiply by gamma. If False, gamma is not used. When the next layer is linear (also e.g. nn.relu), this can be disabled since the scaling will be done by the next layer. beta_initializer Initializer for the beta weight. gamma_initializer Initializer for the gamma weight. moving_mean_initializer Initializer for the moving mean. moving_variance_initializer Initializer for the moving variance. beta_regularizer Optional regularizer for the beta weight. gamma_regularizer Optional regularizer for the gamma weight. beta_constraint Optional constraint for the beta weight. gamma_constraint Optional constraint for the gamma weight. renorm Whether to use Batch Renormalization. This adds extra variables during training. The inference is the same for either value of this parameter. renorm_clipping A dictionary that may map keys 'rmax', 'rmin', 'dmax' to scalar Tensors used to clip the renorm correction. The correction (r, d) is used as corrected_value = normalized_value * r + d, with r clipped to [rmin, rmax], and d to [-dmax, dmax]. Missing rmax, rmin, dmax are set to inf, 0, inf, respectively. renorm_momentum Momentum used to update the moving means and standard deviations with renorm. Unlike momentum, this affects training and should be neither too small (which would add noise) nor too large (which would give stale estimates). Note that momentum is still applied to get the means and variances for inference. fused if True, use a faster, fused implementation, or raise a ValueError if the fused implementation cannot be used. If None, use the faster implementation if possible. If False, do not used the fused implementation. trainable Boolean, if True the variables will be marked as trainable. virtual_batch_size An int. By default, virtual_batch_size is None, which means batch normalization is performed across the whole batch. When virtual_batch_size is not None, instead perform "Ghost Batch Normalization", which creates virtual sub-batches which are each normalized separately (with shared gamma, beta, and moving statistics). Must divide the actual batch size during execution. adjustment A function taking the Tensor containing the (dynamic) shape of the input tensor and returning a pair (scale, bias) to apply to the normalized values (before gamma and beta), only during training. For example, if axis==-1, adjustment = lambda shape: ( tf.random.uniform(shape[-1:], 0.93, 1.07), tf.random.uniform(shape[-1:], -0.1, 0.1)) will scale the normalized value by up to 7% up or down, then shift the result by up to 0.1 (with independent scaling and bias for each feature but shared across all examples), and finally apply gamma and/or beta. If None, no adjustment is applied. Cannot be specified if virtual_batch_size is specified. Call arguments: inputs: Input tensor (of any rank). training: Python boolean indicating whether the layer should behave in training mode or in inference mode. training=True: The layer will normalize its inputs using the mean and variance of the current batch of inputs. training=False: The layer will normalize its inputs using the mean and variance of its moving statistics, learned during training. Input shape: Arbitrary. Use the keyword argument input_shape (tuple of integers, does not include the samples axis) when using this layer as the first layer in a model. Output shape: Same shape as input. About setting layer.trainable = False on a BatchNormalization layer: The meaning of setting layer.trainable = False is to freeze the layer, i.e. its internal state will not change during training: its trainable weights will not be updated during fit() or train_on_batch(), and its state updates will not be run. Usually, this does not necessarily mean that the layer is run in inference mode (which is normally controlled by the training argument that can be passed when calling a layer). "Frozen state" and "inference mode" are two separate concepts. However, in the case of the BatchNormalization layer, setting trainable = False on the layer means that the layer will be subsequently run in inference mode (meaning that it will use the moving mean and the moving variance to normalize the current batch, rather than using the mean and variance of the current batch). This behavior has been introduced in TensorFlow 2.0, in order to enable layer.trainable = False to produce the most commonly expected behavior in the convnet fine-tuning use case. Note that: This behavior only occurs as of TensorFlow 2.0. In 1.*, setting layer.trainable = False would freeze the layer but would not switch it to inference mode. Setting trainable on an model containing other layers will recursively set the trainable value of all inner layers. If the value of the trainable attribute is changed after calling compile() on a model, the new value doesn't take effect for this model until compile() is called again. Reference: Ioffe and Szegedy, 2015.
tensorflow.keras.layers.batchnormalization
tf.keras.layers.Bidirectional View source on GitHub Bidirectional wrapper for RNNs. Inherits From: Wrapper, Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.Bidirectional tf.keras.layers.Bidirectional( layer, merge_mode='concat', weights=None, backward_layer=None, **kwargs ) Arguments layer keras.layers.RNN instance, such as keras.layers.LSTM or keras.layers.GRU. It could also be a keras.layers.Layer instance that meets the following criteria: Be a sequence-processing layer (accepts 3D+ inputs). Have a go_backwards, return_sequences and return_state attribute (with the same semantics as for the RNN class). Have an input_spec attribute. Implement serialization via get_config() and from_config(). Note that the recommended way to create new RNN layers is to write a custom RNN cell and use it with keras.layers.RNN, instead of subclassing keras.layers.Layer directly. merge_mode Mode by which outputs of the forward and backward RNNs will be combined. One of {'sum', 'mul', 'concat', 'ave', None}. If None, the outputs will not be combined, they will be returned as a list. Default value is 'concat'. backward_layer Optional keras.layers.RNN, or keras.layers.Layer instance to be used to handle backwards input processing. If backward_layer is not provided, the layer instance passed as the layer argument will be used to generate the backward layer automatically. Note that the provided backward_layer layer should have properties matching those of the layer argument, in particular it should have the same values for stateful, return_states, return_sequence, etc. In addition, backward_layer and layer should have different go_backwards argument values. A ValueError will be raised if these requirements are not met. Call arguments: The call arguments for this layer are the same as those of the wrapped RNN layer. Beware that when passing the initial_state argument during the call of this layer, the first half in the list of elements in the initial_state list will be passed to the forward RNN call and the last half in the list of elements will be passed to the backward RNN call. Raises ValueError If layer or backward_layer is not a Layer instance. In case of invalid merge_mode argument. If backward_layer has mismatched properties compared to layer. Examples: model = Sequential() model.add(Bidirectional(LSTM(10, return_sequences=True), input_shape=(5, 10))) model.add(Bidirectional(LSTM(10))) model.add(Dense(5)) model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer='rmsprop') # With custom backward layer model = Sequential() forward_layer = LSTM(10, return_sequences=True) backward_layer = LSTM(10, activation='relu', return_sequences=True, go_backwards=True) model.add(Bidirectional(forward_layer, backward_layer=backward_layer, input_shape=(5, 10))) model.add(Dense(5)) model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer='rmsprop') Attributes constraints Methods reset_states View source reset_states()
tensorflow.keras.layers.bidirectional
tf.keras.layers.Concatenate View source on GitHub Layer that concatenates a list of inputs. Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.Concatenate tf.keras.layers.Concatenate( axis=-1, **kwargs ) It takes as input a list of tensors, all of the same shape except for the concatenation axis, and returns a single tensor that is the concatenation of all inputs. x = np.arange(20).reshape(2, 2, 5) print(x) [[[ 0 1 2 3 4] [ 5 6 7 8 9]] [[10 11 12 13 14] [15 16 17 18 19]]] y = np.arange(20, 30).reshape(2, 1, 5) print(y) [[[20 21 22 23 24]] [[25 26 27 28 29]]] tf.keras.layers.Concatenate(axis=1)([x, y]) <tf.Tensor: shape=(2, 3, 5), dtype=int64, numpy= array([[[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [20, 21, 22, 23, 24]], [[10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [25, 26, 27, 28, 29]]])> x1 = tf.keras.layers.Dense(8)(np.arange(10).reshape(5, 2)) x2 = tf.keras.layers.Dense(8)(np.arange(10, 20).reshape(5, 2)) concatted = tf.keras.layers.Concatenate()([x1, x2]) concatted.shape TensorShape([5, 16]) Arguments axis Axis along which to concatenate. **kwargs standard layer keyword arguments.
tensorflow.keras.layers.concatenate
tf.keras.layers.Conv1D View source on GitHub 1D convolution layer (e.g. temporal convolution). Inherits From: Layer, Module View aliases Main aliases tf.keras.layers.Convolution1D Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.Conv1D, tf.compat.v1.keras.layers.Convolution1D tf.keras.layers.Conv1D( filters, kernel_size, strides=1, padding='valid', data_format='channels_last', dilation_rate=1, groups=1, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs ) This layer creates a convolution kernel that is convolved with the layer input over a single spatial (or temporal) dimension to produce a tensor of outputs. If use_bias is True, a bias vector is created and added to the outputs. Finally, if activation is not None, it is applied to the outputs as well. When using this layer as the first layer in a model, provide an input_shape argument (tuple of integers or None, e.g. (10, 128) for sequences of 10 vectors of 128-dimensional vectors, or (None, 128) for variable-length sequences of 128-dimensional vectors. Examples: # The inputs are 128-length vectors with 10 timesteps, and the batch size # is 4. input_shape = (4, 10, 128) x = tf.random.normal(input_shape) y = tf.keras.layers.Conv1D( 32, 3, activation='relu',input_shape=input_shape[1:])(x) print(y.shape) (4, 8, 32) # With extended batch shape [4, 7] (e.g. weather data where batch # dimensions correspond to spatial location and the third dimension # corresponds to time.) input_shape = (4, 7, 10, 128) x = tf.random.normal(input_shape) y = tf.keras.layers.Conv1D( 32, 3, activation='relu', input_shape=input_shape[2:])(x) print(y.shape) (4, 7, 8, 32) Arguments filters Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution). kernel_size An integer or tuple/list of a single integer, specifying the length of the 1D convolution window. strides An integer or tuple/list of a single integer, specifying the stride length of the convolution. Specifying any stride value != 1 is incompatible with specifying any dilation_rate value != 1. padding One of "valid", "same" or "causal" (case-insensitive). "valid" means no padding. "same" results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. "causal" results in causal (dilated) convolutions, e.g. output[t] does not depend on input[t+1:]. Useful when modeling temporal data where the model should not violate the temporal order. See WaveNet: A Generative Model for Raw Audio, section 2.1. data_format A string, one of channels_last (default) or channels_first. dilation_rate an integer or tuple/list of a single integer, specifying the dilation rate to use for dilated convolution. Currently, specifying any dilation_rate value != 1 is incompatible with specifying any strides value != 1. groups A positive integer specifying the number of groups in which the input is split along the channel axis. Each group is convolved separately with filters / groups filters. The output is the concatenation of all the groups results along the channel axis. Input channels and filters must both be divisible by groups. activation Activation function to use. If you don't specify anything, no activation is applied ( see keras.activations). use_bias Boolean, whether the layer uses a bias vector. kernel_initializer Initializer for the kernel weights matrix ( see keras.initializers). bias_initializer Initializer for the bias vector ( see keras.initializers). kernel_regularizer Regularizer function applied to the kernel weights matrix (see keras.regularizers). bias_regularizer Regularizer function applied to the bias vector ( see keras.regularizers). activity_regularizer Regularizer function applied to the output of the layer (its "activation") ( see keras.regularizers). kernel_constraint Constraint function applied to the kernel matrix ( see keras.constraints). bias_constraint Constraint function applied to the bias vector ( see keras.constraints). Input shape: 3+D tensor with shape: batch_shape + (steps, input_dim) Output shape: 3+D tensor with shape: batch_shape + (new_steps, filters) steps value might have changed due to padding or strides. Returns A tensor of rank 3 representing activation(conv1d(inputs, kernel) + bias). Raises ValueError when both strides > 1 and dilation_rate > 1.
tensorflow.keras.layers.conv1d
tf.keras.layers.Conv1DTranspose Transposed convolution layer (sometimes called Deconvolution). Inherits From: Conv1D, Layer, Module View aliases Main aliases tf.keras.layers.Convolution1DTranspose Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.Conv1DTranspose, tf.compat.v1.keras.layers.Convolution1DTranspose tf.keras.layers.Conv1DTranspose( filters, kernel_size, strides=1, padding='valid', output_padding=None, data_format=None, dilation_rate=1, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs ) The need for transposed convolutions generally arises from the desire to use a transformation going in the opposite direction of a normal convolution, i.e., from something that has the shape of the output of some convolution to something that has the shape of its input while maintaining a connectivity pattern that is compatible with said convolution. When using this layer as the first layer in a model, provide the keyword argument input_shape (tuple of integers, does not include the sample axis), e.g. input_shape=(128, 3) for data with 128 time steps and 3 channels. Arguments filters Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution). kernel_size An integer length of the 1D convolution window. strides An integer specifying the stride of the convolution along the time dimension. Specifying a stride value != 1 is incompatible with specifying a dilation_rate value != 1. Defaults to 1. padding one of "valid" or "same" (case-insensitive). "valid" means no padding. "same" results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. output_padding An integer specifying the amount of padding along the time dimension of the output tensor. The amount of output padding must be lower than the stride. If set to None (default), the output shape is inferred. data_format A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, length, channels) while channels_first corresponds to inputs with shape (batch_size, channels, length). dilation_rate an integer, specifying the dilation rate to use for dilated convolution. Currently, specifying a dilation_rate value != 1 is incompatible with specifying a stride value != 1. Also dilation rate larger than 1 is not currently supported. activation Activation function to use. If you don't specify anything, no activation is applied ( see keras.activations). use_bias Boolean, whether the layer uses a bias vector. kernel_initializer Initializer for the kernel weights matrix ( see keras.initializers). bias_initializer Initializer for the bias vector ( see keras.initializers). kernel_regularizer Regularizer function applied to the kernel weights matrix (see keras.regularizers). bias_regularizer Regularizer function applied to the bias vector ( see keras.regularizers). activity_regularizer Regularizer function applied to the output of the layer (its "activation") (see keras.regularizers). kernel_constraint Constraint function applied to the kernel matrix ( see keras.constraints). bias_constraint Constraint function applied to the bias vector ( see keras.constraints). Input shape: 3D tensor with shape: (batch_size, steps, channels) Output shape: 3D tensor with shape: (batch_size, new_steps, filters) If output_padding is specified: new_timesteps = ((timesteps - 1) * strides + kernel_size - 2 * padding + output_padding) Returns A tensor of rank 3 representing activation(conv1dtranspose(inputs, kernel) + bias). Raises ValueError if padding is "causal". ValueError when both strides > 1 and dilation_rate > 1. References: A guide to convolution arithmetic for deep learning Deconvolutional Networks
tensorflow.keras.layers.conv1dtranspose
tf.keras.layers.Conv2D View source on GitHub 2D convolution layer (e.g. spatial convolution over images). Inherits From: Layer, Module View aliases Main aliases tf.keras.layers.Convolution2D Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.Conv2D, tf.compat.v1.keras.layers.Convolution2D tf.keras.layers.Conv2D( filters, kernel_size, strides=(1, 1), padding='valid', data_format=None, dilation_rate=(1, 1), groups=1, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs ) This layer creates a convolution kernel that is convolved with the layer input to produce a tensor of outputs. If use_bias is True, a bias vector is created and added to the outputs. Finally, if activation is not None, it is applied to the outputs as well. When using this layer as the first layer in a model, provide the keyword argument input_shape (tuple of integers, does not include the sample axis), e.g. input_shape=(128, 128, 3) for 128x128 RGB pictures in data_format="channels_last". Examples: # The inputs are 28x28 RGB images with `channels_last` and the batch # size is 4. input_shape = (4, 28, 28, 3) x = tf.random.normal(input_shape) y = tf.keras.layers.Conv2D( 2, 3, activation='relu', input_shape=input_shape[1:])(x) print(y.shape) (4, 26, 26, 2) # With `dilation_rate` as 2. input_shape = (4, 28, 28, 3) x = tf.random.normal(input_shape) y = tf.keras.layers.Conv2D( 2, 3, activation='relu', dilation_rate=2, input_shape=input_shape[1:])(x) print(y.shape) (4, 24, 24, 2) # With `padding` as "same". input_shape = (4, 28, 28, 3) x = tf.random.normal(input_shape) y = tf.keras.layers.Conv2D( 2, 3, activation='relu', padding="same", input_shape=input_shape[1:])(x) print(y.shape) (4, 28, 28, 2) # With extended batch shape [4, 7]: input_shape = (4, 7, 28, 28, 3) x = tf.random.normal(input_shape) y = tf.keras.layers.Conv2D( 2, 3, activation='relu', input_shape=input_shape[2:])(x) print(y.shape) (4, 7, 26, 26, 2) Arguments filters Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution). kernel_size An integer or tuple/list of 2 integers, specifying the height and width of the 2D convolution window. Can be a single integer to specify the same value for all spatial dimensions. strides An integer or tuple/list of 2 integers, specifying the strides of the convolution along the height and width. Can be a single integer to specify the same value for all spatial dimensions. Specifying any stride value != 1 is incompatible with specifying any dilation_rate value != 1. padding one of "valid" or "same" (case-insensitive). "valid" means no padding. "same" results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. data_format A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, height, width, channels) while channels_first corresponds to inputs with shape (batch_size, channels, height, width). It defaults to the image_data_format value found in your Keras config file at ~/.keras/keras.json. If you never set it, then it will be channels_last. dilation_rate an integer or tuple/list of 2 integers, specifying the dilation rate to use for dilated convolution. Can be a single integer to specify the same value for all spatial dimensions. Currently, specifying any dilation_rate value != 1 is incompatible with specifying any stride value != 1. groups A positive integer specifying the number of groups in which the input is split along the channel axis. Each group is convolved separately with filters / groups filters. The output is the concatenation of all the groups results along the channel axis. Input channels and filters must both be divisible by groups. activation Activation function to use. If you don't specify anything, no activation is applied (see keras.activations). use_bias Boolean, whether the layer uses a bias vector. kernel_initializer Initializer for the kernel weights matrix (see keras.initializers). bias_initializer Initializer for the bias vector (see keras.initializers). kernel_regularizer Regularizer function applied to the kernel weights matrix (see keras.regularizers). bias_regularizer Regularizer function applied to the bias vector (see keras.regularizers). activity_regularizer Regularizer function applied to the output of the layer (its "activation") (see keras.regularizers). kernel_constraint Constraint function applied to the kernel matrix (see keras.constraints). bias_constraint Constraint function applied to the bias vector (see keras.constraints). Input shape: 4+D tensor with shape: batch_shape + (channels, rows, cols) if data_format='channels_first' or 4+D tensor with shape: batch_shape + (rows, cols, channels) if data_format='channels_last'. Output shape: 4+D tensor with shape: batch_shape + (filters, new_rows, new_cols) if data_format='channels_first' or 4+D tensor with shape: batch_shape + (new_rows, new_cols, filters) if data_format='channels_last'. rows and cols values might have changed due to padding. Returns A tensor of rank 4+ representing activation(conv2d(inputs, kernel) + bias). Raises ValueError if padding is "causal". ValueError when both strides > 1 and dilation_rate > 1.
tensorflow.keras.layers.conv2d
tf.keras.layers.Conv2DTranspose View source on GitHub Transposed convolution layer (sometimes called Deconvolution). Inherits From: Conv2D, Layer, Module View aliases Main aliases tf.keras.layers.Convolution2DTranspose Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.Conv2DTranspose, tf.compat.v1.keras.layers.Convolution2DTranspose tf.keras.layers.Conv2DTranspose( filters, kernel_size, strides=(1, 1), padding='valid', output_padding=None, data_format=None, dilation_rate=(1, 1), activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs ) The need for transposed convolutions generally arises from the desire to use a transformation going in the opposite direction of a normal convolution, i.e., from something that has the shape of the output of some convolution to something that has the shape of its input while maintaining a connectivity pattern that is compatible with said convolution. When using this layer as the first layer in a model, provide the keyword argument input_shape (tuple of integers, does not include the sample axis), e.g. input_shape=(128, 128, 3) for 128x128 RGB pictures in data_format="channels_last". Arguments filters Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution). kernel_size An integer or tuple/list of 2 integers, specifying the height and width of the 2D convolution window. Can be a single integer to specify the same value for all spatial dimensions. strides An integer or tuple/list of 2 integers, specifying the strides of the convolution along the height and width. Can be a single integer to specify the same value for all spatial dimensions. Specifying any stride value != 1 is incompatible with specifying any dilation_rate value != 1. padding one of "valid" or "same" (case-insensitive). "valid" means no padding. "same" results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. output_padding An integer or tuple/list of 2 integers, specifying the amount of padding along the height and width of the output tensor. Can be a single integer to specify the same value for all spatial dimensions. The amount of output padding along a given dimension must be lower than the stride along that same dimension. If set to None (default), the output shape is inferred. data_format A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, height, width, channels) while channels_first corresponds to inputs with shape (batch_size, channels, height, width). It defaults to the image_data_format value found in your Keras config file at ~/.keras/keras.json. If you never set it, then it will be "channels_last". dilation_rate an integer or tuple/list of 2 integers, specifying the dilation rate to use for dilated convolution. Can be a single integer to specify the same value for all spatial dimensions. Currently, specifying any dilation_rate value != 1 is incompatible with specifying any stride value != 1. activation Activation function to use. If you don't specify anything, no activation is applied ( see keras.activations). use_bias Boolean, whether the layer uses a bias vector. kernel_initializer Initializer for the kernel weights matrix ( see keras.initializers). bias_initializer Initializer for the bias vector ( see keras.initializers). kernel_regularizer Regularizer function applied to the kernel weights matrix (see keras.regularizers). bias_regularizer Regularizer function applied to the bias vector ( see keras.regularizers). activity_regularizer Regularizer function applied to the output of the layer (its "activation") (see keras.regularizers). kernel_constraint Constraint function applied to the kernel matrix ( see keras.constraints). bias_constraint Constraint function applied to the bias vector ( see keras.constraints). Input shape: 4D tensor with shape: (batch_size, channels, rows, cols) if data_format='channels_first' or 4D tensor with shape: (batch_size, rows, cols, channels) if data_format='channels_last'. Output shape: 4D tensor with shape: (batch_size, filters, new_rows, new_cols) if data_format='channels_first' or 4D tensor with shape: (batch_size, new_rows, new_cols, filters) if data_format='channels_last'. rows and cols values might have changed due to padding. If output_padding is specified: new_rows = ((rows - 1) * strides[0] + kernel_size[0] - 2 * padding[0] + output_padding[0]) new_cols = ((cols - 1) * strides[1] + kernel_size[1] - 2 * padding[1] + output_padding[1]) Returns A tensor of rank 4 representing activation(conv2dtranspose(inputs, kernel) + bias). Raises ValueError if padding is "causal". ValueError when both strides > 1 and dilation_rate > 1. References: A guide to convolution arithmetic for deep learning Deconvolutional Networks
tensorflow.keras.layers.conv2dtranspose
tf.keras.layers.Conv3D View source on GitHub 3D convolution layer (e.g. spatial convolution over volumes). Inherits From: Layer, Module View aliases Main aliases tf.keras.layers.Convolution3D Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.Conv3D, tf.compat.v1.keras.layers.Convolution3D tf.keras.layers.Conv3D( filters, kernel_size, strides=(1, 1, 1), padding='valid', data_format=None, dilation_rate=(1, 1, 1), groups=1, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs ) This layer creates a convolution kernel that is convolved with the layer input to produce a tensor of outputs. If use_bias is True, a bias vector is created and added to the outputs. Finally, if activation is not None, it is applied to the outputs as well. When using this layer as the first layer in a model, provide the keyword argument input_shape (tuple of integers, does not include the sample axis), e.g. input_shape=(128, 128, 128, 1) for 128x128x128 volumes with a single channel, in data_format="channels_last". Examples: # The inputs are 28x28x28 volumes with a single channel, and the # batch size is 4 input_shape =(4, 28, 28, 28, 1) x = tf.random.normal(input_shape) y = tf.keras.layers.Conv3D( 2, 3, activation='relu', input_shape=input_shape[1:])(x) print(y.shape) (4, 26, 26, 26, 2) # With extended batch shape [4, 7], e.g. a batch of 4 videos of 3D frames, # with 7 frames per video. input_shape = (4, 7, 28, 28, 28, 1) x = tf.random.normal(input_shape) y = tf.keras.layers.Conv3D( 2, 3, activation='relu', input_shape=input_shape[2:])(x) print(y.shape) (4, 7, 26, 26, 26, 2) Arguments filters Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution). kernel_size An integer or tuple/list of 3 integers, specifying the depth, height and width of the 3D convolution window. Can be a single integer to specify the same value for all spatial dimensions. strides An integer or tuple/list of 3 integers, specifying the strides of the convolution along each spatial dimension. Can be a single integer to specify the same value for all spatial dimensions. Specifying any stride value != 1 is incompatible with specifying any dilation_rate value != 1. padding one of "valid" or "same" (case-insensitive). "valid" means no padding. "same" results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. data_format A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape batch_shape + (spatial_dim1, spatial_dim2, spatial_dim3, channels) while channels_first corresponds to inputs with shape batch_shape + (channels, spatial_dim1, spatial_dim2, spatial_dim3). It defaults to the image_data_format value found in your Keras config file at ~/.keras/keras.json. If you never set it, then it will be "channels_last". dilation_rate an integer or tuple/list of 3 integers, specifying the dilation rate to use for dilated convolution. Can be a single integer to specify the same value for all spatial dimensions. Currently, specifying any dilation_rate value != 1 is incompatible with specifying any stride value != 1. groups A positive integer specifying the number of groups in which the input is split along the channel axis. Each group is convolved separately with filters / groups filters. The output is the concatenation of all the groups results along the channel axis. Input channels and filters must both be divisible by groups. activation Activation function to use. If you don't specify anything, no activation is applied (see keras.activations). use_bias Boolean, whether the layer uses a bias vector. kernel_initializer Initializer for the kernel weights matrix (see keras.initializers). bias_initializer Initializer for the bias vector (see keras.initializers). kernel_regularizer Regularizer function applied to the kernel weights matrix (see keras.regularizers). bias_regularizer Regularizer function applied to the bias vector (see keras.regularizers). activity_regularizer Regularizer function applied to the output of the layer (its "activation") (see keras.regularizers). kernel_constraint Constraint function applied to the kernel matrix (see keras.constraints). bias_constraint Constraint function applied to the bias vector (see keras.constraints). Input shape: 5+D tensor with shape: batch_shape + (channels, conv_dim1, conv_dim2, conv_dim3) if data_format='channels_first' or 5+D tensor with shape: batch_shape + (conv_dim1, conv_dim2, conv_dim3, channels) if data_format='channels_last'. Output shape: 5+D tensor with shape: batch_shape + (filters, new_conv_dim1, new_conv_dim2, new_conv_dim3) if data_format='channels_first' or 5+D tensor with shape: batch_shape + (new_conv_dim1, new_conv_dim2, new_conv_dim3, filters) if data_format='channels_last'. new_conv_dim1, new_conv_dim2 and new_conv_dim3 values might have changed due to padding. Returns A tensor of rank 5+ representing activation(conv3d(inputs, kernel) + bias). Raises ValueError if padding is "causal". ValueError when both strides > 1 and dilation_rate > 1.
tensorflow.keras.layers.conv3d
tf.keras.layers.Conv3DTranspose View source on GitHub Transposed convolution layer (sometimes called Deconvolution). Inherits From: Conv3D, Layer, Module View aliases Main aliases tf.keras.layers.Convolution3DTranspose Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.Conv3DTranspose, tf.compat.v1.keras.layers.Convolution3DTranspose tf.keras.layers.Conv3DTranspose( filters, kernel_size, strides=(1, 1, 1), padding='valid', output_padding=None, data_format=None, dilation_rate=(1, 1, 1), activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs ) The need for transposed convolutions generally arises from the desire to use a transformation going in the opposite direction of a normal convolution, i.e., from something that has the shape of the output of some convolution to something that has the shape of its input while maintaining a connectivity pattern that is compatible with said convolution. When using this layer as the first layer in a model, provide the keyword argument input_shape (tuple of integers, does not include the sample axis), e.g. input_shape=(128, 128, 128, 3) for a 128x128x128 volume with 3 channels if data_format="channels_last". Arguments filters Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution). kernel_size An integer or tuple/list of 3 integers, specifying the depth, height and width of the 3D convolution window. Can be a single integer to specify the same value for all spatial dimensions. strides An integer or tuple/list of 3 integers, specifying the strides of the convolution along the depth, height and width. Can be a single integer to specify the same value for all spatial dimensions. Specifying any stride value != 1 is incompatible with specifying any dilation_rate value != 1. padding one of "valid" or "same" (case-insensitive). "valid" means no padding. "same" results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. output_padding An integer or tuple/list of 3 integers, specifying the amount of padding along the depth, height, and width. Can be a single integer to specify the same value for all spatial dimensions. The amount of output padding along a given dimension must be lower than the stride along that same dimension. If set to None (default), the output shape is inferred. data_format A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, depth, height, width, channels) while channels_first corresponds to inputs with shape (batch_size, channels, depth, height, width). It defaults to the image_data_format value found in your Keras config file at ~/.keras/keras.json. If you never set it, then it will be "channels_last". dilation_rate an integer or tuple/list of 3 integers, specifying the dilation rate to use for dilated convolution. Can be a single integer to specify the same value for all spatial dimensions. Currently, specifying any dilation_rate value != 1 is incompatible with specifying any stride value != 1. activation Activation function to use. If you don't specify anything, no activation is applied ( see keras.activations). use_bias Boolean, whether the layer uses a bias vector. kernel_initializer Initializer for the kernel weights matrix. bias_initializer Initializer for the bias vector. kernel_regularizer Regularizer function applied to the kernel weights matrix ( see keras.regularizers). bias_regularizer Regularizer function applied to the bias vector ( see keras.regularizers). activity_regularizer Regularizer function applied to the output of the layer (its "activation") ( see keras.regularizers). kernel_constraint Constraint function applied to the kernel matrix ( see keras.constraints). bias_constraint Constraint function applied to the bias vector ( see keras.constraints). Input shape: 5D tensor with shape: (batch_size, channels, depth, rows, cols) if data_format='channels_first' or 5D tensor with shape: (batch_size, depth, rows, cols, channels) if data_format='channels_last'. Output shape: 5D tensor with shape: (batch_size, filters, new_depth, new_rows, new_cols) if data_format='channels_first' or 5D tensor with shape: (batch_size, new_depth, new_rows, new_cols, filters) if data_format='channels_last'. depth and rows and cols values might have changed due to padding. If output_padding is specified:: new_depth = ((depth - 1) * strides[0] + kernel_size[0] - 2 * padding[0] + output_padding[0]) new_rows = ((rows - 1) * strides[1] + kernel_size[1] - 2 * padding[1] + output_padding[1]) new_cols = ((cols - 1) * strides[2] + kernel_size[2] - 2 * padding[2] + output_padding[2]) Returns A tensor of rank 5 representing activation(conv3dtranspose(inputs, kernel) + bias). Raises ValueError if padding is "causal". ValueError when both strides > 1 and dilation_rate > 1. References: A guide to convolution arithmetic for deep learning Deconvolutional Networks
tensorflow.keras.layers.conv3dtranspose
tf.keras.layers.ConvLSTM2D View source on GitHub Convolutional LSTM. Inherits From: RNN, Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.ConvLSTM2D tf.keras.layers.ConvLSTM2D( filters, kernel_size, strides=(1, 1), padding='valid', data_format=None, dilation_rate=(1, 1), activation='tanh', recurrent_activation='hard_sigmoid', use_bias=True, kernel_initializer='glorot_uniform', recurrent_initializer='orthogonal', bias_initializer='zeros', unit_forget_bias=True, kernel_regularizer=None, recurrent_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, recurrent_constraint=None, bias_constraint=None, return_sequences=False, return_state=False, go_backwards=False, stateful=False, dropout=0.0, recurrent_dropout=0.0, **kwargs ) It is similar to an LSTM layer, but the input transformations and recurrent transformations are both convolutional. Arguments filters Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution). kernel_size An integer or tuple/list of n integers, specifying the dimensions of the convolution window. strides An integer or tuple/list of n integers, specifying the strides of the convolution. Specifying any stride value != 1 is incompatible with specifying any dilation_rate value != 1. padding One of "valid" or "same" (case-insensitive). "valid" means no padding. "same" results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. data_format A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch, time, ..., channels) while channels_first corresponds to inputs with shape (batch, time, channels, ...). It defaults to the image_data_format value found in your Keras config file at ~/.keras/keras.json. If you never set it, then it will be "channels_last". dilation_rate An integer or tuple/list of n integers, specifying the dilation rate to use for dilated convolution. Currently, specifying any dilation_rate value != 1 is incompatible with specifying any strides value != 1. activation Activation function to use. By default hyperbolic tangent activation function is applied (tanh(x)). recurrent_activation Activation function to use for the recurrent step. use_bias Boolean, whether the layer uses a bias vector. kernel_initializer Initializer for the kernel weights matrix, used for the linear transformation of the inputs. recurrent_initializer Initializer for the recurrent_kernel weights matrix, used for the linear transformation of the recurrent state. bias_initializer Initializer for the bias vector. unit_forget_bias Boolean. If True, add 1 to the bias of the forget gate at initialization. Use in combination with bias_initializer="zeros". This is recommended in Jozefowicz et al., 2015 kernel_regularizer Regularizer function applied to the kernel weights matrix. recurrent_regularizer Regularizer function applied to the recurrent_kernel weights matrix. bias_regularizer Regularizer function applied to the bias vector. activity_regularizer Regularizer function applied to. kernel_constraint Constraint function applied to the kernel weights matrix. recurrent_constraint Constraint function applied to the recurrent_kernel weights matrix. bias_constraint Constraint function applied to the bias vector. return_sequences Boolean. Whether to return the last output in the output sequence, or the full sequence. (default False) return_state Boolean Whether to return the last state in addition to the output. (default False) go_backwards Boolean (default False). If True, process the input sequence backwards. stateful Boolean (default False). If True, the last state for each sample at index i in a batch will be used as initial state for the sample of index i in the following batch. dropout Float between 0 and 1. Fraction of the units to drop for the linear transformation of the inputs. recurrent_dropout Float between 0 and 1. Fraction of the units to drop for the linear transformation of the recurrent state. Call arguments: inputs: A 5D tensor. mask: Binary tensor of shape (samples, timesteps) indicating whether a given timestep should be masked. training: Python boolean indicating whether the layer should behave in training mode or in inference mode. This argument is passed to the cell when calling it. This is only relevant if dropout or recurrent_dropout are set. initial_state: List of initial state tensors to be passed to the first call of the cell. Input shape: If data_format='channels_first' 5D tensor with shape: (samples, time, channels, rows, cols) If data_format='channels_last' 5D tensor with shape: (samples, time, rows, cols, channels) Output shape: If return_state: a list of tensors. The first tensor is the output. The remaining tensors are the last states, each 4D tensor with shape: (samples, filters, new_rows, new_cols) if data_format='channels_first' or 4D tensor with shape: (samples, new_rows, new_cols, filters) if data_format='channels_last'. rows and cols values might have changed due to padding. If return_sequences: 5D tensor with shape: (samples, timesteps, filters, new_rows, new_cols) if data_format='channels_first' or 5D tensor with shape: (samples, timesteps, new_rows, new_cols, filters) if data_format='channels_last'. Else, 4D tensor with shape: (samples, filters, new_rows, new_cols) if data_format='channels_first' or 4D tensor with shape: (samples, new_rows, new_cols, filters) if data_format='channels_last'. Raises ValueError in case of invalid constructor arguments. References: Shi et al., 2015 (the current implementation does not include the feedback loop on the cells output). Attributes activation bias_constraint bias_initializer bias_regularizer data_format dilation_rate dropout filters kernel_constraint kernel_initializer kernel_regularizer kernel_size padding recurrent_activation recurrent_constraint recurrent_dropout recurrent_initializer recurrent_regularizer states strides unit_forget_bias use_bias Methods reset_states View source reset_states( states=None ) Reset the recorded states for the stateful RNN layer. Can only be used when RNN layer is constructed with stateful = True. Args: states: Numpy arrays that contains the value for the initial state, which will be feed to cell at the first time step. When the value is None, zero filled numpy array will be created based on the cell state size. Raises AttributeError When the RNN layer is not stateful. ValueError When the batch size of the RNN layer is unknown. ValueError When the input numpy array is not compatible with the RNN layer state, either size wise or dtype wise.
tensorflow.keras.layers.convlstm2d
tf.keras.layers.Cropping1D View source on GitHub Cropping layer for 1D input (e.g. temporal sequence). Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.Cropping1D tf.keras.layers.Cropping1D( cropping=(1, 1), **kwargs ) It crops along the time dimension (axis 1). Examples: input_shape = (2, 3, 2) x = np.arange(np.prod(input_shape)).reshape(input_shape) print(x) [[[ 0 1] [ 2 3] [ 4 5]] [[ 6 7] [ 8 9] [10 11]]] y = tf.keras.layers.Cropping1D(cropping=1)(x) print(y) tf.Tensor( [[[2 3]] [[8 9]]], shape=(2, 1, 2), dtype=int64) Arguments cropping Int or tuple of int (length 2) How many units should be trimmed off at the beginning and end of the cropping dimension (axis 1). If a single int is provided, the same value will be used for both. Input shape: 3D tensor with shape (batch_size, axis_to_crop, features) Output shape: 3D tensor with shape (batch_size, cropped_axis, features)
tensorflow.keras.layers.cropping1d
tf.keras.layers.Cropping2D View source on GitHub Cropping layer for 2D input (e.g. picture). Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.Cropping2D tf.keras.layers.Cropping2D( cropping=((0, 0), (0, 0)), data_format=None, **kwargs ) It crops along spatial dimensions, i.e. height and width. Examples: input_shape = (2, 28, 28, 3) x = np.arange(np.prod(input_shape)).reshape(input_shape) y = tf.keras.layers.Cropping2D(cropping=((2, 2), (4, 4)))(x) print(y.shape) (2, 24, 20, 3) Arguments cropping Int, or tuple of 2 ints, or tuple of 2 tuples of 2 ints. If int: the same symmetric cropping is applied to height and width. If tuple of 2 ints: interpreted as two different symmetric cropping values for height and width: (symmetric_height_crop, symmetric_width_crop). If tuple of 2 tuples of 2 ints: interpreted as ((top_crop, bottom_crop), (left_crop, right_crop)) data_format A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, height, width, channels) while channels_first corresponds to inputs with shape (batch_size, channels, height, width). It defaults to the image_data_format value found in your Keras config file at ~/.keras/keras.json. If you never set it, then it will be "channels_last". Input shape: 4D tensor with shape: If data_format is "channels_last": (batch_size, rows, cols, channels) If data_format is "channels_first": (batch_size, channels, rows, cols) Output shape: 4D tensor with shape: If data_format is "channels_last": (batch_size, cropped_rows, cropped_cols, channels) If data_format is "channels_first": (batch_size, channels, cropped_rows, cropped_cols)
tensorflow.keras.layers.cropping2d
tf.keras.layers.Cropping3D View source on GitHub Cropping layer for 3D data (e.g. spatial or spatio-temporal). Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.Cropping3D tf.keras.layers.Cropping3D( cropping=((1, 1), (1, 1), (1, 1)), data_format=None, **kwargs ) Examples: input_shape = (2, 28, 28, 10, 3) x = np.arange(np.prod(input_shape)).reshape(input_shape) y = tf.keras.layers.Cropping3D(cropping=(2, 4, 2))(x) print(y.shape) (2, 24, 20, 6, 3) Arguments cropping Int, or tuple of 3 ints, or tuple of 3 tuples of 2 ints. If int: the same symmetric cropping is applied to depth, height, and width. If tuple of 3 ints: interpreted as two different symmetric cropping values for depth, height, and width: (symmetric_dim1_crop, symmetric_dim2_crop, symmetric_dim3_crop). If tuple of 3 tuples of 2 ints: interpreted as ((left_dim1_crop, right_dim1_crop), (left_dim2_crop, right_dim2_crop), (left_dim3_crop, right_dim3_crop)) data_format A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels) while channels_first corresponds to inputs with shape (batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3). It defaults to the image_data_format value found in your Keras config file at ~/.keras/keras.json. If you never set it, then it will be "channels_last". Input shape: 5D tensor with shape: If data_format is "channels_last": (batch_size, first_axis_to_crop, second_axis_to_crop, third_axis_to_crop, depth) If data_format is "channels_first": (batch_size, depth, first_axis_to_crop, second_axis_to_crop, third_axis_to_crop) Output shape: 5D tensor with shape: If data_format is "channels_last": (batch_size, first_cropped_axis, second_cropped_axis, third_cropped_axis, depth) If data_format is "channels_first": (batch_size, depth, first_cropped_axis, second_cropped_axis, third_cropped_axis)
tensorflow.keras.layers.cropping3d
tf.keras.layers.Dense View source on GitHub Just your regular densely-connected NN layer. Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.Dense tf.keras.layers.Dense( units, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs ) Dense implements the operation: output = activation(dot(input, kernel) + bias) where activation is the element-wise activation function passed as the activation argument, kernel is a weights matrix created by the layer, and bias is a bias vector created by the layer (only applicable if use_bias is True). Note: If the input to the layer has a rank greater than 2, then Dense computes the dot product between the inputs and the kernel along the last axis of the inputs and axis 1 of the kernel (using tf.tensordot). For example, if input has dimensions (batch_size, d0, d1), then we create a kernel with shape (d1, units), and the kernel operates along axis 2 of the input, on every sub-tensor of shape (1, 1, d1) (there are batch_size * d0 such sub-tensors). The output in this case will have shape (batch_size, d0, units). Besides, layer attributes cannot be modified after the layer has been called once (except the trainable attribute). Example: # Create a `Sequential` model and add a Dense layer as the first layer. model = tf.keras.models.Sequential() model.add(tf.keras.Input(shape=(16,))) model.add(tf.keras.layers.Dense(32, activation='relu')) # Now the model will take as input arrays of shape (None, 16) # and output arrays of shape (None, 32). # Note that after the first layer, you don't need to specify # the size of the input anymore: model.add(tf.keras.layers.Dense(32)) model.output_shape (None, 32) Arguments units Positive integer, dimensionality of the output space. activation Activation function to use. If you don't specify anything, no activation is applied (ie. "linear" activation: a(x) = x). use_bias Boolean, whether the layer uses a bias vector. kernel_initializer Initializer for the kernel weights matrix. bias_initializer Initializer for the bias vector. kernel_regularizer Regularizer function applied to the kernel weights matrix. bias_regularizer Regularizer function applied to the bias vector. activity_regularizer Regularizer function applied to the output of the layer (its "activation"). kernel_constraint Constraint function applied to the kernel weights matrix. bias_constraint Constraint function applied to the bias vector. Input shape: N-D tensor with shape: (batch_size, ..., input_dim). The most common situation would be a 2D input with shape (batch_size, input_dim). Output shape: N-D tensor with shape: (batch_size, ..., units). For instance, for a 2D input with shape (batch_size, input_dim), the output would have shape (batch_size, units).
tensorflow.keras.layers.dense
tf.keras.layers.DenseFeatures View source on GitHub A layer that produces a dense Tensor based on given feature_columns. Inherits From: DenseFeatures, Layer, Module tf.keras.layers.DenseFeatures( feature_columns, trainable=True, name=None, **kwargs ) Generally a single example in training data is described with FeatureColumns. At the first layer of the model, this column oriented data should be converted to a single Tensor. This layer can be called multiple times with different features. This is the V2 version of this layer that uses name_scopes to create variables instead of variable_scopes. But this approach currently lacks support for partitioned variables. In that case, use the V1 version instead. Example: price = tf.feature_column.numeric_column('price') keywords_embedded = tf.feature_column.embedding_column( tf.feature_column.categorical_column_with_hash_bucket("keywords", 10K), dimensions=16) columns = [price, keywords_embedded, ...] feature_layer = tf.keras.layers.DenseFeatures(columns) features = tf.io.parse_example( ..., features=tf.feature_column.make_parse_example_spec(columns)) dense_tensor = feature_layer(features) for units in [128, 64, 32]: dense_tensor = tf.keras.layers.Dense(units, activation='relu')(dense_tensor) prediction = tf.keras.layers.Dense(1)(dense_tensor) Args feature_columns An iterable containing the FeatureColumns to use as inputs to your model. All items should be instances of classes derived from DenseColumn such as numeric_column, embedding_column, bucketized_column, indicator_column. If you have categorical features, you can wrap them with an embedding_column or indicator_column. trainable Boolean, whether the layer's variables will be updated via gradient descent during training. name Name to give to the DenseFeatures. **kwargs Keyword arguments to construct a layer. Raises ValueError if an item in feature_columns is not a DenseColumn.
tensorflow.keras.layers.densefeatures
tf.keras.layers.DepthwiseConv2D View source on GitHub Depthwise separable 2D convolution. Inherits From: Conv2D, Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.DepthwiseConv2D tf.keras.layers.DepthwiseConv2D( kernel_size, strides=(1, 1), padding='valid', depth_multiplier=1, data_format=None, dilation_rate=(1, 1), activation=None, use_bias=True, depthwise_initializer='glorot_uniform', bias_initializer='zeros', depthwise_regularizer=None, bias_regularizer=None, activity_regularizer=None, depthwise_constraint=None, bias_constraint=None, **kwargs ) Depthwise Separable convolutions consist of performing just the first step in a depthwise spatial convolution (which acts on each input channel separately). The depth_multiplier argument controls how many output channels are generated per input channel in the depthwise step. Arguments kernel_size An integer or tuple/list of 2 integers, specifying the height and width of the 2D convolution window. Can be a single integer to specify the same value for all spatial dimensions. strides An integer or tuple/list of 2 integers, specifying the strides of the convolution along the height and width. Can be a single integer to specify the same value for all spatial dimensions. Specifying any stride value != 1 is incompatible with specifying any dilation_rate value != 1. padding one of 'valid' or 'same' (case-insensitive). "valid" means no padding. "same" results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. depth_multiplier The number of depthwise convolution output channels for each input channel. The total number of depthwise convolution output channels will be equal to filters_in * depth_multiplier. data_format A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, height, width, channels) while channels_first corresponds to inputs with shape (batch_size, channels, height, width). It defaults to the image_data_format value found in your Keras config file at ~/.keras/keras.json. If you never set it, then it will be 'channels_last'. dilation_rate An integer or tuple/list of 2 integers, specifying the dilation rate to use for dilated convolution. Currently, specifying any dilation_rate value != 1 is incompatible with specifying any strides value != 1. activation Activation function to use. If you don't specify anything, no activation is applied ( see keras.activations). use_bias Boolean, whether the layer uses a bias vector. depthwise_initializer Initializer for the depthwise kernel matrix ( see keras.initializers). bias_initializer Initializer for the bias vector ( see keras.initializers). depthwise_regularizer Regularizer function applied to the depthwise kernel matrix (see keras.regularizers). bias_regularizer Regularizer function applied to the bias vector ( see keras.regularizers). activity_regularizer Regularizer function applied to the output of the layer (its 'activation') ( see keras.regularizers). depthwise_constraint Constraint function applied to the depthwise kernel matrix ( see keras.constraints). bias_constraint Constraint function applied to the bias vector ( see keras.constraints). Input shape: 4D tensor with shape: [batch_size, channels, rows, cols] if data_format='channels_first' or 4D tensor with shape: [batch_size, rows, cols, channels] if data_format='channels_last'. Output shape: 4D tensor with shape: [batch_size, filters, new_rows, new_cols] if data_format='channels_first' or 4D tensor with shape: [batch_size, new_rows, new_cols, filters] if data_format='channels_last'. rows and cols values might have changed due to padding. Returns A tensor of rank 4 representing activation(depthwiseconv2d(inputs, kernel) + bias). Raises ValueError if padding is "causal". ValueError when both strides > 1 and dilation_rate > 1.
tensorflow.keras.layers.depthwiseconv2d
tf.keras.layers.deserialize View source on GitHub Instantiates a layer from a config dictionary. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.deserialize tf.keras.layers.deserialize( config, custom_objects=None ) Arguments config dict of the form {'class_name': str, 'config': dict} custom_objects dict mapping class names (or function names) of custom (non-Keras) objects to class/functions Returns Layer instance (may be Model, Sequential, Network, Layer...)
tensorflow.keras.layers.deserialize
tf.keras.layers.Dot View source on GitHub Layer that computes a dot product between samples in two tensors. Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.Dot tf.keras.layers.Dot( axes, normalize=False, **kwargs ) E.g. if applied to a list of two tensors a and b of shape (batch_size, n), the output will be a tensor of shape (batch_size, 1) where each entry i will be the dot product between a[i] and b[i]. x = np.arange(10).reshape(1, 5, 2) print(x) [[[0 1] [2 3] [4 5] [6 7] [8 9]]] y = np.arange(10, 20).reshape(1, 2, 5) print(y) [[[10 11 12 13 14] [15 16 17 18 19]]] tf.keras.layers.Dot(axes=(1, 2))([x, y]) <tf.Tensor: shape=(1, 2, 2), dtype=int64, numpy= array([[[260, 360], [320, 445]]])> x1 = tf.keras.layers.Dense(8)(np.arange(10).reshape(5, 2)) x2 = tf.keras.layers.Dense(8)(np.arange(10, 20).reshape(5, 2)) dotted = tf.keras.layers.Dot(axes=1)([x1, x2]) dotted.shape TensorShape([5, 1]) Arguments axes Integer or tuple of integers, axis or axes along which to take the dot product. If a tuple, should be two integers corresponding to the desired axis from the first input and the desired axis from the second input, respectively. Note that the size of the two selected axes must match. normalize Whether to L2-normalize samples along the dot product axis before taking the dot product. If set to True, then the output of the dot product is the cosine proximity between the two samples. **kwargs Standard layer keyword arguments.
tensorflow.keras.layers.dot
tf.keras.layers.Dropout View source on GitHub Applies Dropout to the input. Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.Dropout tf.keras.layers.Dropout( rate, noise_shape=None, seed=None, **kwargs ) The Dropout layer randomly sets input units to 0 with a frequency of rate at each step during training time, which helps prevent overfitting. Inputs not set to 0 are scaled up by 1/(1 - rate) such that the sum over all inputs is unchanged. Note that the Dropout layer only applies when training is set to True such that no values are dropped during inference. When using model.fit, training will be appropriately set to True automatically, and in other contexts, you can set the kwarg explicitly to True when calling the layer. (This is in contrast to setting trainable=False for a Dropout layer. trainable does not affect the layer's behavior, as Dropout does not have any variables/weights that can be frozen during training.) tf.random.set_seed(0) layer = tf.keras.layers.Dropout(.2, input_shape=(2,)) data = np.arange(10).reshape(5, 2).astype(np.float32) print(data) [[0. 1.] [2. 3.] [4. 5.] [6. 7.] [8. 9.]] outputs = layer(data, training=True) print(outputs) tf.Tensor( [[ 0. 1.25] [ 2.5 3.75] [ 5. 6.25] [ 7.5 8.75] [10. 0. ]], shape=(5, 2), dtype=float32) Arguments rate Float between 0 and 1. Fraction of the input units to drop. noise_shape 1D integer tensor representing the shape of the binary dropout mask that will be multiplied with the input. For instance, if your inputs have shape (batch_size, timesteps, features) and you want the dropout mask to be the same for all timesteps, you can use noise_shape=(batch_size, 1, features). seed A Python integer to use as random seed. Call arguments: inputs: Input tensor (of any rank). training: Python boolean indicating whether the layer should behave in training mode (adding dropout) or in inference mode (doing nothing).
tensorflow.keras.layers.dropout
tf.keras.layers.ELU View source on GitHub Exponential Linear Unit. Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.ELU tf.keras.layers.ELU( alpha=1.0, **kwargs ) It follows: f(x) = alpha * (exp(x) - 1.) for x < 0 f(x) = x for x >= 0 Input shape: Arbitrary. Use the keyword argument input_shape (tuple of integers, does not include the samples axis) when using this layer as the first layer in a model. Output shape: Same shape as the input. Arguments alpha Scale for the negative factor.
tensorflow.keras.layers.elu
tf.keras.layers.Embedding View source on GitHub Turns positive integers (indexes) into dense vectors of fixed size. Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.Embedding tf.keras.layers.Embedding( input_dim, output_dim, embeddings_initializer='uniform', embeddings_regularizer=None, activity_regularizer=None, embeddings_constraint=None, mask_zero=False, input_length=None, **kwargs ) e.g. [[4], [20]] -> [[0.25, 0.1], [0.6, -0.2]] This layer can only be used as the first layer in a model. Example: model = tf.keras.Sequential() model.add(tf.keras.layers.Embedding(1000, 64, input_length=10)) # The model will take as input an integer matrix of size (batch, # input_length), and the largest integer (i.e. word index) in the input # should be no larger than 999 (vocabulary size). # Now model.output_shape is (None, 10, 64), where `None` is the batch # dimension. input_array = np.random.randint(1000, size=(32, 10)) model.compile('rmsprop', 'mse') output_array = model.predict(input_array) print(output_array.shape) (32, 10, 64) Arguments input_dim Integer. Size of the vocabulary, i.e. maximum integer index + 1. output_dim Integer. Dimension of the dense embedding. embeddings_initializer Initializer for the embeddings matrix (see keras.initializers). embeddings_regularizer Regularizer function applied to the embeddings matrix (see keras.regularizers). embeddings_constraint Constraint function applied to the embeddings matrix (see keras.constraints). mask_zero Boolean, whether or not the input value 0 is a special "padding" value that should be masked out. This is useful when using recurrent layers which may take variable length input. If this is True, then all subsequent layers in the model need to support masking or an exception will be raised. If mask_zero is set to True, as a consequence, index 0 cannot be used in the vocabulary (input_dim should equal size of vocabulary + 1). input_length Length of input sequences, when it is constant. This argument is required if you are going to connect Flatten then Dense layers upstream (without it, the shape of the dense outputs cannot be computed). Input shape: 2D tensor with shape: (batch_size, input_length). Output shape: 3D tensor with shape: (batch_size, input_length, output_dim).
tensorflow.keras.layers.embedding
Module: tf.keras.layers.experimental Public API for tf.keras.layers.experimental namespace. Modules preprocessing module: Public API for tf.keras.layers.experimental.preprocessing namespace. Classes class EinsumDense: A layer that uses tf.einsum as the backing computation. class RandomFourierFeatures: Layer that projects its inputs into a random feature space. class SyncBatchNormalization: Normalize and scale inputs or activations synchronously across replicas.
tensorflow.keras.layers.experimental
tf.keras.layers.experimental.EinsumDense A layer that uses tf.einsum as the backing computation. Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.experimental.EinsumDense tf.keras.layers.experimental.EinsumDense( equation, output_shape, activation=None, bias_axes=None, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs ) This layer can perform einsum calculations of arbitrary dimensionality. Arguments equation An equation describing the einsum to perform. This equation must be a valid einsum string of the form ab,bc->ac, ...ab,bc->...ac, or ab...,bc->ac... where 'ab', 'bc', and 'ac' can be any valid einsum axis expression sequence. output_shape The expected shape of the output tensor (excluding the batch dimension and any dimensions represented by ellipses). You can specify None for any dimension that is unknown or can be inferred from the input shape. activation Activation function to use. If you don't specify anything, no activation is applied (that is, a "linear" activation: a(x) = x). bias_axes A string containing the output dimension(s) to apply a bias to. Each character in the bias_axes string should correspond to a character in the output portion of the equation string. kernel_initializer Initializer for the kernel weights matrix. bias_initializer Initializer for the bias vector. kernel_regularizer Regularizer function applied to the kernel weights matrix. bias_regularizer Regularizer function applied to the bias vector. activity_regularizer Regularizer function applied to the output of the layer (its "activation").. kernel_constraint Constraint function applied to the kernel weights matrix. bias_constraint Constraint function applied to the bias vector. Examples: Biased dense layer with einsums This example shows how to instantiate a standard Keras dense layer using einsum operations. This example is equivalent to tf.keras.layers.Dense(64, use_bias=True). layer = EinsumDense("ab,bc->ac", output_shape=64, bias_axes="c") input_tensor = tf.keras.Input(shape=[32]) output_tensor = layer(input_tensor) output_tensor <... shape=(None, 64) dtype=...> Applying a dense layer to a sequence This example shows how to instantiate a layer that applies the same dense operation to every element in a sequence. Here, the 'output_shape' has two values (since there are two non-batch dimensions in the output); the first dimension in the output_shape is None, because the sequence dimension b has an unknown shape. layer = EinsumDense("abc,cd->abd", output_shape=(None, 64), bias_axes="d") input_tensor = tf.keras.Input(shape=[32, 128]) output_tensor = layer(input_tensor) output_tensor <... shape=(None, 32, 64) dtype=...> Applying a dense layer to a sequence using ellipses This example shows how to instantiate a layer that applies the same dense operation to every element in a sequence, but uses the ellipsis notation instead of specifying the batch and sequence dimensions. Because we are using ellipsis notation and have specified only one axis, the output_shape arg is a single value. When instantiated in this way, the layer can handle any number of sequence dimensions - including the case where no sequence dimension exists. layer = EinsumDense("...x,xy->...y", output_shape=64, bias_axes="y") input_tensor = tf.keras.Input(shape=[32, 128]) output_tensor = layer(input_tensor) output_tensor <... shape=(None, 32, 64) dtype=...>
tensorflow.keras.layers.experimental.einsumdense
Module: tf.keras.layers.experimental.preprocessing Public API for tf.keras.layers.experimental.preprocessing namespace. Classes class CategoryCrossing: Category crossing layer. class CategoryEncoding: Category encoding layer. class CenterCrop: Crop the central portion of the images to target height and width. class Discretization: Buckets data into discrete ranges. class Hashing: Implements categorical feature hashing, also known as "hashing trick". class IntegerLookup: Maps integers from a vocabulary to integer indices. class Normalization: Feature-wise normalization of the data. class PreprocessingLayer: Base class for PreprocessingLayers. class RandomContrast: Adjust the contrast of an image or images by a random factor. class RandomCrop: Randomly crop the images to target height and width. class RandomFlip: Randomly flip each image horizontally and vertically. class RandomHeight: Randomly vary the height of a batch of images during training. class RandomRotation: Randomly rotate each image. class RandomTranslation: Randomly translate each image during training. class RandomWidth: Randomly vary the width of a batch of images during training. class RandomZoom: Randomly zoom each image during training. class Rescaling: Multiply inputs by scale and adds offset. class Resizing: Image resizing layer. class StringLookup: Maps strings from a vocabulary to integer indices. class TextVectorization: Text vectorization layer.
tensorflow.keras.layers.experimental.preprocessing
tf.keras.layers.experimental.preprocessing.CategoryCrossing Category crossing layer. Inherits From: PreprocessingLayer, Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.experimental.preprocessing.CategoryCrossing tf.keras.layers.experimental.preprocessing.CategoryCrossing( depth=None, name=None, separator=None, **kwargs ) This layer concatenates multiple categorical inputs into a single categorical output (similar to Cartesian product). The output dtype is string. Usage: inp_1 = ['a', 'b', 'c'] inp_2 = ['d', 'e', 'f'] layer = tf.keras.layers.experimental.preprocessing.CategoryCrossing() layer([inp_1, inp_2]) <tf.Tensor: shape=(3, 1), dtype=string, numpy= array([[b'a_X_d'], [b'b_X_e'], [b'c_X_f']], dtype=object)> inp_1 = ['a', 'b', 'c'] inp_2 = ['d', 'e', 'f'] layer = tf.keras.layers.experimental.preprocessing.CategoryCrossing( separator='-') layer([inp_1, inp_2]) <tf.Tensor: shape=(3, 1), dtype=string, numpy= array([[b'a-d'], [b'b-e'], [b'c-f']], dtype=object)> Arguments depth depth of input crossing. By default None, all inputs are crossed into one output. It can also be an int or tuple/list of ints. Passing an integer will create combinations of crossed outputs with depth up to that integer, i.e., [1, 2, ..., depth), and passing a tuple of integers will create crossed outputs with depth for the specified values in the tuple, i.e., depth=(N1, N2) will create all possible crossed outputs with depth equal to N1 or N2. Passing None means a single crossed output with all inputs. For example, with inputs a, b and c, depth=2 means the output will be [a;b;c;cross(a, b);cross(bc);cross(ca)]. separator A string added between each input being joined. Defaults to 'X'. name Name to give to the layer. **kwargs Keyword arguments to construct a layer. Input shape: a list of string or int tensors or sparse tensors of shape [batch_size, d1, ..., dm] Output shape: a single string or int tensor or sparse tensor of shape [batch_size, d1, ..., dm] Returns If any input is RaggedTensor, the output is RaggedTensor. Else, if any input is SparseTensor, the output is SparseTensor. Otherwise, the output is Tensor. Example: (depth=None) If the layer receives three inputs: a=[[1], [4]], b=[[2], [5]], c=[[3], [6]] the output will be a string tensor: [[b'1_X_2_X_3'], [b'4_X_5_X_6']] Example: (depth is an integer) With the same input above, and if depth=2, the output will be a list of 6 string tensors: [[b'1'], [b'4']] [[b'2'], [b'5']] [[b'3'], [b'6']] [[b'1_X_2'], [b'4_X_5']], [[b'2_X_3'], [b'5_X_6']], [[b'3_X_1'], [b'6_X_4']] Example: (depth is a tuple/list of integers) With the same input above, and if depth=(2, 3) the output will be a list of 4 string tensors: [[b'1_X_2'], [b'4_X_5']], [[b'2_X_3'], [b'5_X_6']], [[b'3_X_1'], [b'6_X_4']], [[b'1_X_2_X_3'], [b'4_X_5_X_6']] Methods adapt View source adapt( data, reset_state=True ) Fits the state of the preprocessing layer to the data being passed. Arguments data The data to train on. It can be passed either as a tf.data Dataset, or as a numpy array. reset_state Optional argument specifying whether to clear the state of the layer at the start of the call to adapt, or whether to start from the existing state. This argument may not be relevant to all preprocessing layers: a subclass of PreprocessingLayer may choose to throw if 'reset_state' is set to False. partial_crossing View source partial_crossing( partial_inputs, ragged_out, sparse_out ) Gets the crossed output from a partial list/tuple of inputs.
tensorflow.keras.layers.experimental.preprocessing.categorycrossing
tf.keras.layers.experimental.preprocessing.CategoryEncoding Category encoding layer. Inherits From: PreprocessingLayer, Layer, Module tf.keras.layers.experimental.preprocessing.CategoryEncoding( max_tokens=None, output_mode=BINARY, sparse=False, **kwargs ) This layer provides options for condensing data into a categorical encoding. It accepts integer values as inputs and outputs a dense representation (one sample = 1-index tensor of float values representing data about the sample's tokens) of those inputs. Examples: layer = tf.keras.layers.experimental.preprocessing.CategoryEncoding( max_tokens=4, output_mode="count") layer([[0, 1], [0, 0], [1, 2], [3, 1]]) <tf.Tensor: shape=(4, 4), dtype=float32, numpy= array([[1., 1., 0., 0.], [2., 0., 0., 0.], [0., 1., 1., 0.], [0., 1., 0., 1.]], dtype=float32)> Examples with weighted inputs: layer = tf.keras.layers.experimental.preprocessing.CategoryEncoding( max_tokens=4, output_mode="count") count_weights = np.array([[.1, .2], [.1, .1], [.2, .3], [.4, .2]]) layer([[0, 1], [0, 0], [1, 2], [3, 1]], count_weights=count_weights) <tf.Tensor: shape=(4, 4), dtype=float64, numpy= array([[0.1, 0.2, 0. , 0. ], [0.2, 0. , 0. , 0. ], [0. , 0.2, 0.3, 0. ], [0. , 0.2, 0. , 0.4]])> Call arguments: inputs: A 2D tensor (samples, timesteps). count_weights: A 2D tensor in the same shape as inputs indicating the weight for each sample value when summing up in count mode. Not used in binary or tfidf mode. Attributes max_tokens The maximum size of the vocabulary for this layer. If None, there is no cap on the size of the vocabulary. output_mode Specification for the output of the layer. Defaults to "binary". Values can be "binary", "count" or "tf-idf", configuring the layer as follows: "binary": Outputs a single int array per batch, of either vocab_size or max_tokens size, containing 1s in all elements where the token mapped to that index exists at least once in the batch item. "count": As "binary", but the int array contains a count of the number of times the token at that index appeared in the batch item. "tf-idf": As "binary", but the TF-IDF algorithm is applied to find the value in each token slot. sparse Boolean. If true, returns a SparseTensor instead of a dense Tensor. Defaults to False. Methods adapt View source adapt( data, reset_state=True ) Fits the state of the preprocessing layer to the dataset. Overrides the default adapt method to apply relevant preprocessing to the inputs before passing to the combiner. Arguments data The data to train on. It can be passed either as a tf.data Dataset, or as a numpy array. reset_state Optional argument specifying whether to clear the state of the layer at the start of the call to adapt. This must be True for this layer, which does not support repeated calls to adapt. Raises RuntimeError if the layer cannot be adapted at this time. set_num_elements View source set_num_elements( num_elements ) set_tfidf_data View source set_tfidf_data( tfidf_data )
tensorflow.keras.layers.experimental.preprocessing.categoryencoding
tf.keras.layers.experimental.preprocessing.CenterCrop Crop the central portion of the images to target height and width. Inherits From: PreprocessingLayer, Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.experimental.preprocessing.CenterCrop tf.keras.layers.experimental.preprocessing.CenterCrop( height, width, name=None, **kwargs ) Input shape: 4D tensor with shape: (samples, height, width, channels), data_format='channels_last'. Output shape: 4D tensor with shape: (samples, target_height, target_width, channels). If the input height/width is even and the target height/width is odd (or inversely), the input image is left-padded by 1 pixel. Arguments height Integer, the height of the output shape. width Integer, the width of the output shape. name A string, the name of the layer. Methods adapt View source adapt( data, reset_state=True ) Fits the state of the preprocessing layer to the data being passed. Arguments data The data to train on. It can be passed either as a tf.data Dataset, or as a numpy array. reset_state Optional argument specifying whether to clear the state of the layer at the start of the call to adapt, or whether to start from the existing state. This argument may not be relevant to all preprocessing layers: a subclass of PreprocessingLayer may choose to throw if 'reset_state' is set to False.
tensorflow.keras.layers.experimental.preprocessing.centercrop
tf.keras.layers.experimental.preprocessing.Discretization Buckets data into discrete ranges. Inherits From: PreprocessingLayer, Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.experimental.preprocessing.Discretization tf.keras.layers.experimental.preprocessing.Discretization( bins, **kwargs ) This layer will place each element of its input data into one of several contiguous ranges and output an integer index indicating which range each element was placed in. Input shape: Any tf.Tensor or tf.RaggedTensor of dimension 2 or higher. Output shape: Same as input shape. Examples: Bucketize float values based on provided buckets. >>> input = np.array([[-1.5, 1.0, 3.4, .5], [0.0, 3.0, 1.3, 0.0]]) >>> layer = tf.keras.layers.experimental.preprocessing.Discretization( ... bins=[0., 1., 2.]) >>> layer(input) <tf.Tensor: shape=(2, 4), dtype=int32, numpy= array([[0, 1, 3, 1], [0, 3, 2, 0]], dtype=int32)> Attributes bins Optional boundary specification. Bins exclude the left boundary and include the right boundary, so bins=[0., 1., 2.] generates bins (-inf, 0.), [0., 1.), [1., 2.), and [2., +inf). Methods adapt View source adapt( data, reset_state=True ) Fits the state of the preprocessing layer to the data being passed. Arguments data The data to train on. It can be passed either as a tf.data Dataset, or as a numpy array. reset_state Optional argument specifying whether to clear the state of the layer at the start of the call to adapt, or whether to start from the existing state. This argument may not be relevant to all preprocessing layers: a subclass of PreprocessingLayer may choose to throw if 'reset_state' is set to False.
tensorflow.keras.layers.experimental.preprocessing.discretization
tf.keras.layers.experimental.preprocessing.Hashing Implements categorical feature hashing, also known as "hashing trick". Inherits From: PreprocessingLayer, Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.experimental.preprocessing.Hashing tf.keras.layers.experimental.preprocessing.Hashing( num_bins, salt=None, name=None, **kwargs ) This layer transforms single or multiple categorical inputs to hashed output. It converts a sequence of int or string to a sequence of int. The stable hash function uses tensorflow::ops::Fingerprint to produce universal output that is consistent across platforms. This layer uses FarmHash64 by default, which provides a consistent hashed output across different platforms and is stable across invocations, regardless of device and context, by mixing the input bits thoroughly. If you want to obfuscate the hashed output, you can also pass a random salt argument in the constructor. In that case, the layer will use the SipHash64 hash function, with the salt value serving as additional input to the hash function. Example (FarmHash64): layer = tf.keras.layers.experimental.preprocessing.Hashing(num_bins=3) inp = [['A'], ['B'], ['C'], ['D'], ['E']] layer(inp) <tf.Tensor: shape=(5, 1), dtype=int64, numpy= array([[1], [0], [1], [1], [2]])> Example (FarmHash64) with list of inputs: >>> layer = tf.keras.layers.experimental.preprocessing.Hashing(num_bins=3) >>> inp_1 = [['A'], ['B'], ['C'], ['D'], ['E']] >>> inp_2 = np.asarray([[5], [4], [3], [2], [1]]) >>> layer([inp_1, inp_2]) <tf.Tensor: shape=(5, 1), dtype=int64, numpy= array([[1], [1], [0], [2], [0]])> Example (SipHash64): layer = tf.keras.layers.experimental.preprocessing.Hashing(num_bins=3, salt=[133, 137]) inp = [['A'], ['B'], ['C'], ['D'], ['E']] layer(inp) <tf.Tensor: shape=(5, 1), dtype=int64, numpy= array([[1], [2], [1], [0], [2]])> Example (Siphash64 with a single integer, same as salt=[133, 133] layer = tf.keras.layers.experimental.preprocessing.Hashing(num_bins=3, salt=133) inp = [['A'], ['B'], ['C'], ['D'], ['E']] layer(inp) <tf.Tensor: shape=(5, 1), dtype=int64, numpy= array([[0], [0], [2], [1], [0]])> Reference: SipHash with salt Arguments num_bins Number of hash bins. salt A single unsigned integer or None. If passed, the hash function used will be SipHash64, with these values used as an additional input (known as a "salt" in cryptography). These should be non-zero. Defaults to None (in that case, the FarmHash64 hash function is used). It also supports tuple/list of 2 unsigned integer numbers, see reference paper for details. name Name to give to the layer. **kwargs Keyword arguments to construct a layer. Input shape: A single or list of string, int32 or int64 Tensor, SparseTensor or RaggedTensor of shape [batch_size, ...,] Output shape: An int64 Tensor, SparseTensor or RaggedTensor of shape [batch_size, ...]. If any input is RaggedTensor then output is RaggedTensor, otherwise if any input is SparseTensor then output is SparseTensor, otherwise the output is Tensor. Methods adapt View source adapt( data, reset_state=True ) Fits the state of the preprocessing layer to the data being passed. Arguments data The data to train on. It can be passed either as a tf.data Dataset, or as a numpy array. reset_state Optional argument specifying whether to clear the state of the layer at the start of the call to adapt, or whether to start from the existing state. This argument may not be relevant to all preprocessing layers: a subclass of PreprocessingLayer may choose to throw if 'reset_state' is set to False.
tensorflow.keras.layers.experimental.preprocessing.hashing
tf.keras.layers.experimental.preprocessing.IntegerLookup Maps integers from a vocabulary to integer indices. Inherits From: PreprocessingLayer, Layer, Module tf.keras.layers.experimental.preprocessing.IntegerLookup( max_values=None, num_oov_indices=1, mask_value=0, oov_value=-1, vocabulary=None, invert=False, **kwargs ) This layer translates a set of arbitrary integers into an integer output via a table-based lookup, with optional out-of-vocabulary handling. If desired, the user can call this layer's adapt() method on a data set, which will analyze the data set, determine the frequency of individual string values, and create a vocabulary from them. This vocabulary can have unlimited size or be capped, depending on the configuration options for this layer; if there are more unique values in the input than the maximum vocabulary size, the most frequent terms will be used to create the vocabulary. Examples: Creating a lookup layer with a known vocabulary This example creates a lookup layer with a pre-existing vocabulary. vocab = [12, 36, 1138, 42] data = tf.constant([[12, 1138, 42], [42, 1000, 36]]) layer = IntegerLookup(vocabulary=vocab) layer(data) <tf.Tensor: shape=(2, 3), dtype=int64, numpy= array([[2, 4, 5], [5, 1, 3]])> Creating a lookup layer with an adapted vocabulary This example creates a lookup layer and generates the vocabulary by analyzing the dataset. data = tf.constant([[12, 1138, 42], [42, 1000, 36]]) layer = IntegerLookup() layer.adapt(data) layer.get_vocabulary() [0, -1, 42, 1138, 1000, 36, 12] Note how the mask value 0 and the OOV value -1 have been added to the vocabulary. The remaining values are sorted by frequency (1138, which has 2 occurrences, is first) then by inverse sort order. data = tf.constant([[12, 1138, 42], [42, 1000, 36]]) layer = IntegerLookup() layer.adapt(data) layer(data) <tf.Tensor: shape=(2, 3), dtype=int64, numpy= array([[6, 3, 2], [2, 4, 5]])> Lookups with multiple OOV tokens. This example demonstrates how to use a lookup layer with multiple OOV tokens. When a layer is created with more than one OOV token, any OOV values are hashed into the number of OOV buckets, distributing OOV values in a deterministic fashion across the set. vocab = [12, 36, 1138, 42] data = tf.constant([[12, 1138, 42], [37, 1000, 36]]) layer = IntegerLookup(vocabulary=vocab, num_oov_indices=2) layer(data) <tf.Tensor: shape=(2, 3), dtype=int64, numpy= array([[3, 5, 6], [2, 1, 4]])> Note that the output for OOV value 37 is 2, while the output for OOV value 1000 is 1. The in-vocab terms have their output index increased by 1 from earlier examples (12 maps to 3, etc) in order to make space for the extra OOV value. Inverse lookup This example demonstrates how to map indices to values using this layer. (You can also use adapt() with inverse=True, but for simplicity we'll pass the vocab in this example.) vocab = [12, 36, 1138, 42] data = tf.constant([[1, 3, 4], [4, 5, 2]]) layer = IntegerLookup(vocabulary=vocab, invert=True) layer(data) <tf.Tensor: shape=(2, 3), dtype=int64, numpy= array([[ 12, 1138, 42], [ 42, -1, 36]])> Note that the integer 5, which is out of the vocabulary space, returns an OOV token. Forward and inverse lookup pairs This example demonstrates how to use the vocabulary of a standard lookup layer to create an inverse lookup layer. vocab = [12, 36, 1138, 42] data = tf.constant([[12, 1138, 42], [42, 1000, 36]]) layer = IntegerLookup(vocabulary=vocab) i_layer = IntegerLookup(vocabulary=layer.get_vocabulary(), invert=True) int_data = layer(data) i_layer(int_data) <tf.Tensor: shape=(2, 3), dtype=int64, numpy= array([[ 12, 1138, 42], [ 42, -1, 36]])> In this example, the input value 1000 resulted in an output of -1, since 1000 was not in the vocabulary - it got represented as an OOV, and all OOV values are returned as -1 in the inverse layer. Also, note that for the inverse to work, you must have already set the forward layer vocabulary either directly or via fit() before calling get_vocabulary(). Attributes max_values The maximum size of the vocabulary for this layer. If None, there is no cap on the size of the vocabulary. Note that this vocabulary includes the OOV and mask values, so the effective number of values is (max_values - num_oov_values - (1 if mask_token else 0)) num_oov_indices The number of out-of-vocabulary values to use; defaults to If this value is more than 1, OOV inputs are modulated to determine their OOV value; if this value is 0, passing an OOV input will result in a '-1' being returned for that value in the output tensor. (Note that, because the value is -1 and not 0, this will allow you to effectively drop OOV values from categorical encodings.) mask_value A value that represents masked inputs, and which is mapped to index 0. Defaults to 0. If set to None, no mask term will be added and the OOV values, if any, will be indexed from (0...num_oov_values) instead of (1...num_oov_values+1). oov_value The value representing an out-of-vocabulary value. Defaults to -1. vocabulary An optional list of values, or a path to a text file containing a vocabulary to load into this layer. The file should contain one value per line. If the list or file contains the same token multiple times, an error will be thrown. invert If true, this layer will map indices to vocabulary items instead of mapping vocabulary items to indices. Methods adapt View source adapt( data, reset_state=True ) Fits the state of the preprocessing layer to the dataset. Overrides the default adapt method to apply relevant preprocessing to the inputs before passing to the combiner. Arguments data The data to train on. It can be passed either as a tf.data Dataset, or as a numpy array. reset_state Optional argument specifying whether to clear the state of the layer at the start of the call to adapt. This must be True for this layer, which does not support repeated calls to adapt. get_vocabulary View source get_vocabulary() set_vocabulary View source set_vocabulary( vocab ) Sets vocabulary data for this layer with inverse=False. This method sets the vocabulary for this layer directly, instead of analyzing a dataset through 'adapt'. It should be used whenever the vocab information is already known. If vocabulary data is already present in the layer, this method will either replace it Arguments vocab An array of string tokens. Raises ValueError If there are too many inputs, the inputs do not match, or input data is missing. vocab_size View source vocab_size()
tensorflow.keras.layers.experimental.preprocessing.integerlookup
tf.keras.layers.experimental.preprocessing.Normalization Feature-wise normalization of the data. Inherits From: PreprocessingLayer, Layer, Module tf.keras.layers.experimental.preprocessing.Normalization( axis=-1, dtype=None, mean=None, variance=None, **kwargs ) This layer will coerce its inputs into a distribution centered around 0 with standard deviation 1. It accomplishes this by precomputing the mean and variance of the data, and calling (input-mean)/sqrt(var) at runtime. What happens in adapt: Compute mean and variance of the data and store them as the layer's weights. adapt should be called before fit, evaluate, or predict. Examples: Calculate the mean and variance by analyzing the dataset in adapt. adapt_data = np.array([[1.], [2.], [3.], [4.], [5.]], dtype=np.float32) input_data = np.array([[1.], [2.], [3.]], np.float32) layer = Normalization() layer.adapt(adapt_data) layer(input_data) <tf.Tensor: shape=(3, 1), dtype=float32, numpy= array([[-1.4142135 ], [-0.70710677], [ 0. ]], dtype=float32)> Pass the mean and variance directly. input_data = np.array([[1.], [2.], [3.]], np.float32) layer = Normalization(mean=3., variance=2.) layer(input_data) <tf.Tensor: shape=(3, 1), dtype=float32, numpy= array([[-1.4142135 ], [-0.70710677], [ 0. ]], dtype=float32)> Attributes axis Integer or tuple of integers, the axis or axes that should be "kept". These axes are not be summed over when calculating the normalization statistics. By default the last axis, the features axis is kept and any space or time axes are summed. Each element in the the axes that are kept is normalized independently. If axis is set to 'None', the layer will perform scalar normalization (dividing the input by a single scalar value). The batch axis, 0, is always summed over (axis=0 is not allowed). mean The mean value(s) to use during normalization. The passed value(s) will be broadcast to the shape of the kept axes above; if the value(s) cannot be broadcast, an error will be raised when this layer's build() method is called. variance The variance value(s) to use during normalization. The passed value(s) will be broadcast to the shape of the kept axes above; if the value(s)cannot be broadcast, an error will be raised when this layer's build() method is called. Methods adapt View source adapt( data, reset_state=True ) Fits the state of the preprocessing layer to the data being passed. Arguments data The data to train on. It can be passed either as a tf.data Dataset, or as a numpy array. reset_state Optional argument specifying whether to clear the state of the layer at the start of the call to adapt, or whether to start from the existing state. Subclasses may choose to throw if reset_state is set to 'False'.
tensorflow.keras.layers.experimental.preprocessing.normalization
tf.keras.layers.experimental.preprocessing.PreprocessingLayer Base class for PreprocessingLayers. Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.experimental.preprocessing.PreprocessingLayer tf.keras.layers.experimental.preprocessing.PreprocessingLayer( trainable=True, name=None, dtype=None, dynamic=False, **kwargs ) Methods adapt View source adapt( data, reset_state=True ) Fits the state of the preprocessing layer to the data being passed. Arguments data The data to train on. It can be passed either as a tf.data Dataset, or as a numpy array. reset_state Optional argument specifying whether to clear the state of the layer at the start of the call to adapt, or whether to start from the existing state. This argument may not be relevant to all preprocessing layers: a subclass of PreprocessingLayer may choose to throw if 'reset_state' is set to False.
tensorflow.keras.layers.experimental.preprocessing.preprocessinglayer
tf.keras.layers.experimental.preprocessing.RandomContrast Adjust the contrast of an image or images by a random factor. Inherits From: PreprocessingLayer, Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.experimental.preprocessing.RandomContrast tf.keras.layers.experimental.preprocessing.RandomContrast( factor, seed=None, name=None, **kwargs ) Contrast is adjusted independently for each channel of each image during training. For each channel, this layer computes the mean of the image pixels in the channel and then adjusts each component x of each pixel to (x - mean) * contrast_factor + mean. Input shape: 4D tensor with shape: (samples, height, width, channels), data_format='channels_last'. Output shape: 4D tensor with shape: (samples, height, width, channels), data_format='channels_last'. Raise ValueError if lower bound is not between [0, 1], or upper bound is negative. Attributes factor a positive float represented as fraction of value, or a tuple of size 2 representing lower and upper bound. When represented as a single float, lower = upper. The contrast factor will be randomly picked between [1.0 - lower, 1.0 + upper]. seed Integer. Used to create a random seed. name A string, the name of the layer. Methods adapt View source adapt( data, reset_state=True ) Fits the state of the preprocessing layer to the data being passed. Arguments data The data to train on. It can be passed either as a tf.data Dataset, or as a numpy array. reset_state Optional argument specifying whether to clear the state of the layer at the start of the call to adapt, or whether to start from the existing state. This argument may not be relevant to all preprocessing layers: a subclass of PreprocessingLayer may choose to throw if 'reset_state' is set to False.
tensorflow.keras.layers.experimental.preprocessing.randomcontrast
tf.keras.layers.experimental.preprocessing.RandomCrop Randomly crop the images to target height and width. Inherits From: PreprocessingLayer, Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.experimental.preprocessing.RandomCrop tf.keras.layers.experimental.preprocessing.RandomCrop( height, width, seed=None, name=None, **kwargs ) This layer will crop all the images in the same batch to the same cropping location. By default, random cropping is only applied during training. At inference time, the images will be first rescaled to preserve the shorter side, and center cropped. If you need to apply random cropping at inference time, set training to True when calling the layer. Input shape: 4D tensor with shape: (samples, height, width, channels), data_format='channels_last'. Output shape: 4D tensor with shape: (samples, target_height, target_width, channels). Arguments height Integer, the height of the output shape. width Integer, the width of the output shape. seed Integer. Used to create a random seed. name A string, the name of the layer. Methods adapt View source adapt( data, reset_state=True ) Fits the state of the preprocessing layer to the data being passed. Arguments data The data to train on. It can be passed either as a tf.data Dataset, or as a numpy array. reset_state Optional argument specifying whether to clear the state of the layer at the start of the call to adapt, or whether to start from the existing state. This argument may not be relevant to all preprocessing layers: a subclass of PreprocessingLayer may choose to throw if 'reset_state' is set to False.
tensorflow.keras.layers.experimental.preprocessing.randomcrop
tf.keras.layers.experimental.preprocessing.RandomFlip Randomly flip each image horizontally and vertically. Inherits From: PreprocessingLayer, Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.experimental.preprocessing.RandomFlip tf.keras.layers.experimental.preprocessing.RandomFlip( mode=HORIZONTAL_AND_VERTICAL, seed=None, name=None, **kwargs ) This layer will flip the images based on the mode attribute. During inference time, the output will be identical to input. Call the layer with training=True to flip the input. Input shape: 4D tensor with shape: (samples, height, width, channels), data_format='channels_last'. Output shape: 4D tensor with shape: (samples, height, width, channels), data_format='channels_last'. Attributes mode String indicating which flip mode to use. Can be "horizontal", "vertical", or "horizontal_and_vertical". Defaults to "horizontal_and_vertical". "horizontal" is a left-right flip and "vertical" is a top-bottom flip. seed Integer. Used to create a random seed. name A string, the name of the layer. Methods adapt View source adapt( data, reset_state=True ) Fits the state of the preprocessing layer to the data being passed. Arguments data The data to train on. It can be passed either as a tf.data Dataset, or as a numpy array. reset_state Optional argument specifying whether to clear the state of the layer at the start of the call to adapt, or whether to start from the existing state. This argument may not be relevant to all preprocessing layers: a subclass of PreprocessingLayer may choose to throw if 'reset_state' is set to False.
tensorflow.keras.layers.experimental.preprocessing.randomflip
tf.keras.layers.experimental.preprocessing.RandomHeight Randomly vary the height of a batch of images during training. Inherits From: PreprocessingLayer, Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.experimental.preprocessing.RandomHeight tf.keras.layers.experimental.preprocessing.RandomHeight( factor, interpolation='bilinear', seed=None, name=None, **kwargs ) Adjusts the height of a batch of images by a random factor. The input should be a 4-D tensor in the "channels_last" image data format. By default, this layer is inactive during inference. Arguments factor A positive float (fraction of original height), or a tuple of size 2 representing lower and upper bound for resizing vertically. When represented as a single float, this value is used for both the upper and lower bound. For instance, factor=(0.2, 0.3) results in an output with height changed by a random amount in the range [20%, 30%]. factor=(-0.2, 0.3) results in an output with height changed by a random amount in the range [-20%, +30%].factor=0.2results in an output with height changed by a random amount in the range[-20%, +20%]. </td> </tr><tr> <td>interpolation</td> <td> String, the interpolation method. Defaults tobilinear. Supportsbilinear,nearest,bicubic,area,lanczos3,lanczos5,gaussian,mitchellcubic</td> </tr><tr> <td>seed</td> <td> Integer. Used to create a random seed. </td> </tr><tr> <td>name` A string, the name of the layer. Input shape: 4D tensor with shape: (samples, height, width, channels) (data_format='channels_last'). Output shape: 4D tensor with shape: (samples, random_height, width, channels). Methods adapt View source adapt( data, reset_state=True ) Fits the state of the preprocessing layer to the data being passed. Arguments data The data to train on. It can be passed either as a tf.data Dataset, or as a numpy array. reset_state Optional argument specifying whether to clear the state of the layer at the start of the call to adapt, or whether to start from the existing state. This argument may not be relevant to all preprocessing layers: a subclass of PreprocessingLayer may choose to throw if 'reset_state' is set to False.
tensorflow.keras.layers.experimental.preprocessing.randomheight
tf.keras.layers.experimental.preprocessing.RandomRotation Randomly rotate each image. Inherits From: PreprocessingLayer, Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.experimental.preprocessing.RandomRotation tf.keras.layers.experimental.preprocessing.RandomRotation( factor, fill_mode='reflect', interpolation='bilinear', seed=None, name=None, fill_value=0.0, **kwargs ) By default, random rotations are only applied during training. At inference time, the layer does nothing. If you need to apply random rotations at inference time, set training to True when calling the layer. Input shape: 4D tensor with shape: (samples, height, width, channels), data_format='channels_last'. Output shape: 4D tensor with shape: (samples, height, width, channels), data_format='channels_last'. Input shape: 4D tensor with shape: (samples, height, width, channels), data_format='channels_last'. Output shape: 4D tensor with shape: (samples, height, width, channels), data_format='channels_last'. Raise ValueError if either bound is not between [0, 1], or upper bound is less than lower bound. Attributes factor a float represented as fraction of 2pi, or a tuple of size 2 representing lower and upper bound for rotating clockwise and counter-clockwise. A positive values means rotating counter clock-wise, while a negative value means clock-wise. When represented as a single float, this value is used for both the upper and lower bound. For instance, factor=(-0.2, 0.3) results in an output rotation by a random amount in the range [-20% * 2pi, 30% * 2pi]. factor=0.2 results in an output rotating by a random amount in the range [-20% * 2pi, 20% * 2pi]. fill_mode Points outside the boundaries of the input are filled according to the given mode (one of {'constant', 'reflect', 'wrap', 'nearest'}). reflect: (d c b a | a b c d | d c b a) The input is extended by reflecting about the edge of the last pixel. constant: (k k k k | a b c d | k k k k) The input is extended by filling all values beyond the edge with the same constant value k = 0. wrap: (a b c d | a b c d | a b c d) The input is extended by wrapping around to the opposite edge. nearest: (a a a a | a b c d | d d d d) The input is extended by the nearest pixel. interpolation Interpolation mode. Supported values: "nearest", "bilinear". seed Integer. Used to create a random seed. name A string, the name of the layer. fill_value a float represents the value to be filled outside the boundaries when fill_mode is "constant". Methods adapt View source adapt( data, reset_state=True ) Fits the state of the preprocessing layer to the data being passed. Arguments data The data to train on. It can be passed either as a tf.data Dataset, or as a numpy array. reset_state Optional argument specifying whether to clear the state of the layer at the start of the call to adapt, or whether to start from the existing state. This argument may not be relevant to all preprocessing layers: a subclass of PreprocessingLayer may choose to throw if 'reset_state' is set to False.
tensorflow.keras.layers.experimental.preprocessing.randomrotation
tf.keras.layers.experimental.preprocessing.RandomTranslation Randomly translate each image during training. Inherits From: PreprocessingLayer, Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.experimental.preprocessing.RandomTranslation tf.keras.layers.experimental.preprocessing.RandomTranslation( height_factor, width_factor, fill_mode='reflect', interpolation='bilinear', seed=None, name=None, fill_value=0.0, **kwargs ) Arguments height_factor a float represented as fraction of value, or a tuple of size 2 representing lower and upper bound for shifting vertically. A negative value means shifting image up, while a positive value means shifting image down. When represented as a single positive float, this value is used for both the upper and lower bound. For instance, height_factor=(-0.2, 0.3) results in an output shifted by a random amount in the range [-20%, +30%]. height_factor=0.2 results in an output height shifted by a random amount in the range [-20%, +20%]. width_factor a float represented as fraction of value, or a tuple of size 2 representing lower and upper bound for shifting horizontally. A negative value means shifting image left, while a positive value means shifting image right. When represented as a single positive float, this value is used for both the upper and lower bound. For instance, width_factor=(-0.2, 0.3) results in an output shifted left by 20%, and shifted right by 30%. width_factor=0.2 results in an output height shifted left or right by 20%. fill_mode Points outside the boundaries of the input are filled according to the given mode (one of {'constant', 'reflect', 'wrap', 'nearest'}). reflect: (d c b a | a b c d | d c b a) The input is extended by reflecting about the edge of the last pixel. constant: (k k k k | a b c d | k k k k) The input is extended by filling all values beyond the edge with the same constant value k = 0. wrap: (a b c d | a b c d | a b c d) The input is extended by wrapping around to the opposite edge. nearest: (a a a a | a b c d | d d d d) The input is extended by the nearest pixel. interpolation Interpolation mode. Supported values: "nearest", "bilinear". seed Integer. Used to create a random seed. name A string, the name of the layer. fill_value a float represents the value to be filled outside the boundaries when fill_mode is "constant". Input shape: 4D tensor with shape: (samples, height, width, channels), data_format='channels_last'. Output shape: 4D tensor with shape: (samples, height, width, channels), data_format='channels_last'. Raise ValueError if either bound is not between [0, 1], or upper bound is less than lower bound. Methods adapt View source adapt( data, reset_state=True ) Fits the state of the preprocessing layer to the data being passed. Arguments data The data to train on. It can be passed either as a tf.data Dataset, or as a numpy array. reset_state Optional argument specifying whether to clear the state of the layer at the start of the call to adapt, or whether to start from the existing state. This argument may not be relevant to all preprocessing layers: a subclass of PreprocessingLayer may choose to throw if 'reset_state' is set to False.
tensorflow.keras.layers.experimental.preprocessing.randomtranslation
tf.keras.layers.experimental.preprocessing.RandomWidth Randomly vary the width of a batch of images during training. Inherits From: PreprocessingLayer, Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.experimental.preprocessing.RandomWidth tf.keras.layers.experimental.preprocessing.RandomWidth( factor, interpolation='bilinear', seed=None, name=None, **kwargs ) Adjusts the width of a batch of images by a random factor. The input should be a 4-D tensor in the "channels_last" image data format. By default, this layer is inactive during inference. Arguments factor A positive float (fraction of original height), or a tuple of size 2 representing lower and upper bound for resizing vertically. When represented as a single float, this value is used for both the upper and lower bound. For instance, factor=(0.2, 0.3) results in an output with width changed by a random amount in the range [20%, 30%]. factor=(-0.2, 0.3) results in an output with width changed by a random amount in the range [-20%, +30%].factor=0.2results in an output with width changed by a random amount in the range[-20%, +20%]. </td> </tr><tr> <td>interpolation</td> <td> String, the interpolation method. Defaults tobilinear. Supportsbilinear,nearest,bicubic,area,lanczos3,lanczos5,gaussian,mitchellcubic</td> </tr><tr> <td>seed</td> <td> Integer. Used to create a random seed. </td> </tr><tr> <td>name` A string, the name of the layer. Input shape: 4D tensor with shape: (samples, height, width, channels) (data_format='channels_last'). Output shape: 4D tensor with shape: (samples, height, random_width, channels). Methods adapt View source adapt( data, reset_state=True ) Fits the state of the preprocessing layer to the data being passed. Arguments data The data to train on. It can be passed either as a tf.data Dataset, or as a numpy array. reset_state Optional argument specifying whether to clear the state of the layer at the start of the call to adapt, or whether to start from the existing state. This argument may not be relevant to all preprocessing layers: a subclass of PreprocessingLayer may choose to throw if 'reset_state' is set to False.
tensorflow.keras.layers.experimental.preprocessing.randomwidth
tf.keras.layers.experimental.preprocessing.RandomZoom Randomly zoom each image during training. Inherits From: PreprocessingLayer, Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.experimental.preprocessing.RandomZoom tf.keras.layers.experimental.preprocessing.RandomZoom( height_factor, width_factor=None, fill_mode='reflect', interpolation='bilinear', seed=None, name=None, fill_value=0.0, **kwargs ) Arguments height_factor a float represented as fraction of value, or a tuple of size 2 representing lower and upper bound for zooming vertically. When represented as a single float, this value is used for both the upper and lower bound. A positive value means zooming out, while a negative value means zooming in. For instance, height_factor=(0.2, 0.3) result in an output zoomed out by a random amount in the range [+20%, +30%]. height_factor=(-0.3, -0.2) result in an output zoomed in by a random amount in the range [+20%, +30%]. width_factor a float represented as fraction of value, or a tuple of size 2 representing lower and upper bound for zooming horizontally. When represented as a single float, this value is used for both the upper and lower bound. For instance, width_factor=(0.2, 0.3) result in an output zooming out between 20% to 30%. width_factor=(-0.3, -0.2) result in an output zooming in between 20% to 30%. Defaults to None, i.e., zooming vertical and horizontal directions by preserving the aspect ratio. fill_mode Points outside the boundaries of the input are filled according to the given mode (one of {'constant', 'reflect', 'wrap', 'nearest'}). reflect: (d c b a | a b c d | d c b a) The input is extended by reflecting about the edge of the last pixel. constant: (k k k k | a b c d | k k k k) The input is extended by filling all values beyond the edge with the same constant value k = 0. wrap: (a b c d | a b c d | a b c d) The input is extended by wrapping around to the opposite edge. nearest: (a a a a | a b c d | d d d d) The input is extended by the nearest pixel. interpolation Interpolation mode. Supported values: "nearest", "bilinear". seed Integer. Used to create a random seed. name A string, the name of the layer. fill_value a float represents the value to be filled outside the boundaries when fill_mode is "constant". Example: input_img = np.random.random((32, 224, 224, 3)) layer = tf.keras.layers.experimental.preprocessing.RandomZoom(.5, .2) out_img = layer(input_img) out_img.shape TensorShape([32, 224, 224, 3]) Input shape: 4D tensor with shape: (samples, height, width, channels), data_format='channels_last'. Output shape: 4D tensor with shape: (samples, height, width, channels), data_format='channels_last'. Raise ValueError if lower bound is not between [0, 1], or upper bound is negative. Methods adapt View source adapt( data, reset_state=True ) Fits the state of the preprocessing layer to the data being passed. Arguments data The data to train on. It can be passed either as a tf.data Dataset, or as a numpy array. reset_state Optional argument specifying whether to clear the state of the layer at the start of the call to adapt, or whether to start from the existing state. This argument may not be relevant to all preprocessing layers: a subclass of PreprocessingLayer may choose to throw if 'reset_state' is set to False.
tensorflow.keras.layers.experimental.preprocessing.randomzoom
tf.keras.layers.experimental.preprocessing.Rescaling Multiply inputs by scale and adds offset. Inherits From: PreprocessingLayer, Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.experimental.preprocessing.Rescaling tf.keras.layers.experimental.preprocessing.Rescaling( scale, offset=0.0, name=None, **kwargs ) For instance: To rescale an input in the [0, 255] range to be in the [0, 1] range, you would pass scale=1./255. To rescale an input in the [0, 255] range to be in the [-1, 1] range, you would pass scale=1./127.5, offset=-1. The rescaling is applied both during training and inference. Input shape: Arbitrary. Output shape: Same as input. Arguments scale Float, the scale to apply to the inputs. offset Float, the offset to apply to the inputs. name A string, the name of the layer. Methods adapt View source adapt( data, reset_state=True ) Fits the state of the preprocessing layer to the data being passed. Arguments data The data to train on. It can be passed either as a tf.data Dataset, or as a numpy array. reset_state Optional argument specifying whether to clear the state of the layer at the start of the call to adapt, or whether to start from the existing state. This argument may not be relevant to all preprocessing layers: a subclass of PreprocessingLayer may choose to throw if 'reset_state' is set to False.
tensorflow.keras.layers.experimental.preprocessing.rescaling
tf.keras.layers.experimental.preprocessing.Resizing Image resizing layer. Inherits From: PreprocessingLayer, Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.experimental.preprocessing.Resizing tf.keras.layers.experimental.preprocessing.Resizing( height, width, interpolation='bilinear', name=None, **kwargs ) Resize the batched image input to target height and width. The input should be a 4-D tensor in the format of NHWC. Arguments height Integer, the height of the output shape. width Integer, the width of the output shape. interpolation String, the interpolation method. Defaults to bilinear. Supports bilinear, nearest, bicubic, area, lanczos3, lanczos5, gaussian, mitchellcubic name A string, the name of the layer. Methods adapt View source adapt( data, reset_state=True ) Fits the state of the preprocessing layer to the data being passed. Arguments data The data to train on. It can be passed either as a tf.data Dataset, or as a numpy array. reset_state Optional argument specifying whether to clear the state of the layer at the start of the call to adapt, or whether to start from the existing state. This argument may not be relevant to all preprocessing layers: a subclass of PreprocessingLayer may choose to throw if 'reset_state' is set to False.
tensorflow.keras.layers.experimental.preprocessing.resizing
tf.keras.layers.experimental.preprocessing.StringLookup Maps strings from a vocabulary to integer indices. Inherits From: PreprocessingLayer, Layer, Module tf.keras.layers.experimental.preprocessing.StringLookup( max_tokens=None, num_oov_indices=1, mask_token='', oov_token='[UNK]', vocabulary=None, encoding=None, invert=False, **kwargs ) This layer translates a set of arbitrary strings into an integer output via a table-based lookup, with optional out-of-vocabulary handling. If desired, the user can call this layer's adapt() method on a data set, which will analyze the data set, determine the frequency of individual string values, and create a vocabulary from them. This vocabulary can have unlimited size or be capped, depending on the configuration options for this layer; if there are more unique values in the input than the maximum vocabulary size, the most frequent terms will be used to create the vocabulary. Examples: Creating a lookup layer with a known vocabulary This example creates a lookup layer with a pre-existing vocabulary. vocab = ["a", "b", "c", "d"] data = tf.constant([["a", "c", "d"], ["d", "z", "b"]]) layer = StringLookup(vocabulary=vocab) layer(data) <tf.Tensor: shape=(2, 3), dtype=int64, numpy= array([[2, 4, 5], [5, 1, 3]])> Creating a lookup layer with an adapted vocabulary This example creates a lookup layer and generates the vocabulary by analyzing the dataset. data = tf.constant([["a", "c", "d"], ["d", "z", "b"]]) layer = StringLookup() layer.adapt(data) layer.get_vocabulary() ['', '[UNK]', 'd', 'z', 'c', 'b', 'a'] Note how the mask token '' and the OOV token [UNK] have been added to the vocabulary. The remaining tokens are sorted by frequency ('d', which has 2 occurrences, is first) then by inverse sort order. data = tf.constant([["a", "c", "d"], ["d", "z", "b"]]) layer = StringLookup() layer.adapt(data) layer(data) <tf.Tensor: shape=(2, 3), dtype=int64, numpy= array([[6, 4, 2], [2, 3, 5]])> Lookups with multiple OOV tokens. This example demonstrates how to use a lookup layer with multiple OOV tokens. When a layer is created with more than one OOV token, any OOV values are hashed into the number of OOV buckets, distributing OOV values in a deterministic fashion across the set. vocab = ["a", "b", "c", "d"] data = tf.constant([["a", "c", "d"], ["m", "z", "b"]]) layer = StringLookup(vocabulary=vocab, num_oov_indices=2) layer(data) <tf.Tensor: shape=(2, 3), dtype=int64, numpy= array([[3, 5, 6], [1, 2, 4]])> Note that the output for OOV value 'm' is 1, while the output for OOV value 'z' is 2. The in-vocab terms have their output index increased by 1 from earlier examples (a maps to 3, etc) in order to make space for the extra OOV value. Inverse lookup This example demonstrates how to map indices to strings using this layer. (You can also use adapt() with inverse=True, but for simplicity we'll pass the vocab in this example.) vocab = ["a", "b", "c", "d"] data = tf.constant([[1, 3, 4], [4, 5, 2]]) layer = StringLookup(vocabulary=vocab, invert=True) layer(data) <tf.Tensor: shape=(2, 3), dtype=string, numpy= array([[b'a', b'c', b'd'], [b'd', b'[UNK]', b'b']], dtype=object)> Note that the integer 5, which is out of the vocabulary space, returns an OOV token. Forward and inverse lookup pairs This example demonstrates how to use the vocabulary of a standard lookup layer to create an inverse lookup layer. vocab = ["a", "b", "c", "d"] data = tf.constant([["a", "c", "d"], ["d", "z", "b"]]) layer = StringLookup(vocabulary=vocab) i_layer = StringLookup(vocabulary=layer.get_vocabulary(), invert=True) int_data = layer(data) i_layer(int_data) <tf.Tensor: shape=(2, 3), dtype=string, numpy= array([[b'a', b'c', b'd'], [b'd', b'[UNK]', b'b']], dtype=object)> In this example, the input value 'z' resulted in an output of '[UNK]', since 1000 was not in the vocabulary - it got represented as an OOV, and all OOV values are returned as '[OOV}' in the inverse layer. Also, note that for the inverse to work, you must have already set the forward layer vocabulary either directly or via fit() before calling get_vocabulary(). Attributes max_tokens The maximum size of the vocabulary for this layer. If None, there is no cap on the size of the vocabulary. Note that this vocabulary includes the OOV and mask tokens, so the effective number of tokens is (max_tokens - num_oov_indices - (1 if mask_token else 0)) num_oov_indices The number of out-of-vocabulary tokens to use; defaults to If this value is more than 1, OOV inputs are hashed to determine their OOV value; if this value is 0, passing an OOV input will result in a '-1' being returned for that value in the output tensor. (Note that, because the value is -1 and not 0, this will allow you to effectively drop OOV values from categorical encodings.) mask_token A token that represents masked values, and which is mapped to index 0. Defaults to the empty string "". If set to None, no mask term will be added and the OOV tokens, if any, will be indexed from (0...num_oov_indices) instead of (1...num_oov_indices+1). oov_token The token representing an out-of-vocabulary value. Defaults to "[UNK]". vocabulary An optional list of vocabulary terms, or a path to a text file containing a vocabulary to load into this layer. The file should contain one token per line. If the list or file contains the same token multiple times, an error will be thrown. encoding The Python string encoding to use. Defaults to 'utf-8'. invert If true, this layer will map indices to vocabulary items instead of mapping vocabulary items to indices. Methods adapt View source adapt( data, reset_state=True ) Fits the state of the preprocessing layer to the dataset. Overrides the default adapt method to apply relevant preprocessing to the inputs before passing to the combiner. Arguments data The data to train on. It can be passed either as a tf.data Dataset, or as a numpy array. reset_state Optional argument specifying whether to clear the state of the layer at the start of the call to adapt. This must be True for this layer, which does not support repeated calls to adapt. get_vocabulary View source get_vocabulary() set_vocabulary View source set_vocabulary( vocab ) Sets vocabulary data for this layer with inverse=False. This method sets the vocabulary for this layer directly, instead of analyzing a dataset through 'adapt'. It should be used whenever the vocab information is already known. If vocabulary data is already present in the layer, this method will either replace it Arguments vocab An array of string tokens. Raises ValueError If there are too many inputs, the inputs do not match, or input data is missing. vocab_size View source vocab_size()
tensorflow.keras.layers.experimental.preprocessing.stringlookup
tf.keras.layers.experimental.preprocessing.TextVectorization Text vectorization layer. Inherits From: PreprocessingLayer, Layer, Module tf.keras.layers.experimental.preprocessing.TextVectorization( max_tokens=None, standardize=LOWER_AND_STRIP_PUNCTUATION, split=SPLIT_ON_WHITESPACE, ngrams=None, output_mode=INT, output_sequence_length=None, pad_to_max_tokens=True, vocabulary=None, **kwargs ) This layer has basic options for managing text in a Keras model. It transforms a batch of strings (one sample = one string) into either a list of token indices (one sample = 1D tensor of integer token indices) or a dense representation (one sample = 1D tensor of float values representing data about the sample's tokens). If desired, the user can call this layer's adapt() method on a dataset. When this layer is adapted, it will analyze the dataset, determine the frequency of individual string values, and create a 'vocabulary' from them. This vocabulary can have unlimited size or be capped, depending on the configuration options for this layer; if there are more unique values in the input than the maximum vocabulary size, the most frequent terms will be used to create the vocabulary. The processing of each sample contains the following steps: standardize each sample (usually lowercasing + punctuation stripping) split each sample into substrings (usually words) recombine substrings into tokens (usually ngrams) index tokens (associate a unique int value with each token) transform each sample using this index, either into a vector of ints or a dense float vector. Some notes on passing Callables to customize splitting and normalization for this layer: Any callable can be passed to this Layer, but if you want to serialize this object you should only pass functions that are registered Keras serializables (see tf.keras.utils.register_keras_serializable for more details). When using a custom callable for standardize, the data received by the callable will be exactly as passed to this layer. The callable should return a tensor of the same shape as the input. When using a custom callable for split, the data received by the callable will have the 1st dimension squeezed out - instead of [["string to split"], ["another string to split"]], the Callable will see ["string to split", "another string to split"]. The callable should return a Tensor with the first dimension containing the split tokens - in this example, we should see something like [["string", "to", "split], ["another", "string", "to", "split"]]. This makes the callable site natively compatible with tf.strings.split(). Example: This example instantiates a TextVectorization layer that lowercases text, splits on whitespace, strips punctuation, and outputs integer vocab indices. text_dataset = tf.data.Dataset.from_tensor_slices(["foo", "bar", "baz"]) max_features = 5000 # Maximum vocab size. max_len = 4 # Sequence length to pad the outputs to. embedding_dims = 2 # Create the layer. vectorize_layer = TextVectorization( max_tokens=max_features, output_mode='int', output_sequence_length=max_len) # Now that the vocab layer has been created, call `adapt` on the text-only # dataset to create the vocabulary. You don't have to batch, but for large # datasets this means we're not keeping spare copies of the dataset. vectorize_layer.adapt(text_dataset.batch(64)) # Create the model that uses the vectorize text layer model = tf.keras.models.Sequential() # Start by creating an explicit input layer. It needs to have a shape of # (1,) (because we need to guarantee that there is exactly one string # input per batch), and the dtype needs to be 'string'. model.add(tf.keras.Input(shape=(1,), dtype=tf.string)) # The first layer in our model is the vectorization layer. After this # layer, we have a tensor of shape (batch_size, max_len) containing vocab # indices. model.add(vectorize_layer) # Now, the model can map strings to integers, and you can add an embedding # layer to map these integers to learned embeddings. input_data = [["foo qux bar"], ["qux baz"]] model.predict(input_data) array([[2, 1, 4, 0], [1, 3, 0, 0]]) Example: This example instantiates a TextVectorization layer by passing a list of vocabulary terms to the layer's init method. input_array = np.array([["earth", "wind", "and", "fire"], ["fire", "and", "earth", "michigan"]]) expected_output = [[2, 3, 4, 5], [5, 4, 2, 1]] input_data = keras.Input(shape=(None,), dtype=dtypes.string) layer = get_layer_class()( max_tokens=None, standardize=None, split=None, output_mode=text_vectorization.INT, vocabulary=vocab_data) int_data = layer(input_data) model = keras.Model(inputs=input_data, outputs=int_data) output_dataset = model.predict(input_array) >>> vocab_data = ["earth", "wind", "and", "fire"] >>> max_len = 4 # Sequence length to pad the outputs to. >>> >>> # Create the layer, passing the vocab directly. You can also pass the >>> # vocabulary arg a path to a file containing one vocabulary word per >>> # line. >>> vectorize_layer = TextVectorization( ... max_tokens=max_features, ... output_mode='int', ... output_sequence_length=max_len, ... vocabulary=vocab_data) >>> >>> # Because we've passed the vocabulary directly, we don't need to adapt >>> # the layer - the vocabulary is already set. The vocabulary contains the >>> # padding token ('') and OOV token ('[UNK]') as well as the passed tokens. >>> vectorize_layer.get_vocabulary() ['', '[UNK]', 'earth', 'wind', 'and', 'fire'] Attributes max_tokens The maximum size of the vocabulary for this layer. If None, there is no cap on the size of the vocabulary. Note that this vocabulary contains 1 OOV token, so the effective number of tokens is (max_tokens - 1 - (1 if output == "int" else 0)). standardize Optional specification for standardization to apply to the input text. Values can be None (no standardization), 'lower_and_strip_punctuation' (lowercase and remove punctuation) or a Callable. Default is 'lower_and_strip_punctuation'. split Optional specification for splitting the input text. Values can be None (no splitting), 'whitespace' (split on ASCII whitespace), or a Callable. The default is 'whitespace'. ngrams Optional specification for ngrams to create from the possibly-split input text. Values can be None, an integer or tuple of integers; passing an integer will create ngrams up to that integer, and passing a tuple of integers will create ngrams for the specified values in the tuple. Passing None means that no ngrams will be created. output_mode Optional specification for the output of the layer. Values can be "int", "binary", "count" or "tf-idf", configuring the layer as follows: "int": Outputs integer indices, one integer index per split string token. When output == "int", 0 is reserved for masked locations; this reduces the vocab size to max_tokens-2 instead of max_tokens-1 "binary": Outputs a single int array per batch, of either vocab_size or max_tokens size, containing 1s in all elements where the token mapped to that index exists at least once in the batch item. "count": As "binary", but the int array contains a count of the number of times the token at that index appeared in the batch item. "tf-idf": As "binary", but the TF-IDF algorithm is applied to find the value in each token slot. output_sequence_length Only valid in INT mode. If set, the output will have its time dimension padded or truncated to exactly output_sequence_length values, resulting in a tensor of shape [batch_size, output_sequence_length] regardless of how many tokens resulted from the splitting step. Defaults to None. pad_to_max_tokens Only valid in "binary", "count", and "tf-idf" modes. If True, the output will have its feature axis padded to max_tokens even if the number of unique tokens in the vocabulary is less than max_tokens, resulting in a tensor of shape [batch_size, max_tokens] regardless of vocabulary size. Defaults to True. vocabulary An optional list of vocabulary terms, or a path to a text file containing a vocabulary to load into this layer. The file should contain one token per line. If the list or file contains the same token multiple times, an error will be thrown. Methods adapt View source adapt( data, reset_state=True ) Fits the state of the preprocessing layer to the dataset. Overrides the default adapt method to apply relevant preprocessing to the inputs before passing to the combiner. Arguments data The data to train on. It can be passed either as a tf.data Dataset, as a NumPy array, a string tensor, or as a list of texts. reset_state Optional argument specifying whether to clear the state of the layer at the start of the call to adapt. This must be True for this layer, which does not support repeated calls to adapt. get_vocabulary View source get_vocabulary() set_vocabulary View source set_vocabulary( vocab, df_data=None, oov_df_value=None ) Sets vocabulary (and optionally document frequency) data for this layer. This method sets the vocabulary and DF data for this layer directly, instead of analyzing a dataset through 'adapt'. It should be used whenever the vocab (and optionally document frequency) information is already known. If vocabulary data is already present in the layer, this method will replace it. Arguments vocab An array of string tokens. df_data An array of document frequency data. Only necessary if the layer output_mode is TFIDF. oov_df_value The document frequency of the OOV token. Only necessary if output_mode is TFIDF. Raises ValueError If there are too many inputs, the inputs do not match, or input data is missing. RuntimeError If the vocabulary cannot be set when this function is called. This happens when "binary", "count", and "tfidf" modes, if "pad_to_max_tokens" is False and the layer itself has already been called.
tensorflow.keras.layers.experimental.preprocessing.textvectorization
tf.keras.layers.experimental.RandomFourierFeatures Layer that projects its inputs into a random feature space. Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.experimental.RandomFourierFeatures tf.keras.layers.experimental.RandomFourierFeatures( output_dim, kernel_initializer='gaussian', scale=None, trainable=False, name=None, **kwargs ) This layer implements a mapping from input space to a space with output_dim dimensions, which approximates shift-invariant kernels. A kernel function K(x, y) is shift-invariant if K(x, y) == k(x - y) for some function k. Many popular Radial Basis Functions (RBF), including Gaussian and Laplacian kernels, are shift-invariant. The implementation of this layer is based on the following paper: "Random Features for Large-Scale Kernel Machines" by Ali Rahimi and Ben Recht. The distribution from which the parameters of the random features map (layer) are sampled determines which shift-invariant kernel the layer approximates (see paper for more details). You can use the distribution of your choice. The layer supports out-of-the-box approximation sof the following two RBF kernels: Gaussian: K(x, y) == exp(- square(x - y) / (2 * square(scale))) Laplacian: K(x, y) = exp(-abs(x - y) / scale)) Note: Unlike what is described in the paper and unlike what is used in the Scikit-Learn implementation, the output of this layer does not apply the sqrt(2 / D) normalization factor. Usage: Typically, this layer is used to "kernelize" linear models by applying a non-linear transformation (this layer) to the input features and then training a linear model on top of the transformed features. Depending on the loss function of the linear model, the composition of this layer and the linear model results to models that are equivalent (up to approximation) to kernel SVMs (for hinge loss), kernel logistic regression (for logistic loss), kernel linear regression (for squared loss), etc. Examples: A kernel multinomial logistic regression model with Gaussian kernel for MNIST: model = keras.Sequential([ keras.Input(shape=(784,)), RandomFourierFeatures( output_dim=4096, scale=10., kernel_initializer='gaussian'), layers.Dense(units=10, activation='softmax'), ]) model.compile( optimizer='adam', loss='categorical_crossentropy', metrics=['categorical_accuracy'] ) A quasi-SVM classifier for MNIST: model = keras.Sequential([ keras.Input(shape=(784,)), RandomFourierFeatures( output_dim=4096, scale=10., kernel_initializer='gaussian'), layers.Dense(units=10), ]) model.compile( optimizer='adam', loss='hinge', metrics=['categorical_accuracy'] ) To use another kernel, just replace the layer creation line with: random_features_layer = RandomFourierFeatures( output_dim=500, kernel_initializer=<my_initializer>, scale=..., ...) Arguments output_dim Positive integer, the dimension of the layer's output, i.e., the number of random features used to approximate the kernel. kernel_initializer Determines the distribution of the parameters of the random features map (and therefore the kernel approximated by the layer). It can be either a string identifier or a Keras Initializer instance. Currently only 'gaussian' and 'laplacian' are supported string identifiers (case insensitive). Note that the kernel matrix is not trainable. scale For Gaussian and Laplacian kernels, this corresponds to a scaling factor of the corresponding kernel approximated by the layer (see concrete definitions above). When provided, it should be a positive float. If None, a default value is used: if the kernel initializer is set to "gaussian", scale defaults to sqrt(input_dim / 2), otherwise, it defaults to 1.0. Both the approximation error of the kernel and the classification quality are sensitive to this parameter. If trainable is set to True, this parameter is learned end-to-end during training and the provided value serves as the initial value. Note: When features from this layer are fed to a linear model, by making scale trainable, the resulting optimization problem is no longer convex (even if the loss function used by the linear model is convex). trainable Whether the scaling parameter of the layer should be trainable. Defaults to False. name String, name to use for this layer.
tensorflow.keras.layers.experimental.randomfourierfeatures
tf.keras.layers.experimental.SyncBatchNormalization Normalize and scale inputs or activations synchronously across replicas. Inherits From: Layer, Module tf.keras.layers.experimental.SyncBatchNormalization( axis=-1, momentum=0.99, epsilon=0.001, center=True, scale=True, beta_initializer='zeros', gamma_initializer='ones', moving_mean_initializer='zeros', moving_variance_initializer='ones', beta_regularizer=None, gamma_regularizer=None, beta_constraint=None, gamma_constraint=None, renorm=False, renorm_clipping=None, renorm_momentum=0.99, trainable=True, adjustment=None, name=None, **kwargs ) Applies batch normalization to activations of the previous layer at each batch by synchronizing the global batch statistics across all devices that are training the model. For specific details about batch normalization please refer to the tf.keras.layers.BatchNormalization layer docs. If this layer is used when using tf.distribute strategy to train models across devices/workers, there will be an allreduce call to aggregate batch statistics across all replicas at every training step. Without tf.distribute strategy, this layer behaves as a regular tf.keras.layers.BatchNormalization layer. Example usage: strategy = tf.distribute.MirroredStrategy() with strategy.scope(): model = tf.keras.Sequential() model.add(tf.keras.layers.Dense(16)) model.add(tf.keras.layers.experimental.SyncBatchNormalization()) Arguments axis Integer, the axis that should be normalized (typically the features axis). For instance, after a Conv2D layer with data_format="channels_first", set axis=1 in BatchNormalization. momentum Momentum for the moving average. epsilon Small float added to variance to avoid dividing by zero. center If True, add offset of beta to normalized tensor. If False, beta is ignored. scale If True, multiply by gamma. If False, gamma is not used. When the next layer is linear (also e.g. nn.relu), this can be disabled since the scaling will be done by the next layer. beta_initializer Initializer for the beta weight. gamma_initializer Initializer for the gamma weight. moving_mean_initializer Initializer for the moving mean. moving_variance_initializer Initializer for the moving variance. beta_regularizer Optional regularizer for the beta weight. gamma_regularizer Optional regularizer for the gamma weight. beta_constraint Optional constraint for the beta weight. gamma_constraint Optional constraint for the gamma weight. renorm Whether to use Batch Renormalization. This adds extra variables during training. The inference is the same for either value of this parameter. renorm_clipping A dictionary that may map keys 'rmax', 'rmin', 'dmax' to scalar Tensors used to clip the renorm correction. The correction (r, d) is used as corrected_value = normalized_value * r + d, with r clipped to [rmin, rmax], and d to [-dmax, dmax]. Missing rmax, rmin, dmax are set to inf, 0, inf, respectively. renorm_momentum Momentum used to update the moving means and standard deviations with renorm. Unlike momentum, this affects training and should be neither too small (which would add noise) nor too large (which would give stale estimates). Note that momentum is still applied to get the means and variances for inference. trainable Boolean, if True the variables will be marked as trainable. Call arguments: inputs: Input tensor (of any rank). training: Python boolean indicating whether the layer should behave in training mode or in inference mode. training=True: The layer will normalize its inputs using the mean and variance of the current batch of inputs. training=False: The layer will normalize its inputs using the mean and variance of its moving statistics, learned during training. Input shape: Arbitrary. Use the keyword argument input_shape (tuple of integers, does not include the samples axis) when using this layer as the first layer in a model. Output shape: Same shape as input.
tensorflow.keras.layers.experimental.syncbatchnormalization
tf.keras.layers.Flatten View source on GitHub Flattens the input. Does not affect the batch size. Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.Flatten tf.keras.layers.Flatten( data_format=None, **kwargs ) Note: If inputs are shaped (batch,) without a feature axis, then flattening adds an extra channel dimension and output shape is (batch, 1). Arguments data_format A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch, ..., channels) while channels_first corresponds to inputs with shape (batch, channels, ...). It defaults to the image_data_format value found in your Keras config file at ~/.keras/keras.json. If you never set it, then it will be "channels_last". Example: model = tf.keras.Sequential() model.add(tf.keras.layers.Conv2D(64, 3, 3, input_shape=(3, 32, 32))) model.output_shape (None, 1, 10, 64) model.add(Flatten()) model.output_shape (None, 640)
tensorflow.keras.layers.flatten
tf.keras.layers.GaussianDropout View source on GitHub Apply multiplicative 1-centered Gaussian noise. Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.GaussianDropout tf.keras.layers.GaussianDropout( rate, **kwargs ) As it is a regularization layer, it is only active at training time. Arguments rate Float, drop probability (as with Dropout). The multiplicative noise will have standard deviation sqrt(rate / (1 - rate)). Call arguments: inputs: Input tensor (of any rank). training: Python boolean indicating whether the layer should behave in training mode (adding dropout) or in inference mode (doing nothing). Input shape: Arbitrary. Use the keyword argument input_shape (tuple of integers, does not include the samples axis) when using this layer as the first layer in a model. Output shape: Same shape as input.
tensorflow.keras.layers.gaussiandropout
tf.keras.layers.GaussianNoise View source on GitHub Apply additive zero-centered Gaussian noise. Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.GaussianNoise tf.keras.layers.GaussianNoise( stddev, **kwargs ) This is useful to mitigate overfitting (you could see it as a form of random data augmentation). Gaussian Noise (GS) is a natural choice as corruption process for real valued inputs. As it is a regularization layer, it is only active at training time. Arguments stddev Float, standard deviation of the noise distribution. Call arguments: inputs: Input tensor (of any rank). training: Python boolean indicating whether the layer should behave in training mode (adding noise) or in inference mode (doing nothing). Input shape: Arbitrary. Use the keyword argument input_shape (tuple of integers, does not include the samples axis) when using this layer as the first layer in a model. Output shape: Same shape as input.
tensorflow.keras.layers.gaussiannoise
tf.keras.layers.GlobalAveragePooling1D View source on GitHub Global average pooling operation for temporal data. Inherits From: Layer, Module View aliases Main aliases tf.keras.layers.GlobalAvgPool1D Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.GlobalAveragePooling1D, tf.compat.v1.keras.layers.GlobalAvgPool1D tf.keras.layers.GlobalAveragePooling1D( data_format='channels_last', **kwargs ) Examples: input_shape = (2, 3, 4) x = tf.random.normal(input_shape) y = tf.keras.layers.GlobalAveragePooling1D()(x) print(y.shape) (2, 4) Arguments data_format A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch, steps, features) while channels_first corresponds to inputs with shape (batch, features, steps). Call arguments: inputs: A 3D tensor. mask: Binary tensor of shape (batch_size, steps) indicating whether a given step should be masked (excluded from the average). Input shape: If data_format='channels_last': 3D tensor with shape: (batch_size, steps, features) If data_format='channels_first': 3D tensor with shape: (batch_size, features, steps) Output shape: 2D tensor with shape (batch_size, features).
tensorflow.keras.layers.globalaveragepooling1d
tf.keras.layers.GlobalAveragePooling2D View source on GitHub Global average pooling operation for spatial data. Inherits From: Layer, Module View aliases Main aliases tf.keras.layers.GlobalAvgPool2D Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.GlobalAveragePooling2D, tf.compat.v1.keras.layers.GlobalAvgPool2D tf.keras.layers.GlobalAveragePooling2D( data_format=None, **kwargs ) Examples: input_shape = (2, 4, 5, 3) x = tf.random.normal(input_shape) y = tf.keras.layers.GlobalAveragePooling2D()(x) print(y.shape) (2, 3) Arguments data_format A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch, height, width, channels) while channels_first corresponds to inputs with shape (batch, channels, height, width). It defaults to the image_data_format value found in your Keras config file at ~/.keras/keras.json. If you never set it, then it will be "channels_last". Input shape: If data_format='channels_last': 4D tensor with shape (batch_size, rows, cols, channels). If data_format='channels_first': 4D tensor with shape (batch_size, channels, rows, cols). Output shape: 2D tensor with shape (batch_size, channels).
tensorflow.keras.layers.globalaveragepooling2d
tf.keras.layers.GlobalAveragePooling3D View source on GitHub Global Average pooling operation for 3D data. Inherits From: Layer, Module View aliases Main aliases tf.keras.layers.GlobalAvgPool3D Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.GlobalAveragePooling3D, tf.compat.v1.keras.layers.GlobalAvgPool3D tf.keras.layers.GlobalAveragePooling3D( data_format=None, **kwargs ) Arguments data_format A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch, spatial_dim1, spatial_dim2, spatial_dim3, channels) while channels_first corresponds to inputs with shape (batch, channels, spatial_dim1, spatial_dim2, spatial_dim3). It defaults to the image_data_format value found in your Keras config file at ~/.keras/keras.json. If you never set it, then it will be "channels_last". Input shape: If data_format='channels_last': 5D tensor with shape: (batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels) If data_format='channels_first': 5D tensor with shape: (batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3) Output shape: 2D tensor with shape (batch_size, channels).
tensorflow.keras.layers.globalaveragepooling3d
tf.keras.layers.GlobalMaxPool1D View source on GitHub Global max pooling operation for 1D temporal data. Inherits From: Layer, Module View aliases Main aliases tf.keras.layers.GlobalMaxPooling1D Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.GlobalMaxPool1D, tf.compat.v1.keras.layers.GlobalMaxPooling1D tf.keras.layers.GlobalMaxPool1D( data_format='channels_last', **kwargs ) Downsamples the input representation by taking the maximum value over the time dimension. For example: x = tf.constant([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]) x = tf.reshape(x, [3, 3, 1]) x <tf.Tensor: shape=(3, 3, 1), dtype=float32, numpy= array([[[1.], [2.], [3.]], [[4.], [5.], [6.]], [[7.], [8.], [9.]]], dtype=float32)> max_pool_1d = tf.keras.layers.GlobalMaxPooling1D() max_pool_1d(x) <tf.Tensor: shape=(3, 1), dtype=float32, numpy= array([[3.], [6.], [9.], dtype=float32)> Arguments data_format A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch, steps, features) while channels_first corresponds to inputs with shape (batch, features, steps). Input shape: If data_format='channels_last': 3D tensor with shape: (batch_size, steps, features) If data_format='channels_first': 3D tensor with shape: (batch_size, features, steps) Output shape: 2D tensor with shape (batch_size, features).
tensorflow.keras.layers.globalmaxpool1d
tf.keras.layers.GlobalMaxPool2D View source on GitHub Global max pooling operation for spatial data. Inherits From: Layer, Module View aliases Main aliases tf.keras.layers.GlobalMaxPooling2D Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.GlobalMaxPool2D, tf.compat.v1.keras.layers.GlobalMaxPooling2D tf.keras.layers.GlobalMaxPool2D( data_format=None, **kwargs ) Examples: input_shape = (2, 4, 5, 3) x = tf.random.normal(input_shape) y = tf.keras.layers.GlobalMaxPool2D()(x) print(y.shape) (2, 3) Arguments data_format A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch, height, width, channels) while channels_first corresponds to inputs with shape (batch, channels, height, width). It defaults to the image_data_format value found in your Keras config file at ~/.keras/keras.json. If you never set it, then it will be "channels_last". Input shape: If data_format='channels_last': 4D tensor with shape (batch_size, rows, cols, channels). If data_format='channels_first': 4D tensor with shape (batch_size, channels, rows, cols). Output shape: 2D tensor with shape (batch_size, channels).
tensorflow.keras.layers.globalmaxpool2d
tf.keras.layers.GlobalMaxPool3D View source on GitHub Global Max pooling operation for 3D data. Inherits From: Layer, Module View aliases Main aliases tf.keras.layers.GlobalMaxPooling3D Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.GlobalMaxPool3D, tf.compat.v1.keras.layers.GlobalMaxPooling3D tf.keras.layers.GlobalMaxPool3D( data_format=None, **kwargs ) Arguments data_format A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch, spatial_dim1, spatial_dim2, spatial_dim3, channels) while channels_first corresponds to inputs with shape (batch, channels, spatial_dim1, spatial_dim2, spatial_dim3). It defaults to the image_data_format value found in your Keras config file at ~/.keras/keras.json. If you never set it, then it will be "channels_last". Input shape: If data_format='channels_last': 5D tensor with shape: (batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels) If data_format='channels_first': 5D tensor with shape: (batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3) Output shape: 2D tensor with shape (batch_size, channels).
tensorflow.keras.layers.globalmaxpool3d
tf.keras.layers.GRU View source on GitHub Gated Recurrent Unit - Cho et al. 2014. Inherits From: GRU, RNN, Layer, Module tf.keras.layers.GRU( units, activation='tanh', recurrent_activation='sigmoid', use_bias=True, kernel_initializer='glorot_uniform', recurrent_initializer='orthogonal', bias_initializer='zeros', kernel_regularizer=None, recurrent_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, recurrent_constraint=None, bias_constraint=None, dropout=0.0, recurrent_dropout=0.0, return_sequences=False, return_state=False, go_backwards=False, stateful=False, unroll=False, time_major=False, reset_after=True, **kwargs ) See the Keras RNN API guide for details about the usage of RNN API. Based on available runtime hardware and constraints, this layer will choose different implementations (cuDNN-based or pure-TensorFlow) to maximize the performance. If a GPU is available and all the arguments to the layer meet the requirement of the CuDNN kernel (see below for details), the layer will use a fast cuDNN implementation. The requirements to use the cuDNN implementation are: activation == tanh recurrent_activation == sigmoid recurrent_dropout == 0 unroll is False use_bias is True reset_after is True Inputs, if use masking, are strictly right-padded. Eager execution is enabled in the outermost context. There are two variants of the GRU implementation. The default one is based on v3 and has reset gate applied to hidden state before matrix multiplication. The other one is based on original and has the order reversed. The second variant is compatible with CuDNNGRU (GPU-only) and allows inference on CPU. Thus it has separate biases for kernel and recurrent_kernel. To use this variant, set 'reset_after'=True and recurrent_activation='sigmoid'. For example: inputs = tf.random.normal([32, 10, 8]) gru = tf.keras.layers.GRU(4) output = gru(inputs) print(output.shape) (32, 4) gru = tf.keras.layers.GRU(4, return_sequences=True, return_state=True) whole_sequence_output, final_state = gru(inputs) print(whole_sequence_output.shape) (32, 10, 4) print(final_state.shape) (32, 4) Arguments units Positive integer, dimensionality of the output space. activation Activation function to use. Default: hyperbolic tangent (tanh). If you pass None, no activation is applied (ie. "linear" activation: a(x) = x). recurrent_activation Activation function to use for the recurrent step. Default: sigmoid (sigmoid). If you pass None, no activation is applied (ie. "linear" activation: a(x) = x). use_bias Boolean, (default True), whether the layer uses a bias vector. kernel_initializer Initializer for the kernel weights matrix, used for the linear transformation of the inputs. Default: glorot_uniform. recurrent_initializer Initializer for the recurrent_kernel weights matrix, used for the linear transformation of the recurrent state. Default: orthogonal. bias_initializer Initializer for the bias vector. Default: zeros. kernel_regularizer Regularizer function applied to the kernel weights matrix. Default: None. recurrent_regularizer Regularizer function applied to the recurrent_kernel weights matrix. Default: None. bias_regularizer Regularizer function applied to the bias vector. Default: None. activity_regularizer Regularizer function applied to the output of the layer (its "activation"). Default: None. kernel_constraint Constraint function applied to the kernel weights matrix. Default: None. recurrent_constraint Constraint function applied to the recurrent_kernel weights matrix. Default: None. bias_constraint Constraint function applied to the bias vector. Default: None. dropout Float between 0 and 1. Fraction of the units to drop for the linear transformation of the inputs. Default: 0. recurrent_dropout Float between 0 and 1. Fraction of the units to drop for the linear transformation of the recurrent state. Default: 0. return_sequences Boolean. Whether to return the last output in the output sequence, or the full sequence. Default: False. return_state Boolean. Whether to return the last state in addition to the output. Default: False. go_backwards Boolean (default False). If True, process the input sequence backwards and return the reversed sequence. stateful Boolean (default False). If True, the last state for each sample at index i in a batch will be used as initial state for the sample of index i in the following batch. unroll Boolean (default False). If True, the network will be unrolled, else a symbolic loop will be used. Unrolling can speed-up a RNN, although it tends to be more memory-intensive. Unrolling is only suitable for short sequences. time_major The shape format of the inputs and outputs tensors. If True, the inputs and outputs will be in shape [timesteps, batch, feature], whereas in the False case, it will be [batch, timesteps, feature]. Using time_major = True is a bit more efficient because it avoids transposes at the beginning and end of the RNN calculation. However, most TensorFlow data is batch-major, so by default this function accepts input and emits output in batch-major form. reset_after GRU convention (whether to apply reset gate after or before matrix multiplication). False = "before", True = "after" (default and CuDNN compatible). Call arguments: inputs: A 3D tensor, with shape [batch, timesteps, feature]. mask: Binary tensor of shape [samples, timesteps] indicating whether a given timestep should be masked (optional, defaults to None). training: Python boolean indicating whether the layer should behave in training mode or in inference mode. This argument is passed to the cell when calling it. This is only relevant if dropout or recurrent_dropout is used (optional, defaults to None). initial_state: List of initial state tensors to be passed to the first call of the cell (optional, defaults to None which causes creation of zero-filled initial state tensors). Attributes activation bias_constraint bias_initializer bias_regularizer dropout implementation kernel_constraint kernel_initializer kernel_regularizer recurrent_activation recurrent_constraint recurrent_dropout recurrent_initializer recurrent_regularizer reset_after states units use_bias Methods get_dropout_mask_for_cell View source get_dropout_mask_for_cell( inputs, training, count=1 ) Get the dropout mask for RNN cell's input. It will create mask based on context if there isn't any existing cached mask. If a new mask is generated, it will update the cache in the cell. Args inputs The input tensor whose shape will be used to generate dropout mask. training Boolean tensor, whether its in training mode, dropout will be ignored in non-training mode. count Int, how many dropout mask will be generated. It is useful for cell that has internal weights fused together. Returns List of mask tensor, generated or cached mask based on context. get_recurrent_dropout_mask_for_cell View source get_recurrent_dropout_mask_for_cell( inputs, training, count=1 ) Get the recurrent dropout mask for RNN cell. It will create mask based on context if there isn't any existing cached mask. If a new mask is generated, it will update the cache in the cell. Args inputs The input tensor whose shape will be used to generate dropout mask. training Boolean tensor, whether its in training mode, dropout will be ignored in non-training mode. count Int, how many dropout mask will be generated. It is useful for cell that has internal weights fused together. Returns List of mask tensor, generated or cached mask based on context. reset_dropout_mask View source reset_dropout_mask() Reset the cached dropout masks if any. This is important for the RNN layer to invoke this in it call() method so that the cached mask is cleared before calling the cell.call(). The mask should be cached across the timestep within the same batch, but shouldn't be cached between batches. Otherwise it will introduce unreasonable bias against certain index of data within the batch. reset_recurrent_dropout_mask View source reset_recurrent_dropout_mask() Reset the cached recurrent dropout masks if any. This is important for the RNN layer to invoke this in it call() method so that the cached mask is cleared before calling the cell.call(). The mask should be cached across the timestep within the same batch, but shouldn't be cached between batches. Otherwise it will introduce unreasonable bias against certain index of data within the batch. reset_states View source reset_states( states=None ) Reset the recorded states for the stateful RNN layer. Can only be used when RNN layer is constructed with stateful = True. Args: states: Numpy arrays that contains the value for the initial state, which will be feed to cell at the first time step. When the value is None, zero filled numpy array will be created based on the cell state size. Raises AttributeError When the RNN layer is not stateful. ValueError When the batch size of the RNN layer is unknown. ValueError When the input numpy array is not compatible with the RNN layer state, either size wise or dtype wise.
tensorflow.keras.layers.gru
tf.keras.layers.GRUCell View source on GitHub Cell class for the GRU layer. Inherits From: GRUCell, Layer, Module tf.keras.layers.GRUCell( units, activation='tanh', recurrent_activation='sigmoid', use_bias=True, kernel_initializer='glorot_uniform', recurrent_initializer='orthogonal', bias_initializer='zeros', kernel_regularizer=None, recurrent_regularizer=None, bias_regularizer=None, kernel_constraint=None, recurrent_constraint=None, bias_constraint=None, dropout=0.0, recurrent_dropout=0.0, reset_after=True, **kwargs ) See the Keras RNN API guide for details about the usage of RNN API. This class processes one step within the whole time sequence input, whereas tf.keras.layer.GRU processes the whole sequence. For example: inputs = tf.random.normal([32, 10, 8]) rnn = tf.keras.layers.RNN(tf.keras.layers.GRUCell(4)) output = rnn(inputs) print(output.shape) (32, 4) rnn = tf.keras.layers.RNN( tf.keras.layers.GRUCell(4), return_sequences=True, return_state=True) whole_sequence_output, final_state = rnn(inputs) print(whole_sequence_output.shape) (32, 10, 4) print(final_state.shape) (32, 4) Arguments units Positive integer, dimensionality of the output space. activation Activation function to use. Default: hyperbolic tangent (tanh). If you pass None, no activation is applied (ie. "linear" activation: a(x) = x). recurrent_activation Activation function to use for the recurrent step. Default: sigmoid (sigmoid). If you pass None, no activation is applied (ie. "linear" activation: a(x) = x). use_bias Boolean, (default True), whether the layer uses a bias vector. kernel_initializer Initializer for the kernel weights matrix, used for the linear transformation of the inputs. Default: glorot_uniform. recurrent_initializer Initializer for the recurrent_kernel weights matrix, used for the linear transformation of the recurrent state. Default: orthogonal. bias_initializer Initializer for the bias vector. Default: zeros. kernel_regularizer Regularizer function applied to the kernel weights matrix. Default: None. recurrent_regularizer Regularizer function applied to the recurrent_kernel weights matrix. Default: None. bias_regularizer Regularizer function applied to the bias vector. Default: None. kernel_constraint Constraint function applied to the kernel weights matrix. Default: None. recurrent_constraint Constraint function applied to the recurrent_kernel weights matrix. Default: None. bias_constraint Constraint function applied to the bias vector. Default: None. dropout Float between 0 and 1. Fraction of the units to drop for the linear transformation of the inputs. Default: 0. recurrent_dropout Float between 0 and 1. Fraction of the units to drop for the linear transformation of the recurrent state. Default: 0. reset_after GRU convention (whether to apply reset gate after or before matrix multiplication). False = "before", True = "after" (default and CuDNN compatible). Call arguments: inputs: A 2D tensor, with shape of [batch, feature]. states: A 2D tensor with shape of [batch, units], which is the state from the previous time step. For timestep 0, the initial state provided by user will be feed to cell. training: Python boolean indicating whether the layer should behave in training mode or in inference mode. Only relevant when dropout or recurrent_dropout is used. Methods get_dropout_mask_for_cell View source get_dropout_mask_for_cell( inputs, training, count=1 ) Get the dropout mask for RNN cell's input. It will create mask based on context if there isn't any existing cached mask. If a new mask is generated, it will update the cache in the cell. Args inputs The input tensor whose shape will be used to generate dropout mask. training Boolean tensor, whether its in training mode, dropout will be ignored in non-training mode. count Int, how many dropout mask will be generated. It is useful for cell that has internal weights fused together. Returns List of mask tensor, generated or cached mask based on context. get_initial_state View source get_initial_state( inputs=None, batch_size=None, dtype=None ) get_recurrent_dropout_mask_for_cell View source get_recurrent_dropout_mask_for_cell( inputs, training, count=1 ) Get the recurrent dropout mask for RNN cell. It will create mask based on context if there isn't any existing cached mask. If a new mask is generated, it will update the cache in the cell. Args inputs The input tensor whose shape will be used to generate dropout mask. training Boolean tensor, whether its in training mode, dropout will be ignored in non-training mode. count Int, how many dropout mask will be generated. It is useful for cell that has internal weights fused together. Returns List of mask tensor, generated or cached mask based on context. reset_dropout_mask View source reset_dropout_mask() Reset the cached dropout masks if any. This is important for the RNN layer to invoke this in it call() method so that the cached mask is cleared before calling the cell.call(). The mask should be cached across the timestep within the same batch, but shouldn't be cached between batches. Otherwise it will introduce unreasonable bias against certain index of data within the batch. reset_recurrent_dropout_mask View source reset_recurrent_dropout_mask() Reset the cached recurrent dropout masks if any. This is important for the RNN layer to invoke this in it call() method so that the cached mask is cleared before calling the cell.call(). The mask should be cached across the timestep within the same batch, but shouldn't be cached between batches. Otherwise it will introduce unreasonable bias against certain index of data within the batch.
tensorflow.keras.layers.grucell
tf.keras.layers.InputLayer View source on GitHub Layer to be used as an entry point into a Network (a graph of layers). Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.InputLayer tf.keras.layers.InputLayer( input_shape=None, batch_size=None, dtype=None, input_tensor=None, sparse=False, name=None, ragged=False, **kwargs ) It can either wrap an existing tensor (pass an input_tensor argument) or create a placeholder tensor (pass arguments input_shape, and optionally, dtype). It is generally recommend to use the functional layer API via Input, (which creates an InputLayer) without directly using InputLayer. When using InputLayer with Keras Sequential model, it can be skipped by moving the input_shape parameter to the first layer after the InputLayer. This class can create placeholders for tf.Tensors, tf.SparseTensors, and tf.RaggedTensors by choosing 'sparse=True' or 'ragged=True'. Note that 'sparse' and 'ragged' can't be configured to True at same time. Usage: # With explicit InputLayer. model = tf.keras.Sequential([ tf.keras.layers.InputLayer(input_shape=(4,)), tf.keras.layers.Dense(8)]) model.compile(tf.optimizers.RMSprop(0.001), loss='mse') model.fit(np.zeros((10, 4)), np.ones((10, 8))) # Without InputLayer and let the first layer to have the input_shape. # Keras will add a input for the model behind the scene. model = tf.keras.Sequential([ tf.keras.layers.Dense(8, input_shape=(4,))]) model.compile(tf.optimizers.RMSprop(0.001), loss='mse') model.fit(np.zeros((10, 4)), np.ones((10, 8))) Arguments input_shape Shape tuple (not including the batch axis), or TensorShape instance (not including the batch axis). batch_size Optional input batch size (integer or None). dtype Optional datatype of the input. When not provided, the Keras default float type will be used. input_tensor Optional tensor to use as layer input. If set, the layer will use the tf.TypeSpec of this tensor rather than creating a new placeholder tensor. sparse Boolean, whether the placeholder created is meant to be sparse. Default to False. ragged Boolean, whether the placeholder created is meant to be ragged. In this case, values of 'None' in the 'shape' argument represent ragged dimensions. For more information about RaggedTensors, see this guide. Default to False. name Optional name of the layer (string).
tensorflow.keras.layers.inputlayer
tf.keras.layers.InputSpec Specifies the rank, dtype and shape of every input to a layer. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.InputSpec, tf.compat.v1.layers.InputSpec tf.keras.layers.InputSpec( dtype=None, shape=None, ndim=None, max_ndim=None, min_ndim=None, axes=None, allow_last_axis_squeeze=False, name=None ) Layers can expose (if appropriate) an input_spec attribute: an instance of InputSpec, or a nested structure of InputSpec instances (one per input tensor). These objects enable the layer to run input compatibility checks for input structure, input rank, input shape, and input dtype. A None entry in a shape is compatible with any dimension, a None shape is compatible with any shape. Arguments dtype Expected DataType of the input. shape Shape tuple, expected shape of the input (may include None for unchecked axes). Includes the batch size. ndim Integer, expected rank of the input. max_ndim Integer, maximum rank of the input. min_ndim Integer, minimum rank of the input. axes Dictionary mapping integer axes to a specific dimension value. allow_last_axis_squeeze If True, then allow inputs of rank N+1 as long as the last axis of the input is 1, as well as inputs of rank N-1 as long as the last axis of the spec is 1. name Expected key corresponding to this input when passing data as a dictionary. Example: class MyLayer(Layer): def __init__(self): super(MyLayer, self).__init__() # The layer will accept inputs with shape (?, 28, 28) & (?, 28, 28, 1) # and raise an appropriate error message otherwise. self.input_spec = InputSpec( shape=(None, 28, 28, 1), allow_last_axis_squeeze=True) Methods from_config View source @classmethod from_config( config ) get_config View source get_config()
tensorflow.keras.layers.inputspec
tf.keras.layers.Lambda View source on GitHub Wraps arbitrary expressions as a Layer object. Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.Lambda tf.keras.layers.Lambda( function, output_shape=None, mask=None, arguments=None, **kwargs ) The Lambda layer exists so that arbitrary TensorFlow functions can be used when constructing Sequential and Functional API models. Lambda layers are best suited for simple operations or quick experimentation. For more advanced use cases, follow this guide for subclassing tf.keras.layers.Layer. The main reason to subclass tf.keras.layers.Layer instead of using a Lambda layer is saving and inspecting a Model. Lambda layers are saved by serializing the Python bytecode, which is fundamentally non-portable. They should only be loaded in the same environment where they were saved. Subclassed layers can be saved in a more portable way by overriding their get_config method. Models that rely on subclassed Layers are also often easier to visualize and reason about. Examples: # add a x -> x^2 layer model.add(Lambda(lambda x: x ** 2)) # add a layer that returns the concatenation # of the positive part of the input and # the opposite of the negative part def antirectifier(x): x -= K.mean(x, axis=1, keepdims=True) x = K.l2_normalize(x, axis=1) pos = K.relu(x) neg = K.relu(-x) return K.concatenate([pos, neg], axis=1) model.add(Lambda(antirectifier)) Variables: While it is possible to use Variables with Lambda layers, this practice is discouraged as it can easily lead to bugs. For instance, consider the following layer: scale = tf.Variable(1.) scale_layer = tf.keras.layers.Lambda(lambda x: x * scale) Because scale_layer does not directly track the scale variable, it will not appear in scale_layer.trainable_weights and will therefore not be trained if scale_layer is used in a Model. A better pattern is to write a subclassed Layer: class ScaleLayer(tf.keras.layers.Layer): def __init__(self): super(ScaleLayer, self).__init__() self.scale = tf.Variable(1.) def call(self, inputs): return inputs * self.scale In general, Lambda layers can be convenient for simple stateless computation, but anything more complex should use a subclass Layer instead. Arguments function The function to be evaluated. Takes input tensor as first argument. output_shape Expected output shape from function. This argument can be inferred if not explicitly provided. Can be a tuple or function. If a tuple, it only specifies the first dimension onward; sample dimension is assumed either the same as the input: output_shape = (input_shape[0], ) + output_shape or, the input is None and the sample dimension is also None: output_shape = (None, ) + output_shape If a function, it specifies the entire shape as a function of the input shape: output_shape = f(input_shape) mask Either None (indicating no masking) or a callable with the same signature as the compute_mask layer method, or a tensor that will be returned as output mask regardless of what the input is. arguments Optional dictionary of keyword arguments to be passed to the function. Input shape: Arbitrary. Use the keyword argument input_shape (tuple of integers, does not include the samples axis) when using this layer as the first layer in a model. Output shape: Specified by output_shape argument
tensorflow.keras.layers.lambda
tf.keras.layers.Layer View source on GitHub This is the class from which all layers inherit. Inherits From: Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.Layer tf.keras.layers.Layer( trainable=True, name=None, dtype=None, dynamic=False, **kwargs ) A layer is a callable object that takes as input one or more tensors and that outputs one or more tensors. It involves computation, defined in the call() method, and a state (weight variables), defined either in the constructor __init__() or in the build() method. Users will just instantiate a layer and then treat it as a callable. Arguments trainable Boolean, whether the layer's variables should be trainable. name String name of the layer. dtype The dtype of the layer's computations and weights. Can also be a tf.keras.mixed_precision.Policy, which allows the computation and weight dtype to differ. Default of None means to use tf.keras.mixed_precision.global_policy(), which is a float32 policy unless set to different value. dynamic Set this to True if your layer should only be run eagerly, and should not be used to generate a static computation graph. This would be the case for a Tree-RNN or a recursive network, for example, or generally for any layer that manipulates tensors using Python control flow. If False, we assume that the layer can safely be used to generate a static computation graph. We recommend that descendants of Layer implement the following methods: __init__(): Defines custom layer attributes, and creates layer state variables that do not depend on input shapes, using add_weight(). build(self, input_shape): This method can be used to create weights that depend on the shape(s) of the input(s), using add_weight(). __call__() will automatically build the layer (if it has not been built yet) by calling build(). call(self, *args, **kwargs): Called in __call__ after making sure build() has been called. call() performs the logic of applying the layer to the input tensors (which should be passed in as argument). Two reserved keyword arguments you can optionally use in call() are: training (boolean, whether the call is in inference mode or training mode) mask (boolean tensor encoding masked timesteps in the input, used in RNN layers) get_config(self): Returns a dictionary containing the configuration used to initialize this layer. If the keys differ from the arguments in __init__, then override from_config(self) as well. This method is used when saving the layer or a model that contains this layer. Examples: Here's a basic example: a layer with two variables, w and b, that returns y = w . x + b. It shows how to implement build() and call(). Variables set as attributes of a layer are tracked as weights of the layers (in layer.weights). class SimpleDense(Layer): def __init__(self, units=32): super(SimpleDense, self).__init__() self.units = units def build(self, input_shape): # Create the state of the layer (weights) w_init = tf.random_normal_initializer() self.w = tf.Variable( initial_value=w_init(shape=(input_shape[-1], self.units), dtype='float32'), trainable=True) b_init = tf.zeros_initializer() self.b = tf.Variable( initial_value=b_init(shape=(self.units,), dtype='float32'), trainable=True) def call(self, inputs): # Defines the computation from inputs to outputs return tf.matmul(inputs, self.w) + self.b # Instantiates the layer. linear_layer = SimpleDense(4) # This will also call `build(input_shape)` and create the weights. y = linear_layer(tf.ones((2, 2))) assert len(linear_layer.weights) == 2 # These weights are trainable, so they're listed in `trainable_weights`: assert len(linear_layer.trainable_weights) == 2 Note that the method add_weight() offers a shortcut to create weights: class SimpleDense(Layer): def __init__(self, units=32): super(SimpleDense, self).__init__() self.units = units def build(self, input_shape): self.w = self.add_weight(shape=(input_shape[-1], self.units), initializer='random_normal', trainable=True) self.b = self.add_weight(shape=(self.units,), initializer='random_normal', trainable=True) def call(self, inputs): return tf.matmul(inputs, self.w) + self.b Besides trainable weights, updated via backpropagation during training, layers can also have non-trainable weights. These weights are meant to be updated manually during call(). Here's a example layer that computes the running sum of its inputs: class ComputeSum(Layer): def __init__(self, input_dim): super(ComputeSum, self).__init__() # Create a non-trainable weight. self.total = tf.Variable(initial_value=tf.zeros((input_dim,)), trainable=False) def call(self, inputs): self.total.assign_add(tf.reduce_sum(inputs, axis=0)) return self.total my_sum = ComputeSum(2) x = tf.ones((2, 2)) y = my_sum(x) print(y.numpy()) # [2. 2.] y = my_sum(x) print(y.numpy()) # [4. 4.] assert my_sum.weights == [my_sum.total] assert my_sum.non_trainable_weights == [my_sum.total] assert my_sum.trainable_weights == [] For more information about creating layers, see the guide Writing custom layers and models with Keras Attributes name The name of the layer (string). dtype The dtype of the layer's weights. variable_dtype Alias of dtype. compute_dtype The dtype of the layer's computations. Layers automatically cast inputs to this dtype which causes the computations and output to also be in this dtype. When mixed precision is used with a tf.keras.mixed_precision.Policy, this will be different than variable_dtype. dtype_policy The layer's dtype policy. See the tf.keras.mixed_precision.Policy documentation for details. trainable_weights List of variables to be included in backprop. non_trainable_weights List of variables that should not be included in backprop. weights The concatenation of the lists trainable_weights and non_trainable_weights (in this order). trainable Whether the layer should be trained (boolean), i.e. whether its potentially-trainable weights should be returned as part of layer.trainable_weights. input_spec Optional (list of) InputSpec object(s) specifying the constraints on inputs that can be accepted by the layer. activity_regularizer Optional regularizer function for the output of this layer. dynamic Whether the layer is dynamic (eager-only); set in the constructor. input Retrieves the input tensor(s) of a layer. Only applicable if the layer has exactly one input, i.e. if it is connected to one incoming layer. losses List of losses added using the add_loss() API. Variable regularization tensors are created when this property is accessed, so it is eager safe: accessing losses under a tf.GradientTape will propagate gradients back to the corresponding variables. class MyLayer(tf.keras.layers.Layer): def call(self, inputs): self.add_loss(tf.abs(tf.reduce_mean(inputs))) return inputs l = MyLayer() l(np.ones((10, 1))) l.losses [1.0] inputs = tf.keras.Input(shape=(10,)) x = tf.keras.layers.Dense(10)(inputs) outputs = tf.keras.layers.Dense(1)(x) model = tf.keras.Model(inputs, outputs) # Activity regularization. len(model.losses) 0 model.add_loss(tf.abs(tf.reduce_mean(x))) len(model.losses) 1 inputs = tf.keras.Input(shape=(10,)) d = tf.keras.layers.Dense(10, kernel_initializer='ones') x = d(inputs) outputs = tf.keras.layers.Dense(1)(x) model = tf.keras.Model(inputs, outputs) # Weight regularization. model.add_loss(lambda: tf.reduce_mean(d.kernel)) model.losses [<tf.Tensor: shape=(), dtype=float32, numpy=1.0>] metrics List of metrics added using the add_metric() API. input = tf.keras.layers.Input(shape=(3,)) d = tf.keras.layers.Dense(2) output = d(input) d.add_metric(tf.reduce_max(output), name='max') d.add_metric(tf.reduce_min(output), name='min') [m.name for m in d.metrics] ['max', 'min'] output Retrieves the output tensor(s) of a layer. Only applicable if the layer has exactly one output, i.e. if it is connected to one incoming layer. supports_masking Whether this layer supports computing a mask using compute_mask. Methods add_loss View source add_loss( losses, **kwargs ) Add loss tensor(s), potentially dependent on layer inputs. Some losses (for instance, activity regularization losses) may be dependent on the inputs passed when calling a layer. Hence, when reusing the same layer on different inputs a and b, some entries in layer.losses may be dependent on a and some on b. This method automatically keeps track of dependencies. This method can be used inside a subclassed layer or model's call function, in which case losses should be a Tensor or list of Tensors. Example: class MyLayer(tf.keras.layers.Layer): def call(self, inputs): self.add_loss(tf.abs(tf.reduce_mean(inputs))) return inputs This method can also be called directly on a Functional Model during construction. In this case, any loss Tensors passed to this Model must be symbolic and be able to be traced back to the model's Inputs. These losses become part of the model's topology and are tracked in get_config. Example: inputs = tf.keras.Input(shape=(10,)) x = tf.keras.layers.Dense(10)(inputs) outputs = tf.keras.layers.Dense(1)(x) model = tf.keras.Model(inputs, outputs) # Activity regularization. model.add_loss(tf.abs(tf.reduce_mean(x))) If this is not the case for your loss (if, for example, your loss references a Variable of one of the model's layers), you can wrap your loss in a zero-argument lambda. These losses are not tracked as part of the model's topology since they can't be serialized. Example: inputs = tf.keras.Input(shape=(10,)) d = tf.keras.layers.Dense(10) x = d(inputs) outputs = tf.keras.layers.Dense(1)(x) model = tf.keras.Model(inputs, outputs) # Weight regularization. model.add_loss(lambda: tf.reduce_mean(d.kernel)) Arguments losses Loss tensor, or list/tuple of tensors. Rather than tensors, losses may also be zero-argument callables which create a loss tensor. **kwargs Additional keyword arguments for backward compatibility. Accepted values: inputs - Deprecated, will be automatically inferred. add_metric View source add_metric( value, name=None, **kwargs ) Adds metric tensor to the layer. This method can be used inside the call() method of a subclassed layer or model. class MyMetricLayer(tf.keras.layers.Layer): def __init__(self): super(MyMetricLayer, self).__init__(name='my_metric_layer') self.mean = tf.keras.metrics.Mean(name='metric_1') def call(self, inputs): self.add_metric(self.mean(x)) self.add_metric(tf.reduce_sum(x), name='metric_2') return inputs This method can also be called directly on a Functional Model during construction. In this case, any tensor passed to this Model must be symbolic and be able to be traced back to the model's Inputs. These metrics become part of the model's topology and are tracked when you save the model via save(). inputs = tf.keras.Input(shape=(10,)) x = tf.keras.layers.Dense(10)(inputs) outputs = tf.keras.layers.Dense(1)(x) model = tf.keras.Model(inputs, outputs) model.add_metric(math_ops.reduce_sum(x), name='metric_1') Note: Calling add_metric() with the result of a metric object on a Functional Model, as shown in the example below, is not supported. This is because we cannot trace the metric result tensor back to the model's inputs. inputs = tf.keras.Input(shape=(10,)) x = tf.keras.layers.Dense(10)(inputs) outputs = tf.keras.layers.Dense(1)(x) model = tf.keras.Model(inputs, outputs) model.add_metric(tf.keras.metrics.Mean()(x), name='metric_1') Args value Metric tensor. name String metric name. **kwargs Additional keyword arguments for backward compatibility. Accepted values: aggregation - When the value tensor provided is not the result of calling a keras.Metric instance, it will be aggregated by default using a keras.Metric.Mean. add_weight View source add_weight( name=None, shape=None, dtype=None, initializer=None, regularizer=None, trainable=None, constraint=None, use_resource=None, synchronization=tf.VariableSynchronization.AUTO, aggregation=tf.compat.v1.VariableAggregation.NONE, **kwargs ) Adds a new variable to the layer. Arguments name Variable name. shape Variable shape. Defaults to scalar if unspecified. dtype The type of the variable. Defaults to self.dtype. initializer Initializer instance (callable). regularizer Regularizer instance (callable). trainable Boolean, whether the variable should be part of the layer's "trainable_variables" (e.g. variables, biases) or "non_trainable_variables" (e.g. BatchNorm mean and variance). Note that trainable cannot be True if synchronization is set to ON_READ. constraint Constraint instance (callable). use_resource Whether to use ResourceVariable. synchronization Indicates when a distributed a variable will be aggregated. Accepted values are constants defined in the class tf.VariableSynchronization. By default the synchronization is set to AUTO and the current DistributionStrategy chooses when to synchronize. If synchronization is set to ON_READ, trainable must not be set to True. aggregation Indicates how a distributed variable will be aggregated. Accepted values are constants defined in the class tf.VariableAggregation. **kwargs Additional keyword arguments. Accepted values are getter, collections, experimental_autocast and caching_device. Returns The variable created. Raises ValueError When giving unsupported dtype and no initializer or when trainable has been set to True with synchronization set as ON_READ. build View source build( input_shape ) Creates the variables of the layer (optional, for subclass implementers). This is a method that implementers of subclasses of Layer or Model can override if they need a state-creation step in-between layer instantiation and layer call. This is typically used to create the weights of Layer subclasses. Arguments input_shape Instance of TensorShape, or list of instances of TensorShape if the layer expects a list of inputs (one instance per input). call View source call( inputs, **kwargs ) This is where the layer's logic lives. Note here that call() method in tf.keras is little bit different from keras API. In keras API, you can pass support masking for layers as additional arguments. Whereas tf.keras has compute_mask() method to support masking. Arguments inputs Input tensor, or list/tuple of input tensors. **kwargs Additional keyword arguments. Currently unused. Returns A tensor or list/tuple of tensors. compute_mask View source compute_mask( inputs, mask=None ) Computes an output mask tensor. Arguments inputs Tensor or list of tensors. mask Tensor or list of tensors. Returns None or a tensor (or list of tensors, one per output tensor of the layer). compute_output_shape View source compute_output_shape( input_shape ) Computes the output shape of the layer. If the layer has not been built, this method will call build on the layer. This assumes that the layer will later be used with inputs that match the input shape provided here. Arguments input_shape Shape tuple (tuple of integers) or list of shape tuples (one per output tensor of the layer). Shape tuples can include None for free dimensions, instead of an integer. Returns An input shape tuple. compute_output_signature View source compute_output_signature( input_signature ) Compute the output tensor signature of the layer based on the inputs. Unlike a TensorShape object, a TensorSpec object contains both shape and dtype information for a tensor. This method allows layers to provide output dtype information if it is different from the input dtype. For any layer that doesn't implement this function, the framework will fall back to use compute_output_shape, and will assume that the output dtype matches the input dtype. Args input_signature Single TensorSpec or nested structure of TensorSpec objects, describing a candidate input for the layer. Returns Single TensorSpec or nested structure of TensorSpec objects, describing how the layer would transform the provided input. Raises TypeError If input_signature contains a non-TensorSpec object. count_params View source count_params() Count the total number of scalars composing the weights. Returns An integer count. Raises ValueError if the layer isn't yet built (in which case its weights aren't yet defined). from_config View source @classmethod from_config( config ) Creates a layer from its config. This method is the reverse of get_config, capable of instantiating the same layer from the config dictionary. It does not handle layer connectivity (handled by Network), nor weights (handled by set_weights). Arguments config A Python dictionary, typically the output of get_config. Returns A layer instance. get_config View source get_config() Returns the config of the layer. A layer config is a Python dictionary (serializable) containing the configuration of a layer. The same layer can be reinstantiated later (without its trained weights) from this configuration. The config of a layer does not include connectivity information, nor the layer class name. These are handled by Network (one layer of abstraction above). Returns Python dictionary. get_weights View source get_weights() Returns the current weights of the layer. The weights of a layer represent the state of the layer. This function returns both trainable and non-trainable weight values associated with this layer as a list of Numpy arrays, which can in turn be used to load state into similarly parameterized layers. For example, a Dense layer returns a list of two values-- per-output weights and the bias value. These can be used to set the weights of another Dense layer: a = tf.keras.layers.Dense(1, kernel_initializer=tf.constant_initializer(1.)) a_out = a(tf.convert_to_tensor([[1., 2., 3.]])) a.get_weights() [array([[1.], [1.], [1.]], dtype=float32), array([0.], dtype=float32)] b = tf.keras.layers.Dense(1, kernel_initializer=tf.constant_initializer(2.)) b_out = b(tf.convert_to_tensor([[10., 20., 30.]])) b.get_weights() [array([[2.], [2.], [2.]], dtype=float32), array([0.], dtype=float32)] b.set_weights(a.get_weights()) b.get_weights() [array([[1.], [1.], [1.]], dtype=float32), array([0.], dtype=float32)] Returns Weights values as a list of numpy arrays. set_weights View source set_weights( weights ) Sets the weights of the layer, from Numpy arrays. The weights of a layer represent the state of the layer. This function sets the weight values from numpy arrays. The weight values should be passed in the order they are created by the layer. Note that the layer's weights must be instantiated before calling this function by calling the layer. For example, a Dense layer returns a list of two values-- per-output weights and the bias value. These can be used to set the weights of another Dense layer: a = tf.keras.layers.Dense(1, kernel_initializer=tf.constant_initializer(1.)) a_out = a(tf.convert_to_tensor([[1., 2., 3.]])) a.get_weights() [array([[1.], [1.], [1.]], dtype=float32), array([0.], dtype=float32)] b = tf.keras.layers.Dense(1, kernel_initializer=tf.constant_initializer(2.)) b_out = b(tf.convert_to_tensor([[10., 20., 30.]])) b.get_weights() [array([[2.], [2.], [2.]], dtype=float32), array([0.], dtype=float32)] b.set_weights(a.get_weights()) b.get_weights() [array([[1.], [1.], [1.]], dtype=float32), array([0.], dtype=float32)] Arguments weights a list of Numpy arrays. The number of arrays and their shape must match number of the dimensions of the weights of the layer (i.e. it should match the output of get_weights). Raises ValueError If the provided weights list does not match the layer's specifications. __call__ View source __call__( *args, **kwargs ) Wraps call, applying pre- and post-processing steps. Arguments *args Positional arguments to be passed to self.call. **kwargs Keyword arguments to be passed to self.call. Returns Output tensor(s). Note: The following optional keyword arguments are reserved for specific uses: training: Boolean scalar tensor of Python boolean indicating whether the call is meant for training or inference. mask: Boolean input mask. If the layer's call method takes a mask argument (as some Keras layers do), its default value will be set to the mask generated for inputs by the previous layer (if input did come from a layer that generated a corresponding mask, i.e. if it came from a Keras layer with masking support. Raises ValueError if the layer's call method returns None (an invalid value). RuntimeError if super().__init__() was not called in the constructor.
tensorflow.keras.layers.layer
tf.keras.layers.LayerNormalization View source on GitHub Layer normalization layer (Ba et al., 2016). Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.LayerNormalization tf.keras.layers.LayerNormalization( axis=-1, epsilon=0.001, center=True, scale=True, beta_initializer='zeros', gamma_initializer='ones', beta_regularizer=None, gamma_regularizer=None, beta_constraint=None, gamma_constraint=None, trainable=True, name=None, **kwargs ) Normalize the activations of the previous layer for each given example in a batch independently, rather than across a batch like Batch Normalization. i.e. applies a transformation that maintains the mean activation within each example close to 0 and the activation standard deviation close to 1. Given a tensor inputs, moments are calculated and normalization is performed across the axes specified in axis. Example: data = tf.constant(np.arange(10).reshape(5, 2) * 10, dtype=tf.float32) print(data) tf.Tensor( [[ 0. 10.] [20. 30.] [40. 50.] [60. 70.] [80. 90.]], shape=(5, 2), dtype=float32) layer = tf.keras.layers.LayerNormalization(axis=1) output = layer(data) print(output) tf.Tensor( [[-1. 1.] [-1. 1.] [-1. 1.] [-1. 1.] [-1. 1.]], shape=(5, 2), dtype=float32) Notice that with Layer Normalization the normalization happens across the axes within each example, rather than across different examples in the batch. If scale or center are enabled, the layer will scale the normalized outputs by broadcasting them with a trainable variable gamma, and center the outputs by broadcasting with a trainable variable beta. gamma will default to a ones tensor and beta will default to a zeros tensor, so that centering and scaling are no-ops before training has begun. So, with scaling and centering enabled the normalization equations are as follows: Let the intermediate activations for a mini-batch to be the inputs. For each sample x_i in inputs with k features, we compute the mean and variance of the sample: mean_i = sum(x_i[j] for j in range(k)) / k var_i = sum((x_i[j] - mean_i) ** 2 for j in range(k)) / k and then compute a normalized x_i_normalized, including a small factor epsilon for numerical stability. x_i_normalized = (x_i - mean_i) / sqrt(var_i + epsilon) And finally x_i_normalized is linearly transformed by gamma and beta, which are learned parameters: output_i = x_i_normalized * gamma + beta gamma and beta will span the axes of inputs specified in axis, and this part of the inputs' shape must be fully defined. For example: layer = tf.keras.layers.LayerNormalization(axis=[1, 2, 3]) layer.build([5, 20, 30, 40]) print(layer.beta.shape) (20, 30, 40) print(layer.gamma.shape) (20, 30, 40) Note that other implementations of layer normalization may choose to define gamma and beta over a separate set of axes from the axes being normalized across. For example, Group Normalization (Wu et al. 2018) with group size of 1 corresponds to a Layer Normalization that normalizes across height, width, and channel and has gamma and beta span only the channel dimension. So, this Layer Normalization implementation will not match a Group Normalization layer with group size set to 1. Arguments axis Integer or List/Tuple. The axis or axes to normalize across. Typically this is the features axis/axes. The left-out axes are typically the batch axis/axes. This argument defaults to -1, the last dimension in the input. epsilon Small float added to variance to avoid dividing by zero. Defaults to 1e-3 center If True, add offset of beta to normalized tensor. If False, beta is ignored. Defaults to True. scale If True, multiply by gamma. If False, gamma is not used. Defaults to True. When the next layer is linear (also e.g. nn.relu), this can be disabled since the scaling will be done by the next layer. beta_initializer Initializer for the beta weight. Defaults to zeros. gamma_initializer Initializer for the gamma weight. Defaults to ones. beta_regularizer Optional regularizer for the beta weight. None by default. gamma_regularizer Optional regularizer for the gamma weight. None by default. beta_constraint Optional constraint for the beta weight. None by default. gamma_constraint Optional constraint for the gamma weight. None by default. trainable Boolean, if True the variables will be marked as trainable. Defaults to True. Input shape: Arbitrary. Use the keyword argument input_shape (tuple of integers, does not include the samples axis) when using this layer as the first layer in a model. Output shape: Same shape as input. Reference: Lei Ba et al., 2016.
tensorflow.keras.layers.layernormalization
tf.keras.layers.LeakyReLU View source on GitHub Leaky version of a Rectified Linear Unit. Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.LeakyReLU tf.keras.layers.LeakyReLU( alpha=0.3, **kwargs ) It allows a small gradient when the unit is not active: f(x) = alpha * x if x < 0 f(x) = x if x >= 0 Usage: layer = tf.keras.layers.LeakyReLU() output = layer([-3.0, -1.0, 0.0, 2.0]) list(output.numpy()) [-0.9, -0.3, 0.0, 2.0] layer = tf.keras.layers.LeakyReLU(alpha=0.1) output = layer([-3.0, -1.0, 0.0, 2.0]) list(output.numpy()) [-0.3, -0.1, 0.0, 2.0] Input shape: Arbitrary. Use the keyword argument input_shape (tuple of integers, does not include the batch axis) when using this layer as the first layer in a model. Output shape: Same shape as the input. Arguments alpha Float >= 0. Negative slope coefficient. Default to 0.3.
tensorflow.keras.layers.leakyrelu
tf.keras.layers.LocallyConnected1D View source on GitHub Locally-connected layer for 1D inputs. Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.LocallyConnected1D tf.keras.layers.LocallyConnected1D( filters, kernel_size, strides=1, padding='valid', data_format=None, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, implementation=1, **kwargs ) The LocallyConnected1D layer works similarly to the Conv1D layer, except that weights are unshared, that is, a different set of filters is applied at each different patch of the input. Note: layer attributes cannot be modified after the layer has been called once (except the trainable attribute). Example: # apply a unshared weight convolution 1d of length 3 to a sequence with # 10 timesteps, with 64 output filters model = Sequential() model.add(LocallyConnected1D(64, 3, input_shape=(10, 32))) # now model.output_shape == (None, 8, 64) # add a new conv1d on top model.add(LocallyConnected1D(32, 3)) # now model.output_shape == (None, 6, 32) Arguments filters Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution). kernel_size An integer or tuple/list of a single integer, specifying the length of the 1D convolution window. strides An integer or tuple/list of a single integer, specifying the stride length of the convolution. Specifying any stride value != 1 is incompatible with specifying any dilation_rate value != 1. padding Currently only supports "valid" (case-insensitive). "same" may be supported in the future. "valid" means no padding. data_format A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch, length, channels) while channels_first corresponds to inputs with shape (batch, channels, length). It defaults to the image_data_format value found in your Keras config file at ~/.keras/keras.json. If you never set it, then it will be "channels_last". activation Activation function to use. If you don't specify anything, no activation is applied (ie. "linear" activation: a(x) = x). use_bias Boolean, whether the layer uses a bias vector. kernel_initializer Initializer for the kernel weights matrix. bias_initializer Initializer for the bias vector. kernel_regularizer Regularizer function applied to the kernel weights matrix. bias_regularizer Regularizer function applied to the bias vector. activity_regularizer Regularizer function applied to the output of the layer (its "activation").. kernel_constraint Constraint function applied to the kernel matrix. bias_constraint Constraint function applied to the bias vector. implementation implementation mode, either 1, 2, or 3. 1 loops over input spatial locations to perform the forward pass. It is memory-efficient but performs a lot of (small) ops. 2 stores layer weights in a dense but sparsely-populated 2D matrix and implements the forward pass as a single matrix-multiply. It uses a lot of RAM but performs few (large) ops. 3 stores layer weights in a sparse tensor and implements the forward pass as a single sparse matrix-multiply. How to choose: 1: large, dense models, 2: small models, 3: large, sparse models, where "large" stands for large input/output activations (i.e. many filters, input_filters, large input_size, output_size), and "sparse" stands for few connections between inputs and outputs, i.e. small ratio filters * input_filters * kernel_size / (input_size * strides), where inputs to and outputs of the layer are assumed to have shapes (input_size, input_filters), (output_size, filters) respectively. It is recommended to benchmark each in the setting of interest to pick the most efficient one (in terms of speed and memory usage). Correct choice of implementation can lead to dramatic speed improvements (e.g. 50X), potentially at the expense of RAM. Also, only padding="valid" is supported by implementation=1. Input shape: 3D tensor with shape: (batch_size, steps, input_dim) Output shape: 3D tensor with shape: (batch_size, new_steps, filters) steps value might have changed due to padding or strides.
tensorflow.keras.layers.locallyconnected1d
tf.keras.layers.LocallyConnected2D View source on GitHub Locally-connected layer for 2D inputs. Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.LocallyConnected2D tf.keras.layers.LocallyConnected2D( filters, kernel_size, strides=(1, 1), padding='valid', data_format=None, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, implementation=1, **kwargs ) The LocallyConnected2D layer works similarly to the Conv2D layer, except that weights are unshared, that is, a different set of filters is applied at each different patch of the input. Note: layer attributes cannot be modified after the layer has been called once (except the trainable attribute). Examples: # apply a 3x3 unshared weights convolution with 64 output filters on a 32x32 image # with `data_format="channels_last"`: model = Sequential() model.add(LocallyConnected2D(64, (3, 3), input_shape=(32, 32, 3))) # now model.output_shape == (None, 30, 30, 64) # notice that this layer will consume (30*30)*(3*3*3*64) + (30*30)*64 parameters # add a 3x3 unshared weights convolution on top, with 32 output filters: model.add(LocallyConnected2D(32, (3, 3))) # now model.output_shape == (None, 28, 28, 32) Arguments filters Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution). kernel_size An integer or tuple/list of 2 integers, specifying the width and height of the 2D convolution window. Can be a single integer to specify the same value for all spatial dimensions. strides An integer or tuple/list of 2 integers, specifying the strides of the convolution along the width and height. Can be a single integer to specify the same value for all spatial dimensions. padding Currently only support "valid" (case-insensitive). "same" will be supported in future. "valid" means no padding. data_format A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch, height, width, channels) while channels_first corresponds to inputs with shape (batch, channels, height, width). It defaults to the image_data_format value found in your Keras config file at ~/.keras/keras.json. If you never set it, then it will be "channels_last". activation Activation function to use. If you don't specify anything, no activation is applied (ie. "linear" activation: a(x) = x). use_bias Boolean, whether the layer uses a bias vector. kernel_initializer Initializer for the kernel weights matrix. bias_initializer Initializer for the bias vector. kernel_regularizer Regularizer function applied to the kernel weights matrix. bias_regularizer Regularizer function applied to the bias vector. activity_regularizer Regularizer function applied to the output of the layer (its "activation"). kernel_constraint Constraint function applied to the kernel matrix. bias_constraint Constraint function applied to the bias vector. implementation implementation mode, either 1, 2, or 3. 1 loops over input spatial locations to perform the forward pass. It is memory-efficient but performs a lot of (small) ops. 2 stores layer weights in a dense but sparsely-populated 2D matrix and implements the forward pass as a single matrix-multiply. It uses a lot of RAM but performs few (large) ops. 3 stores layer weights in a sparse tensor and implements the forward pass as a single sparse matrix-multiply. How to choose: 1: large, dense models, 2: small models, 3: large, sparse models, where "large" stands for large input/output activations (i.e. many filters, input_filters, large np.prod(input_size), np.prod(output_size)), and "sparse" stands for few connections between inputs and outputs, i.e. small ratio `filters * input_filters * np.prod(kernel_size) / (np.prod(input_size) np.prod(strides)), where inputs to and outputs of the layer are assumed to have shapesinput_size + (input_filters,),output_size + (filters,)` respectively. It is recommended to benchmark each in the setting of interest to pick the most efficient one (in terms of speed and memory usage). Correct choice of implementation can lead to dramatic speed improvements (e.g. 50X), potentially at the expense of RAM. Also, only padding="valid" is supported by implementation=1. Input shape: 4D tensor with shape: (samples, channels, rows, cols) if data_format='channels_first' or 4D tensor with shape: (samples, rows, cols, channels) if data_format='channels_last'. Output shape: 4D tensor with shape: (samples, filters, new_rows, new_cols) if data_format='channels_first' or 4D tensor with shape: (samples, new_rows, new_cols, filters) if data_format='channels_last'. rows and cols values might have changed due to padding.
tensorflow.keras.layers.locallyconnected2d
tf.keras.layers.LSTM View source on GitHub Long Short-Term Memory layer - Hochreiter 1997. Inherits From: LSTM, RNN, Layer, Module tf.keras.layers.LSTM( units, activation='tanh', recurrent_activation='sigmoid', use_bias=True, kernel_initializer='glorot_uniform', recurrent_initializer='orthogonal', bias_initializer='zeros', unit_forget_bias=True, kernel_regularizer=None, recurrent_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, recurrent_constraint=None, bias_constraint=None, dropout=0.0, recurrent_dropout=0.0, return_sequences=False, return_state=False, go_backwards=False, stateful=False, time_major=False, unroll=False, **kwargs ) See the Keras RNN API guide for details about the usage of RNN API. Based on available runtime hardware and constraints, this layer will choose different implementations (cuDNN-based or pure-TensorFlow) to maximize the performance. If a GPU is available and all the arguments to the layer meet the requirement of the CuDNN kernel (see below for details), the layer will use a fast cuDNN implementation. The requirements to use the cuDNN implementation are: activation == tanh recurrent_activation == sigmoid recurrent_dropout == 0 unroll is False use_bias is True Inputs, if use masking, are strictly right-padded. Eager execution is enabled in the outermost context. For example: inputs = tf.random.normal([32, 10, 8]) lstm = tf.keras.layers.LSTM(4) output = lstm(inputs) print(output.shape) (32, 4) lstm = tf.keras.layers.LSTM(4, return_sequences=True, return_state=True) whole_seq_output, final_memory_state, final_carry_state = lstm(inputs) print(whole_seq_output.shape) (32, 10, 4) print(final_memory_state.shape) (32, 4) print(final_carry_state.shape) (32, 4) Arguments units Positive integer, dimensionality of the output space. activation Activation function to use. Default: hyperbolic tangent (tanh). If you pass None, no activation is applied (ie. "linear" activation: a(x) = x). recurrent_activation Activation function to use for the recurrent step. Default: sigmoid (sigmoid). If you pass None, no activation is applied (ie. "linear" activation: a(x) = x). use_bias Boolean (default True), whether the layer uses a bias vector. kernel_initializer Initializer for the kernel weights matrix, used for the linear transformation of the inputs. Default: glorot_uniform. recurrent_initializer Initializer for the recurrent_kernel weights matrix, used for the linear transformation of the recurrent state. Default: orthogonal. bias_initializer Initializer for the bias vector. Default: zeros. unit_forget_bias Boolean (default True). If True, add 1 to the bias of the forget gate at initialization. Setting it to true will also force bias_initializer="zeros". This is recommended in Jozefowicz et al.. kernel_regularizer Regularizer function applied to the kernel weights matrix. Default: None. recurrent_regularizer Regularizer function applied to the recurrent_kernel weights matrix. Default: None. bias_regularizer Regularizer function applied to the bias vector. Default: None. activity_regularizer Regularizer function applied to the output of the layer (its "activation"). Default: None. kernel_constraint Constraint function applied to the kernel weights matrix. Default: None. recurrent_constraint Constraint function applied to the recurrent_kernel weights matrix. Default: None. bias_constraint Constraint function applied to the bias vector. Default: None. dropout Float between 0 and 1. Fraction of the units to drop for the linear transformation of the inputs. Default: 0. recurrent_dropout Float between 0 and 1. Fraction of the units to drop for the linear transformation of the recurrent state. Default: 0. return_sequences Boolean. Whether to return the last output. in the output sequence, or the full sequence. Default: False. return_state Boolean. Whether to return the last state in addition to the output. Default: False. go_backwards Boolean (default False). If True, process the input sequence backwards and return the reversed sequence. stateful Boolean (default False). If True, the last state for each sample at index i in a batch will be used as initial state for the sample of index i in the following batch. time_major The shape format of the inputs and outputs tensors. If True, the inputs and outputs will be in shape [timesteps, batch, feature], whereas in the False case, it will be [batch, timesteps, feature]. Using time_major = True is a bit more efficient because it avoids transposes at the beginning and end of the RNN calculation. However, most TensorFlow data is batch-major, so by default this function accepts input and emits output in batch-major form. unroll Boolean (default False). If True, the network will be unrolled, else a symbolic loop will be used. Unrolling can speed-up a RNN, although it tends to be more memory-intensive. Unrolling is only suitable for short sequences. Call arguments: inputs: A 3D tensor with shape [batch, timesteps, feature]. mask: Binary tensor of shape [batch, timesteps] indicating whether a given timestep should be masked (optional, defaults to None). training: Python boolean indicating whether the layer should behave in training mode or in inference mode. This argument is passed to the cell when calling it. This is only relevant if dropout or recurrent_dropout is used (optional, defaults to None). initial_state: List of initial state tensors to be passed to the first call of the cell (optional, defaults to None which causes creation of zero-filled initial state tensors). Attributes activation bias_constraint bias_initializer bias_regularizer dropout implementation kernel_constraint kernel_initializer kernel_regularizer recurrent_activation recurrent_constraint recurrent_dropout recurrent_initializer recurrent_regularizer states unit_forget_bias units use_bias Methods get_dropout_mask_for_cell View source get_dropout_mask_for_cell( inputs, training, count=1 ) Get the dropout mask for RNN cell's input. It will create mask based on context if there isn't any existing cached mask. If a new mask is generated, it will update the cache in the cell. Args inputs The input tensor whose shape will be used to generate dropout mask. training Boolean tensor, whether its in training mode, dropout will be ignored in non-training mode. count Int, how many dropout mask will be generated. It is useful for cell that has internal weights fused together. Returns List of mask tensor, generated or cached mask based on context. get_recurrent_dropout_mask_for_cell View source get_recurrent_dropout_mask_for_cell( inputs, training, count=1 ) Get the recurrent dropout mask for RNN cell. It will create mask based on context if there isn't any existing cached mask. If a new mask is generated, it will update the cache in the cell. Args inputs The input tensor whose shape will be used to generate dropout mask. training Boolean tensor, whether its in training mode, dropout will be ignored in non-training mode. count Int, how many dropout mask will be generated. It is useful for cell that has internal weights fused together. Returns List of mask tensor, generated or cached mask based on context. reset_dropout_mask View source reset_dropout_mask() Reset the cached dropout masks if any. This is important for the RNN layer to invoke this in it call() method so that the cached mask is cleared before calling the cell.call(). The mask should be cached across the timestep within the same batch, but shouldn't be cached between batches. Otherwise it will introduce unreasonable bias against certain index of data within the batch. reset_recurrent_dropout_mask View source reset_recurrent_dropout_mask() Reset the cached recurrent dropout masks if any. This is important for the RNN layer to invoke this in it call() method so that the cached mask is cleared before calling the cell.call(). The mask should be cached across the timestep within the same batch, but shouldn't be cached between batches. Otherwise it will introduce unreasonable bias against certain index of data within the batch. reset_states View source reset_states( states=None ) Reset the recorded states for the stateful RNN layer. Can only be used when RNN layer is constructed with stateful = True. Args: states: Numpy arrays that contains the value for the initial state, which will be feed to cell at the first time step. When the value is None, zero filled numpy array will be created based on the cell state size. Raises AttributeError When the RNN layer is not stateful. ValueError When the batch size of the RNN layer is unknown. ValueError When the input numpy array is not compatible with the RNN layer state, either size wise or dtype wise.
tensorflow.keras.layers.lstm
tf.keras.layers.LSTMCell View source on GitHub Cell class for the LSTM layer. Inherits From: LSTMCell, Layer, Module tf.keras.layers.LSTMCell( units, activation='tanh', recurrent_activation='sigmoid', use_bias=True, kernel_initializer='glorot_uniform', recurrent_initializer='orthogonal', bias_initializer='zeros', unit_forget_bias=True, kernel_regularizer=None, recurrent_regularizer=None, bias_regularizer=None, kernel_constraint=None, recurrent_constraint=None, bias_constraint=None, dropout=0.0, recurrent_dropout=0.0, **kwargs ) See the Keras RNN API guide for details about the usage of RNN API. This class processes one step within the whole time sequence input, whereas tf.keras.layer.LSTM processes the whole sequence. For example: inputs = tf.random.normal([32, 10, 8]) rnn = tf.keras.layers.RNN(tf.keras.layers.LSTMCell(4)) output = rnn(inputs) print(output.shape) (32, 4) rnn = tf.keras.layers.RNN( tf.keras.layers.LSTMCell(4), return_sequences=True, return_state=True) whole_seq_output, final_memory_state, final_carry_state = rnn(inputs) print(whole_seq_output.shape) (32, 10, 4) print(final_memory_state.shape) (32, 4) print(final_carry_state.shape) (32, 4) Arguments units Positive integer, dimensionality of the output space. activation Activation function to use. Default: hyperbolic tangent (tanh). If you pass None, no activation is applied (ie. "linear" activation: a(x) = x). recurrent_activation Activation function to use for the recurrent step. Default: sigmoid (sigmoid). If you pass None, no activation is applied (ie. "linear" activation: a(x) = x). use_bias Boolean, (default True), whether the layer uses a bias vector. kernel_initializer Initializer for the kernel weights matrix, used for the linear transformation of the inputs. Default: glorot_uniform. recurrent_initializer Initializer for the recurrent_kernel weights matrix, used for the linear transformation of the recurrent state. Default: orthogonal. bias_initializer Initializer for the bias vector. Default: zeros. unit_forget_bias Boolean (default True). If True, add 1 to the bias of the forget gate at initialization. Setting it to true will also force bias_initializer="zeros". This is recommended in Jozefowicz et al. kernel_regularizer Regularizer function applied to the kernel weights matrix. Default: None. recurrent_regularizer Regularizer function applied to the recurrent_kernel weights matrix. Default: None. bias_regularizer Regularizer function applied to the bias vector. Default: None. kernel_constraint Constraint function applied to the kernel weights matrix. Default: None. recurrent_constraint Constraint function applied to the recurrent_kernel weights matrix. Default: None. bias_constraint Constraint function applied to the bias vector. Default: None. dropout Float between 0 and 1. Fraction of the units to drop for the linear transformation of the inputs. Default: 0. recurrent_dropout Float between 0 and 1. Fraction of the units to drop for the linear transformation of the recurrent state. Default: 0. Call arguments: inputs: A 2D tensor, with shape of [batch, feature]. states: List of 2 tensors that corresponding to the cell's units. Both of them have shape [batch, units], the first tensor is the memory state from previous time step, the second tensor is the carry state from previous time step. For timestep 0, the initial state provided by user will be feed to cell. training: Python boolean indicating whether the layer should behave in training mode or in inference mode. Only relevant when dropout or recurrent_dropout is used. Methods get_dropout_mask_for_cell View source get_dropout_mask_for_cell( inputs, training, count=1 ) Get the dropout mask for RNN cell's input. It will create mask based on context if there isn't any existing cached mask. If a new mask is generated, it will update the cache in the cell. Args inputs The input tensor whose shape will be used to generate dropout mask. training Boolean tensor, whether its in training mode, dropout will be ignored in non-training mode. count Int, how many dropout mask will be generated. It is useful for cell that has internal weights fused together. Returns List of mask tensor, generated or cached mask based on context. get_initial_state View source get_initial_state( inputs=None, batch_size=None, dtype=None ) get_recurrent_dropout_mask_for_cell View source get_recurrent_dropout_mask_for_cell( inputs, training, count=1 ) Get the recurrent dropout mask for RNN cell. It will create mask based on context if there isn't any existing cached mask. If a new mask is generated, it will update the cache in the cell. Args inputs The input tensor whose shape will be used to generate dropout mask. training Boolean tensor, whether its in training mode, dropout will be ignored in non-training mode. count Int, how many dropout mask will be generated. It is useful for cell that has internal weights fused together. Returns List of mask tensor, generated or cached mask based on context. reset_dropout_mask View source reset_dropout_mask() Reset the cached dropout masks if any. This is important for the RNN layer to invoke this in it call() method so that the cached mask is cleared before calling the cell.call(). The mask should be cached across the timestep within the same batch, but shouldn't be cached between batches. Otherwise it will introduce unreasonable bias against certain index of data within the batch. reset_recurrent_dropout_mask View source reset_recurrent_dropout_mask() Reset the cached recurrent dropout masks if any. This is important for the RNN layer to invoke this in it call() method so that the cached mask is cleared before calling the cell.call(). The mask should be cached across the timestep within the same batch, but shouldn't be cached between batches. Otherwise it will introduce unreasonable bias against certain index of data within the batch.
tensorflow.keras.layers.lstmcell
tf.keras.layers.Masking View source on GitHub Masks a sequence by using a mask value to skip timesteps. Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.Masking tf.keras.layers.Masking( mask_value=0.0, **kwargs ) For each timestep in the input tensor (dimension #1 in the tensor), if all values in the input tensor at that timestep are equal to mask_value, then the timestep will be masked (skipped) in all downstream layers (as long as they support masking). If any downstream layer does not support masking yet receives such an input mask, an exception will be raised. Example: Consider a Numpy data array x of shape (samples, timesteps, features), to be fed to an LSTM layer. You want to mask timestep #3 and #5 because you lack data for these timesteps. You can: Set x[:, 3, :] = 0. and x[:, 5, :] = 0. Insert a Masking layer with mask_value=0. before the LSTM layer: samples, timesteps, features = 32, 10, 8 inputs = np.random.random([samples, timesteps, features]).astype(np.float32) inputs[:, 3, :] = 0. inputs[:, 5, :] = 0. model = tf.keras.models.Sequential() model.add(tf.keras.layers.Masking(mask_value=0., input_shape=(timesteps, features))) model.add(tf.keras.layers.LSTM(32)) output = model(inputs) # The time step 3 and 5 will be skipped from LSTM calculation. See the masking and padding guide for more details.
tensorflow.keras.layers.masking
tf.keras.layers.Maximum View source on GitHub Layer that computes the maximum (element-wise) a list of inputs. Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.Maximum tf.keras.layers.Maximum( **kwargs ) It takes as input a list of tensors, all of the same shape, and returns a single tensor (also of the same shape). tf.keras.layers.Maximum()([np.arange(5).reshape(5, 1), np.arange(5, 10).reshape(5, 1)]) <tf.Tensor: shape=(5, 1), dtype=int64, numpy= array([[5], [6], [7], [8], [9]])> x1 = tf.keras.layers.Dense(8)(np.arange(10).reshape(5, 2)) x2 = tf.keras.layers.Dense(8)(np.arange(10, 20).reshape(5, 2)) maxed = tf.keras.layers.Maximum()([x1, x2]) maxed.shape TensorShape([5, 8]) Arguments **kwargs standard layer keyword arguments.
tensorflow.keras.layers.maximum
tf.keras.layers.MaxPool1D View source on GitHub Max pooling operation for 1D temporal data. Inherits From: Layer, Module View aliases Main aliases tf.keras.layers.MaxPooling1D Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.MaxPool1D, tf.compat.v1.keras.layers.MaxPooling1D tf.keras.layers.MaxPool1D( pool_size=2, strides=None, padding='valid', data_format='channels_last', **kwargs ) Downsamples the input representation by taking the maximum value over the window defined by pool_size. The window is shifted by strides. The resulting output when using "valid" padding option has a shape of: output_shape = (input_shape - pool_size + 1) / strides) The resulting output shape when using the "same" padding option is: output_shape = input_shape / strides For example, for strides=1 and padding="valid": x = tf.constant([1., 2., 3., 4., 5.]) x = tf.reshape(x, [1, 5, 1]) max_pool_1d = tf.keras.layers.MaxPooling1D(pool_size=2, strides=1, padding='valid') max_pool_1d(x) <tf.Tensor: shape=(1, 4, 1), dtype=float32, numpy= array([[[2.], [3.], [4.], [5.]]], dtype=float32)> For example, for strides=2 and padding="valid": x = tf.constant([1., 2., 3., 4., 5.]) x = tf.reshape(x, [1, 5, 1]) max_pool_1d = tf.keras.layers.MaxPooling1D(pool_size=2, strides=2, padding='valid') max_pool_1d(x) <tf.Tensor: shape=(1, 2, 1), dtype=float32, numpy= array([[[2.], [4.]]], dtype=float32)> For example, for strides=1 and padding="same": x = tf.constant([1., 2., 3., 4., 5.]) x = tf.reshape(x, [1, 5, 1]) max_pool_1d = tf.keras.layers.MaxPooling1D(pool_size=2, strides=1, padding='same') max_pool_1d(x) <tf.Tensor: shape=(1, 5, 1), dtype=float32, numpy= array([[[2.], [3.], [4.], [5.], [5.]]], dtype=float32)> Arguments pool_size Integer, size of the max pooling window. strides Integer, or None. Specifies how much the pooling window moves for each pooling step. If None, it will default to pool_size. padding One of "valid" or "same" (case-insensitive). "valid" means no padding. "same" results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. data_format A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch, steps, features) while channels_first corresponds to inputs with shape (batch, features, steps). Input shape: If data_format='channels_last': 3D tensor with shape (batch_size, steps, features). If data_format='channels_first': 3D tensor with shape (batch_size, features, steps). Output shape: If data_format='channels_last': 3D tensor with shape (batch_size, downsampled_steps, features). If data_format='channels_first': 3D tensor with shape (batch_size, features, downsampled_steps).
tensorflow.keras.layers.maxpool1d
tf.keras.layers.MaxPool2D View source on GitHub Max pooling operation for 2D spatial data. Inherits From: Layer, Module View aliases Main aliases tf.keras.layers.MaxPooling2D Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.MaxPool2D, tf.compat.v1.keras.layers.MaxPooling2D tf.keras.layers.MaxPool2D( pool_size=(2, 2), strides=None, padding='valid', data_format=None, **kwargs ) Downsamples the input representation by taking the maximum value over the window defined by pool_size for each dimension along the features axis. The window is shifted by strides in each dimension. The resulting output when using "valid" padding option has a shape(number of rows or columns) of: output_shape = (input_shape - pool_size + 1) / strides) The resulting output shape when using the "same" padding option is: output_shape = input_shape / strides For example, for stride=(1,1) and padding="valid": x = tf.constant([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]) x = tf.reshape(x, [1, 3, 3, 1]) max_pool_2d = tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(1, 1), padding='valid') max_pool_2d(x) <tf.Tensor: shape=(1, 2, 2, 1), dtype=float32, numpy= array([[[[5.], [6.]], [[8.], [9.]]]], dtype=float32)> For example, for stride=(2,2) and padding="valid": x = tf.constant([[1., 2., 3., 4.], [5., 6., 7., 8.], [9., 10., 11., 12.]]) x = tf.reshape(x, [1, 3, 4, 1]) max_pool_2d = tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(1, 1), padding='valid') max_pool_2d(x) <tf.Tensor: shape=(1, 2, 3, 1), dtype=float32, numpy= array([[[[ 6.], [ 7.], [ 8.]], [[10.], [11.], [12.]]]], dtype=float32)> Usage Example: input_image = tf.constant([[[[1.], [1.], [2.], [4.]], [[2.], [2.], [3.], [2.]], [[4.], [1.], [1.], [1.]], [[2.], [2.], [1.], [4.]]]]) output = tf.constant([[[[1], [0]], [[0], [1]]]]) model = tf.keras.models.Sequential() model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2), input_shape=(4,4,1))) model.compile('adam', 'mean_squared_error') model.predict(input_image, steps=1) array([[[[2.], [4.]], [[4.], [4.]]]], dtype=float32) For example, for stride=(1,1) and padding="same": x = tf.constant([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]) x = tf.reshape(x, [1, 3, 3, 1]) max_pool_2d = tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(1, 1), padding='same') max_pool_2d(x) <tf.Tensor: shape=(1, 3, 3, 1), dtype=float32, numpy= array([[[[5.], [6.], [6.]], [[8.], [9.], [9.]], [[8.], [9.], [9.]]]], dtype=float32)> Arguments pool_size integer or tuple of 2 integers, window size over which to take the maximum. (2, 2) will take the max value over a 2x2 pooling window. If only one integer is specified, the same window length will be used for both dimensions. strides Integer, tuple of 2 integers, or None. Strides values. Specifies how far the pooling window moves for each pooling step. If None, it will default to pool_size. padding One of "valid" or "same" (case-insensitive). "valid" means no padding. "same" results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. data_format A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch, height, width, channels) while channels_first corresponds to inputs with shape (batch, channels, height, width). It defaults to the image_data_format value found in your Keras config file at ~/.keras/keras.json. If you never set it, then it will be "channels_last". Input shape: If data_format='channels_last': 4D tensor with shape (batch_size, rows, cols, channels). If data_format='channels_first': 4D tensor with shape (batch_size, channels, rows, cols). Output shape: If data_format='channels_last': 4D tensor with shape (batch_size, pooled_rows, pooled_cols, channels). If data_format='channels_first': 4D tensor with shape (batch_size, channels, pooled_rows, pooled_cols). Returns A tensor of rank 4 representing the maximum pooled values. See above for output shape.
tensorflow.keras.layers.maxpool2d
tf.keras.layers.MaxPool3D View source on GitHub Max pooling operation for 3D data (spatial or spatio-temporal). Inherits From: Layer, Module View aliases Main aliases tf.keras.layers.MaxPooling3D Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.MaxPool3D, tf.compat.v1.keras.layers.MaxPooling3D tf.keras.layers.MaxPool3D( pool_size=(2, 2, 2), strides=None, padding='valid', data_format=None, **kwargs ) Arguments pool_size Tuple of 3 integers, factors by which to downscale (dim1, dim2, dim3). (2, 2, 2) will halve the size of the 3D input in each dimension. strides tuple of 3 integers, or None. Strides values. padding One of "valid" or "same" (case-insensitive). "valid" means no padding. "same" results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. data_format A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch, spatial_dim1, spatial_dim2, spatial_dim3, channels) while channels_first corresponds to inputs with shape (batch, channels, spatial_dim1, spatial_dim2, spatial_dim3). It defaults to the image_data_format value found in your Keras config file at ~/.keras/keras.json. If you never set it, then it will be "channels_last". Input shape: If data_format='channels_last': 5D tensor with shape: (batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels) If data_format='channels_first': 5D tensor with shape: (batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3) Output shape: If data_format='channels_last': 5D tensor with shape: (batch_size, pooled_dim1, pooled_dim2, pooled_dim3, channels) If data_format='channels_first': 5D tensor with shape: (batch_size, channels, pooled_dim1, pooled_dim2, pooled_dim3)
tensorflow.keras.layers.maxpool3d
tf.keras.layers.Minimum View source on GitHub Layer that computes the minimum (element-wise) a list of inputs. Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.Minimum tf.keras.layers.Minimum( **kwargs ) It takes as input a list of tensors, all of the same shape, and returns a single tensor (also of the same shape). tf.keras.layers.Minimum()([np.arange(5).reshape(5, 1), np.arange(5, 10).reshape(5, 1)]) <tf.Tensor: shape=(5, 1), dtype=int64, numpy= array([[0], [1], [2], [3], [4]])> x1 = tf.keras.layers.Dense(8)(np.arange(10).reshape(5, 2)) x2 = tf.keras.layers.Dense(8)(np.arange(10, 20).reshape(5, 2)) minned = tf.keras.layers.Minimum()([x1, x2]) minned.shape TensorShape([5, 8]) Arguments **kwargs standard layer keyword arguments.
tensorflow.keras.layers.minimum
tf.keras.layers.MultiHeadAttention MultiHeadAttention layer. Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.MultiHeadAttention tf.keras.layers.MultiHeadAttention( num_heads, key_dim, value_dim=None, dropout=0.0, use_bias=True, output_shape=None, attention_axes=None, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs ) This is an implementation of multi-headed attention based on "Attention is all you Need". If query, key, value are the same, then this is self-attention. Each timestep in query attends to the corresponding sequence in key, and returns a fixed-width vector. This layer first projects query, key and value. These are (effectively) a list of tensors of length num_attention_heads, where the corresponding shapes are [batch_size, , key_dim], [batch_size, , key_dim], [batch_size, , value_dim]. Then, the query and key tensors are dot-producted and scaled. These are softmaxed to obtain attention probabilities. The value tensors are then interpolated by these probabilities, then concatenated back to a single tensor. Finally, the result tensor with the last dimension as value_dim can take an linear projection and return. Examples: Performs 1D cross-attention over two sequence inputs with an attention mask. Returns the additional attention weights over heads. layer = MultiHeadAttention(num_heads=2, key_dim=2) target = tf.keras.Input(shape=[8, 16]) source = tf.keras.Input(shape=[4, 16]) output_tensor, weights = layer(target, source, return_attention_scores=True) print(output_tensor.shape) (None, 8, 16) print(weights.shape) (None, 2, 8, 4) Performs 2D self-attention over a 5D input tensor on axes 2 and 3. layer = MultiHeadAttention(num_heads=2, key_dim=2, attention_axes=(2, 3)) input_tensor = tf.keras.Input(shape=[5, 3, 4, 16]) output_tensor = layer(input_tensor, input_tensor) print(output_tensor.shape) (None, 5, 3, 4, 16) Arguments num_heads Number of attention heads. key_dim Size of each attention head for query and key. value_dim Size of each attention head for value. dropout Dropout probability. use_bias Boolean, whether the dense layers use bias vectors/matrices. output_shape The expected shape of an output tensor, besides the batch and sequence dims. If not specified, projects back to the key feature dim. attention_axes axes over which the attention is applied. None means attention over all axes, but batch, heads, and features. kernel_initializer Initializer for dense layer kernels. bias_initializer Initializer for dense layer biases. kernel_regularizer Regularizer for dense layer kernels. bias_regularizer Regularizer for dense layer biases. activity_regularizer Regularizer for dense layer activity. kernel_constraint Constraint for dense layer kernels. bias_constraint Constraint for dense layer kernels. Call arguments: query: Query Tensor of shape [B, T, dim]. value: Value Tensor of shape [B, S, dim]. key: Optional key Tensor of shape [B, S, dim]. If not given, will use value for both key and value, which is the most common case. attention_mask: a boolean mask of shape [B, T, S], that prevents attention to certain positions. return_attention_scores: A boolean to indicate whether the output should be attention output if True, or (attention_output, attention_scores) if False. Defaults to False. training: Python boolean indicating whether the layer should behave in training mode (adding dropout) or in inference mode (no dropout). Defaults to either using the training mode of the parent layer/model, or False (inference) if there is no parent layer. Returns attention_output The result of the computation, of shape [B, T, E], where T is for target sequence shapes and E is the query input last dimension if output_shape is None. Otherwise, the multi-head outputs are project to the shape specified by output_shape. attention_scores [Optional] multi-head attention coeffients over attention axes.
tensorflow.keras.layers.multiheadattention
tf.keras.layers.Multiply View source on GitHub Layer that multiplies (element-wise) a list of inputs. Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.Multiply tf.keras.layers.Multiply( **kwargs ) It takes as input a list of tensors, all of the same shape, and returns a single tensor (also of the same shape). tf.keras.layers.Multiply()([np.arange(5).reshape(5, 1), np.arange(5, 10).reshape(5, 1)]) <tf.Tensor: shape=(5, 1), dtype=int64, numpy= array([[ 0], [ 6], [14], [24], [36]])> x1 = tf.keras.layers.Dense(8)(np.arange(10).reshape(5, 2)) x2 = tf.keras.layers.Dense(8)(np.arange(10, 20).reshape(5, 2)) multiplied = tf.keras.layers.Multiply()([x1, x2]) multiplied.shape TensorShape([5, 8]) Arguments **kwargs standard layer keyword arguments.
tensorflow.keras.layers.multiply
tf.keras.layers.Permute View source on GitHub Permutes the dimensions of the input according to a given pattern. Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.Permute tf.keras.layers.Permute( dims, **kwargs ) Useful e.g. connecting RNNs and convnets. Example: model = Sequential() model.add(Permute((2, 1), input_shape=(10, 64))) # now: model.output_shape == (None, 64, 10) # note: `None` is the batch dimension Arguments dims Tuple of integers. Permutation pattern does not include the samples dimension. Indexing starts at 1. For instance, (2, 1) permutes the first and second dimensions of the input. Input shape: Arbitrary. Use the keyword argument input_shape (tuple of integers, does not include the samples axis) when using this layer as the first layer in a model. Output shape: Same as the input shape, but with the dimensions re-ordered according to the specified pattern.
tensorflow.keras.layers.permute
tf.keras.layers.PReLU View source on GitHub Parametric Rectified Linear Unit. Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.PReLU tf.keras.layers.PReLU( alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None, shared_axes=None, **kwargs ) It follows: f(x) = alpha * x for x < 0 f(x) = x for x >= 0 where alpha is a learned array with the same shape as x. Input shape: Arbitrary. Use the keyword argument input_shape (tuple of integers, does not include the samples axis) when using this layer as the first layer in a model. Output shape: Same shape as the input. Arguments alpha_initializer Initializer function for the weights. alpha_regularizer Regularizer for the weights. alpha_constraint Constraint for the weights. shared_axes The axes along which to share learnable parameters for the activation function. For example, if the incoming feature maps are from a 2D convolution with output shape (batch, height, width, channels), and you wish to share parameters across space so that each filter only has one set of parameters, set shared_axes=[1, 2].
tensorflow.keras.layers.prelu
tf.keras.layers.ReLU View source on GitHub Rectified Linear Unit activation function. Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.ReLU tf.keras.layers.ReLU( max_value=None, negative_slope=0, threshold=0, **kwargs ) With default values, it returns element-wise max(x, 0). Otherwise, it follows: f(x) = max_value if x >= max_value f(x) = x if threshold <= x < max_value f(x) = negative_slope * (x - threshold) otherwise Usage: layer = tf.keras.layers.ReLU() output = layer([-3.0, -1.0, 0.0, 2.0]) list(output.numpy()) [0.0, 0.0, 0.0, 2.0] layer = tf.keras.layers.ReLU(max_value=1.0) output = layer([-3.0, -1.0, 0.0, 2.0]) list(output.numpy()) [0.0, 0.0, 0.0, 1.0] layer = tf.keras.layers.ReLU(negative_slope=1.0) output = layer([-3.0, -1.0, 0.0, 2.0]) list(output.numpy()) [-3.0, -1.0, 0.0, 2.0] layer = tf.keras.layers.ReLU(threshold=1.5) output = layer([-3.0, -1.0, 1.0, 2.0]) list(output.numpy()) [0.0, 0.0, 0.0, 2.0] Input shape: Arbitrary. Use the keyword argument input_shape (tuple of integers, does not include the batch axis) when using this layer as the first layer in a model. Output shape: Same shape as the input. Arguments max_value Float >= 0. Maximum activation value. Default to None, which means unlimited. negative_slope Float >= 0. Negative slope coefficient. Default to 0. threshold Float. Threshold value for thresholded activation. Default to 0.
tensorflow.keras.layers.relu
tf.keras.layers.RepeatVector View source on GitHub Repeats the input n times. Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.RepeatVector tf.keras.layers.RepeatVector( n, **kwargs ) Example: model = Sequential() model.add(Dense(32, input_dim=32)) # now: model.output_shape == (None, 32) # note: `None` is the batch dimension model.add(RepeatVector(3)) # now: model.output_shape == (None, 3, 32) Arguments n Integer, repetition factor. Input shape: 2D tensor of shape (num_samples, features). Output shape: 3D tensor of shape (num_samples, n, features).
tensorflow.keras.layers.repeatvector
tf.keras.layers.Reshape View source on GitHub Layer that reshapes inputs into the given shape. Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.Reshape tf.keras.layers.Reshape( target_shape, **kwargs ) Input shape: Arbitrary, although all dimensions in the input shape must be known/fixed. Use the keyword argument input_shape (tuple of integers, does not include the samples/batch size axis) when using this layer as the first layer in a model. Output shape: (batch_size,) + target_shape Example: # as first layer in a Sequential model model = tf.keras.Sequential() model.add(tf.keras.layers.Reshape((3, 4), input_shape=(12,))) # model.output_shape == (None, 3, 4), `None` is the batch size. model.output_shape (None, 3, 4) # as intermediate layer in a Sequential model model.add(tf.keras.layers.Reshape((6, 2))) model.output_shape (None, 6, 2) # also supports shape inference using `-1` as dimension model.add(tf.keras.layers.Reshape((-1, 2, 2))) model.output_shape (None, 3, 2, 2) Args target_shape Target shape. Tuple of integers, does not include the samples dimension (batch size). **kwargs Any additional layer keyword arguments.
tensorflow.keras.layers.reshape
tf.keras.layers.RNN View source on GitHub Base class for recurrent layers. Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.RNN tf.keras.layers.RNN( cell, return_sequences=False, return_state=False, go_backwards=False, stateful=False, unroll=False, time_major=False, **kwargs ) See the Keras RNN API guide for details about the usage of RNN API. Arguments cell A RNN cell instance or a list of RNN cell instances. A RNN cell is a class that has: A call(input_at_t, states_at_t) method, returning (output_at_t, states_at_t_plus_1). The call method of the cell can also take the optional argument constants, see section "Note on passing external constants" below. A state_size attribute. This can be a single integer (single state) in which case it is the size of the recurrent state. This can also be a list/tuple of integers (one size per state). The state_size can also be TensorShape or tuple/list of TensorShape, to represent high dimension state. A output_size attribute. This can be a single integer or a TensorShape, which represent the shape of the output. For backward compatible reason, if this attribute is not available for the cell, the value will be inferred by the first element of the state_size. A get_initial_state(inputs=None, batch_size=None, dtype=None) method that creates a tensor meant to be fed to call() as the initial state, if the user didn't specify any initial state via other means. The returned initial state should have a shape of [batch_size, cell.state_size]. The cell might choose to create a tensor full of zeros, or full of other values based on the cell's implementation. inputs is the input tensor to the RNN layer, which should contain the batch size as its shape[0], and also dtype. Note that the shape[0] might be None during the graph construction. Either the inputs or the pair of batch_size and dtype are provided. batch_size is a scalar tensor that represents the batch size of the inputs. dtype is tf.DType that represents the dtype of the inputs. For backward compatible reason, if this method is not implemented by the cell, the RNN layer will create a zero filled tensor with the size of [batch_size, cell.state_size]. In the case that cell is a list of RNN cell instances, the cells will be stacked on top of each other in the RNN, resulting in an efficient stacked RNN. return_sequences Boolean (default False). Whether to return the last output in the output sequence, or the full sequence. return_state Boolean (default False). Whether to return the last state in addition to the output. go_backwards Boolean (default False). If True, process the input sequence backwards and return the reversed sequence. stateful Boolean (default False). If True, the last state for each sample at index i in a batch will be used as initial state for the sample of index i in the following batch. unroll Boolean (default False). If True, the network will be unrolled, else a symbolic loop will be used. Unrolling can speed-up a RNN, although it tends to be more memory-intensive. Unrolling is only suitable for short sequences. time_major The shape format of the inputs and outputs tensors. If True, the inputs and outputs will be in shape (timesteps, batch, ...), whereas in the False case, it will be (batch, timesteps, ...). Using time_major = True is a bit more efficient because it avoids transposes at the beginning and end of the RNN calculation. However, most TensorFlow data is batch-major, so by default this function accepts input and emits output in batch-major form. zero_output_for_mask Boolean (default False). Whether the output should use zeros for the masked timesteps. Note that this field is only used when return_sequences is True and mask is provided. It can useful if you want to reuse the raw output sequence of the RNN without interference from the masked timesteps, eg, merging bidirectional RNNs. Call arguments: inputs: Input tensor. mask: Binary tensor of shape [batch_size, timesteps] indicating whether a given timestep should be masked. training: Python boolean indicating whether the layer should behave in training mode or in inference mode. This argument is passed to the cell when calling it. This is for use with cells that use dropout. initial_state: List of initial state tensors to be passed to the first call of the cell. constants: List of constant tensors to be passed to the cell at each timestep. Input shape: N-D tensor with shape [batch_size, timesteps, ...] or [timesteps, batch_size, ...] when time_major is True. Output shape: If return_state: a list of tensors. The first tensor is the output. The remaining tensors are the last states, each with shape [batch_size, state_size], where state_size could be a high dimension tensor shape. If return_sequences: N-D tensor with shape [batch_size, timesteps, output_size], where output_size could be a high dimension tensor shape, or [timesteps, batch_size, output_size] when time_major is True. Else, N-D tensor with shape [batch_size, output_size], where output_size could be a high dimension tensor shape. Masking: This layer supports masking for input data with a variable number of timesteps. To introduce masks to your data, use an [tf.keras.layers.Embedding] layer with the mask_zero parameter set to True. Note on using statefulness in RNNs: You can set RNN layers to be 'stateful', which means that the states computed for the samples in one batch will be reused as initial states for the samples in the next batch. This assumes a one-to-one mapping between samples in different successive batches. To enable statefulness: - Specify `stateful=True` in the layer constructor. - Specify a fixed batch size for your model, by passing If sequential model: `batch_input_shape=(...)` to the first layer in your model. Else for functional model with 1 or more Input layers: `batch_shape=(...)` to all the first layers in your model. This is the expected shape of your inputs *including the batch size*. It should be a tuple of integers, e.g. `(32, 10, 100)`. - Specify `shuffle=False` when calling `fit()`. To reset the states of your model, call .reset_states() on either a specific layer, or on your entire model. Note on specifying the initial state of RNNs: You can specify the initial state of RNN layers symbolically by calling them with the keyword argument initial_state. The value of initial_state should be a tensor or list of tensors representing the initial state of the RNN layer. You can specify the initial state of RNN layers numerically by calling reset_states with the keyword argument states. The value of states should be a numpy array or list of numpy arrays representing the initial state of the RNN layer. Note on passing external constants to RNNs: You can pass "external" constants to the cell using the constants keyword argument of RNN.call (as well as RNN.call) method. This requires that the cell.call method accepts the same keyword argument constants. Such constants can be used to condition the cell transformation on additional static inputs (not changing over time), a.k.a. an attention mechanism. Examples: # First, let's define a RNN Cell, as a layer subclass. class MinimalRNNCell(keras.layers.Layer): def __init__(self, units, **kwargs): self.units = units self.state_size = units super(MinimalRNNCell, self).__init__(**kwargs) def build(self, input_shape): self.kernel = self.add_weight(shape=(input_shape[-1], self.units), initializer='uniform', name='kernel') self.recurrent_kernel = self.add_weight( shape=(self.units, self.units), initializer='uniform', name='recurrent_kernel') self.built = True def call(self, inputs, states): prev_output = states[0] h = K.dot(inputs, self.kernel) output = h + K.dot(prev_output, self.recurrent_kernel) return output, [output] # Let's use this cell in a RNN layer: cell = MinimalRNNCell(32) x = keras.Input((None, 5)) layer = RNN(cell) y = layer(x) # Here's how to use the cell to build a stacked RNN: cells = [MinimalRNNCell(32), MinimalRNNCell(64)] x = keras.Input((None, 5)) layer = RNN(cells) y = layer(x) Attributes states Methods reset_states View source reset_states( states=None ) Reset the recorded states for the stateful RNN layer. Can only be used when RNN layer is constructed with stateful = True. Args: states: Numpy arrays that contains the value for the initial state, which will be feed to cell at the first time step. When the value is None, zero filled numpy array will be created based on the cell state size. Raises AttributeError When the RNN layer is not stateful. ValueError When the batch size of the RNN layer is unknown. ValueError When the input numpy array is not compatible with the RNN layer state, either size wise or dtype wise.
tensorflow.keras.layers.rnn
tf.keras.layers.SeparableConv1D View source on GitHub Depthwise separable 1D convolution. Inherits From: Layer, Module View aliases Main aliases tf.keras.layers.SeparableConvolution1D Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.SeparableConv1D, tf.compat.v1.keras.layers.SeparableConvolution1D tf.keras.layers.SeparableConv1D( filters, kernel_size, strides=1, padding='valid', data_format=None, dilation_rate=1, depth_multiplier=1, activation=None, use_bias=True, depthwise_initializer='glorot_uniform', pointwise_initializer='glorot_uniform', bias_initializer='zeros', depthwise_regularizer=None, pointwise_regularizer=None, bias_regularizer=None, activity_regularizer=None, depthwise_constraint=None, pointwise_constraint=None, bias_constraint=None, **kwargs ) This layer performs a depthwise convolution that acts separately on channels, followed by a pointwise convolution that mixes channels. If use_bias is True and a bias initializer is provided, it adds a bias vector to the output. It then optionally applies an activation function to produce the final output. Arguments filters Integer, the dimensionality of the output space (i.e. the number of filters in the convolution). kernel_size A single integer specifying the spatial dimensions of the filters. strides A single integer specifying the strides of the convolution. Specifying any stride value != 1 is incompatible with specifying any dilation_rate value != 1. padding One of "valid", "same", or "causal" (case-insensitive). "valid" means no padding. "same" results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. "causal" results in causal (dilated) convolutions, e.g. output[t] does not depend on input[t+1:]. data_format A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, length, channels) while channels_first corresponds to inputs with shape (batch_size, channels, length). dilation_rate A single integer, specifying the dilation rate to use for dilated convolution. Currently, specifying any dilation_rate value != 1 is incompatible with specifying any stride value != 1. depth_multiplier The number of depthwise convolution output channels for each input channel. The total number of depthwise convolution output channels will be equal to num_filters_in * depth_multiplier. activation Activation function to use. If you don't specify anything, no activation is applied ( see keras.activations). use_bias Boolean, whether the layer uses a bias. depthwise_initializer An initializer for the depthwise convolution kernel ( see keras.initializers). pointwise_initializer An initializer for the pointwise convolution kernel ( see keras.initializers). bias_initializer An initializer for the bias vector. If None, the default initializer will be used (see keras.initializers). depthwise_regularizer Optional regularizer for the depthwise convolution kernel (see keras.regularizers). pointwise_regularizer Optional regularizer for the pointwise convolution kernel (see keras.regularizers). bias_regularizer Optional regularizer for the bias vector ( see keras.regularizers). activity_regularizer Optional regularizer function for the output ( see keras.regularizers). depthwise_constraint Optional projection function to be applied to the depthwise kernel after being updated by an Optimizer (e.g. used for norm constraints or value constraints for layer weights). The function must take as input the unprojected variable and must return the projected variable (which must have the same shape). Constraints are not safe to use when doing asynchronous distributed training ( see keras.constraints). pointwise_constraint Optional projection function to be applied to the pointwise kernel after being updated by an Optimizer ( see keras.constraints). bias_constraint Optional projection function to be applied to the bias after being updated by an Optimizer ( see keras.constraints). trainable Boolean, if True the weights of this layer will be marked as trainable (and listed in layer.trainable_weights). Input shape: 3D tensor with shape: (batch_size, channels, steps) if data_format='channels_first' or 5D tensor with shape: (batch_size, steps, channels) if data_format='channels_last'. Output shape: 3D tensor with shape: (batch_size, filters, new_steps) if data_format='channels_first' or 3D tensor with shape: (batch_size, new_steps, filters) if data_format='channels_last'. new_steps value might have changed due to padding or strides. Returns A tensor of rank 3 representing activation(separableconv1d(inputs, kernel) + bias). Raises ValueError when both strides > 1 and dilation_rate > 1.
tensorflow.keras.layers.separableconv1d
tf.keras.layers.SeparableConv2D View source on GitHub Depthwise separable 2D convolution. Inherits From: Layer, Module View aliases Main aliases tf.keras.layers.SeparableConvolution2D Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.SeparableConv2D, tf.compat.v1.keras.layers.SeparableConvolution2D tf.keras.layers.SeparableConv2D( filters, kernel_size, strides=(1, 1), padding='valid', data_format=None, dilation_rate=(1, 1), depth_multiplier=1, activation=None, use_bias=True, depthwise_initializer='glorot_uniform', pointwise_initializer='glorot_uniform', bias_initializer='zeros', depthwise_regularizer=None, pointwise_regularizer=None, bias_regularizer=None, activity_regularizer=None, depthwise_constraint=None, pointwise_constraint=None, bias_constraint=None, **kwargs ) Separable convolutions consist of first performing a depthwise spatial convolution (which acts on each input channel separately) followed by a pointwise convolution which mixes the resulting output channels. The depth_multiplier argument controls how many output channels are generated per input channel in the depthwise step. Intuitively, separable convolutions can be understood as a way to factorize a convolution kernel into two smaller kernels, or as an extreme version of an Inception block. Arguments filters Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution). kernel_size An integer or tuple/list of 2 integers, specifying the height and width of the 2D convolution window. Can be a single integer to specify the same value for all spatial dimensions. strides An integer or tuple/list of 2 integers, specifying the strides of the convolution along the height and width. Can be a single integer to specify the same value for all spatial dimensions. Specifying any stride value != 1 is incompatible with specifying any dilation_rate value != 1. padding one of "valid" or "same" (case-insensitive). "valid" means no padding. "same" results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. data_format A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, height, width, channels) while channels_first corresponds to inputs with shape (batch_size, channels, height, width). It defaults to the image_data_format value found in your Keras config file at ~/.keras/keras.json. If you never set it, then it will be "channels_last". dilation_rate An integer or tuple/list of 2 integers, specifying the dilation rate to use for dilated convolution. Currently, specifying any dilation_rate value != 1 is incompatible with specifying any strides value != 1. depth_multiplier The number of depthwise convolution output channels for each input channel. The total number of depthwise convolution output channels will be equal to filters_in * depth_multiplier. activation Activation function to use. If you don't specify anything, no activation is applied ( see keras.activations). use_bias Boolean, whether the layer uses a bias vector. depthwise_initializer Initializer for the depthwise kernel matrix ( see keras.initializers). pointwise_initializer Initializer for the pointwise kernel matrix ( see keras.initializers). bias_initializer Initializer for the bias vector ( see keras.initializers). depthwise_regularizer Regularizer function applied to the depthwise kernel matrix (see keras.regularizers). pointwise_regularizer Regularizer function applied to the pointwise kernel matrix (see keras.regularizers). bias_regularizer Regularizer function applied to the bias vector ( see keras.regularizers). activity_regularizer Regularizer function applied to the output of the layer (its "activation") ( see keras.regularizers). depthwise_constraint Constraint function applied to the depthwise kernel matrix ( see keras.constraints). pointwise_constraint Constraint function applied to the pointwise kernel matrix ( see keras.constraints). bias_constraint Constraint function applied to the bias vector ( see keras.constraints). Input shape: 4D tensor with shape: (batch_size, channels, rows, cols) if data_format='channels_first' or 4D tensor with shape: (batch_size, rows, cols, channels) if data_format='channels_last'. Output shape: 4D tensor with shape: (batch_size, filters, new_rows, new_cols) if data_format='channels_first' or 4D tensor with shape: (batch_size, new_rows, new_cols, filters) if data_format='channels_last'. rows and cols values might have changed due to padding. Returns A tensor of rank 4 representing activation(separableconv2d(inputs, kernel) + bias). Raises ValueError if padding is "causal". ValueError when both strides > 1 and dilation_rate > 1.
tensorflow.keras.layers.separableconv2d
tf.keras.layers.serialize View source on GitHub View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.serialize tf.keras.layers.serialize( layer )
tensorflow.keras.layers.serialize
tf.keras.layers.SimpleRNN View source on GitHub Fully-connected RNN where the output is to be fed back to input. Inherits From: RNN, Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.SimpleRNN tf.keras.layers.SimpleRNN( units, activation='tanh', use_bias=True, kernel_initializer='glorot_uniform', recurrent_initializer='orthogonal', bias_initializer='zeros', kernel_regularizer=None, recurrent_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, recurrent_constraint=None, bias_constraint=None, dropout=0.0, recurrent_dropout=0.0, return_sequences=False, return_state=False, go_backwards=False, stateful=False, unroll=False, **kwargs ) See the Keras RNN API guide for details about the usage of RNN API. Arguments units Positive integer, dimensionality of the output space. activation Activation function to use. Default: hyperbolic tangent (tanh). If you pass None, no activation is applied (ie. "linear" activation: a(x) = x). use_bias Boolean, (default True), whether the layer uses a bias vector. kernel_initializer Initializer for the kernel weights matrix, used for the linear transformation of the inputs. Default: glorot_uniform. recurrent_initializer Initializer for the recurrent_kernel weights matrix, used for the linear transformation of the recurrent state. Default: orthogonal. bias_initializer Initializer for the bias vector. Default: zeros. kernel_regularizer Regularizer function applied to the kernel weights matrix. Default: None. recurrent_regularizer Regularizer function applied to the recurrent_kernel weights matrix. Default: None. bias_regularizer Regularizer function applied to the bias vector. Default: None. activity_regularizer Regularizer function applied to the output of the layer (its "activation"). Default: None. kernel_constraint Constraint function applied to the kernel weights matrix. Default: None. recurrent_constraint Constraint function applied to the recurrent_kernel weights matrix. Default: None. bias_constraint Constraint function applied to the bias vector. Default: None. dropout Float between 0 and 1. Fraction of the units to drop for the linear transformation of the inputs. Default: 0. recurrent_dropout Float between 0 and 1. Fraction of the units to drop for the linear transformation of the recurrent state. Default: 0. return_sequences Boolean. Whether to return the last output in the output sequence, or the full sequence. Default: False. return_state Boolean. Whether to return the last state in addition to the output. Default: False go_backwards Boolean (default False). If True, process the input sequence backwards and return the reversed sequence. stateful Boolean (default False). If True, the last state for each sample at index i in a batch will be used as initial state for the sample of index i in the following batch. unroll Boolean (default False). If True, the network will be unrolled, else a symbolic loop will be used. Unrolling can speed-up a RNN, although it tends to be more memory-intensive. Unrolling is only suitable for short sequences. Call arguments: inputs: A 3D tensor, with shape [batch, timesteps, feature]. mask: Binary tensor of shape [batch, timesteps] indicating whether a given timestep should be masked. training: Python boolean indicating whether the layer should behave in training mode or in inference mode. This argument is passed to the cell when calling it. This is only relevant if dropout or recurrent_dropout is used. initial_state: List of initial state tensors to be passed to the first call of the cell. Examples: inputs = np.random.random([32, 10, 8]).astype(np.float32) simple_rnn = tf.keras.layers.SimpleRNN(4) output = simple_rnn(inputs) # The output has shape `[32, 4]`. simple_rnn = tf.keras.layers.SimpleRNN( 4, return_sequences=True, return_state=True) # whole_sequence_output has shape `[32, 10, 4]`. # final_state has shape `[32, 4]`. whole_sequence_output, final_state = simple_rnn(inputs) Attributes activation bias_constraint bias_initializer bias_regularizer dropout kernel_constraint kernel_initializer kernel_regularizer recurrent_constraint recurrent_dropout recurrent_initializer recurrent_regularizer states units use_bias Methods reset_states View source reset_states( states=None ) Reset the recorded states for the stateful RNN layer. Can only be used when RNN layer is constructed with stateful = True. Args: states: Numpy arrays that contains the value for the initial state, which will be feed to cell at the first time step. When the value is None, zero filled numpy array will be created based on the cell state size. Raises AttributeError When the RNN layer is not stateful. ValueError When the batch size of the RNN layer is unknown. ValueError When the input numpy array is not compatible with the RNN layer state, either size wise or dtype wise.
tensorflow.keras.layers.simplernn
tf.keras.layers.SimpleRNNCell View source on GitHub Cell class for SimpleRNN. Inherits From: Layer, Module View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.SimpleRNNCell tf.keras.layers.SimpleRNNCell( units, activation='tanh', use_bias=True, kernel_initializer='glorot_uniform', recurrent_initializer='orthogonal', bias_initializer='zeros', kernel_regularizer=None, recurrent_regularizer=None, bias_regularizer=None, kernel_constraint=None, recurrent_constraint=None, bias_constraint=None, dropout=0.0, recurrent_dropout=0.0, **kwargs ) See the Keras RNN API guide for details about the usage of RNN API. This class processes one step within the whole time sequence input, whereas tf.keras.layer.SimpleRNN processes the whole sequence. Arguments units Positive integer, dimensionality of the output space. activation Activation function to use. Default: hyperbolic tangent (tanh). If you pass None, no activation is applied (ie. "linear" activation: a(x) = x). use_bias Boolean, (default True), whether the layer uses a bias vector. kernel_initializer Initializer for the kernel weights matrix, used for the linear transformation of the inputs. Default: glorot_uniform. recurrent_initializer Initializer for the recurrent_kernel weights matrix, used for the linear transformation of the recurrent state. Default: orthogonal. bias_initializer Initializer for the bias vector. Default: zeros. kernel_regularizer Regularizer function applied to the kernel weights matrix. Default: None. recurrent_regularizer Regularizer function applied to the recurrent_kernel weights matrix. Default: None. bias_regularizer Regularizer function applied to the bias vector. Default: None. kernel_constraint Constraint function applied to the kernel weights matrix. Default: None. recurrent_constraint Constraint function applied to the recurrent_kernel weights matrix. Default: None. bias_constraint Constraint function applied to the bias vector. Default: None. dropout Float between 0 and 1. Fraction of the units to drop for the linear transformation of the inputs. Default: 0. recurrent_dropout Float between 0 and 1. Fraction of the units to drop for the linear transformation of the recurrent state. Default: 0. Call arguments: inputs: A 2D tensor, with shape of [batch, feature]. states: A 2D tensor with shape of [batch, units], which is the state from the previous time step. For timestep 0, the initial state provided by user will be feed to cell. training: Python boolean indicating whether the layer should behave in training mode or in inference mode. Only relevant when dropout or recurrent_dropout is used. Examples: inputs = np.random.random([32, 10, 8]).astype(np.float32) rnn = tf.keras.layers.RNN(tf.keras.layers.SimpleRNNCell(4)) output = rnn(inputs) # The output has shape `[32, 4]`. rnn = tf.keras.layers.RNN( tf.keras.layers.SimpleRNNCell(4), return_sequences=True, return_state=True) # whole_sequence_output has shape `[32, 10, 4]`. # final_state has shape `[32, 4]`. whole_sequence_output, final_state = rnn(inputs) Methods get_dropout_mask_for_cell View source get_dropout_mask_for_cell( inputs, training, count=1 ) Get the dropout mask for RNN cell's input. It will create mask based on context if there isn't any existing cached mask. If a new mask is generated, it will update the cache in the cell. Args inputs The input tensor whose shape will be used to generate dropout mask. training Boolean tensor, whether its in training mode, dropout will be ignored in non-training mode. count Int, how many dropout mask will be generated. It is useful for cell that has internal weights fused together. Returns List of mask tensor, generated or cached mask based on context. get_initial_state View source get_initial_state( inputs=None, batch_size=None, dtype=None ) get_recurrent_dropout_mask_for_cell View source get_recurrent_dropout_mask_for_cell( inputs, training, count=1 ) Get the recurrent dropout mask for RNN cell. It will create mask based on context if there isn't any existing cached mask. If a new mask is generated, it will update the cache in the cell. Args inputs The input tensor whose shape will be used to generate dropout mask. training Boolean tensor, whether its in training mode, dropout will be ignored in non-training mode. count Int, how many dropout mask will be generated. It is useful for cell that has internal weights fused together. Returns List of mask tensor, generated or cached mask based on context. reset_dropout_mask View source reset_dropout_mask() Reset the cached dropout masks if any. This is important for the RNN layer to invoke this in it call() method so that the cached mask is cleared before calling the cell.call(). The mask should be cached across the timestep within the same batch, but shouldn't be cached between batches. Otherwise it will introduce unreasonable bias against certain index of data within the batch. reset_recurrent_dropout_mask View source reset_recurrent_dropout_mask() Reset the cached recurrent dropout masks if any. This is important for the RNN layer to invoke this in it call() method so that the cached mask is cleared before calling the cell.call(). The mask should be cached across the timestep within the same batch, but shouldn't be cached between batches. Otherwise it will introduce unreasonable bias against certain index of data within the batch.
tensorflow.keras.layers.simplernncell