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

时间:2016-05-31 14:46:03

标签: c++ tensorflow eigen

这可能是一个愚蠢的问题,但我在张量流中的自定义op函数(void Compute)中访问Eigen :: Tensor类函数时遇到了困难。

Eigen :: Tensor有一个名为" extract_patches"的成员函数。我想从操作系统内部访问。当我" typeid()"张量对象,它返回tensorflow :: 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

1 个答案:

答案 0 :(得分:0)

我怀疑问题是extract_patches()返回Eigen::TensorPatchOp<...>(表示未评估的表达式)而不是Eigen::Tensor<...>(表示评估值)。要完成这项工作,您需要(i)对.eval()的结果调用.extract_patches(),以及(ii)将patch声明为row-major以获取所需类型的对象。

以下代码以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();