View source on GitHub
|
This is the class from which all layers inherit.
Inherits From: Operation
tf.keras.Layer(
*,
activity_regularizer=None,
trainable=True,
dtype=None,
autocast=True,
name=None,
**kwargs
)
Used in the notebooks
| Used in the guide | Used in the tutorials |
|---|---|
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). State can be
created:
- in
__init__(), for instance viaself.add_weight(); - in the optional
build()method, which is invoked by the first__call__()to the layer, and supplies the shape(s) of the input(s), which may not have been known at initialization time.
Layers are recursively composable: If you assign a Layer instance as an
attribute of another Layer, the outer layer will start tracking the weights
created by the inner layer. Nested layers should be instantiated in the
__init__() method or build() method.
Users will just instantiate a layer and then treat it as a callable.
Args |
|---|
trainable
name
dtype
keras.DTypePolicy,
which allows the computation and
weight dtype to differ. Defaults to None. None means to use
keras.config.dtype_policy(),
which is a float32 policy unless set to different value
(via keras.config.set_dtype_policy()).
We recommend that descendants of Layer implement the following methods:
__init__(): Defines custom layer attributes, and creates layer weights that do not depend on input shapes, usingadd_weight(), or other state.build(self, input_shape): This method can be used to create weights that depend on the shape(s) of the input(s), usingadd_weight(), or other state.__call__()will automatically build the layer (if it has not been built yet) by callingbuild().call(self, *args, **kwargs): Called in__call__after making surebuild()has been called.call()performs the logic of applying the layer to the input arguments. Two reserved keyword arguments you can optionally use incall()are: 1.training(boolean, whether the call is in inference mode or training mode). 2.mask(boolean tensor encoding masked timesteps in the input, used e.g. in RNN layers). A typical signature for this method iscall(self, inputs), and user could optionally addtrainingandmaskif the layer need them.get_config(self): Returns a dictionary containing the configuration used to initialize this layer. If the keys differ from the arguments in__init__(), then overridefrom_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().__init__()
self.units = units
# Create the state of the layer (weights)
def build(self, input_shape):
self.kernel = self.add_weight(
shape=(input_shape[-1], self.units),
initializer="glorot_uniform",
trainable=True,
name="kernel",
)
self.bias = self.add_weight(
shape=(self.units,),
initializer="zeros",
trainable=True,
name="bias",
)
# Defines the computation
def call(self, inputs):
return ops.matmul(inputs, self.kernel) + self.bias
# Instantiates the layer.
linear_layer = SimpleDense(4)
# This will also call `build(input_shape)` and create the weights.
y = linear_layer(ops.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
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 = self.add_weight(
shape=(),
initializer="zeros",
trainable=False,
name="total",
)
def call(self, inputs):
self.total.assign(self.total + ops.sum(inputs))
return self.total
my_sum = ComputeSum(2)
x = ops.ones((2, 2))
y = my_sum(x)
assert my_sum.weights == [my_sum.total]
assert my_sum.non_trainable_weights == [my_sum.total]
assert my_sum.trainable_weights == []
Attributes |
|---|
name
dtype
layer.variable_dtype.
variable_dtype
compute_dtype
keras.DTypePolicy, this will be different
than variable_dtype.
trainable_weights
non_trainable_weights
weights
trainable
layer.trainable_weights.
input_spec
InputSpec object(s) specifying the
constraints on inputs that can be accepted by the layer.
dtype_policy
input
Only returns the tensor(s) corresponding to the first time the operation was called.
input_dtype
losses
add_loss, regularizers and sublayers.
metrics
metrics_variables
non_trainable_variables
This extends layer.non_trainable_weights to include all state used by
the layer including state for metrics and SeedGenerators.
output
Only returns the tensor(s) corresponding to the first time the operation was called.
supports_masking
compute_mask.
trainable_variables
This is equivalent to layer.trainable_weights.
variables
This extends layer.weights to include all state used by the layer
including SeedGenerators.
Note that metrics variables are not included here, use
metrics_variables to visit all the metric variables.
Methods
add_loss
add_loss(
loss
)
Can be called inside of the call() method to add a scalar loss.
Example:
class MyLayer(Layer):
...
def call(self, x):
self.add_loss(ops.sum(x))
return x
add_metric
add_metric()
add_variable
add_variable(
shape,
initializer,
dtype=None,
trainable=True,
autocast=True,
regularizer=None,
constraint=None,
name=None
)
Add a weight variable to the layer.
Alias of add_weight().
add_weight
add_weight(
shape=None,
initializer=None,
dtype=None,
trainable=True,
autocast=True,
regularizer=None,
constraint=None,
aggregation='mean',
name=None
)
Add a weight variable to the layer.
| Args |
|---|
shape
None entries). Defaults to () (scalar) if unspecified.
initializer
"random_normal"). If unspecified, defaults to
"glorot_uniform" for floating-point variables and to "zeros"
for all other types (e.g. int, bool).
dtype
"float32". If
unspecified, defaults to the layer's variable dtype
(which itself defaults to "float32" if unspecified).
trainable
True.
autocast
True.
regularizer
None.
constraint
None.
aggregation
'mean', 'sum',
'only_first_replica'. Annotates the variable with the type
of multi-replica aggregation to be used for this variable
when writing custom data parallel training loops.
name
build
build(
input_shape
)
build_from_config
build_from_config(
config
)
Builds the layer's states with the supplied config dict.
By default, this method calls the build(config["input_shape"]) method,
which creates weights based on the layer's input shape in the supplied
config. If your config contains other information needed to load the
layer's state, you should override this method.
| Args |
|---|
config
call
call(
*args, **kwargs
)
compute_mask
compute_mask(
inputs, previous_mask
)
compute_output_shape
compute_output_shape(
*args, **kwargs
)
compute_output_spec
compute_output_spec(
*args, **kwargs
)
count_params
count_params()
Count the total number of scalars composing the weights.
| Returns | |
|---|---|
| An integer count. |
from_config
@classmethodfrom_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).
| Args |
|---|
config
| Returns | |
|---|---|
| A layer instance. |
get_build_config
get_build_config()
Returns a dictionary with the layer's input shape.
This method returns a config dict that can be used by
build_from_config(config) to create all states (e.g. Variables and
Lookup tables) needed by the layer.
By default, the config only contains the input shape that the layer was built with. If you're writing a custom layer that creates state in an unusual way, you should override this method to make sure this state is already created when Keras attempts to load its value upon model loading.
| Returns | |
|---|---|
| A dict containing the input shape associated with the layer. |
get_config
get_config()
Returns the config of the object.
An object config is a Python dictionary (serializable) containing the information needed to re-instantiate it.
get_weights
get_weights()
Return the values of layer.weights as a list of NumPy arrays.
load_own_variables
load_own_variables(
store
)
Loads the state of the layer.
You can override this method to take full control of how the state of
the layer is loaded upon calling keras.models.load_model().
| Args |
|---|
store
quantize
quantize(
mode
)
quantized_call
quantized_call(
*args, **kwargs
)
save_own_variables
save_own_variables(
store
)
Saves the state of the layer.
You can override this method to take full control of how the state of
the layer is saved upon calling model.save().
| Args |
|---|
store
set_weights
set_weights(
weights
)
Sets the values of layer.weights from a list of NumPy arrays.
stateless_call
stateless_call(
trainable_variables,
non_trainable_variables,
*args,
return_losses=False,
**kwargs
)
Call the layer without any side effects.
| Args |
|---|
trainable_variables
non_trainable_variables
*args
call().
return_losses
True, stateless_call() will return the list of
losses created during call() as part of its return values.
**kwargs
call().
| Returns | |
|---|---|
A tuple. By default, returns (outputs, non_trainable_variables).
If return_losses = True, then returns
(outputs, non_trainable_variables, losses).
|
Example:
model = ...
data = ...
trainable_variables = model.trainable_variables
non_trainable_variables = model.non_trainable_variables
# Call the model with zero side effects
outputs, non_trainable_variables = model.stateless_call(
trainable_variables,
non_trainable_variables,
data,
)
# Attach the updated state to the model
# (until you do this, the model is still in its pre-call state).
for ref_var, value in zip(
model.non_trainable_variables, non_trainable_variables
):
ref_var.assign(value)
symbolic_call
symbolic_call(
*args, **kwargs
)
__call__
__call__(
*args, **kwargs
)
Call self as a function.
View source on GitHub