C++从张量流::张量对象访问Eigen::张量类函数

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

本文关键字:张量 Eigen 类函数 访问 对象 C++ 张量流      更新时间:2023-10-16

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

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