做tf.nn公司.l2_损失和tf.contrib.layers公司.l2_正则化器用于在tensorflow中添加l2正则化的相同目的?

2024-05-14 22:28:33 发布

您现在位置:Python中文网/ 问答频道 /正文

张量流中的L2正则化似乎可以通过两种方式实现:

(一)使用tf.nn公司.l2_丢失或 (二)使用tf.contrib.layers公司.l2_正则化器

这两种方法的目的是否相同?如果他们不同,他们有什么不同?在


Tags: 方法目的layerstf方式公司nncontrib
1条回答
网友
1楼 · 发布于 2024-05-14 22:28:33

他们做同样的事情(至少现在)。唯一的区别是tf.contrib.layers.l2_regularizertf.nn.l2_loss的结果乘以scale

看看tf.contrib.layers.l2_regularizer[https://github.com/tensorflow/tensorflow/blob/r1.1/tensorflow/contrib/layers/python/layers/regularizers.py]的实现:

def l2_regularizer(scale, scope=None):
  """Returns a function that can be used to apply L2 regularization to weights.
  Small values of L2 can help prevent overfitting the training data.
  Args:
    scale: A scalar multiplier `Tensor`. 0.0 disables the regularizer.
    scope: An optional scope name.
  Returns:
    A function with signature `l2(weights)` that applies L2 regularization.
  Raises:
    ValueError: If scale is negative or if scale is not a float.
  """
  if isinstance(scale, numbers.Integral):
    raise ValueError('scale cannot be an integer: %s' % (scale,))
  if isinstance(scale, numbers.Real):
    if scale < 0.:
      raise ValueError('Setting a scale less than 0 on a regularizer: %g.' %
                       scale)
    if scale == 0.:
      logging.info('Scale of 0 disables regularizer.')
      return lambda _: None

  def l2(weights):
    """Applies l2 regularization to weights."""
    with ops.name_scope(scope, 'l2_regularizer', [weights]) as name:
      my_scale = ops.convert_to_tensor(scale,
                                       dtype=weights.dtype.base_dtype,
                                       name='scale')
      return standard_ops.multiply(my_scale, nn.l2_loss(weights), name=name)

  return l2

您感兴趣的线路是:

^{pr2}$

所以在实践中,tf.contrib.layers.l2_regularizer在内部调用tf.nn.l2_loss,并简单地将结果乘以scale参数。

相关问题 更多 >

    热门问题