C++ 从 Tensorflow::Tensor 对象访问 Eigen::Tensor Class 函数

C++ Accessing Eigen::Tensor Class function from Tensorflow::Tensor object

这可能是一个愚蠢的问题,但我很难从 tensorflow 中的自定义操作函数(void Compute)中访问 Eigen::Tensor class 函数。

Eigen::Tensor 有一个名为 "extract_patches" 的成员函数,我想从操作内部访问它。当我"typeid()"张量对象时,它returnstensorflow::Tensor。如何访问底层Eigen::Tensor?

请注意 "extract_patches" 的代码直接来自 Eigen 文档。

#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/util/padding.h"
#include "tensorflow/core/framework/numeric_op.h"
#include "tensorflow/core/util/tensor_format.h"
#include <vector>
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"

using namespace tensorflow;

class SauronOp : public OpKernel {
 public:
  explicit SauronOp(OpKernelConstruction* context) : OpKernel(context) {// Some checks}

  void Compute(OpKernelContext* context) override {

    //declare temporary storage 
    TensorShape a_shape_temp({act_in_batch, act_in_rows, act_in_cols });
    Tensor a_temp;
    OP_REQUIRES_OK(context, context->allocate_temp( DataTypeToEnum<float>::value,
                                        a_shape_temp,  &a_temp));
    //auto a_matrix = a_temp.shaped<float,3>({{act_in_batch, act_in_rows, act_in_cols });
    auto a_tensor = a_temp.tensor<float,3>();

    //unrelated stuff

    Eigen::Tensor<float, 4> patch;
    Eigen::array<ptrdiff_t, 3> patch_dims;
    patch_dims[0] = filter_height;
    patch_dims[1] = filter_width;
    patch_dims[2] = act_in_cols;

// THIS LINE GENERATES THIS PROBLEM (sorry for yelling)
    patch = a_tensor.extract_patches(patch_dims);

// output for debug
    std::cout<<"type "<< typeid(a_tensor).name()<<std::endl;
    std::cout<<"type "<< typeid(a_temp).name()<<std::endl;
  }

输出

type N5Eigen9TensorMapINS_6TensorIfLi3ELi1ElEELi16EEE
type N10tensorflow6TensorE

我怀疑问题是 extract_patches() returns 一个 Eigen::TensorPatchOp<...> (代表未评估的表达式)而不是 Eigen::Tensor<...> (代表评估的值)。要完成这项工作,您需要 (i) 在 .extract_patches() 的结果上调用 .eval(),以及 (ii) 将 patch 声明为行优先以获得所需类型的对象。

以下代码在 Compute() 方法中为我编译:

Tensor a_temp;
// Initialize `a_temp`...

const auto& a_tensor = a_temp.shaped<float, 3>(
    {act_in_batch, act_in_rows, act_in_cols});

Eigen::array<ptrdiff_t, 3> patch_dims;
patch_dims[0] = filter_height;
patch_dims[1] = filter_width;
patch_dims[2] = act_in_cols;

const auto& patch_expr = a_tensor.extract_patches(patch_dims);

Eigen::Tensor<float, 4, Eigen::RowMajor> patch = patch_expr.eval();