且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Eigen中生成张量的外积?

更新时间:2023-11-26 13:40:10

解决方案可能太简单了:您必须在没有索引的情况下进行合约



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


In eigen, one can do quite easily tensor contractions using:

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]

I am looking for a method that does the opposite of contraction, meaning it takes two tensors A and B, say of dimensions 5 x 10 and 3 x 2 and defines a new tensor C of dimensions 5 x 10 x 3 x 2 such that

  C_ijkl = A_ij * B_kl

I could easily write such a method if necessary, but I get the sense it would be more optimized if I used a native eigen method. I also want to be able to use GPU support which is quite easy with eigen if you use the native methods.

Thanks.

The solution is perhaps too simple: You have to contract over no indices.

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