【动手学深度学习】---0x01:pytorch基础知识

【动手学深度学习】—基础知识

1:Tensor:提供GPU计算自动求梯度

2:"tensor"这个单词一般可译作“张量”,张量可以看作是一个多维数组。标量可以看作是0维张量,向量可以看作1维张量,矩阵可以看作是二维张量。

3:创建Tensor

x = torch.empty(5, 3) # 5x3的未初始化的Tensor
print(x)
'''
tensor([[ 0.0000e+00,  1.5846e+29,  0.0000e+00],
        [ 1.5846e+29,  5.6052e-45,  0.0000e+00],
        [ 0.0000e+00,  0.0000e+00,  0.0000e+00],
        [ 0.0000e+00,  0.0000e+00,  0.0000e+00],
        [ 0.0000e+00,  1.5846e+29, -2.4336e+02]])
'''
x = torch.rand(5, 3) # 5x3的随机初始化的Tensor
print(x)
'''
tensor([[0.4963, 0.7682, 0.0885],
        [0.1320, 0.3074, 0.6341],
        [0.4901, 0.8964, 0.4556],
        [0.6323, 0.3489, 0.4017],
        [0.0223, 0.1689, 0.2939]])
'''
x = torch.zeros(5, 3, dtype=torch.long) # 5x3的long型全0的Tensor
print(x)
'''
tensor([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]])
'''
x = torch.tensor([5.5, 3]) # 根据数据创建
print(x)
'''
tensor([5.5000, 3.0000])
'''
x = x.new_ones(5, 3, dtype=torch.float64)  # 返回的tensor默认具有相同的torch.dtype和torch.device
print(x)
'''
tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]], dtype=torch.float64)
'''
x = torch.randn_like(x, dtype=torch.float) # 指定新的数据类型
print(x) 
'''
tensor([[ 0.6035,  0.8110, -0.0451],
        [ 0.8797,  1.0482, -0.0445],
        [-0.7229,  2.8663, -0.5655],
        [ 0.1604, -0.0254,  1.0739],
        [ 2.2628, -0.9175, -0.2251]])
'''

4:Tensor形状

print(x.size())
print(x.shape)
'''
torch.Size([5, 3])
torch.Size([5, 3]) # 返回的torch.Size其实就是一个tuple, 支持所有tuple的操作。
'''

5:操作

 y = torch.rand(5, 3)
 print(x + y) # 1
 
 print(torch.add(x, y)) # 2
 
 result = torch.empty(5, 3)
 torch.add(x, y, out=result) # 3
 print(result)
 
   # adds x to y
  y.add_(x) # 4
  print(y)

:PyTorch操作inplace版本都有后缀_, 例如x.copy_(y), x.t_()

6:索引—和numpy类似,但索引出来的结果与原数据共享内存,也即修改一个,另一个会跟着修改

7:改变形状

y = x.view(15)
z = x.view(-1, 5)  # -1所指的维度可以根据其他维度的值推出来
print(x.size(), y.size(), z.size())

注意:view仅仅是改变了对这个张量的观察角度,内部数据并未改变

# 返回一个真正新的副本(即不共享daat内存)
x_cp = x.clone().view(15)
x -= 1
print(x)
print(x_cp)
'''
tensor([[ 0.6035,  0.8110, -0.0451],
        [ 0.8797,  1.0482, -0.0445],
        [-0.7229,  2.8663, -0.5655],
        [ 0.1604, -0.0254,  1.0739],
        [ 2.2628, -0.9175, -0.2251]])
tensor([1.6035, 1.8110, 0.9549, 1.8797, 2.0482, 0.9555, 0.2771, 3.8663, 0.4345,
        1.1604, 0.9746, 2.0739, 3.2628, 0.0825, 0.7749])

'''

:使用clone还有一个好处是会被记录在计算图中,即梯度回传到副本时也会传到源Tensor。

8:转换成number

x = torch.randn(1)
print(x)
print(x.item())
'''
tensor([2.3466])
2.3466382026672363
'''

9:线性代数

函数 功能
trace 对角线元素之和(矩阵的迹)
diag 对角线元素
triu/tril 矩阵的上三角/下三角,可指定偏移量
mm/bmm 矩阵乘法,batch的矩阵乘法
addmm/addbmm/addmv/addr/baddbmm… 矩阵运算
t 转置
dot/cross 内积/外积
inverse 求逆矩阵
svd 奇异值分解

10:广播机制
两个数组的后缘维度相同,或者在其中一方的维度为1。广播在缺失或者长度为1的维度上补充。

11:运算的内存开销
索引操作是不会开辟新内存的,而像y = x + y这样的运算是会新开内存的,然后将y指向新内存。

