[source]

Dense

  1. 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)

Just your regular densely-connected NN layer.

Dense implements the operation:output = activation(dot(input, kernel) + bias)where activation is the element-wise activation functionpassed as the activation argument, kernel is a weights matrixcreated 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, thenit is flattened prior to the initial dot product with kernel.

Example

  1. # as first layer in a sequential model:
  2. model = Sequential()
  3. model.add(Dense(32, input_shape=(16,)))
  4. # now the model will take as input arrays of shape (*, 16)
  5. # and output arrays of shape (*, 32)
  6. # after the first layer, you don't need to specify
  7. # the size of the input anymore:
  8. model.add(Dense(32))

Arguments

  • units: Positive integer, dimensionality of the output space.
  • activation: Activation function to use (see activations). 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 (see initializers).
  • bias_initializer: Initializer for the bias vector (see initializers).
  • kernel_regularizer: Regularizer function applied to the kernel weights matrix (see regularizer).
  • bias_regularizer: Regularizer function applied to the bias vector (see regularizer).
  • activity_regularizer: Regularizer function applied to the output of the layer (its "activation"). (see regularizer).
  • kernel_constraint: Constraint function applied to the kernel weights matrix (see constraints).
  • bias_constraint: Constraint function applied to the bias vector (see constraints).

Input shape

nD tensor with shape: (batch_size, …, input_dim).The most common situation would bea 2D input with shape (batch_size, input_dim).

Output shape

nD 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).

[source]

Activation

  1. keras.layers.Activation(activation)

Applies an activation function to an output.

Arguments

  • activation: name of activation function to use (see: activations), or alternatively, a Theano or TensorFlow operation.

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.

[source]

Dropout

  1. keras.layers.Dropout(rate, noise_shape=None, seed=None)

Applies Dropout to the input.

Dropout consists in randomly settinga fraction rate of input units to 0 at each update during training time,which helps prevent overfitting.

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.

References

[source]

Flatten

  1. keras.layers.Flatten(data_format=None)

Flattens the input. Does not affect the batch size.

Arguments

  • data_format: A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. The purpose of this argument is to preserve weight ordering when switching a model from one data format to another. 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

  1. model = Sequential()
  2. model.add(Conv2D(64, (3, 3),
  3. input_shape=(3, 32, 32), padding='same',))
  4. # now: model.output_shape == (None, 64, 32, 32)
  5. model.add(Flatten())
  6. # now: model.output_shape == (None, 65536)

[source]

Input

  1. keras.engine.input_layer.Input()

Input() is used to instantiate a Keras tensor.

A Keras tensor is a tensor object from the underlying backend(Theano, TensorFlow or CNTK), which we augment with certainattributes that allow us to build a Keras modeljust 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)

The added Keras attributes are:_keras_shape: Integer shape tuple propagatedvia Keras-side shape inference._keras_history: Last layer applied to the tensor.the entire layer graph is retrievable from that layer,recursively.

Arguments

  • shape: A shape tuple (integer), not including the batch size. For instance, shape=(32,) indicates that the expected input will be batches of 32-dimensional vectors.
  • batch_shape: A shape tuple (integer), including the batch size. For instance, batch_shape=(10, 32) indicates that the expected input will be batches of 10 32-dimensional vectors. batch_shape=(None, 32) indicates batches of an arbitrary number of 32-dimensional vectors.
  • 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.
  • tensor: Optional existing tensor to wrap into the Input layer. If set, the layer will not create a placeholder tensor.

Returns

A tensor.

Example

  1. # this is a logistic regression in Keras
  2. x = Input(shape=(32,))
  3. y = Dense(16, activation='softmax')(x)
  4. model = Model(x, y)

[source]

Reshape

  1. keras.layers.Reshape(target_shape)

Reshapes an output to a certain shape.

Arguments

  • target_shape: target shape. Tuple of integers. Does not include the batch axis.

Input shape

Arbitrary, although all dimensions in the input shaped must be fixed.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

(batch_size,) + target_shape

Example

  1. # as first layer in a Sequential model
  2. model = Sequential()
  3. model.add(Reshape((3, 4), input_shape=(12,)))
  4. # now: model.output_shape == (None, 3, 4)
  5. # note: `None` is the batch dimension
  6. # as intermediate layer in a Sequential model
  7. model.add(Reshape((6, 2)))
  8. # now: model.output_shape == (None, 6, 2)
  9. # also supports shape inference using `-1` as dimension
  10. model.add(Reshape((-1, 2, 2)))
  11. # now: model.output_shape == (None, 3, 2, 2)

[source]

Permute

  1. keras.layers.Permute(dims)

Permutes the dimensions of the input according to a given pattern.

Useful for e.g. connecting RNNs and convnets together.

Example

  1. model = Sequential()
  2. model.add(Permute((2, 1), input_shape=(10, 64)))
  3. # now: model.output_shape == (None, 64, 10)
  4. # 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 dimension 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 accordingto the specified pattern.

[source]

RepeatVector

  1. keras.layers.RepeatVector(n)

Repeats the input n times.

Example

  1. model = Sequential()
  2. model.add(Dense(32, input_dim=32))
  3. # now: model.output_shape == (None, 32)
  4. # note: `None` is the batch dimension
  5. model.add(RepeatVector(3))
  6. # 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).

[source]

