A layer is a grouping of operations and weights that can be composed to create a tf.LayersModel.

Layers are constructed by using the functions under the tf.layers namespace.

Doc

Hierarchy

Properties

addInboundNode: any

Internal method to create an inbound node for the layer.

Param: inputTensors

List of input tensors.

Param: outputTensors

List of output tensors.

Param: inputMasks

List of input masks (a mask can be a tensor, or null).

Param: outputMasks

List of output masks (a mask can be a tensor, or null).

Param: inputShapes

List of input shape tuples.

Param: outputShapes

List of output shape tuples.

Param: kwargs

Dictionary of keyword arguments that were passed to the call method of the layer at the call that created the node.

getNodeAtIndex: any

Returns this.inboundNode at index nodeIndex.

Porting note: This is a replacement for _get_node_attribute_at_index()

Param: nodeIndex

Param: attrName

The name of the attribute related to request for this node.

inputSpec: InputSpec[]

List of InputSpec class instances.

Each entry describes one required input:

  • ndim
  • dtype A layer with n input tensors must have an inputSpec of length n.
name: string

Name for this layer. Must be unique within a model.

trainable_: boolean

Whether the layer weights will be updated during training.

Accessors

  • get input(): SymbolicTensor | SymbolicTensor[]
  • Retrieves the input tensor(s) of a layer.

    Only applicable if the layer has exactly one inbound node, i.e. if it is connected to one incoming layer.

    Returns SymbolicTensor | SymbolicTensor[]

    Input tensor or list of input tensors.

    Exception

    AttributeError if the layer is connected to more than one incoming layers.

  • get output(): SymbolicTensor | SymbolicTensor[]
  • Retrieves the output tensor(s) of a layer.

    Only applicable if the layer has exactly one inbound node, i.e. if it is connected to one incoming layer.

    Returns SymbolicTensor | SymbolicTensor[]

    Output tensor or list of output tensors.

    Exception

    AttributeError if the layer is connected to more than one incoming layers.

  • get outputShape(): Shape | Shape[]
  • Retrieves the output shape(s) of a layer.

    Only applicable if the layer has only one inbound node, or if all inbound nodes have the same output shape.

    Returns Shape | Shape[]

    Output shape or shapes.

    Throws

    AttributeError: if the layer is connected to more than one incoming nodes.

    Doc

  • get weights(): LayerVariable[]
  • The concatenation of the lists trainableWeights and nonTrainableWeights (in this order).

    Returns LayerVariable[]

Methods

  • Add losses to the layer.

    The loss may potentially be conditional on some inputs tensors, for instance activity losses are conditional on the layer's inputs.

    Parameters

    • losses: RegularizerFn | RegularizerFn[]

    Returns void

    Doc

  • Adds a weight variable to the layer.

    Parameters

    • name: string

      Name of the new weight variable.

    • shape: Shape

      The shape of the weight.

    • Optional dtype: keyof DataTypeMap

      The dtype of the weight.

    • Optional initializer: Initializer

      An initializer instance.

    • Optional regularizer: Regularizer

      A regularizer instance.

    • Optional trainable: boolean

      Whether the weight should be trained via backprop or not (assuming that the layer itself is also trainable).

    • Optional constraint: Constraint

      An optional trainable.

    • Optional getInitializerFunc: Function

    Returns LayerVariable

    The created weight variable.

    Doc

  • Builds or executes a Layer's logic.

    When called with tf.Tensor(s), execute the Layer's computation and return Tensor(s). For example:

    const denseLayer = tf.layers.dense({
    units: 1,
    kernelInitializer: 'zeros',
    useBias: false
    });

    // Invoke the layer's apply() method with a `tf.Tensor` (with concrete
    // numeric values).
    const input = tf.ones([2, 2]);
    const output = denseLayer.apply(input);

    // The output's value is expected to be [[0], [0]], due to the fact that
    // the dense layer has a kernel initialized to all-zeros and does not have
    // a bias.
    output.print();

    When called with tf.SymbolicTensor(s), this will prepare the layer for future execution. This entails internal book-keeping on shapes of expected Tensors, wiring layers together, and initializing weights.

    Calling apply with tf.SymbolicTensors are typically used during the building of non-tf.Sequential models. For example:

    const flattenLayer = tf.layers.flatten();
    const denseLayer = tf.layers.dense({units: 1});

    // Use tf.layers.input() to obtain a SymbolicTensor as input to apply().
    const input = tf.input({shape: [2, 2]});
    const output1 = flattenLayer.apply(input);

    // output1.shape is [null, 4]. The first dimension is the undetermined
    // batch size. The second dimension comes from flattening the [2, 2]
    // shape.
    console.log(JSON.stringify(output1.shape));

    // The output SymbolicTensor of the flatten layer can be used to call
    // the apply() of the dense layer:
    const output2 = denseLayer.apply(output1);

    // output2.shape is [null, 1]. The first dimension is the undetermined
    // batch size. The second dimension matches the number of units of the
    // dense layer.
    console.log(JSON.stringify(output2.shape));

    // The input and output can be used to construct a model that consists
    // of the flatten and dense layers.
    const model = tf.model({inputs: input, outputs: output2});

    Parameters

    • inputs: SymbolicTensor | SymbolicTensor[] | Tensor<Rank> | Tensor<Rank>[]

      a tf.Tensor or tf.SymbolicTensor or an Array of them.

    • Optional kwargs: Kwargs

      Additional keyword arguments to be passed to call().

    Returns SymbolicTensor | SymbolicTensor[] | Tensor<Rank> | Tensor<Rank>[]

    Output of the layer's call method.

    Exception

    ValueError error in case the layer is missing shape information for its build call.

    Doc

  • Checks compatibility between the layer and provided inputs.

    This checks that the tensor(s) input verify the input assumptions of the layer (if any). If not, exceptions are raised.

    Parameters

    Returns void

    Exception

    ValueError in case of mismatch between the provided inputs and the expectations of the layer.

  • Creates the layer weights.

    Must be implemented on all layers that have weights.

    Called when apply() is called to construct the weights.

    Parameters

    • inputShape: Shape | Shape[]

      A Shape or array of Shape (unused).

    Returns void

    Doc

  • Retrieves the Layer's current loss values.

    Used for regularizers during training.

    Returns Scalar[]

  • This is where the layer's logic lives.

    Parameters

    • inputs: Tensor<Rank> | Tensor<Rank>[]

      Input tensor, or list/tuple of input tensors.

    • kwargs: Kwargs

      Additional keyword arguments.

    Returns Tensor<Rank> | Tensor<Rank>[]

    A tensor or list/tuple of tensors.

  • Clear call hook. This is currently used for testing only.

    Returns void

  • Computes an output mask tensor.

    Parameters

    • inputs: Tensor<Rank> | Tensor<Rank>[]

      Tensor or list of tensors.

    • Optional mask: Tensor<Rank> | Tensor<Rank>[]

      Tensor or list of tensors.

    Returns Tensor<Rank> | Tensor<Rank>[]

    null or a tensor (or list of tensors, one per output tensor of the layer).

  • Computes the output shape of the layer.

    Assumes that the layer will be built to match that input shape provided.

    Parameters

    • inputShape: Shape | Shape[]

      A shape (tuple of integers) or a list of shape tuples (one per output tensor of the layer). Shape tuples can include null for free dimensions, instead of an integer.

    Returns Shape | Shape[]

    Doc

  • Counts the total number of numbers (e.g., float32, int32) in the weights.

    Returns number

    An integer count.

    Throws

    RuntimeError: If the layer is not built yet (in which case its weights are not defined yet.)

    Doc

  • Attempt to dispose layer's weights.

    This method decreases the reference count of the Layer object by 1.

    A Layer is reference-counted. Its reference count is incremented by 1 the first item its apply() method is called and when it becomes a part of a new Node (through calling the apply() method on a tf.SymbolicTensor).

    If the reference count of a Layer becomes 0, all the weights will be disposed and the underlying memory (e.g., the textures allocated in WebGL) will be freed.

    Note: If the reference count is greater than 0 after the decrement, the weights of the Layer will not be disposed.

    After a Layer is disposed, it cannot be used in calls such as apply(), getWeights() or setWeights() anymore.

    Returns DisposeResult

    A DisposeResult Object with the following fields:

    • refCountAfterDispose: The reference count of the Container after this dispose() call.
    • numDisposedVariables: Number of tf.Variables (i.e., weights) disposed during this dispose() call.

    Throws

    If the layer is not built yet, or if the layer has already been disposed.

    Doc

  • Dispose the weight variables that this Layer instance holds.

    Returns number

    Number of disposed variables.

  • Return the class name for this class to use in serialization contexts.

    Generally speaking this will be the same thing that constructor.name would have returned. However, the class name needs to be robust against minification for serialization/deserialization to work properly.

    There's also places such as initializers.VarianceScaling, where implementation details between different languages led to different class hierarchies and a non-leaf node is used for serialization purposes.

    Returns string

  • Returns the config of the layer.

    A layer config is a TS 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 'Container' (one layer of abstraction above).

    Porting Note: The TS dictionary follows TS naming standards for keys, and uses tfjs-layers type-safe Enums. Serialization methods should use a helper function to convert to the pythonic storage standard. (see serialization_utils.convertTsToPythonic)

    Returns ConfigDict

    TS dictionary of configuration.

    Doc

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

    Parameters

    • nodeIndex: number

      Integer, index of the node from which to retrieve the attribute. E.g. nodeIndex=0 will correspond to the first time the layer was called.

    Returns SymbolicTensor | SymbolicTensor[]

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

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

    Parameters

    • nodeIndex: number

      Integer, index of the node from which to retrieve the attribute. E.g. nodeIndex=0 will correspond to the first time the layer was called.

    Returns SymbolicTensor | SymbolicTensor[]

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

  • Returns the current values of the weights of the layer.

    Parameters

    • Optional trainableOnly: boolean

      Whether to get the values of only trainable weights.

    Returns Tensor<Rank>[]

    Weight values as an Array of tf.Tensors.

    Doc

  • Reset the states of the layer.

    This method of the base Layer class is essentially a no-op. Subclasses that are stateful (e.g., stateful RNNs) should override this method.

    Returns void

  • Set call hook. This is currently used for testing only.

    Parameters

    • callHook: CallHook

    Returns void

  • Set the fast-weight-initialization flag.

    In cases where the initialized weight values will be immediately overwritten by loaded weight values during model loading, setting the flag to true saves unnecessary calls to potentially expensive initializers and speeds up the loading process.

    Parameters

    • value: boolean

      Target value of the flag.

    Returns void

  • Sets the weights of the layer, from Tensors.

    Parameters

    • weights: Tensor<Rank>[]

      a list of Tensors. 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 getWeights).

    Returns void

    Exception

    ValueError If the provided weights list does not match the layer's specifications.

    Doc

  • Check compatibility between input shape and this layer's batchInputShape.

    Print warning if any incompatibility is found.

    Parameters

    • inputShape: Shape

      Input shape to be checked.

    Returns void

  • Type Parameters

    Parameters

    Returns T

    Nocollapse

  • Converts a layer and its index to a unique (immutable type) name. This function is used internally with this.containerNodes.

    Parameters

    • layer: Layer

      The layer.

    • nodeIndex: number

      The layer's position (e.g. via enumerate) in a list of nodes.

    Returns string

    The unique name.

Generated using TypeDoc