x = torch.tensor([1, 2])
y = torch.tensor([3, 4])
id_before = id(y)
y = y + x
print(id(y) == id_before) # False 

x = torch.tensor([1, 2])
y = torch.tensor([3, 4])
id_before = id(y)
y[:] = y + x
print(id(y) == id_before) # True

x = torch.tensor([1, 2])
y = torch.tensor([3, 4])
id_before = id(y)
torch.add(x, y, out=y) # y += x, y.add_(x)
print(id(y) == id_before) # True

:虽然view返回的Tensor与源Tensor是共享data的,但是依然是一个新的Tensor(因为Tensor除了包含data外还有一些其他属性),二者id(内存地址)并不一致。

12:Tensor和NumPy相互转换
numpy()和from_numpy()将Tensor和NumPy中的数组相互转换—(但是数据共享)。

torch.tensor()—(数据不共享)

a = torch.ones(5)
b = a.numpy()
print(a, b)

a = np.ones(5)
b = torch.from_numpy(a)
print(a, b)

13:Tensor on GPU

# 以下代码只有在PyTorch GPU版本上才会执行
if torch.cuda.is_available():
    device = torch.device("cuda")          # GPU
    y = torch.ones_like(x, device=device)  # 直接创建一个在GPU上的Tensor
    x = x.to(device)                       # 等价于 .to("cuda")
    z = x + y
    print(z)
    print(z.to("cpu", torch.double))       # to()还可以同时更改数据类型

14:求梯度
属性.requires_grad设置为True,开始追踪(track)在其上的所有操作,完成计算后,可以调用.backward()来完成所有梯度计算,并将Tensor的梯度将累积到.grad属性中。

注意:在y.backward()时,如果y是标量,则不需要为backward()传入任何参数;否则,需要传入一个与y同形的Tensor(进行累加操作)

如果不想要被继续追踪,可以调用.detach()将其从追踪记录中分离出来。此外,还可以用with torch.no_grad()将不想被追踪的操作代码块包裹起来,这种方法在评估模型的时候很常用,因为在评估模型时,我们并不需要计算可训练参数(requires_grad=True)的梯度。

Function是另外一个很重要的类。Tensor和Function互相结合就可以构建一个记录有整个计算过程的有向无环图(DAG)。每个Tensor都有一个.grad_fn属性,该属性即创建该Tensor的Function, 就是说该Tensor是不是通过某些运算得到的,若是,则grad_fn返回一个与这些运算相关的对象,否则是None。

x = torch.ones(2, 2, requires_grad=True)
print(x)
print(x.grad_fn)
'''
tensor([[1., 1.],
        [1., 1.]], requires_grad=True)
None
'''
y = x + 2
print(y)
print(y.grad_fn)
'''
tensor([[3., 3.],
        [3., 3.]], grad_fn=<AddBackward>)
<AddBackward object at 0x1100477b8>
'''

叶子节点对应的grad_fn是None。

# 通过.requires_grad_()来用in-place的方式改变requires_grad属性:
a = torch.randn(2, 2) # 缺失情况下默认 requires_grad = False
a = ((a * 3) / (a - 1))
print(a.requires_grad) # False
a.requires_grad_(True)
print(a.requires_grad) # True
b = (a * a).sum()
print(b.grad_fn)
'''
False
True
<SumBackward0 object at 0x118f50cc0>
'''
x = torch.tensor([1.0, 2.0, 3.0, 4.0], requires_grad=True)
y = 2 * x
z = y.view(2, 2)
print(z)
'''
tensor([[2., 4.],
        [6., 8.]], grad_fn=<ViewBackward>)
'''
# 现在 z 不是一个标量,所以在调用backward时需要传入一个和z同形的权重向量进行加权求和得到一个标量。
v = torch.tensor([[1.0, 0.1], [0.01, 0.001]], dtype=torch.float)
z.backward(v)
print(x.grad)
'''
tensor([2.0000, 0.2000, 0.0200, 0.0020])
'''

如果我们想要修改tensor的数值,但是又不希望被autograd记录(即不会影响反向传播),那么我么可以对tensor.data进行操作。

x = torch.ones(1,requires_grad=True)

print(x.data) # 还是一个tensor
print(x.data.requires_grad) # 但是已经是独立于计算图之外

y = 2 * x
x.data *= 100 # 只改变了值,不会记录在计算图,所以不会影响梯度传播

y.backward()
print(x) # 更改data的值也会影响tensor的值
print(x.grad)

参考资料

https://tangshusen.me/Dive-into-DL-PyTorch/#/chapter02_prerequisite/2.2_tensor

猜你喜欢

转载自blog.csdn.net/qq_45914759/article/details/113337558