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