1

I would like to get this result with torch functions. Do you have suggestions?

import torch
test_tensor=torch.tensor([[1,  2,  3, 4,  5,  6],
                         [7,  8,  9, 10,  11,  12]]
                        )
print(test_tensor)
'''
I would like to get:
t_1 = torch.tensor([[6], #1+2+3
                  [24]])#7+8+9
t_2 = torch.tensor([[9], #1+3+5
                  [27]])#7+9+11
'''
trsvchn
  • 8,033
  • 3
  • 23
  • 30
mark
  • 99
  • 7

1 Answers1

3

Using standard Python stride notation

import torch
test_tensor=torch.tensor([[1,  2,  3, 4,  5,  6],
                         [7,  8,  9, 10,  11,  12]]
                        )

t1 = test_tensor[:, :3].sum(dim=1)
print(t1)
t2 = test_tensor[:, ::2].sum(dim=1)
print(t2)
Gulzar
  • 23,452
  • 27
  • 113
  • 201
  • Thank you @Gulzar Is there any similar way to get t_3 = torch.tensor([[14], #1+2+5+6 [38]])#7+8+11+12 ?- the pattern is: sum two elements and skip two elements to the end of tensor row – mark May 22 '21 at 13:19
  • see [this](https://stackoverflow.com/questions/67650289/torch-equivalent-of-numpy-r), maybe it will be answered. Until then, try using masks: `mask = torch.ones_like(t, dtype=torch.bool)`, `mask[:, 2:4]=0`, `t3_temp=torch.tensor(t)`, `t3_temp[mask]=t[mask]`, `t3=t3_temp.sum(dim=1)` – Gulzar May 22 '21 at 13:57
  • @mark [also see here](https://stackoverflow.com/questions/38193958/how-to-properly-mask-a-numpy-2d-array) – Gulzar May 22 '21 at 14:02