mlpack
huber_loss_impl.hpp
Go to the documentation of this file.
1 
12 #ifndef MLPACK_METHODS_ANN_LOSS_FUNCTION_HUBER_LOSS_IMPL_HPP
13 #define MLPACK_METHODS_ANN_LOSS_FUNCTION_HUBER_LOSS_IMPL_HPP
14 
15 // In case it hasn't yet been included.
16 #include "huber_loss.hpp"
17 
18 namespace mlpack {
19 namespace ann {
20 
21 template<typename InputDataType, typename OutputDataType>
23  const double delta,
24  const bool mean):
25  delta(delta),
26  mean(mean)
27 {
28  // Nothing to do here.
29 }
30 
31 template<typename InputDataType, typename OutputDataType>
32 template<typename PredictionType, typename TargetType>
33 typename PredictionType::elem_type
35  const PredictionType& prediction,
36  const TargetType& target)
37 {
38  typedef typename PredictionType::elem_type ElemType;
39  ElemType loss = 0;
40  for (size_t i = 0; i < prediction.n_elem; ++i)
41  {
42  const ElemType absError = std::abs(target[i] - prediction[i]);
43  loss += absError > delta ?
44  delta * (absError - 0.5 * delta) : 0.5 * std::pow(absError, 2);
45  }
46  return mean ? loss / prediction.n_elem : loss;
47 }
48 
49 template<typename InputDataType, typename OutputDataType>
50 template<typename PredictionType, typename TargetType, typename LossType>
52  const PredictionType& prediction,
53  const TargetType& target,
54  LossType& loss)
55 {
56  typedef typename PredictionType::elem_type ElemType;
57 
58  loss.set_size(size(prediction));
59  for (size_t i = 0; i < loss.n_elem; ++i)
60  {
61  const ElemType absError = std::abs(target[i] - prediction[i]);
62  loss[i] = absError > delta ?
63  -delta * (target[i] - prediction[i]) / absError :
64  prediction[i] - target[i];
65  if (mean)
66  loss[i] /= loss.n_elem;
67  }
68 }
69 
70 template<typename InputDataType, typename OutputDataType>
71 template<typename Archive>
73  Archive& ar,
74  const uint32_t /* version */)
75 {
76  ar(CEREAL_NVP(delta));
77  ar(CEREAL_NVP(mean));
78 }
79 
80 } // namespace ann
81 } // namespace mlpack
82 
83 #endif
Linear algebra utility functions, generally performed on matrices or vectors.
Definition: cv.hpp:1
void serialize(Archive &ar, const uint32_t)
Serialize the layer.
Definition: huber_loss_impl.hpp:72
HuberLoss(const double delta=1.0, const bool mean=true)
Create the HuberLoss object.
Definition: huber_loss_impl.hpp:22
void Backward(const PredictionType &prediction, const TargetType &target, LossType &loss)
Ordinary feed backward pass of a neural network.
Definition: huber_loss_impl.hpp:51
PredictionType::elem_type Forward(const PredictionType &prediction, const TargetType &target)
Computes the Huber Loss function.
Definition: huber_loss_impl.hpp:34