Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added file on index_select #5673

Merged
merged 10 commits into from
Dec 16, 2024
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
---
Title: '.index_select()'
Description: 'Extract specific elements from a tensor and return a new tensor.'
SaviDahegaonkar marked this conversation as resolved.
Show resolved Hide resolved
Subjects:
- 'AI'
- 'Data Science'
Tags:
- 'AI'
- 'Arrays'
- 'Data Structures'
- 'Deep Learning'
CatalogContent:
- 'intro-to-py-torch-and-neural-networks'
- 'paths/computer-science'
---

**`Index_select()`** is used to extract specific elements (rows, columns) from the tensor to return a new tensor.
SaviDahegaonkar marked this conversation as resolved.
Show resolved Hide resolved

## Syntax

```pseudo
torch.index_select(input, dim, index, out)
```

- `input`: The input tensor.
- `dim`: The dimension to index (0 for rows, 1 for columns).
- `index`: The 1-D tensor containing the indices to select.
- `out` (optional): The output tensor (optional).
SaviDahegaonkar marked this conversation as resolved.
Show resolved Hide resolved

Note: If the result is to be stored in an existing tensor, the output tensor can be specified using the optional out argument.
SaviDahegaonkar marked this conversation as resolved.
Show resolved Hide resolved

## Example

The following example demonstrates the use of `.index_select()`:

```py
import torch

#Define a tensor
ten = torch.tensor([[1, 2, 3, -8],
[4, 3, 8, 0],
[-1, 7, 6, 3],
[5, 6, 9, 0]])

indices = torch.tensor([0, 2])

#Define a new tensor using index_select
r = torch.index_select(ten, 0, indices)
print(r)

#Define a new tensor using index_select
c = torch.index_select(ten, 1, indices)
print(c)
```

```shell
tensor([[1, 2, 3, -8],
[-1, 7, 6, 3]])
tensor([[1, 3],
[4, 8],
[-1, 6],
[5, 9]])
```
Loading