Caffe2 - C++ API
A deep learning, cross platform ML framework
summarize_op.cc
1 #include "caffe2/operators/summarize_op.h"
2 
3 namespace caffe2 {
4 
5 template <>
6 bool SummarizeOp<float, CPUContext>::RunOnDevice() {
7  auto& X = Input(0);
8  const auto N = X.size();
9  CAFFE_ENFORCE_GT(N, 0);
10 
11  const float* Xdata = X.data<float>();
12  double mean = 0;
13  float max = Xdata[0];
14  float min = Xdata[0];
15  for (auto i = 0; i < N; ++i) {
16  mean += static_cast<double>(Xdata[i]) / N;
17  max = std::max(max, Xdata[i]);
18  min = std::min(min, Xdata[i]);
19  }
20  // We will simply do a two-pass. More efficient solutions can be written but
21  // I'll keep code simple for now.
22  double standard_deviation = 0;
23  for (auto i = 0; i < N; ++i) {
24  double diff = Xdata[i] - mean;
25  standard_deviation += diff * diff;
26  }
27  // Unbiased or biased? Let's do unbiased now.
28  standard_deviation = N == 1 ? 0 : std::sqrt(standard_deviation / (N - 1));
29  if (to_file_) {
30  (*log_file_) << min << " " << max << " " << mean << " "
31  << standard_deviation << std::endl;
32  }
33  if (OutputSize()) {
34  auto* Y = Output(0);
35  Y->Resize(NUM_STATS);
36  float* Ydata = Y->mutable_data<float>();
37  Ydata[MIN_IDX] = min;
38  Ydata[MAX_IDX] = max;
39  Ydata[MEAN_IDX] = static_cast<float>(mean);
40  Ydata[STD_IDX] = static_cast<float>(standard_deviation);
41  }
42  return true;
43 }
44 
45 REGISTER_CPU_OPERATOR(Summarize, SummarizeOp<float, CPUContext>);
46 
47 // Input: X; output: if set, a summarized Tensor of shape 4, with the values
48 // being min, max, mean and std respectively.
49 OPERATOR_SCHEMA(Summarize)
50  .NumInputs(1)
51  .NumOutputs(0, 1)
52  .SetDoc(R"DOC(
53 Summarize computes four statistics of the input tensor (Tensor<float>)- min,
54 max, mean and standard deviation. The output will be written to a 1-D tensor of
55 size 4 if an output tensor is provided. Else, if the argument 'to_file' is
56 greater than 0, the values are written to a log file in the root folder.
57 )DOC")
58  .Arg(
59  "to_file",
60  "(int, default 0) flag to indicate if the summarized "
61  "statistics have to be written to a log file.")
62  .Input(0, "data", "The input data as Tensor<float>.")
63  .Output(
64  0,
65  "output",
66  "1-D tensor (Tensor<float>) of size 4 containing min, "
67  "max, mean and standard deviation");
68 
69 SHOULD_NOT_DO_GRADIENT(Summarize);
70 } // namespace caffe2
A global dictionary that holds information about what Caffe2 modules have been loaded in the current ...