tf.keras.layers.Layer

View source on GitHub

Base layer class.

Inherits From: Module

tf.keras.layers.Layer(
    trainable=True, name=None, dtype=None, dynamic=False, **kwargs
)

This is the class from which all layers inherit.

A layer is a class implementing common neural networks operations, such as convolution, batch norm, etc. These operations require managing weights, losses, updates, and inter-layer connectivity.

Users will just instantiate a layer and then treat it as a callable.

We recommend that descendants of Layer implement the following methods:

Arguments:

Read-only properties: name: The name of the layer (string). dtype: The dtype of the layer's computations and weights. If mixed precision is used with a tf.keras.mixed_precision.experimental.Policy, this is instead just the dtype of the layer's weights, as the computations are done in a different dtype. updates: List of update ops of this layer. losses: List of losses added by this layer. 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).

Mutable properties:

Dtypes and casting

Each layer has a dtype, which is typically the dtype of the layer's computations and variables. A layer's dtype can be queried via the Layer.dtype property. The dtype is specified with the dtype constructor argument. In TensorFlow 2, the dtype defaults to tf.keras.backend.floatx() if no dtype is passed. floatx() itself defaults to "float32". Additionally, layers will cast their inputs to the layer's dtype in TensorFlow 2. When mixed precision is used, layers may have different computation and variable dtypes. See tf.keras.mixed_precision.experimental.Policy for details on layer dtypes.

Attributes:

Methods

__call__

View source

__call__(
    inputs, *args, **kwargs
)

Wraps call, applying pre- and post-processing steps.

Arguments:

Returns:

Output tensor(s).

Note:

Raises:

add_loss

View source

add_loss(
    losses, inputs=None
)

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(inputs, self):
    self.add_loss(tf.abs(tf.reduce_mean(inputs)), inputs=True)
    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)
# Actvity 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,))
x = tf.keras.layers.Dense(10)(inputs)
outputs = tf.keras.layers.Dense(1)(x)
model = tf.keras.Model(inputs, outputs)
# Weight regularization.
model.add_loss(lambda: tf.reduce_mean(x.kernel))

The get_losses_for method allows to retrieve the losses relevant to a specific set of inputs.

Arguments:

add_metric

View source

add_metric(
    value, aggregation=None, name=None
)

Adds metric tensor to the layer.

Args:

Raises:

add_update

View source

add_update(
    updates, inputs=None
)

Add update op(s), potentially dependent on layer inputs. (deprecated arguments)

Warning: SOME ARGUMENTS ARE DEPRECATED: (inputs). They will be removed in a future version. Instructions for updating: inputs is now automatically inferred

Weight updates (for instance, the updates of the moving mean and variance in a BatchNormalization layer) 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.updates may be dependent on a and some on b. This method automatically keeps track of dependencies.

The get_updates_for method allows to retrieve the updates relevant to a specific set of inputs.

This call is ignored when eager execution is enabled (in that case, variable updates are run on the fly and thus do not need to be tracked for later execution).

Arguments:

add_weight

View source

add_weight(
    name=None, shape=None, dtype=None, initializer=None, regularizer=None,
    trainable=None, constraint=None, partitioner=None, use_resource=None,
    synchronization=tf.VariableSynchronization.AUTO,
    aggregation=tf.compat.v1.VariableAggregation.NONE, **kwargs
)

Adds a new variable to the layer.

Arguments:

Returns:

The created variable. Usually either a Variable or ResourceVariable instance. If partitioner is not None, a PartitionedVariable instance is returned.

Raises:

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:

call

View source

call(
    inputs, **kwargs
)

This is where the layer's logic lives.

Arguments:

Returns:

A tensor or list/tuple of tensors.

compute_mask

View source

compute_mask(
    inputs, mask=None
)

Computes an output mask tensor.

Arguments:

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:

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:

Returns:

Single TensorSpec or nested structure of TensorSpec objects, describing how the layer would transform the provided input.

Raises:

count_params

View source

count_params()

Count the total number of scalars composing the weights.

Returns:

An integer count.

Raises:

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:

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_input_at

View source

get_input_at(
    node_index
)

Retrieves the input tensor(s) of a layer at a given node.

Arguments:

Returns:

A tensor (or list of tensors if the layer has multiple inputs).

Raises:

get_input_mask_at

View source

get_input_mask_at(
    node_index
)

Retrieves the input mask tensor(s) of a layer at a given node.

Arguments:

Returns:

A mask tensor (or list of tensors if the layer has multiple inputs).

get_input_shape_at

View source

get_input_shape_at(
    node_index
)

Retrieves the input shape(s) of a layer at a given node.

Arguments:

Returns:

A shape tuple (or list of shape tuples if the layer has multiple inputs).

Raises:

get_losses_for

View source

get_losses_for(
    inputs
)

Retrieves losses relevant to a specific set of inputs.

Arguments:

Returns:

List of loss tensors of the layer that depend on inputs.

get_output_at

View source

get_output_at(
    node_index
)

Retrieves the output tensor(s) of a layer at a given node.

Arguments:

Returns:

A tensor (or list of tensors if the layer has multiple outputs).

Raises:

get_output_mask_at

View source

get_output_mask_at(
    node_index
)

Retrieves the output mask tensor(s) of a layer at a given node.

Arguments:

Returns:

A mask tensor (or list of tensors if the layer has multiple outputs).

get_output_shape_at

View source

get_output_shape_at(
    node_index
)

Retrieves the output shape(s) of a layer at a given node.

Arguments:

Returns:

A shape tuple (or list of shape tuples if the layer has multiple outputs).

Raises:

get_updates_for

View source

get_updates_for(
    inputs
)

Retrieves updates relevant to a specific set of inputs.

Arguments:

Returns:

List of update ops of the layer that depend on inputs.

get_weights

View source

get_weights()

Returns the current weights of the layer.

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.

Arguments:

Raises: