翻译自
参考
张量
张量是一种类似数组和矩阵的数据结构。在PyTorch中,我们使用张量去封装模型的输入和输出,另外,模型的参数也是用张量表示。
张量类似于NumPy的n维数组,除了张量能使用GPU或者特定的硬件加速计算。
import torch
import numpy as np
张量初始化
张量可以通过多种方式初始化。
从数据初始化
data = [1, 2], [3, 4]]
x_data = torch.tensor(data)
从NumPy数组初始化
np_array = np.array(data) x_np = torch.from_numpy(np_array)
从另一个张量初始化 ```python x_ones = torch.ones_like(x_data) # retains the properties of x_data print(f”Ones Tensor: \n {x_ones} \n”)
x_rand = torch.rand_like(x_data, dtype=torch.float) # overrides the datatype of x_data print(f”Random Tensor: \n {x_rand} \n”)
输出
```python
Ones Tensor:
tensor([[1, 1],
[1, 1]])
Random Tensor:
tensor([[0.7712, 0.3382],
[0.2964, 0.6167]])
- 使用随机数或者固定值初始化 ```python 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}”)
输出
```python
Random Tensor:
tensor([[0.5419, 0.5118, 0.7665],
[0.6088, 0.6369, 0.0696]])
Ones Tensor:
tensor([[1., 1., 1.],
[1., 1., 1.]])
Zeros Tensor:
tensor([[0., 0., 0.],
[0., 0., 0.]])
张量的属性
张量的属性描述张量的形状(shape)、数据类型(dtype)、存储的设备(device)
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}")
输出
Shape of tensor: torch.Size([3, 4])
Datatype of tensor: torch.float32
Device tensor is stored on: cpu
张量的操作
张量有100多种操作,包括转置、索引、切片、数值运算、线性代数等等,张量的每一种操作都可以在GPU上运行。
# We move our tensor to the GPU if available
if torch.cuda.is_available():
tensor = tensor.to('cuda')
NumPy风格的索引和切片
tensor = torch.ones(4, 4) tensor[:,1] = 0 print(tensor)
输出
tensor([[1., 0., 1., 1.], [1., 0., 1., 1.], [1., 0., 1., 1.], [1., 0., 1., 1.]])
拼接
t1 = torch.cat([tensor, tensor, tensor], dim=1) print(t1)
输出
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.]])
乘法
点乘
# This computes the element-wise product
print(f"tensor.mul(tensor) \n {tensor.mul(tensor)} \n")
# Alternative syntax:
print(f"tensor * tensor \n {tensor * tensor}")
输出
tensor.mul(tensor)
tensor([[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.]])
tensor * tensor
tensor([[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.]])
矩阵乘
print(f"tensor.matmul(tensor.T) \n {tensor.matmul(tensor.T)} \n")
# Alternative syntax:
print(f"tensor @ tensor.T \n {tensor @ tensor.T}")
输出
tensor.matmul(tensor.T)
tensor([[3., 3., 3., 3.],
[3., 3., 3., 3.],
[3., 3., 3., 3.],
[3., 3., 3., 3.]])
tensor @ tensor.T
tensor([[3., 3., 3., 3.],
[3., 3., 3., 3.],
[3., 3., 3., 3.],
[3., 3., 3., 3.]])
- 原地运算(in-place operations)
输出 ```python tensor([[1., 0., 1., 1.],print(tensor, "\n") tensor.add_(5) print(tensor)
[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.]])
<a name="N2QHE"></a>
# 与NumPy的桥梁
在CPU上的张量可以和NumPy数组共享数据存储的内存,改变其中一个会改变另一个。
- Tensor to NumPy array
```python
t = torch.ones(5)
print(f"t: {t}")
n = t.numpy()
print(f"n: {n}")
输出
t: tensor([1., 1., 1., 1., 1.])
n: [1. 1. 1. 1. 1.]
改变张量会影响NumPy数组
t.add_(1)
print(f"t: {t}")
print(f"n: {n}")
输出
t: tensor([2., 2., 2., 2., 2.])
n: [2. 2. 2. 2. 2.]
- NumPy array to Tensor
改变NumPy数组会影响张量的值n = np.ones(5) t = torch.from_numpy(n)
输出np.add(n, 1, out=n) print(f"t: {t}") print(f"n: {n}")
t: tensor([2., 2., 2., 2., 2.], dtype=torch.float64) n: [2. 2. 2. 2. 2.]