Lambda

  1. keras.layers.Lambda(function, output_shape=None, mask=None, arguments=None)

Wraps arbitrary expression as a Layer object.

Examples

  1. # add a x -> x^2 layer
  2. model.add(Lambda(lambda x: x ** 2))
  1. # add a layer that returns the concatenation
  2. # of the positive part of the input and
  3. # the opposite of the negative part
  4. def antirectifier(x):
  5. x -= K.mean(x, axis=1, keepdims=True)
  6. x = K.l2_normalize(x, axis=1)
  7. pos = K.relu(x)
  8. neg = K.relu(-x)
  9. return K.concatenate([pos, neg], axis=1)
  10. def antirectifier_output_shape(input_shape):
  11. shape = list(input_shape)
  12. assert len(shape) == 2 # only valid for 2D tensors
  13. shape[-1] *= 2
  14. return tuple(shape)
  15. model.add(Lambda(antirectifier,
  16. output_shape=antirectifier_output_shape))
  1. # add a layer that returns the hadamard product
  2. # and sum of it from two input tensors
  3. def hadamard_product_sum(tensors):
  4. out1 = tensors[0] * tensors[1]
  5. out2 = K.sum(out1, axis=-1)
  6. return [out1, out2]
  7. def hadamard_product_sum_output_shape(input_shapes):
  8. shape1 = list(input_shapes[0])
  9. shape2 = list(input_shapes[1])
  10. assert shape1 == shape2 # else hadamard product isn't possible
  11. return [tuple(shape1), tuple(shape2[:-1])]
  12. x1 = Dense(32)(input_1)
  13. x2 = Dense(32)(input_2)
  14. layer = Lambda(hadamard_product_sum, hadamard_product_sum_output_shape)
  15. x_hadamard, x_sum = layer([x1, x2])

Arguments

  • function: The function to be evaluated. Takes input tensor or list of tensors as first argument.
  • output_shape: Expected output shape from function. Only relevant when using Theano. 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 Tensor indicating the input mask for Embedding.
  • 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(or auto-inferred when using TensorFlow or CNTK).

[source]

ActivityRegularization

  1. keras.layers.ActivityRegularization(l1=0.0, l2=0.0)

Layer that applies an update to the cost function based input activity.

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.

[source]

Masking

  1. keras.layers.Masking(mask_value=0.0)

Masks a sequence by using a mask value to skip timesteps.

If all features for a given sample timestep are equal to mask_value,then the sample 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 suchan 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 sample #0 at timestep #3, and sample #2 at timestep #5,because you lack features for these sample timesteps. You can do:

  • set x[0, 3, :] = 0. and x[2, 5, :] = 0.
  • insert a Masking layer with mask_value=0. before the LSTM layer:
  1. model = Sequential()
  2. model.add(Masking(mask_value=0., input_shape=(timesteps, features)))
  3. model.add(LSTM(32))

Arguments

  • mask_value: Either None or mask value to skip

[source]

SpatialDropout1D

  1. keras.layers.SpatialDropout1D(rate)

Spatial 1D version of Dropout.

This version performs the same function as Dropout, however it dropsentire 1D feature maps instead of individual elements. If adjacent frameswithin feature maps are strongly correlated (as is normally the case inearly convolution layers) then regular dropout will not regularize theactivations and will otherwise just result in an effective learning ratedecrease. In this case, SpatialDropout1D will help promote independencebetween feature maps and should be used instead.

Arguments

  • rate: float between 0 and 1. Fraction of the input units to drop.

Input shape

3D tensor with shape:(samples, timesteps, channels)

Output shape

Same as input

References

[source]

SpatialDropout2D

  1. keras.layers.SpatialDropout2D(rate, data_format=None)

Spatial 2D version of Dropout.

This version performs the same function as Dropout, however it dropsentire 2D feature maps instead of individual elements. If adjacent pixelswithin feature maps are strongly correlated (as is normally the case inearly convolution layers) then regular dropout will not regularize theactivations and will otherwise just result in an effective learning ratedecrease. In this case, SpatialDropout2D will help promote independencebetween feature maps and should be used instead.

Arguments

  • rate: float between 0 and 1. Fraction of the input units to drop.
  • data_format: 'channels_first' or 'channels_last'. In 'channels_first' mode, the channels dimension (the depth) is at index 1, in 'channels_last' mode is it at index 3. 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:(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

Same as input

References

[source]

SpatialDropout3D

  1. keras.layers.SpatialDropout3D(rate, data_format=None)

Spatial 3D version of Dropout.

This version performs the same function as Dropout, however it dropsentire 3D feature maps instead of individual elements. If adjacent voxelswithin feature maps are strongly correlated (as is normally the case inearly convolution layers) then regular dropout will not regularize theactivations and will otherwise just result in an effective learning ratedecrease. In this case, SpatialDropout3D will help promote independencebetween feature maps and should be used instead.

Arguments

  • rate: float between 0 and 1. Fraction of the input units to drop.
  • data_format: 'channels_first' or 'channels_last'. In 'channels_first' mode, the channels dimension (the depth) is at index 1, in 'channels_last' mode is it at index 4. 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:(samples, channels, dim1, dim2, dim3) if data_format='channels_first'or 5D tensor with shape:(samples, dim1, dim2, dim3, channels) if data_format='channels_last'.

Output shape

Same as input

References