Eigen::Tensor实现permute方法

发布时间 2023-07-14 16:06:53作者: azureology

需求

使用C++处理Eigen::Tensor希望交换指定维度的位置
注意是交换(改变内存顺序)而不是reshape

实现

torch.tensor中内置了permute方法实现快速交换
Eigen::Tensor中实现相同操作需要一点技巧
例如,将一个1x2x3的tensor排列为3x1x2
那么对应t1[0,1,1] == t2[1,0,1]则排列生效
代码如下:

#include <iostream>
#include <unsupported/Eigen/CXX11/Tensor>

template <size_t... dims>
using TensorXf = Eigen::TensorFixedSize<float, Eigen::Sizes<dims...>, Eigen::RowMajor>;

int main()
{
    TensorXf<1,2,3> t1;
    t1.setValues(
    {
        {
            {1, 2, 3},
            {4, 5, 6}
        }
    });
    // permute the tensor
    TensorXf<3,1,2> t2;
    Eigen::array<int, 3> view({2, 0, 1});
    t2 = t1.shuffle(view);

    std::cout << t1(0,1,1) << std::endl;
    std::cout << t2(1,0,1) << std::endl;
}
// output:
// 5
// 5

在线运行Compiler Explorer
注:以上TensorFixedSize模板仅为项目加速使用,非强制。

参考

Eigen-unsupported: Eigen Tensors