03.md 7.3 KB
Newer Older
W
wizardforcel 已提交
1 2
# 张量

考拉不是大叔's avatar
考拉不是大叔 已提交
3
>原文: <https://pytorch.org/tutorials/beginner/blitz/tensor_tutorial.html#sphx-glr-beginner-blitz-tensor-tutorial-py>
W
wizardforcel 已提交
4

考拉不是大叔's avatar
考拉不是大叔 已提交
5
张量如同数组和矩阵一样, 是一种特殊的数据结构。在`PyTorch`中, 神经网络的输入、输出以及网络的参数等数据, 都是使用张量来进行描述。
W
wizardforcel 已提交
6

考拉不是大叔's avatar
考拉不是大叔 已提交
7
张量的使用和`Numpy`中的`ndarrays`很类似, 区别在于张量可以在`GPU`或其它专用硬件上运行, 这样可以得到更快的加速效果。如果你对`ndarrays`很熟悉的话, 张量的使用对你来说就很容易了。如果不太熟悉的话, 希望这篇有关张量`API`的快速入门教程能够帮到你。
W
wizardforcel 已提交
8

考拉不是大叔's avatar
考拉不是大叔 已提交
9
```python
W
wizardforcel 已提交
10 11 12 13 14 15
import torch
import numpy as np
```

## 张量初始化

考拉不是大叔's avatar
考拉不是大叔 已提交
16
张量有很多种不同的初始化方法, 先来看看四个简单的例子:
W
wizardforcel 已提交
17

考拉不是大叔's avatar
考拉不是大叔 已提交
18
**1. 直接生成张量**
W
wizardforcel 已提交
19

考拉不是大叔's avatar
考拉不是大叔 已提交
20
由原始数据直接生成张量, 张量类型由原始数据类型决定。
W
wizardforcel 已提交
21

考拉不是大叔's avatar
考拉不是大叔 已提交
22 23
```python
data = [[1, 2], [3, 4]]
W
wizardforcel 已提交
24 25 26
x_data = torch.tensor(data)
```

考拉不是大叔's avatar
考拉不是大叔 已提交
27
**2. 通过Numpy数组来生成张量**
W
wizardforcel 已提交
28

