简体   繁体   English

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

[英]Tensorflow - adding L2 regularization loss simple example

I am familiar with machine learning, but I am learning Tensorflow on my own by reading some slides from universities. 我熟悉机器学习,但是我正在阅读大学的一些幻灯片,从而独自学习Tensorflow。 Below I'm setting up the loss function for linear regression with only one feature. 下面,我仅使用一项功能设置线性回归的损失函数。 I'm adding an L2 loss to the total loss, but I am not sure if I'm doing it correctly: 我正在将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)

My specific questions are: 我的具体问题是:

  1. I have two lines (commented as reg 1 and reg 2 ) that compute the L2 loss of the weight W . 我有两条线(分别称为reg 1reg 2 )来计算重量W的L2损失。 The line marked with reg 1 uses the Tensorflow built-in function. 标记为reg 1的行使用Tensorflow内置函数。 Are these two L2 implementations equivalent? 这两个L2实现是否等效?

  2. Am I adding the regularization loss reg_loss correctly to the final loss function? 我是否将正则化损失reg_loss正确添加到最终损失函数中?

Almost 几乎

According to the L2Loss operation code 根据L2Loss操作码

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

It multiplies also for 0.5 (or in other words it divides by 2 ) 它也乘以0.5(或除以2 )。

Are these two L2 implementations equivalent? 这两个L2实现是否等效?

Almost, as @fabrizioM pointed out, you can see here for the introduction to the l2_loss in TensorFlow docs. 就像@fabrizioM指出的那样,几乎可以在这里看到TensorFlow文档中l2_loss的介绍。

Am I adding the regularization loss reg_loss correctly to the final loss function? 我是否将正则化损失reg_loss正确添加到最终损失函数中?

So far so good : ) 到现在为止还挺好 : )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM