简体   繁体   English

如何在 Eigen3 中重塑张量?

[英]How to reshape a tensor in Eigen3?

I get some Eigen::TensorMap from the outputs vector from a tensorflow session in C++.我从 C++ 中的 tensorflow 会话的输出向量中得到了一些 Eigen::TensorMap。 I want to do some operations to the Eigen::TensorMap (reshape and concat etc.).我想对 Eigen::TensorMap (重塑和连接等)进行一些操作。

However, my codes cannot be compiled due to some weird error.但是,由于一些奇怪的错误,我的代码无法编译。 I tried to reproduce it in pure Eigen3 code.我试图用纯 Eigen3 代码重现它。

#include <unsupported/Eigen/CXX11/Tensor>
using Eigen::Tensor;
using Eigen::TensorMap;
using Eigen::TensorRef;
using std::vector;
int main() {
    int storage[128];
    TensorMap<Tensor<int, 4>> t_4d(storage, 2, 4, 2, 8);
    vector<TensorRef<Tensor<int,2>>> reshapedTensors;
    std::array<int, 2> shape{ 16,8 };
    auto re_op = t_4d.reshape(shape);
    reshapedTensors.push_back(re_op);
    return 0;
}

According to the Eigen Doc , the return type of reshape function is an eigen operation, it will be caculate lazily.根据Eigen Doc ,reshape 函数的返回类型是一个 eigen 操作,它将被延迟计算。 The TensorRef is the wrapper of all tensor operations. TensorRef 是所有张量操作的包装器。

This piece of codes will complain that:这段代码会抱怨:

Severity Code Description Project File Line Suppression State Error C2679 binary '=': no operator found which takes a right-hand operand of type 'const std::array' (or there is no acceptable conversion) testEigen D:\\Programming\\cpp library\\eigen-eigen-323c052e1731\\unsupported\\Eigen\\CXX11\\src\\Tensor\\TensorRef.h 49严重性代码描述项目文件行抑制状态错误 C2679 二进制“=”:未找到采用“const std::array”类型的右侧操作数的运算符(或没有可接受的转换) testEigen D:\\Programming\\cpp library \\eigen-eigen-323c052e1731\\unsupported\\Eigen\\CXX11\\src\\Tensor\\TensorRef.h 49

You can't mix different IndexType for Tensor operations (that is the implicit 4th template parameter of Tensor ).你可以混用不同IndexType张量操作(即隐含的第4个模板参数Tensor )。 This also means the type of the std::array must match the IndexType .这也意味着std::array的类型必须与IndexType匹配。 By default, Eigen::Tensor uses Eigen::DenseIndex which is the same as Eigen::Index .默认情况下, Eigen::Tensor使用与Eigen::Index相同的Eigen::DenseIndex You can either write this instead of Eigen::Tensor<int,4> (similar for Tensor<int,2> )你可以写这个而不是Eigen::Tensor<int,4> (类似于Tensor<int,2>

Eigen::Tensor<int, 4, 0, int>

or you replace std::array<int, 2> by std::array<Eigen::Index, 2> .或者你用std::array<int, 2> std::array<Eigen::Index, 2>替换std::array<int, 2> std::array<Eigen::Index, 2> Of course making typedef s for both will safe you some typing and will simplify refactoring, if you ever need to do that.当然,为两者制作typedef为您提供一些打字的安全,并且可以简化重构,如果您需要这样做的话。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM