MachineIntelligenceCore:NeuralNets
 All Classes Namespaces Files Functions Variables Enumerations Enumerator Friends Macros
SquaredErrorLoss.hpp
Go to the documentation of this file.
1 
26 #ifndef SQUAREDLOSS_HPP_
27 #define SQUAREDLOSS_HPP_
28 
29 #include "loss/Loss.hpp"
30 
31 namespace mic {
32 namespace neural_nets {
33 namespace loss {
34 
40 template <typename dtype=float>
41 class SquaredErrorLoss : public Loss<dtype> {
42 public:
46  dtype calculateLoss (mic::types::MatrixPtr<dtype> target_y_, mic::types::MatrixPtr<dtype> predicted_y_) {
47  // Sizes must match.
48  assert(predicted_y_->size() == target_y_->size());
49 
50  // Calculate loss.
51  dtype loss =0;
52  for (size_t i=0; i <(size_t)predicted_y_->size(); i++) {
53  loss += ((*target_y_)[i] - (*predicted_y_)[i])*((*target_y_)[i] - (*predicted_y_)[i]);
54  }
55  // Return squared error (SE).
56  // The mean squared error (MSE) is calculated by dividing the SE by the size of a batch.
57  return loss/2.0;
58  }
59 
63  mic::types::MatrixPtr<dtype> calculateGradient (mic::types::MatrixPtr<dtype> target_y_, mic::types::MatrixPtr<dtype> predicted_y_) {
64  // Sizes must match.
65  assert(predicted_y_->size() == target_y_->size());
66 
67  // Calculate gradient.
68  mic::types::MatrixPtr<dtype> dy = MAKE_MATRIX_PTR(dtype, predicted_y_->rows(), predicted_y_->cols());
69  for (size_t i=0; i <(size_t)predicted_y_->size(); i++) {
70  (*dy)[i] = -((*target_y_)[i] - (*predicted_y_)[i]);
71  }
72 
73  /*std::cout << " predicted_y_ = " << (*predicted_y_) << std::endl;
74  std::cout << " target_y_ = " << (*target_y_) << std::endl;
75  std::cout << " dy = (p-t) = " << (*dy) << std::endl;*/
76 
77  return dy;
78  }
79 
80 };
81 
82 } //: loss
83 } //: neural_nets
84 } //: mic
85 
86 #endif /* SQUAREDLOSS_HPP_ */
mic::types::MatrixPtr< dtype > calculateGradient(mic::types::MatrixPtr< dtype > target_y_, mic::types::MatrixPtr< dtype > predicted_y_)
Function calculating gradient - for squared difference (regression).
Class representing a squared error loss function (regression). L = 1/2 sum (t - p)^2.
Abstract class representing a loss function. Defines interfaces.
Definition: Loss.hpp:41
dtype calculateLoss(mic::types::MatrixPtr< dtype > target_y_, mic::types::MatrixPtr< dtype > predicted_y_)
Function calculates squared difference loss (regression) and returns squared error (SE)...