如何在 Eigen3 中重塑张量? [英] How to reshape a tensor in Eigen3?

查看:66
本文介绍了如何在 Eigen3 中重塑张量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从 C++ 中的 tensorflow 会话的输出向量中得到了一些 Eigen::TensorMap.我想对 Eigen::TensorMap 做一些操作(reshape 和 concat 等).

I get some Eigen::TensorMap from the outputs vector from a tensorflow session in C++. I want to do some operations to the Eigen::TensorMap (reshape and concat etc.).

但是,由于一些奇怪的错误,我的代码无法编译.我试图用纯 Eigen3 代码重现它.

However, my codes cannot be compiled due to some weird error. I tried to reproduce it in pure Eigen3 code.

#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;
}

根据Eigen Doc,reshape函数的返回类型是一个特征操作,它会被懒惰地计算.TensorRef 是所有张量操作的包装器.

According to the Eigen Doc, the return type of reshape function is an eigen operation, it will be caculate lazily. The TensorRef is the wrapper of all tensor operations.

这段代码会抱怨:

严重性代码描述项目文件行抑制状态错误 C2679 二进制=":未找到采用const std::array"类型的右侧操作数的运算符(或没有可接受的转换) testEigen D:\Programming\cpp library\eigen-eigen-323c052e1731\unsupported\Eigen\CXX11\src\Tensor\TensorRef.h 49

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

推荐答案

你不能混合不同的 IndexType 进行 Tensor 操作(也就是 Tensor).这也意味着 std::array 的类型必须与 IndexType 匹配.默认情况下,Eigen::Tensor 使用与 Eigen::Index 相同的 Eigen::DenseIndex.你可以用它来代替 Eigen::Tensor(类似于 Tensor)

You can't mix different IndexType for Tensor operations (that is the implicit 4th template parameter of Tensor). This also means the type of the std::array must match the IndexType. By default, Eigen::Tensor uses Eigen::DenseIndex which is the same as Eigen::Index. You can either write this instead of Eigen::Tensor<int,4> (similar for Tensor<int,2>)

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

或者您将 std::array 替换为 std::array.当然,为两者制作 typedef 可以为您提供一些打字的安全,并且如果您需要这样做,将简化重构.

or you replace std::array<int, 2> by std::array<Eigen::Index, 2>. Of course making typedefs for both will safe you some typing and will simplify refactoring, if you ever need to do that.

这篇关于如何在 Eigen3 中重塑张量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