# Reduce Tensor Dimension by Random Sampling/Indexing

I have a 3-D tensor of shape `(10, 15, 20)`. I want to reduce it to be a 2-D tensor with shape `(10, 15)`, making sure that I select only a random element from the original 3-D tensor’s third dimension (of length 20).

I have tried index notation by generating an index tensor that matches the third dimension, but am running into dimensional broadcasting issues.

Any help would be appreciated!

How do you use index tensor?

``````a = torch.rand(10, 15, 20)
result = a[:, :, idx]
``````

for generated random integer `idx`

That’s exactly how I’m using my index tensor, but I am ending up with the same dimensional tensor.

`result = a[:, :, 1]` gets me the correct dimensional result, but `result = a[:, :, idx]` returns the same dimension as `a`, the original tensor.

What dimensions should the `idx` tensor have for correct slicing?

I understood what bothers you

``````a = torch.rand(10, 15, 20)
idx = torch.LongTensor([idx])

# torch.Size([10, 15, 1])
result1 = a[:, :, idx]
# torch.Size([10, 15])
result2 = a[:, :, idx].squeeze()
``````

`tensor.squeeze()` is what you are looking for.
Indexing with a list (or tensor) keeps the dimension of the original.

You can compare the different outputs by
`a[:, :, idx]` and `a[:, :, idx.item()]`.
First one is indexing with a tensor and second one is with an integer.

Thank you for your input @thecho7 - much appreciated.

The problem still persists for me.

`tensor.squeeze()` only works for removing dimensions of size 1. I am ending with a dimension `(10, 15, 20)`, which remains unaltered by the squeeze operation.

Isn’t your question about making `(10, 15, 20)` to `(10, 15)` by sampling one element?