Caffe2 - C++ API
A deep learning, cross platform ML framework
perplexity_op.cc
1 
17 #include "caffe2/operators/perplexity_op.h"
18 
19 namespace caffe2 {
20 
21 template <>
22 bool PerplexityOp<float, CPUContext>::RunOnDevice() {
23  auto& X = Input(0);
24  auto* Y = Output(0);
25 
26  DCHECK_EQ(X.ndim(), 1);
27  int N = X.dim32(0);
28 
29  Y->Resize(vector<TIndex>());
30  const auto* Xdata = X.data<float>();
31 
32  float perplexity = 1.0;
33  for (int i = 0; i < N; ++i) {
34  perplexity *= pow(Xdata[i], -1.0/N);
35  }
36  *(Y->mutable_data<float>()) = perplexity;
37  return true;
38 }
39 
40 REGISTER_CPU_OPERATOR(Perplexity, PerplexityOp<float, CPUContext>);
41 
42 OPERATOR_SCHEMA(Perplexity).NumInputs(1).NumOutputs(1)
43 .SetDoc(R"DOC(
44 Perplexity calculates how well a probability distribution predicts a sample.
45 Perplexity takes a 1-D tensor containing a batch of probabilities. Each value
46 in the tensor belongs to a different sample and represents the probability of
47 the model predicting the true label for that sample. The operator returns a
48 single (float) perplexity value for the batch.
49 )DOC")
50 .Input(0, "probabilities", "The input data as Tensor. It contains a batch of"
51  "true label or target probabilities")
52 .Output(0, "output", "The output- a single (float) perplexity value for the "
53  "batch");
54 
55 SHOULD_NOT_DO_GRADIENT(Perplexity);
56 } // namespace caffe2
Copyright (c) 2016-present, Facebook, Inc.