我如何在特征中进行张量的外产物

How do I do outer product of tensors in Eigen?

本文关键字:张量 特征      更新时间:2023-10-16

在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]

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

  C_ijkl = A_ij * B_kl

,我可以在必要时轻松地编写这样的方法,但是我可以感觉到,如果我使用本机eigen方法会更加优化。我也希望能够使用GPU支持,如果您使用本机方法,那么对于特征,它很容易。

谢谢。

解决方案也许太简单了:您必须

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和一个等级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);
}