Skip to content Skip to sidebar Skip to footer

Tensor Reduction Based Off Index Vector

As an example, I have 2 tensors: A = [1;2;3;4;5;6;7] and B = [2;3;2]. The idea is that I want to reduce A based off B - such that B's values represent how to sum A's values- such t

Solution 1:

Here is the solution.

  • First, we create an array of indices B_idx with the same size of A.
  • Then, accumulate (add) all elements in A based on the indices B_idx using index_add_.
A = torch.arange(1, 8) 
B = torch.tensor([2, 3, 2])

B_idx = [idx.repeat(times) for idx, times in zip(torch.arange(len(B)), B)]
B_idx = torch.cat(B_idx) # tensor([0, 0, 1, 1, 1, 2, 2])

A_sum = torch.zeros_like(B)
A_sum.index_add_(dim=0, index=B_idx, source=A)
print(A_sum) # tensor([ 3, 12, 13])

Post a Comment for "Tensor Reduction Based Off Index Vector"