Home | History | Annotate | Download | only in kernels
      1 /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
      2 
      3 Licensed under the Apache License, Version 2.0 (the "License");
      4 you may not use this file except in compliance with the License.
      5 You may obtain a copy of the License at
      6 
      7     http://www.apache.org/licenses/LICENSE-2.0
      8 
      9 Unless required by applicable law or agreed to in writing, software
     10 distributed under the License is distributed on an "AS IS" BASIS,
     11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     12 See the License for the specific language governing permissions and
     13 limitations under the License.
     14 ==============================================================================*/
     15 
     16 // See docs in ../ops/nn_ops.cc.
     17 
     18 #define EIGEN_USE_THREADS
     19 
     20 #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
     21 #include "tensorflow/core/framework/op_kernel.h"
     22 #include "tensorflow/core/framework/tensor.h"
     23 #include "tensorflow/core/framework/tensor_shape.h"
     24 #include "tensorflow/core/kernels/bounds_check.h"
     25 
     26 namespace tensorflow {
     27 
     28 template <typename T, typename TARGET_T>
     29 class InTopK : public OpKernel {
     30  public:
     31   explicit InTopK(OpKernelConstruction* context) : OpKernel(context) {
     32     if (context->num_inputs() == 2) {
     33       OP_REQUIRES_OK(context, context->GetAttr("k", &k_));
     34     }
     35   }
     36 
     37   void Compute(OpKernelContext* context) override {
     38     const auto& predictions_in = context->input(0);
     39     const auto& targets_in = context->input(1);
     40     int64 k_val = k_;
     41     if (context->num_inputs() == 3) {
     42       const auto& k_in = context->input(2);
     43 
     44       OP_REQUIRES(context, TensorShapeUtils::IsScalar(k_in.shape()),
     45                   errors::InvalidArgument("k must be 0-D, got shape ",
     46                                           k_in.shape().DebugString()));
     47 
     48       if (k_in.dtype() == DT_INT32) {
     49         k_val = k_in.scalar<int32>()();
     50       } else {
     51         k_val = k_in.scalar<int64>()();
     52       }
     53     }
     54 
     55     OP_REQUIRES(context, predictions_in.dims() == 2,
     56                 errors::InvalidArgument("predictions must be 2-dimensional"));
     57     OP_REQUIRES(context, targets_in.dims() == 1,
     58                 errors::InvalidArgument("targets must be 1-dimensional"));
     59     OP_REQUIRES(context, predictions_in.dim_size(0) == targets_in.dim_size(0),
     60                 errors::InvalidArgument("First dimension of predictions ",
     61                                         predictions_in.dim_size(0),
     62                                         " must match length of targets ",
     63                                         targets_in.dim_size(0)));
     64     const auto& predictions = predictions_in.matrix<T>();
     65     const auto& targets = targets_in.vec<TARGET_T>();
     66 
     67     Tensor* t_out = nullptr;
     68     OP_REQUIRES_OK(context,
     69                    context->allocate_output(
     70                        0, TensorShape({targets_in.dim_size(0)}), &t_out));
     71     auto out = t_out->vec<bool>();
     72 
     73     const auto size = targets.size();
     74     const auto num_classes = predictions.dimension(1);
     75     for (int b = 0; b < size; b++) {
     76       auto target = internal::SubtleMustCopy(targets(b));
     77       OP_REQUIRES(context, FastBoundsCheck(target, num_classes),
     78                   errors::InvalidArgument("targets[", b, "] is out of range"));
     79       T target_prediction = predictions(b, target);
     80       bool cannot_say = !std::isfinite(target_prediction);
     81       int more_probable_classes = 0;
     82       if (!cannot_say) {
     83         for (int i = 0; i < num_classes; ++i) {
     84           T pred = predictions(b, i);
     85           if (!std::isfinite(pred)) {
     86             cannot_say = true;
     87             break;
     88           } else if (pred > target_prediction) {
     89             ++more_probable_classes;
     90           }
     91         }
     92       }
     93       out(b) = cannot_say ? false : (more_probable_classes < k_val);
     94     }
     95   }
     96 
     97  private:
     98   int k_;
     99 };
    100 
    101 REGISTER_KERNEL_BUILDER(Name("InTopK")
    102                             .Device(DEVICE_CPU)
    103                             .HostMemory("predictions")
    104                             .HostMemory("targets")
    105                             .HostMemory("precision")
    106                             .TypeConstraint<int32>("T"),
    107                         InTopK<float, int32>);
    108 REGISTER_KERNEL_BUILDER(Name("InTopK")
    109                             .Device(DEVICE_CPU)
    110                             .HostMemory("predictions")
    111                             .HostMemory("targets")
    112                             .HostMemory("precision")
    113                             .TypeConstraint<int64>("T"),
    114                         InTopK<float, int64>);
    115 
    116 REGISTER_KERNEL_BUILDER(Name("InTopKV2")
    117                             .Device(DEVICE_CPU)
    118                             .HostMemory("predictions")
    119                             .HostMemory("targets")
    120                             .HostMemory("k")
    121                             .HostMemory("precision")
    122                             .TypeConstraint<int32>("T"),
    123                         InTopK<float, int32>);
    124 REGISTER_KERNEL_BUILDER(Name("InTopKV2")
    125                             .Device(DEVICE_CPU)
    126                             .HostMemory("predictions")
    127                             .HostMemory("targets")
    128                             .HostMemory("k")
    129                             .HostMemory("precision")
    130                             .TypeConstraint<int64>("T"),
    131                         InTopK<float, int64>);
    132 
    133 }  // namespace tensorflow
    134