Reputation: 4117
For example, I have a tensor A(2,3,4) and tensor B(3,4) and want to make koefs multiplication(not Contraction operation) of A along dimension 0( batch dimension) with B. How to do this without for loop?
Upvotes: 0
Views: 1105
Reputation: 4655
If I understand your question, you could first reshape B to (1,3,4) and then use broadcasting to replicate the values along axis 0. Don't know if this is very efficient, but it works.
auto A = Tensor<float, 3>(2, 3, 4);
A.setValues({
{
{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
},{
{ 10,20,30,40 },
{ 50,60,70,80 },
{ 90,100,110,120 },
}
});
auto W = Tensor<float, 2>(3,4);
W.setValues({
{ 1,2,3,4 },
{ 5,6,7,8 },
{ 9,10,11,12 }
});
auto three_dims = Eigen::array<int, 3>({ 1,3,4 });
auto bcast = Eigen::array<int, 3>({ 2,1,1 });
auto X = W.reshape(three_dims).broadcast(bcast);
auto Y = A*X;
std::cout << Y << std::endl;
Prints:
1 25 81 4 36 100 9 49 121 16 64 144
10 250 810 40 360 1000 90 490 1210 160 640 1440
Upvotes: 2