【问题标题】:How do I do outer product of tensors in Eigen?如何在 Eigen 中做张量的外积?
【发布时间】:2016-11-27 14:13:54
【问题描述】:

在 eigen 中,可以很容易地使用以下方法进行张量收缩:

Tensor<double, 1> tensor1;
Tensor<double, 2> tensor2;

// fill with data so that
// tensor1 is of dimensions [10] and tensor2 of dimensions [5,10]

std::array<Eigen::IndexPair<int>, 1> product_dims1 = { IndexPair<int>(1, 0) };

auto tensor = tensor2.contract(tensor1, product_dims1);

// now tensor is of dimensions [5]

我正在寻找一种与收缩相反的方法,这意味着它需要两个张量 A 和 B,例如尺寸为 5 x 10 和 3 x 2,并定义一个尺寸为 5 x 10 x 3 x 2 的新张量 C这样

  C_ijkl = A_ij * B_kl

如有必要,我可以轻松编写这样的方法,但我觉得如果我使用本机特征方法会更加优化。我还希望能够使用 GPU 支持,如果您使用本机方法,这对于 eigen 来说非常容易。

谢谢。

【问题讨论】:

标签: c++ eigen


【解决方案1】:

解决方案可能过于简单:您必须在没有索引的情况下收缩

Eigen::array<Eigen::IndexPair<long>,0> empty_index_list = {};
Tensor<double, 2> A_ij(4, 4);
Tensor<double, 2> B_kl(4, 4);
Tensor<double, 4> C_ijkl = A_ij.contract(B_kl, empty_index_list);

【讨论】:

    【解决方案2】:

    您可以通过重塑输入张量来实现外积,用额外的一维维度填充维度,然后在新维度上广播。

    对于两个 rank-2 和一个 rank-4 张量,你有 C_ijkl = A_ij * B_kl 它看起来像:

    #include <Eigen/Core>
    #include <unsupported/Eigen/CXX11/Tensor>
    
    using namespace Eigen;
    
    int main() {
    
    Tensor<double, 2> A_ij(4, 4);
    Tensor<double, 2> B_kl(4, 4);
    Tensor<double, 4> C_ijkl(4, 4, 4, 4);
    
    Tensor<double, 4>::Dimensions A_pad(4, 4, 1, 1);
    array<int, 4> A_bcast(1, 1, 4, 4);
    
    Tensor<double, 4>::Dimensions B_pad(1, 1, 4, 4);
    array<int, 4> B_bcast(4, 4, 1, 1);
    
    C_ijkl = A_ij.reshape(A_pad).broadcast(A_bcast) * 
             B_kl.reshape(B_pad).broadcast(B_bcast);
    
    }
    

    【讨论】:

      猜你喜欢
      • 2019-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多