Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transpose Tensor in Eigen

Tags:

eigen

I'm trying to get matrix product of two tensors, where one of the tensor should be transposed before it multiplied (At*B).

So far what I've found in eigen documentation is matrix product without any transposed and with both matrix transposed.

I'm looking for a way to either directly contracting two tensor with one of the tensor is transposed, or either by transposing one tensor before contracting it.

like image 210
Fs02 Avatar asked Oct 24 '25 13:10

Fs02


2 Answers

I figured it out, transpose effect can be done using shuffle method.

Eigen::Tensor<int, 2> m(3, 5);
m.setValues(
{
    {1, 2, 3, 4, 5},
    {6, 7, 8, 9, 10},
    {11, 12, 13, 14, 15}
});

Eigen::array<int, 2> shuffling({1, 0});

Eigen::Tensor<int, 2> transposed = m.shuffle(shuffling);
Eigen::Tensor<int, 2> original = transposed.shuffle(shuffling);
like image 56
Fs02 Avatar answered Oct 26 '25 08:10

Fs02


You can also use the contraction directly:

Eigen::Tensor<int, 2> A(3, 5);
Eigen::Tensor<int, 2> B(3, 5);
Eigen::array<int, 1> contraction_indices;
// This will contract the first dimension of A with the first dim of B,
// effectively computing At*B
contraction_indices[0] = {0, 0};
Eigen::Tensor<int, 2> Result = A.contract(B, contraction_indices);
like image 21
Benoit Steiner Avatar answered Oct 26 '25 08:10

Benoit Steiner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!