什么是 dense 函数?
在深度学习中,dense 函数(也称为全连接层或线性层)是最基础且常用的神经网络组件之一。
它将输入向量通过一个可学习的权重矩阵和偏置向量进行线性变换,通常后接一个非线性激活函数(如 ReLU)。
数学表达
对于输入向量 x,dense 层的输出为:
y = Wx + b
其中 W 是权重矩阵,b 是偏置向量。
代码示例
TensorFlow / Keras
from tensorflow.keras.layers import Dense
model.add(Dense(units=128, activation='relu'))
PyTorch
import torch.nn as nn
layer = nn.Linear(in_features=784, out_features=128)
应用场景
- 多层感知机(MLP)中的隐藏层
- 分类任务的输出层(配合 softmax)
- 作为卷积神经网络(CNN)最后的分类头
- Transformer 模型中的前馈网络部分