首页 > 解决方案 > 如何将 Eigen::Tensor 广播到更高维度?

问题描述

我想将 N 维 Eigen::Tensor 广播到 (N+1) 维张量来做一些简单的代数。我无法弄清楚正确的语法。

我已经尝试过就地广播,并将广播的结果分配给一个新的张量。两者都无法通过大量模板错误消息进行编译(在 Mac 上使用 Apple Clang 10.0.1 进行编译)。我认为相关的问题是编译器无法为.resize(). 我已经尝试使用 , 和 `Eigen::Tensor::Dimensions 进行广播操作以std::array获取Eigen::array维度类型,但没有一个有效:

    srand(time(0));
    Eigen::Tensor<float, 3> t3(3, 4, 5);
    Eigen::Tensor<float, 2> t2(3, 4);
    t3.setRandom();
    t2.setRandom();
    // In-place operation
    t3 /= t2.broadcast(std::array<long, 3>{1, 1, 5}); // Does not compile
    // With temporary
    Eigen::Tensor<float, 3> t2b = t2.broadcast(Eigen::array<long, 3>{1, 1, 5}); // Does not compile either
    t3 /= t2b;

这是 Eigen::Tensor 不支持的东西吗?

标签: c++eigentensor

解决方案


广播的工作方式略有不同。它需要一个参数来指定张量在每个维度上应该重复多少次。这意味着参数数组长度等于张量等级,并且结果张量与原始张量具有相同的等级。

但是,这与您最初的意图很接近:只需添加一个重塑!

例如:

    Eigen::Tensor<float, 1> t1(3);
    t1 << 1,2,3;
    auto copies  = std::array<long,1> {3};
    auto shape   = std::array<long,2> {3,3};
    Eigen::Tensor<float,2> t2 = t1.broadcast(copies).reshape(shape);

应该产生一个 3 x 3 的“矩阵”,其中包含

1 2 3
1 2 3
1 2 3

推荐阅读