# 常用Tensor操作

最近在看开发文档们就顺便记录一下。

### 1： torch.index_select(input, dim, indices,out=None)

• input (Tensor) – 输入张量
• dim (int) – 索引的轴
• index (LongTensor) – 包含索引下标的一维张量
• out (Tensor, optional) – 目标张量
```>>> x = torch.randn(3, 4)
>>> x
1.2045  2.4084  0.4001  1.1372
0.5596  1.5677  0.6219 -0.7954
1.3635 -1.2313 -0.5414 -1.8478
[torch.FloatTensor of size 3x4]
>>> indices = torch.LongTensor([0, 2])
>>> torch.index_select(x, 0, indices)
1.2045  2.4084  0.4001  1.1372
1.3635 -1.2313 -0.5414 -1.8478
[torch.FloatTensor of size 2x4]
>>> torch.index_select(x, 1, indices)
1.2045  0.4001
0.5596  0.6219
1.3635 -0.5414
[torch.FloatTensor of size 3x2]```

• input (Tensor) – 输入张量
• mask (ByteTensor) – 掩码张量，包含了二元索引值
• out (Tensor, optional) – 目标张量

```>>> x = torch.randn(3, 4)
>>> x
tensor([[ 0.3552, -2.3825, -0.8297,  0.3477],
[-1.2035,  1.2252,  0.5002,  0.6248],
[ 0.1307, -2.0608,  0.1244,  2.0139]])
>>> mask = x.ge(0.5)   # 构建大于0.5的Bool tensor
tensor([[False, False, False, False],
[False, True, True, True],
[False, False, False, True]])
tensor([ 1.2252,  0.5002,  0.6248,  2.0139])```

### 3 torch.nonzero (input, out)       返回非0索引

• input (Tensor) – 源张量
• out (LongTensor, optional) – 包含索引值的结果张量

```>>> torch.nonzero(torch.Tensor([1, 1, 1, 0, 1]))
0
1
2
4
[torch.LongTensor of size 4x1]
>>> torch.nonzero(torch.Tensor([[0.6, 0.0, 0.0, 0.0],
...                             [0.0, 0.4, 0.0, 0.0],
...                             [0.0, 0.0, 1.2, 0.0],
...                             [0.0, 0.0, 0.0,-0.4]]))
0  0
1  1
2  2
3  3
[torch.LongTensor of size 4x2]```

### 4  torch.clamp   设置上下阈值

torch.clamp(input, min, max, out=None) Tensor

1. ` | min, if x_i < min`
2. `y_i = | x_i, if min <= x_i <= max`
3. ` | max, if x_i > max`
```>>> a = torch.randn(4)
>>> a
1.3869
0.3912
-0.8634
-0.5468
[torch.FloatTensor of size 4]
>>> torch.clamp(a, min=-0.5, max=0.5)
0.5000
0.3912
-0.5000
-0.5000
[torch.FloatTensor of size 4]```

### 5 torch.frac     返回分数部分

torch.frac(tensor, out=None) Tensor

```>>> torch.frac(torch.Tensor([1, 2.5, -3.2])
torch.FloatTensor([0, 0.5, -0.2])```

### 6 torch.lerp   线性插值（一次函数）

torch.lerp(start, end, weight, out=None)

• start (Tensor) – 起始点张量
• end (Tensor) – 终止点张量
• weight (float) – 插值公式的weight
• out (Tensor, optional) – 结果张量
```>>> start = torch.arange(1, 5)
>>> end = torch.Tensor(4).fill_(10)
>>> start
1
2
3
4
[torch.FloatTensor of size 4]
>>> end
10
10
10
10
[torch.FloatTensor of size 4]
>>> torch.lerp(start, end, 0.5)
5.5000
6.0000
6.5000
7.0000
[torch.FloatTensor of size 4]```

(0)
(0)

© 2014 mamicode.com 版权所有 京ICP备13008772号-2