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,59 @@
---
Title: '.index_select()'
Description: 'Extracts specific elements from a tensor to return a new tensor.'
Neema-Joju 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.
Neema-Joju marked this conversation as resolved.
Show resolved Hide resolved

## Syntax

```pseudo
torch.index_select(input,dim,index,out)
Neema-Joju marked this conversation as resolved.
Show resolved Hide resolved
```

- `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)
Neema-Joju marked this conversation as resolved.
Show resolved Hide resolved

## Example

The following example demonstrates the usage of `.index_select()`:
Neema-Joju marked this conversation as resolved.
Show resolved Hide resolved

```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, 4, -1, 5],
[3, 8, 6, 9]])
Neema-Joju marked this conversation as resolved.
Show resolved Hide resolved
```
Loading