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.numel();
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, {NUM_STATS}, at::dtype<float>());
35  float* Ydata = Y->template mutable_data<float>();
36  Ydata[MIN_IDX] = min;
37  Ydata[MAX_IDX] = max;
38  Ydata[MEAN_IDX] = static_cast<float>(mean);
39  Ydata[STD_IDX] = static_cast<float>(standard_deviation);
40  }
41  return true;
42 }
43 
44 REGISTER_CPU_OPERATOR(Summarize, SummarizeOp<float, CPUContext>);
45 
46 // Input: X; output: if set, a summarized Tensor of shape 4, with the values
47 // being min, max, mean and std respectively.
48 OPERATOR_SCHEMA(Summarize)
49  .NumInputs(1)
50  .NumOutputs(0, 1)
51  .SetDoc(R"DOC(
52 Summarize computes four statistics of the input tensor (Tensor)- min,
53 max, mean and standard deviation. The output will be written to a 1-D tensor of
54 size 4 if an output tensor is provided. Else, if the argument 'to_file' is
55 greater than 0, the values are written to a log file in the root folder.
56 )DOC")
57  .Arg(
58  "to_file",
59  "(int, default 0) flag to indicate if the summarized "
60  "statistics have to be written to a log file.")
61  .Input(0, "data", "The input data as Tensor.")
62  .Output(
63  0,
64  "output",
65  "1-D tensor (Tensor) of size 4 containing min, "
66  "max, mean and standard deviation");
67 
68 SHOULD_NOT_DO_GRADIENT(Summarize);
69 } // namespace caffe2
A global dictionary that holds information about what Caffe2 modules have been loaded in the current ...
Definition: blob.h:13