考拉不是大叔's avatar
考拉不是大叔 已提交
29
由已有的`Numpy`数组来生成张量(反过来也可以由张量来生成`Numpy`数组, 参考[张量与Numpy之间的转换](#jump))。
W
wizardforcel 已提交
30

考拉不是大叔's avatar
考拉不是大叔 已提交
31
```python
W
wizardforcel 已提交
32 33 34
np_array = np.array(data)
x_np = torch.from_numpy(np_array)
```
考拉不是大叔's avatar
考拉不是大叔 已提交
35
**3. 通过已有的张量来生成新的张量**
W
wizardforcel 已提交
36

考拉不是大叔's avatar
考拉不是大叔 已提交
37
新的张量将继承已有张量的数据属性(结构、类型), 也可以重新指定新的数据类型。
W
wizardforcel 已提交
38

考拉不是大叔's avatar
考拉不是大叔 已提交
39 40
```python
x_ones = torch.ones_like(x_data)   # 保留 x_data 的属性
W
wizardforcel 已提交
41 42
print(f"Ones Tensor: \n {x_ones} \n")

H
hummingg 已提交
43
x_rand = torch.rand_like(x_data, dtype=torch.float)   # 重写 x_data 的数据类型:int -> float
W
wizardforcel 已提交
44 45 46
print(f"Random Tensor: \n {x_rand} \n")
```

考拉不是大叔's avatar
考拉不是大叔 已提交
47
显示:
W
wizardforcel 已提交
48

考拉不是大叔's avatar
考拉不是大叔 已提交
49
```python
W
wizardforcel 已提交
50 51
Ones Tensor:
 tensor([[1, 1],
考拉不是大叔's avatar
考拉不是大叔 已提交
52
         [1, 1]])
W
wizardforcel 已提交
53 54

Random Tensor:
考拉不是大叔's avatar
考拉不是大叔 已提交
55 56
 tensor([[0.0381, 0.5780],
         [0.3963, 0.0840]])
W
wizardforcel 已提交
57
```
考拉不是大叔's avatar
考拉不是大叔 已提交
58
**4. 通过指定数据维度来生成张量**
W
wizardforcel 已提交
59

考拉不是大叔's avatar
考拉不是大叔 已提交
60
`shape`是元组类型, 用来描述张量的维数, 下面3个函数通过传入`shape`来指定生成张量的维数。
W
wizardforcel 已提交
61

考拉不是大叔's avatar
考拉不是大叔 已提交
62
```python
W
wizardforcel 已提交
63 64 65 66 67 68 69 70 71 72
shape = (2,3,)
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape)

print(f"Random Tensor: \n {rand_tensor} \n")
print(f"Ones Tensor: \n {ones_tensor} \n")
print(f"Zeros Tensor: \n {zeros_tensor}")
```

考拉不是大叔's avatar
考拉不是大叔 已提交
73
显示:
W
wizardforcel 已提交
74

考拉不是大叔's avatar
考拉不是大叔 已提交
75
```python
W
wizardforcel 已提交
76
Random Tensor:
考拉不是大叔's avatar
考拉不是大叔 已提交
77 78
 tensor([[0.0266, 0.0553, 0.9843],
         [0.0398, 0.8964, 0.3457]])
W
wizardforcel 已提交
79 80 81

Ones Tensor:
 tensor([[1., 1., 1.],
考拉不是大叔's avatar
考拉不是大叔 已提交
82
         [1., 1., 1.]])
W
wizardforcel 已提交
83 84 85

Zeros Tensor:
 tensor([[0., 0., 0.],
考拉不是大叔's avatar
考拉不是大叔 已提交
86
         [0., 0., 0.]])
W
wizardforcel 已提交
87 88 89 90
```

## 张量属性

考拉不是大叔's avatar
考拉不是大叔 已提交
91 92 93
从张量属性我们可以得到张量的维数、数据类型以及它们所存储的设备(CPU或GPU)。

来看一个简单的例子:
W
wizardforcel 已提交
94

考拉不是大叔's avatar
考拉不是大叔 已提交
95
```python
W
wizardforcel 已提交
96 97 98 99 100 101 102
tensor = torch.rand(3,4)

print(f"Shape of tensor: {tensor.shape}")
print(f"Datatype of tensor: {tensor.dtype}")
print(f"Device tensor is stored on: {tensor.device}")
```

考拉不是大叔's avatar
考拉不是大叔 已提交
103
显示:
W
wizardforcel 已提交
104

考拉不是大叔's avatar
考拉不是大叔 已提交
105 106 107 108
```python
Shape of tensor: torch.Size([3, 4])   # 维数
Datatype of tensor: torch.float32     # 数据类型
Device tensor is stored on: cpu       # 存储设备
W
wizardforcel 已提交
109 110 111 112
```

## 张量运算

考拉不是大叔's avatar
考拉不是大叔 已提交
113
有超过100种张量相关的运算操作, 例如转置、索引、切片、数学运算、线性代数、随机采样等。更多的运算可以在这里[查看](https://pytorch.org/docs/stable/torch.html)
W
wizardforcel 已提交
114

考拉不是大叔's avatar
考拉不是大叔 已提交
115
所有这些运算都可以在GPU上运行(相对于CPU来说可以达到更高的运算速度)。如果你使用的是Google的Colab环境, 可以通过 `Edit > Notebook Settings` 来分配一个GPU使用。
W
wizardforcel 已提交
116

考拉不是大叔's avatar
考拉不是大叔 已提交
117 118
```python
# 判断当前环境GPU是否可用, 然后将tensor导入GPU内运行
W
wizardforcel 已提交
119 120 121 122
if torch.cuda.is_available():
  tensor = tensor.to('cuda')
```

考拉不是大叔's avatar
考拉不是大叔 已提交
123
光说不练假把式, 接下来的例子一定要动手跑一跑。如果你对Numpy的运算非常熟悉的话, 那tensor的运算对你来说就是小菜一碟。
W
wizardforcel 已提交
124

考拉不是大叔's avatar
考拉不是大叔 已提交
125
**1. 张量的索引和切片**
W
wizardforcel 已提交
126

考拉不是大叔's avatar
考拉不是大叔 已提交
127
```python
W
wizardforcel 已提交
128
tensor = torch.ones(4, 4)
考拉不是大叔's avatar
考拉不是大叔 已提交
129
tensor[:,1] = 0            # 将第1列(从0开始)的数据全部赋值为0
W
wizardforcel 已提交
130 131 132
print(tensor)
```

考拉不是大叔's avatar
考拉不是大叔 已提交
133
显示:
W
wizardforcel 已提交
134

考拉不是大叔's avatar
考拉不是大叔 已提交
135
```python
W
wizardforcel 已提交
136 137 138 139 140 141
tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])
```

考拉不是大叔's avatar
考拉不是大叔 已提交
142 143 144
**2. 张量的拼接**

你可以通过`torch.cat`方法将一组张量按照指定的维度进行拼接, 也可以参考[`torch.stack`](https://pytorch.org/docs/stable/generated/torch.stack.html)方法。这个方法也可以实现拼接操作, 但和`torch.cat`稍微有点不同。
W
wizardforcel 已提交
145

考拉不是大叔's avatar
考拉不是大叔 已提交
146
```python
W
wizardforcel 已提交
147 148 149 150
t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(t1)
```

考拉不是大叔's avatar
考拉不是大叔 已提交
151
 显示:
W
wizardforcel 已提交
152

考拉不是大叔's avatar
考拉不是大叔 已提交
153
```
W
wizardforcel 已提交
154 155 156 157 158 159
tensor([[1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.]])
```

考拉不是大叔's avatar
考拉不是大叔 已提交
160
**3. 张量的乘积和矩阵乘法**
W
wizardforcel 已提交
161

考拉不是大叔's avatar
考拉不是大叔 已提交
162 163 164 165 166
```python
# 逐个元素相乘结果
print(f"tensor.mul(tensor): \n {tensor.mul(tensor)} \n")
# 等价写法:
print(f"tensor * tensor: \n {tensor * tensor}")
W
wizardforcel 已提交
167 168
```

考拉不是大叔's avatar
考拉不是大叔 已提交
169
显示:
W
wizardforcel 已提交
170

考拉不是大叔's avatar
考拉不是大叔 已提交
171 172
```python
tensor.mul(tensor):
W
wizardforcel 已提交
173 174 175 176 177
 tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

考拉不是大叔's avatar
考拉不是大叔 已提交
178
tensor * tensor:
W
wizardforcel 已提交
179 180 181 182 183 184
 tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])
```

考拉不是大叔's avatar
考拉不是大叔 已提交
185
下面写法表示张量与张量的矩阵乘法:
W
wizardforcel 已提交
186

考拉不是大叔's avatar
考拉不是大叔 已提交
187 188 189 190
```python
print(f"tensor.matmul(tensor.T): \n {tensor.matmul(tensor.T)} \n")
# 等价写法:
print(f"tensor @ tensor.T: \n {tensor @ tensor.T}")
W
wizardforcel 已提交
191 192
```

考拉不是大叔's avatar
考拉不是大叔 已提交
193
显示:
W
wizardforcel 已提交
194

考拉不是大叔's avatar
考拉不是大叔 已提交
195 196
```python
tensor.matmul(tensor.T):
W
wizardforcel 已提交
197 198 199 200 201
 tensor([[3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.]])

考拉不是大叔's avatar
考拉不是大叔 已提交
202
tensor @ tensor.T:
W
wizardforcel 已提交
203 204 205 206 207 208
 tensor([[3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.]])
```

考拉不是大叔's avatar
考拉不是大叔 已提交
209 210 211
**4. 自动赋值运算**

自动赋值运算通常在方法后有 `_` 作为后缀, 例如: `x.copy_(y)`, `x.t_()`操作会改变 `x` 的取值。
W
wizardforcel 已提交
212

考拉不是大叔's avatar
考拉不是大叔 已提交
213
```python
W
wizardforcel 已提交
214 215 216 217 218
print(tensor, "\n")
tensor.add_(5)
print(tensor)
```

考拉不是大叔's avatar
考拉不是大叔 已提交
219
显示:
W
wizardforcel 已提交
220

考拉不是大叔's avatar
考拉不是大叔 已提交
221
```python
W
wizardforcel 已提交
222 223 224 225 226 227 228 229 230 231 232
tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

tensor([[6., 5., 6., 6.],
        [6., 5., 6., 6.],
        [6., 5., 6., 6.],
        [6., 5., 6., 6.]])
```

考拉不是大叔's avatar
考拉不是大叔 已提交
233 234 235
> 注意:
>
> 自动赋值运算虽然可以节省内存, 但在求导时会因为丢失了中间过程而导致一些问题, 所以我们并不鼓励使用它。
W
wizardforcel 已提交
236

考拉不是大叔's avatar
考拉不是大叔 已提交
237 238
## <span id="jump">Tensor与Numpy的转化</span>
张量和`Numpy array`数组在CPU上可以共用一块内存区域, 改变其中一个另一个也会随之改变。
H
hummingg 已提交
239

考拉不是大叔's avatar
考拉不是大叔 已提交
240 241
**1. 由张量变换为Numpy array数组**
```python
W
wizardforcel 已提交
242 243 244 245 246
t = torch.ones(5)
print(f"t: {t}")
n = t.numpy()
print(f"n: {n}")
```
考拉不是大叔's avatar
考拉不是大叔 已提交
247 248
显示:
```python
W
wizardforcel 已提交
249
t: tensor([1., 1., 1., 1., 1.])
考拉不是大叔's avatar
考拉不是大叔 已提交
250
n: [1. 1. 1. 1. 1.]
W
wizardforcel 已提交
251
```
考拉不是大叔's avatar
考拉不是大叔 已提交
252 253
修改张量的值,则`Numpy array`数组值也会随之改变。
```python
W
wizardforcel 已提交
254 255 256 257
t.add_(1)
print(f"t: {t}")
print(f"n: {n}")
```
考拉不是大叔's avatar
考拉不是大叔 已提交
258 259
显示:
```python
W
wizardforcel 已提交
260
t: tensor([2., 2., 2., 2., 2.])
考拉不是大叔's avatar
考拉不是大叔 已提交
261
n: [2. 2. 2. 2. 2.]
W
wizardforcel 已提交
262 263
```

考拉不是大叔's avatar
考拉不是大叔 已提交
264
**2. 由Numpy array数组转为张量**
W
wizardforcel 已提交
265

考拉不是大叔's avatar
考拉不是大叔 已提交
266
```python
W
wizardforcel 已提交
267 268 269 270
n = np.ones(5)
t = torch.from_numpy(n)
```

考拉不是大叔's avatar
考拉不是大叔 已提交
271
修改`Numpy array`数组的值,则张量值也会随之改变。
W
wizardforcel 已提交
272

考拉不是大叔's avatar
考拉不是大叔 已提交
273
```python
W
wizardforcel 已提交
274 275 276 277 278
np.add(n, 1, out=n)
print(f"t: {t}")
print(f"n: {n}")
```

考拉不是大叔's avatar
考拉不是大叔 已提交
279
显示:
W
wizardforcel 已提交
280

考拉不是大叔's avatar
考拉不是大叔 已提交
281
```python
W
wizardforcel 已提交
282
t: tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
考拉不是大叔's avatar
考拉不是大叔 已提交
283
n: [2. 2. 2. 2. 2.]
W
wizardforcel 已提交
284 285 286 287 288 289 290 291
```

**脚本的总运行时间**:(0 分钟 0.045 秒)

[下载 Python 源码:`tensor_tutorial.py`](https://pytorch.org/tutorials/_downloads/092fba3c36cb2ab226bfdaa78248b310/tensor_tutorial.py)

[下载 Jupyter 笔记本:`tensor_tutorial.ipynb`](https://pytorch.org/tutorials/_downloads/3c2b25b8a9f72db7780a6bf9b5fc9f62/tensor_tutorial.ipynb)

H
hummingg 已提交
292
[由 Sphinx 画廊](https://sphinx-gallery.readthedocs.io)生成的画廊