dense函数(也称为全连接层或线性层)是神经网络中最基础且常用的组件之一。在Python的深度学习生态中,它广泛应用于TensorFlow/Keras、PyTorch等框架。
1. 在TensorFlow/Keras中使用Dense层
Keras提供了 tf.keras.layers.Dense 类来定义全连接层:
import tensorflow as tf
model = tf.keras.Sequential([
tf.keras.layers.Dense(128, activation='relu', input_shape=(784,)),
tf.keras.layers.Dense(10, activation='softmax')
])
2. 在PyTorch中使用Linear层
PyTorch中对应的模块是 torch.nn.Linear:
import torch
import torch.nn as nn
class Net(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(784, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = torch.softmax(self.fc2(x), dim=1)
return x
3. Dense层参数说明
- units / out_features:输出神经元数量
- activation:激活函数(如 'relu', 'sigmoid')
- use_bias:是否使用偏置项(默认为True)
- kernel_initializer:权重初始化方法
4. 应用场景
Dense层常用于:
- 分类任务的最后一层
- 多层感知机(MLP)结构
- 特征提取后的整合层
掌握dense函数的使用,是构建神经网络模型的第一步。建议结合具体项目进行实践。