简体   繁体   English

如何将Eigen :: tensor广播到更高尺寸?

[英]How to broadcast Eigen::Tensor to higher dimensions?

I would like to broadcast an N-dimensional Eigen::Tensor to an (N+1)-dimensional Tensor to do some simple algebra. 我想将N维Eigen :: Tensor广播到(N + 1)维Tensor,以做一些简单的代数。 I cannot figure out the correct syntax. 我找不到正确的语法。

I have already tried broadcasting in-place, and assigning the result of the broadcast to a new tensor. 我已经尝试过就地广播,并将广播结果分配给新的张量。 Both fail to compile with substantial template error messages (compiling on Mac with Apple Clang 10.0.1). 两者均无法使用大量模板错误消息进行编译(在Mac上使用Apple Clang 10.0.1进行编译)。 I think the relevant problem is that the compiler cannot find a valid overload for .resize() . 我认为相关的问题是编译器无法为.resize()找到有效的重载。 I have tried the broadcasting operation with both std::array , Eigen::array , and `Eigen::Tensor::Dimensions for the type of the dimensions but none worked: 我已经尝试使用std::arrayEigen::array和`Eigen :: Tensor :: Dimensions的广播操作来获取尺寸类型,但是没有一个起作用:

    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;

Is this something Eigen::Tensor does not support? 这是Eigen :: Tensor不支持的东西吗?

Broadcast works in a slightly different way. 广播的工作方式略有不同。 It takes an argument specifying how many times the tensor should be repeated in each dimension. 它使用一个参数来指定张量在每个维度上应重复多少次。 This means both that the argument array length is equal to the tensor rank, and that the resulting tensor has the same rank as the original. 这意味着参数数组长度等于张量秩,并且所得张量具有与原始张数相同的秩。

However, this is close to what you had intended originally: just add a reshape! 但是,这与您原本的意图很接近:只需重新塑形!

For instance: 例如:

    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);

Should result in a 3 by 3 "matrix" containing 应该导致包含3 x 3的“矩阵”

1 2 3
1 2 3
1 2 3

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

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