IndexError: Can only index with tensors that are scalars(zero-dim)

How to use the tensor index in CPP?

In pytorch, we can in this way.

import torch

data = torch.tensor([1, 2, 3, 4, 5, 6])

index = torch.tensor([0, 2, 4])

result = data[index] 

We can get result’s value

>>> tensor([1, 3, 5])

But how to use in cpp?

torch::Tensor data;  // just a demo  

torch::Tensor index;  // just a demo

torch::Tensor result = data[index];  // IndexError: Can only index with tensors that are scalars(zero-dim)

please help me, thanks a lot. :handshake:

I found a good way

at::Tensor at::index_select(const at::Tensor &self, at::Dimname dim, const at::Tensor &index)
torch::Tensor a = at::index_select(torch::Tensor data, torch::Tensor index)

But there’s still a problem.

error : no matching function for call to 'index_select(at::Tensor&, at::Tensor$)'

Maybe this method takes three arguments, But How to get dim???

Thanks.

I found it,at::Dimanme dim is equivalent to int

In this way:

torch::Tensor data;

torch::Tensot index;

torch::result = at::index_select(data, 0, index);

So funny :grin: