tf.layers.Dense

tf.layers.Dense是一个全连接层类,用于实现激活函数为非线性转换的线性运算。该层创建权重矩阵和(如果使用的话)偏置向量,并允许设置激活函数、是否使用偏置、权重初始化方式等参数。它还包含属性和方法来获取输入输出、损失、更新等相关信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

tf.layers.Dense

Class Dense

Inherits From: Layer

Defined in tensorflow/python/layers/core.py.

Densely-connected layer class.

This layer implements the operation:outputs = activation(inputs * kernel + bias)Where activation is the activation function passed as the activationargument (if not None), kernel is a weights matrix created by the layer,and bias is a bias vector created by the layer(only if use_bias is True).

Note: if the input to the layer has a rank greater than 2, then it isflattened prior to the initial matrix multiply by kernel.
Arguments:
  • units: Integer or Long, dimensionality of the output space.
  • activation: Activation function (callable). Set it to None to maintain a linear activation.
  • use_bias: Boolean, whether the layer uses a bias.
  • kernel_initializer: Initializer function for the weight matrix. If None (default), weights are initialized using the default initializer used by tf.get_variable.
  • bias_initializer: Initializer function for the bias.
  • kernel_regularizer: Regularizer function for the weight matrix.
  • bias_regularizer: Regularizer function for the bias.
  • activity_regularizer: Regularizer function for the output.
  • kernel_constraint: An optional projection function to be applied to the kernel after being updated by an Optimizer (e.g. used to implement 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.
  • bias_constraint: An optional projection function to be applied to the bias after being updated by an Optimizer.
  • trainable: Boolean, if True also add variables to the graph collection GraphKeys.TRAINABLE_VARIABLES (see tf.Variable).
  • name: String, the name of the layer. Layers with the same name will share weights, but to avoid mistakes we require reuse=True in such cases.
  • reuse: Boolean, whether to reuse the weights of a previous layer by the same name.

Properties: units: Python integer, dimensionality of the output space. activation: Activation function (callable). use_bias: Boolean, whether the layer uses a bias. kernel_initializer: Initializer instance (or name) for the kernel matrix. bias_initializer: Initializer instance (or name) for the bias. kernel_regularizer: Regularizer instance for the kernel matrix (callable) bias_regularizer: Regularizer instance for the bias (callable). activity_regularizer: Regularizer instance for the output (callable) kernel_constraint: Constraint function for the kernel matrix. bias_constraint: Constraint function for the bias. kernel: Weight matrix (TensorFlow variable or tensor). bias: Bias vector, if applicable (TensorFlow variable or tensor).

Properties

activity_regularizer

Optional regularizer function for the output of this layer.

dtype

graph

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.

Returns:

Input tensor or list of input tensors.

Raises:
  • AttributeError: if the layer is connected to more than one incoming layers.
Raises:
  • RuntimeError: If called in Eager mode.
  • AttributeError: If no inbound nodes are found.

input_shape

Retrieves the input shape(s) of a layer.

Only applicable if the layer has exactly one input,i.e. if it is connected to one incoming layer, or if all inputshave the same shape.

Returns:

Input shape, as an integer shape tuple(or list of shape tuples, one tuple per input tensor).

Raises:
  • AttributeError: if the layer has no defined input_shape.
  • RuntimeError: if called in Eager mode.

losses

Losses which are associated with this Layer.

Note that when executing eagerly, getting this property evaluatesregularizers. When using graph execution, variable regularization ops havealready been created and are simply returned here.

Returns:

A list of tensors.

name

non_trainable_variables

non_trainable_weights

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.

Returns:

Output tensor or list of output tensors.

Raises:
  • AttributeError: if the layer is connected to more than one incoming layers.
  • RuntimeError: if called in Eager mode.

output_shape

Retrieves the output shape(s) of a layer.

Only applicable if the layer has one output,or if all outputs have the same shape.

Returns:

Output shape, as an integer shape tuple(or list of shape tuples, one tuple per output tensor).

Raises:
  • AttributeError: if the layer has no defined output shape.
  • RuntimeError: if called in Eager mode.

scope_name

trainable_variables

trainable_weights

updates

variables

Returns the list of all layer variables/weights.

Returns:

A list of variables.

weights

Returns the list of all layer variables/weights.

Returns:

A list of variables.

Methods

__init__

__init__(
    units,
    activation=None,
    use_bias=True,
    kernel_initializer=None,
    bias_initializer=tf.zeros_initializer(),
    kernel_regularizer=None,
    bias_regularizer=None,
    activity_regularizer=None,
    kernel_constraint=None,
    bias_constraint=None,
    trainable=True,
    name=None,
    **kwargs
)

__call__

__call__(
    inputs,
    *args,
    **kwargs
)

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

Arguments:
  • inputs: input tensor(s).
  • *args: additional positional arguments to be passed to self.call.
  • **kwargs: additional keyword arguments to be passed to self.call. Note: kwarg scope is reserved for use by the layer.
Returns:

Output tensor(s).

Note: - If the layer's call method takes a scope keyword argument, this argument will be automatically set to the current variable scope. - 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).

__deepcopy__

__deepcopy__(memo)

add_loss

add_loss(
    losses,
    inputs=None
)

Add loss tensor(s), potentially dependent on layer inputs.

Some losses (for instance, activity regularization losses) may be dependenton the inputs passed when calling a layer. Hence, when reusing the samelayer on different inputs a and b, some entries in layer.losses maybe dependent on a and some on b. This method automatically keeps trackof dependencies.

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

Note that add_loss is not supported when executing eagerly. Instead,variable regularizers may be added through add_variable. Activityregularization is not supported directly (but such losses may be returnedfrom Layer.call()).

Arguments:
  • losses: Loss tensor, or list/tuple of tensors.
  • inputs: Optional input tensor(s) that the loss(es) depend on. Must match the inputs argument passed to the __call__ method at the time the losses are created. If None is passed, the losses are assumed to be unconditional, and will apply across all dataflows of the layer (e.g. weight regularization losses).
Raises:
  • RuntimeError: If called in Eager mode.

add_update

add_update(
    updates,
    inputs=None
)

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

Weight updates (for instance, the updates of the moving mean and variancein a BatchNormalization layer) may be dependent on the inputs passedwhen calling a layer. Hence, when reusing the same layer ondifferent inputs a and b, some entries in layer.updates may bedependent on a and some on b. This method automatically keeps trackof dependencies.

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

This call is ignored in Eager mode.

Arguments:
  • updates: Update op, or list/tuple of update ops.
  • inputs: Optional input tensor(s) that the update(s) depend on. Must match the inputs argument passed to the __call__ method at the time the updates are created. If None is passed, the updates are assumed to be unconditional, and will apply across all dataflows of the layer.

add_variable

add_variable(
    name,
    shape,
    dtype=None,
    initializer=None,
    regularizer=None,
    trainable=True,
    constraint=None,
    partitioner=None
)

Adds a new variable to the layer, or gets an existing one; returns it.

Arguments:
  • name: variable name.
  • shape: variable shape.
  • dtype: The type of the variable. Defaults to self.dtype or float32.
  • initializer: initializer instance (callable).
  • regularizer: regularizer instance (callable).
  • trainable: whether the variable should be part of the layer's "trainable_variables" (e.g. variables, biases) or "non_trainable_variables" (e.g. BatchNorm mean, stddev). Note, if the current variable scope is marked as non-trainable then this parameter is ignored and any added variables are also marked as non-trainable.
  • constraint: constraint instance (callable).
  • partitioner: (optional) partitioner instance (callable). If provided, when the requested variable is created it will be split into multiple partitions according to partitioner. In this case, an instance of PartitionedVariable is returned. Available partitioners include tf.fixed_size_partitioner and tf.variable_axis_size_partitioner. For more details, see the documentation of tf.get_variable and the "Variable Partitioners and Sharding" section of the API guide.
Returns:

The created variable. Usually either a Variable or ResourceVariableinstance. If partitioner is not None, a PartitionedVariableinstance is returned.

Raises:
  • RuntimeError: If called in Eager mode with regularizers.

apply

apply(
    inputs,
    *args,
    **kwargs
)

Apply the layer on a input.

This simply wraps self.__call__.

Arguments:
  • inputs: Input tensor(s).
  • *args: additional positional arguments to be passed to self.call.
  • **kwargs: additional keyword arguments to be passed to self.call.
Returns:

Output tensor(s).

build

build(input_shape)

call

call(inputs)

count_params

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

get_input_at

get_input_at(node_index)

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

Arguments:
  • node_index: Integer, index of the node from which to retrieve the attribute. E.g. node_index=0 will correspond to the first time the layer was called.
Returns:

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

Raises:
  • RuntimeError: If called in Eager mode.

get_input_shape_at

get_input_shape_at(node_index)

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

Arguments:
  • node_index: Integer, index of the node from which to retrieve the attribute. E.g. node_index=0 will correspond to the first time the layer was called.
Returns:

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

Raises:
  • RuntimeError: If called in Eager mode.

get_losses_for

get_losses_for(inputs)

Retrieves losses relevant to a specific set of inputs.

Arguments:
  • inputs: Input tensor or list/tuple of input tensors. Must match the inputs argument passed to the __call__ method at the time the losses were created. If you pass inputs=None, unconditional losses are returned, such as weight regularization losses.
Returns:

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

Raises:
  • RuntimeError: If called in Eager mode.

get_output_at

get_output_at(node_index)

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

Arguments:
  • node_index: Integer, index of the node from which to retrieve the attribute. E.g. node_index=0 will correspond to the first time the layer was called.
Returns:

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

Raises:
  • RuntimeError: If called in Eager mode.

get_output_shape_at

get_output_shape_at(node_index)

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

Arguments:
  • node_index: Integer, index of the node from which to retrieve the attribute. E.g. node_index=0 will correspond to the first time the layer was called.
Returns:

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

Raises:
  • RuntimeError: If called in Eager mode.

get_updates_for

get_updates_for(inputs)

Retrieves updates relevant to a specific set of inputs.

Arguments:
  • inputs: Input tensor or list/tuple of input tensors. Must match the inputs argument passed to the __call__ method at the time the updates were created. If you pass inputs=None, unconditional updates are returned.
Returns:

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

Raises:
  • RuntimeError: If called in Eager mode.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值