From 90b0eb085251ab75ed668972b9750160c32e93f0 Mon Sep 17 00:00:00 2001 From: Yangqing Jia Date: Fri, 27 Sep 2013 09:54:10 -0700 Subject: [PATCH] forgot to add the renamed file --- .../layers/multinomial_logistic_loss_layer.cu | 52 ++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 src/caffe/layers/multinomial_logistic_loss_layer.cu diff --git a/src/caffe/layers/multinomial_logistic_loss_layer.cu b/src/caffe/layers/multinomial_logistic_loss_layer.cu new file mode 100644 index 0000000..5ffa4ac --- /dev/null +++ b/src/caffe/layers/multinomial_logistic_loss_layer.cu @@ -0,0 +1,52 @@ +// Copyright 2013 Yangqing Jia + +#include "caffe/layer.hpp" +#include "caffe/vision_layers.hpp" +#include "caffe/util/math_functions.hpp" +#include +#include + +using std::max; + +namespace caffe { + +template +void MultinomialLogisticLossLayer::SetUp( + const vector*>& bottom, vector*>* top) { + CHECK_EQ(bottom.size(), 2) << "Loss Layer takes two blobs as input."; + CHECK_EQ(top->size(), 0) << "Loss Layer takes no as output."; + CHECK_EQ(bottom[0]->num(), bottom[1]->num()) + << "The data and label should have the same number."; + CHECK_EQ(bottom[1]->channels(), 1); + CHECK_EQ(bottom[1]->height(), 1); + CHECK_EQ(bottom[1]->width(), 1); +}; + + +template +Dtype MultinomialLogisticLossLayer::Backward_cpu(const vector*>& top, + const bool propagate_down, + vector*>* bottom) { + const Dtype* bottom_data = (*bottom)[0]->cpu_data(); + const Dtype* bottom_label = (*bottom)[1]->cpu_data(); + Dtype* bottom_diff = (*bottom)[0]->mutable_cpu_diff(); + int num = (*bottom)[0]->num(); + int dim = (*bottom)[0]->count() / (*bottom)[0]->num(); + memset(bottom_diff, 0, sizeof(Dtype) * (*bottom)[0]->count()); + Dtype loss = 0; + const Dtype kLOG_THRESHOLD = 1e-8; + for (int i = 0; i < num; ++i) { + int label = static_cast(bottom_label[i]); + Dtype prob = max(bottom_data[i * dim + label], kLOG_THRESHOLD); + loss -= log(prob); + bottom_diff[i * dim + label] = - 1. / prob / num; + } + return loss / num; +} + +// TODO: implement the GPU version + +INSTANTIATE_CLASS(MultinomialLogisticLossLayer); + + +} // namespace caffe -- 2.7.4