我熟悉机器学习,但我正在通过阅读大学的一些幻灯片来自学 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)
我的具体问题是:
我有两行(注释为
reg 1和reg 2)计算权重W的 L2 损失。标记为reg 1的行使用了 Tensorflow 内置函数。这两个 L2 实现是否等效?我是否将正则化损失
reg_loss正确添加到最终损失函数?
请您参考如下方法:
差不多
According to the L2Loss operation code
output.device(d) = (input.square() * static_cast<T>(0.5)).sum();
它也乘以 0.5(或者换句话说,它除以 2)
