aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/contrib/layers/python/ops/loss_ops.py
blob: ae3d6203fe57bd0e505db225e8e321291a478006 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================

"""## Loss operations for use in neural networks.

The loss ops measure error for use in neural networks. These losses
can be used for measuring accuracy of a network in a regression task
or for regularization purposes (e.g., weight decay).

These loss ops are, by design, minimal, enabling flexibility in how
their output can be used.

@@reduce_batch_sum
@@reduce_batch_mean

@@absolute_loss
@@squared_loss

@@sum_squared_loss
@@mean_absolute_loss
@@mean_squared_loss
@@root_mean_squared_loss
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops


__all__ = ["reduce_batch_sum", "reduce_batch_mean", "absolute_loss",
           "squared_loss", "sum_squared_loss", "mean_absolute_loss",
           "mean_squared_loss", "root_mean_squared_loss"]


def _reduce_batch(x, reduce_fn, name=None):
  """Given a tensor `x`, calls reduce_fn to reduce it across dimensions.

  Given a tensor with number of dimensions > 1, _reduce_batch will reduce the
  tensor across all dimensions except for dimension 0. As an example, given a
  tensor of shape [batch_size, d1, d2], this function will reduce across
  dimensions d1 and d2, returning a tensor of shape [batch_size].

  Tensors of dimension 1 are returned as-is, while tensors of dimension 0
  raise a ValueError.

  Args:
    x: A `Tensor` with dimension > 0.
    reduce_fn: A math_ops reduce function that takes arguments of
      `x`, `reduction_indices`, and `name`.
    name: A name for the operation (optional).

  Returns:
    A `Tensor` with values reduced by reduce_fn across all dimensions > 0.

  Raises:
    ValueError: If `x` has dimension 0.
  """
  x = ops.convert_to_tensor(x, name="x")
  with ops.op_scope([x], name, "reduce_batch"):
    ndims = x.get_shape().ndims
    if ndims == 0:
      raise ValueError("Cannot reduce a scalar into batches.")
    elif ndims == 1:
      return x  # Don't include a useless reduction.
    elif ndims:
      reduction_indices = list(range(1, ndims))
      shape = [x.get_shape().dims[0]]
    else:
      reduction_indices = math_ops.range(1, array_ops.size(array_ops.shape(x)))
      shape = [None]  # We don't know much about the shape, but it is rank 1.
    result = reduce_fn(x, reduction_indices=reduction_indices)

    # Give a shape hint in case we have extra information.
    result.set_shape(shape)
    return result


def reduce_batch_sum(x, name=None):
  """Given a tensor `x`, sums across all dimensions except dimension 0.

  Given a tensor with the number of dimensions > 1, reduce_batch_sum
  will sum across all dimensions except for dimension 0. This function
  is useful for summing the loss (error) across all examples in a
  batch when training. As an example, given a tensor of shape
  [batch_size, d1, d2], this function will sum across dimensions d1
  and d2, returning a tensor of shape [batch_size].

  Tensors of dimension 1 are returned as-is, while tensors of dimension 0
  raise a ValueError.

  Args:
    x: A `Tensor` with dimension > 0.
    name: A name for the operation (optional).

  Returns:
    A `Tensor` with values summed across all dimensions > 0.

  Raises:
    ValueError: If `x` has dimension 0.

  """
  return _reduce_batch(x, math_ops.reduce_sum, name)


def reduce_batch_mean(x, name=None):
  """Given a tensor `x`, returns the mean across all dimensions except dim 0.

  Given a tensor with the number of dimensions > 1, reduce_batch_mean
  will calculate the mean across all dimensions except for dimension
  0. This function is useful for calculating the mean loss (error)
  across all examples in a batch when training. As an example, given a
  tensor of shape [batch_size, d1, d2], this function will calculate
  the mean across dimensions d1 and d2, returning a tensor of shape
  [batch_size].

  Tensors of dimension 1 are returned as-is.

  Args:
    x: A `Tensor` with dimension > 0.
    name: A name for the operation (optional).

  Returns:
    A `Tensor` with values averaged across all dimensions > 0.

  Raises:
    ValueError: If `x` has dimension 0.

  """
  return _reduce_batch(x, math_ops.reduce_mean, name)


def absolute_loss(predicted, target, name=None):
  """Computes and returns the per-example absolute loss.

  Computes the per-example absolute value of the difference between
  the target and predicted tensors. The tensors must have the same
  shape.

  Args:
    predicted: A `Tensor` of shape `[batch_size, dim_1, ..., dim_n]`
      of predicted values.
    target: A `Tensor` of shape `[batch_size, dim_1, ..., dim_n]` of
      target values. The shape of the target tensor should match the
      `predicted` tensor.
    name: A name for the operation (optional).

  Returns:
    A `[batch_size, dim_1, ..., dim_n]` tensor of per-example absolute losses.

  Raises:
    ValueError: If `predicted` and `target` shapes do not match.

  """
  with ops.op_scope([predicted, target], name, "absolute_loss") as scope:
    predicted = ops.convert_to_tensor(predicted, name="predicted")
    target = ops.convert_to_tensor(target, name="target")
    predicted.get_shape().assert_is_compatible_with(target.get_shape())
    return math_ops.abs(target - predicted, name=scope)


def squared_loss(predicted, target, name=None):
  """Computes and returns the per-example squared loss.

  Computes the per-example squared difference between the target and
  predicted tensors. The tensors must have the same shape.

  Args:
    predicted: A `Tensor` of shape `[batch_size, dim_1, ..., dim_n]`
      of predicted values.
    target: A `Tensor` of shape `[batch_size, dim_1, ..., dim_n]` of
      target values. The shape of the target tensor should match the
      `predicted` tensor.
    name: A name for the operation (optional).

  Returns:
    A `[batch_size, dim_1, ..., dim_n]` tensor of per-example squared losses.

  Raises:
    ValueError: If `predicted` and `target` shapes do not match.

  """
  with ops.op_scope([predicted, target], name, "squared_loss") as scope:
    predicted = ops.convert_to_tensor(predicted, name="predicted")
    target = ops.convert_to_tensor(target, name="target")
    predicted.get_shape().assert_is_compatible_with(target.get_shape())
    return math_ops.square(target - predicted, name=scope)


def sum_squared_loss(predicted, target, name=None):
  # pylint: disable=line-too-long
  """Calculates 1/2 the sum of the squared loss across batches.

  Computes the squared difference between the target and predicted
  tensors, sums across all dimensions except dimension 0, and divides
  by 2:

      losses = reduce_batch_sum(squared_loss(predicted, target)) / 2.0

  where `losses` is a tensor with dimensions [batch_size].

  The tensors must have the same shape.

  This function is equivalent to typical formulations of L2 loss, and similar
  to TensorFlow's l2_loss function. It differs from the l2_loss function
  by allowing the caller to specify both the predicted and target tensors.

  Args:
    predicted: A `Tensor` of shape `[batch_size, dim_1, ..., dim_n]`
      of predicted values.
    target: A `Tensor` of shape `[batch_size, dim_1, ..., dim_n]` of
      target values. The shape of the target tensor should match the
      `predicted` tensor.
    name: A name for the operation (optional).

  Returns:
    A `[batch_size]` tensor of squared losses summed across all dimensions
    except dimension 0, divided by 2.

  Raises:
    ValueError: If `predicted` and `target` shapes do not match.

  """
  # pylint: enable=line-too-long
  with ops.op_scope(
      [predicted, target],
      name,
      "sum_squared_loss") as scope:
    return math_ops.div(reduce_batch_sum(squared_loss(predicted, target)),
                        2.0,
                        name=scope)


def mean_absolute_loss(predicted, target, name=None):
  """Calculates the mean absolute loss across batches.

  Computes the absolute difference between the target and predicted
  tensors, averaged across all dimensions except dimension 0:

        losses = reduce_batch_mean(absolute_loss(predicted, target))

  where `losses` is a tensor with dimensions [batch_size].

  The tensors must have the same shape.

  This loss function is a form of L1 loss.

  Args:
    predicted: A `Tensor` of shape `[batch_size, dim_1, ..., dim_n]`
      of predicted values.
    target: A `Tensor` of shape `[batch_size, dim_1, ..., dim_n]` of
      target values. The shape of the target tensor should match the
      `predicted` tensor.
    name: A name for the operation (optional).

  Returns:
    A `[batch_size]` tensor of absolute differences, averaged across all
    dimensions except dimension 0.

  Raises:
    ValueError: If `predicted` and `target` shapes do not match.

  """
  with ops.op_scope([predicted, target], name, "mean_absolute_loss") as scope:
    return reduce_batch_mean(absolute_loss(predicted, target), name=scope)


def mean_squared_loss(predicted, target, name=None):
  """Calculates the mean squared loss across batches.

  Computes the squared difference between the target and predicted
  tensors, and averages across all dimensions except dimension 0:

        losses = reduce_batch_mean(squared_loss(predicted, target))

  where `losses` is a tensor with dimensions [batch_size].

  The tensors must have the same shape.

  Args:
    predicted: A `Tensor` of shape `[batch_size, dim_1, ..., dim_n]`
      of predicted values.
    target: A `Tensor` of shape `[batch_size, dim_1, ..., dim_n]` of
      target values. The shape of the target tensor should match the
      `predicted` tensor.
    name: A name for the operation (optional).

  Returns:
    A `[batch_size]` tensor of squared differences, averaged across
    all dimensions except dimension 0.

  Raises:
    ValueError: If `predicted` and `target` shapes do not match.

  """
  with ops.op_scope([predicted, target], name, "mean_squared_loss") as scope:
    return reduce_batch_mean(squared_loss(predicted, target), name=scope)


def root_mean_squared_loss(predicted, target, name=None):
  """Calculates the root mean squared loss across batches.

  Computes the root mean squared loss between the target and predicted
  tensors, which is the square root of the mean squared differences
  between the predicted and target tensors:

        losses = sqrt(mean_squared_loss(predicted, target))

  where `losses` is a tensor with dimensions [batch_size].

  The tensors must have the same shape.

  Args:
    predicted: A `Tensor` of shape `[batch_size, dim_1, ..., dim_n]`
      of predicted values.
    target: A `Tensor` of shape `[batch_size, dim_1, ..., dim_n]` of
      target values. The shape of the target tensor should match the
      `predicted` tensor.
    name: A name for the operation (optional).

  Returns:
    A `[batch_size]` tensor of the root mean squared differences.

  Raises:
    ValueError: If `predicted` and `target` shapes do not match.

  """
  with ops.op_scope([predicted, target],
                    name,
                    "root_mean_squared_loss") as scope:
    return math_ops.sqrt(mean_squared_loss(predicted, target),
                         name=scope)