1 #include "caffe2/operators/multi_class_accuracy_op.h" 6 bool MultiClassAccuracyOp<float, CPUContext>::RunOnDevice() {
7 auto& X = Input(PREDICTION);
8 auto& label = Input(LABEL);
10 DCHECK_EQ(X.dim(), 2);
15 DCHECK_EQ(label.dim(), 1);
16 DCHECK_EQ(label.dim32(0), N);
17 auto* Y0 = Output(0, {D}, at::dtype<float>());
18 auto* Y1 = Output(1, {D}, at::dtype<int>());
20 const auto* Xdata = X.data<
float>();
21 const auto* labeldata = label.data<
int>();
22 auto* accuracies = Y0->template mutable_data<float>();
23 auto* amounts = Y1->template mutable_data<int>();
24 std::fill(accuracies, accuracies + D, 0);
25 std::fill(amounts, amounts + D, 0);
27 for (
int i = 0; i < N; ++i) {
28 float maxval = std::numeric_limits<float>::lowest();
30 for (
int j = 0; j < D; ++j) {
31 if (Xdata[i * D + j] > maxval) {
32 maxval = Xdata[i * D + j];
36 int labelid = labeldata[i];
37 DCHECK_LT(labelid, D);
38 if (maxid == labelid) {
39 accuracies[labelid]++;
44 for (
int i = 0; i < D; ++i) {
45 int amount = amounts[i];
47 accuracies[i] /= amount;
54 REGISTER_CPU_OPERATOR(
55 MultiClassAccuracy, MultiClassAccuracyOp<float, CPUContext>);
57 OPERATOR_SCHEMA(MultiClassAccuracy)
61 Respectively compute accuracy score for each class given a number of instances 62 and predicted scores of each class for each instance. 67 "2-D float tensor (N,D,) of predicted scores of each class for " 68 "each data. N is the number of instances, i.e., batch size. D is number of " 69 "possible classes/labels.")
73 "1-D int tensor (N,) of labels for each instance.")
77 "1-D float tensor (D,) of accuracy for each class. If a class has no " 78 "instance in the batch, its accuracy score is set to zero.")
82 "1-D int tensor (D,) of number of instances for each class in the batch.");
84 SHOULD_NOT_DO_GRADIENT(MultiClassAccuracy);
A global dictionary that holds information about what Caffe2 modules have been loaded in the current ...