gpt4 book ai didi

python - Tensorflow——添加L2正则化损失简单示例

转载 作者:太空宇宙 更新时间:2023-11-04 00:46:18 27 4
gpt4 key购买 nike

我熟悉机器学习,但我正在通过阅读大学的一些幻灯片来自学 Tensorflow。下面我设置了只有一个特征的线性回归的损失函数。我在总损失中添加了 L2 损失,但我不确定我是否做对了:

# Regularization
reg_strength = 0.01

# Create the loss function.
with tf.variable_scope("linear-regression"):
W = tf.get_variable("W", shape=(1, 1), initializer=tf.contrib.layers.xavier_initializer())
b = tf.get_variable("b", shape=(1,), initializer=tf.constant_initializer(0.0))
yhat = tf.matmul(X, W) + b

error_loss = tf.reduce_sum(((y - yhat)**2)/number_of_examples)
#reg_loss = reg_strength * tf.nn.l2_loss(W) # reg 1
reg_loss = reg_strength * tf.reduce_sum(W**2) # reg 2
loss = error_loss + reg_loss

# Set up the optimizer.
opt_operation = tf.train.GradientDescentOptimizer(0.001).minimize(loss)

我的具体问题是:

  1. 我有两行(注释为 reg 1reg 2)计算权重 W 的 L2 损失。标记为 reg 1 的行使用了 Tensorflow 内置函数。这两个 L2 实现是否等效?

  2. 我是否将正则化损失 reg_loss 正确添加到最终损失函数?

最佳答案

差不多

According to the L2Loss operation code

output.device(d) = (input.square() * static_cast<T>(0.5)).sum();

它也乘以 0.5(或者换句话说,它除以 2)

关于python - Tensorflow——添加L2正则化损失简单示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39460338/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com