edit_distance_op.h 2.3 KB
Newer Older
Y
Yibing Liu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License. */

#pragma once
#include <algorithm>
#include "paddle/framework/eigen.h"
#include "paddle/framework/op_registry.h"

namespace paddle {
namespace operators {

template <typename Place, typename T>
24
class EditDistanceKernel : public framework::OpKernel<T> {
Y
Yibing Liu 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37
 public:
  void Compute(const framework::ExecutionContext& ctx) const {
    auto* out_t = ctx.Output<framework::Tensor>("Out");

    auto* x1_t = ctx.Input<framework::Tensor>("X1");
    auto* x2_t = ctx.Input<framework::Tensor>("X2");

    out_t->mutable_data<float>(ctx.GetPlace());

    auto normalized = ctx.Attr<bool>("normalized");

    auto m = x1_t->numel();
    auto n = x2_t->numel();
Y
Yibing Liu 已提交
38
    T distance = 0.0;
Y
Yibing Liu 已提交
39 40 41 42 43 44 45 46 47
    if (m == 0) {
      distance = n;
    } else if (n == 0) {
      distance = m;
    } else {
      framework::Tensor dist_t;
      dist_t.Resize({m + 1, n + 1});
      dist_t.mutable_data<T>(ctx.GetPlace());
      auto dist = dist_t.data<T>();
Y
Yibing Liu 已提交
48 49 50
      auto x1 = x1_t->data<int>();
      auto x2 = x2_t->data<int>();
      for (int64_t i = 0; i < m + 1; ++i) {
51
        dist[i * (n + 1)] = i;
Y
Yibing Liu 已提交
52
      }
Y
Yibing Liu 已提交
53
      for (int64_t j = 0; j < n + 1; ++j) {
54
        dist[j] = j;
Y
Yibing Liu 已提交
55
      }
Y
Yibing Liu 已提交
56 57
      for (int64_t i = 1; i < m + 1; ++i) {
        for (int64_t j = 1; j < n + 1; ++j) {
Y
Yibing Liu 已提交
58
          int cost = x1[i - 1] == x2[j - 1] ? 0 : 1;
59 60 61 62
          int dels = dist[(i - 1) * (n + 1) + j] + 1;
          int ins = dist[i * (n + 1) + (j - 1)] + 1;
          int subs = dist[(i - 1) * (n + 1) + (j - 1)] + cost;
          dist[i * (n + 1) + j] = std::min(dels, std::min(ins, subs));
Y
Yibing Liu 已提交
63 64 65 66 67 68 69 70
        }
      }
      distance = dist[m * (n + 1) + n];
    }

    if (normalized) {
      distance = distance / n;
    }
Y
Yibing Liu 已提交
71
    auto out = out_t->data<T>();
Y
Yibing Liu 已提交
72 73 74 75 76 77
    out[0] = distance;
  }
};

}  // namespace operators
}  // namespace paddle