How can I compute the tensor in Pytorch efficiently?


I have a tensor x and x.shape=(batch_size,10), now I want to take 

 x[i][0] = x[i][0]*x[i][1]*...*x[i][9] for i in range(batch_size)


Here is my code:

for i in range(batch_size):
    for k in range(1, 10):
        x[i][0] = x[i][0] * x[i][k]


But when I implement this in forward() and call loss.backward(), the speed of back-propagation is very slow. Why is it slow and is there any way to implement it efficiently?

It is slow because you use two for loops. 

You can use .prod See: https://pytorch.org/docs/stable/torch.html#torch.prod

In your case, 

x = torch.prod(x, dim=1) or x = x.prod(dim=1)

should work
