MachineIntelligenceCore:NeuralNets
 All Classes Namespaces Files Functions Variables Enumerations Enumerator Friends Macros
LogLikelihoodLoss.hpp
Go to the documentation of this file.
1 
25 #ifndef LOGLIKELIHOODLOSS_HPP_
26 #define LOGLIKELIHOODLOSS_HPP_
27 
28 
29 
30 
31 
32 
33 #include <cmath>
34 #include <loss/Loss.hpp>
35 
36 namespace mic {
37 namespace neural_nets {
38 namespace loss {
39 
45 template <typename dtype=float>
46 class LogLikelihoodLoss : public Loss<dtype> {
47 public:
51  dtype calculateLoss (mic::types::MatrixPtr<dtype> target_y_, mic::types::MatrixPtr<dtype> predicted_y_) {
52  // Sizes must match.
53  assert(predicted_y_->size() == target_y_->size());
54 
55  size_t ind;
56  // Calculate loss.
57  dtype loss =0;
58  // For each column (sample from batch).
59  for (size_t i=0; i <(size_t)predicted_y_->cols(); i++) {
60  // Get index of max coefficient in given column.
61  target_y_.col(i).maxCoeff(ind);
62 
63  // Add loss.
64  loss -= std::log((*predicted_y_)[ind]);
65  }//: for
66  // Return sum of log-likelihood cost.
67  return loss;
68  // Divide it by the batch size in order to calculate the mean loss.
69  }
70 
74  mic::types::MatrixPtr<dtype> calculateGradient (mic::types::MatrixPtr<dtype> target_y_, mic::types::MatrixPtr<dtype> predicted_y_) {
75  // Sizes must match.
76  assert(predicted_y_->size() == target_y_->size());
77 
78  // Calculate gradient.
79  mic::types::MatrixPtr<dtype> dy = MAKE_MATRIX_PTR(dtype, predicted_y_->rows(), predicted_y_->cols());
80  for (size_t i=0; i <(size_t)predicted_y_->size(); i++) {
81  (*dy)[i] = 0.0;
82  }
83  return dy;
84  }
85 
86 };
87 
88 } //: loss
89 } //: neural_nets
90 } //: mic
91 
92 #endif /* LOGLIKELIHOODLOSS_HPP_ */
mic::types::MatrixPtr< dtype > calculateGradient(mic::types::MatrixPtr< dtype > target_y_, mic::types::MatrixPtr< dtype > predicted_y_)
Gradient calculation for log-likelihood cost. NOT FINISHED!!
dtype calculateLoss(mic::types::MatrixPtr< dtype > target_y_, mic::types::MatrixPtr< dtype > predicted_y_)
Calculates log-likelihood cost.
Abstract class representing a loss function. Defines interfaces.
Definition: Loss.hpp:41
Class representing a log-likelihood cost (to be used with softmax logistic regression).