summaryrefslogtreecommitdiff
path: root/src/caffe/test/test_accuracy_layer.cpp
blob: 40b08748d1f2a0a697b3cef9f4cd01192cb96b69 (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
// Copyright 2014 BVLC and contributors.

#include <cmath>
#include <cstring>
#include <cfloat>
#include <vector>

#include "gtest/gtest.h"
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/filler.hpp"
#include "caffe/vision_layers.hpp"

#include "caffe/test/test_caffe_main.hpp"

namespace caffe {

template <typename Dtype>
class AccuracyLayerTest : public ::testing::Test {
 protected:
  AccuracyLayerTest()
      : blob_bottom_data_(new Blob<Dtype>(2, 10, 1, 1)),
        blob_bottom_label_(new Blob<Dtype>(2, 1, 1, 1)),
        blob_top_(new Blob<Dtype>()),
        top_k_(3) {
    // fill the probability values
    FillerParameter filler_param;
    GaussianFiller<Dtype> filler(filler_param);
    filler.Fill(this->blob_bottom_data_);

    // set the labels; first label is set to max-probability index
    Dtype m_val = -FLT_MAX;
    int m_id = 0;
    for (int i = 0; i < 10; i++)
      if (blob_bottom_data_->data_at(0, i, 0, 0) > m_val) {
        m_val = blob_bottom_data_->data_at(0, i, 0, 0);
        m_id = i;
      }
    Dtype* label_data = blob_bottom_label_->mutable_cpu_data();
    int offset = blob_bottom_label_->offset(0);
    label_data[offset] = m_id;

    // set the labels; second label is set to min-probability index
    m_val = FLT_MAX;
    m_id = 0;
    for (int i = 0; i < 10; i++)
      if (blob_bottom_data_->data_at(1, i, 0, 0) < m_val) {
        m_val = blob_bottom_data_->data_at(1, i, 0, 0);
        m_id = i;
      }
    offset = blob_bottom_label_->offset(1);
    label_data[offset] = m_id;

    blob_bottom_vec_.push_back(blob_bottom_data_);
    blob_bottom_vec_.push_back(blob_bottom_label_);
    blob_top_vec_.push_back(blob_top_);
  }
  virtual ~AccuracyLayerTest() {
    delete blob_bottom_data_;
    delete blob_bottom_label_;
    delete blob_top_;
  }
  Blob<Dtype>* const blob_bottom_data_;
  Blob<Dtype>* const blob_bottom_label_;
  Blob<Dtype>* const blob_top_;
  vector<Blob<Dtype>*> blob_bottom_vec_;
  vector<Blob<Dtype>*> blob_top_vec_;
  int top_k_;
};

TYPED_TEST_CASE(AccuracyLayerTest, TestDtypes);

TYPED_TEST(AccuracyLayerTest, TestForwardCPU) {
  LayerParameter layer_param;
  AccuracyParameter* accuracy_param = layer_param.mutable_accuracy_param();
  accuracy_param->set_top_k(this->top_k_);
  AccuracyLayer<TypeParam> layer(layer_param);
  layer.SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));
  layer.Forward(this->blob_bottom_vec_, &(this->blob_top_vec_));

  // Output accuracy should be ~0.5
  EXPECT_NEAR(this->blob_top_->data_at(0, 0, 0, 0), 0.5, 1e-4);
}

}  // namespace caffe