tensorflow中权重和偏置初始化的几种方式

https://www.cnblogs.com/denny402/p/6932956.html

神经网络的 Multi-Layer Perceptron (MLP) 或全连接层通常使用特定的方式初始化权重偏置。在 Python ,我们可以用深度学习库如 TensorFlow、PyTorch 或 Keras 来处理。这里分别给出几种常见的初始化方法: 1. **随机初始化(默认)**: ```python from tensorflow.keras.initializers import RandomNormal, glorot_uniform, zeros, ones # 随机正态分布 weights = tf.Variable(RandomNormal(mean=0.0, stddev=0.01, shape=(input_size, hidden_units))) # Glorot uniform 初始化(Xavier初始化) weights = tf.Variable(glorot_uniform(shape=(input_size, hidden_units))) ``` 2. **He初始化**: 这种方法适合激活函数为 ReLU 类型,推荐权重的偏差使用 zeros 初始化。 ```python from tensorflow.keras.initializers import he_normal weights = tf.Variable(he_normal(stddev=math.sqrt(2 / input_size), shape=(input_size, hidden_units))) ``` 3. **Zeros 和 Ones**: 对于一些简单的用途,可以直接设置所有权重偏置为零或一。 ```python biases = tf.Variable(zeros([hidden_units])) # 所有偏置设为0 biases = tf.Variable(ones([hidden_units])) # 所有偏置设为1 ``` 4. **预训练初始化(如 Word2Vec 或 GloVe)**: 如果应用到某些特定的上下文,可能需要加载预训练的词向量作为权重。 记得在实际代码,`input_size` 是输入特征的数量,`hidden_units` 是隐藏层的神经元数量。初始化方法的选择取决于具体的任务需求以及希望模型快速收敛还是优化梯度传播。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值