1. Pytorch的基本语法

学习目标

  • 了解什么是Pytorch.

  • 掌握Pytorch的基本元素操作.

  • 掌握Pytorch的基本运算操作.

什么是Pytorch

Pytorch是一个基于Numpy的科学计算包, 向它的使用者提供了两大功能.

  • 作为Numpy的替代者, 向用户提供使用GPU强大功能的能力.

  • 做为一款深度学习的平台, 向用户提供最大的灵活性和速度.

Pytorch的基本元素操作

  • Tensors张量: 张量的概念类似于Numpy中的ndarray数据结构, 最大的区别在于Tensor可以利用GPU的加速功能.

  • 我们使用Pytorch的时候, 常规步骤是先将torch引用进来, 如下所示:

from __future__ import print_function
import torch
x = torch.empty(5, 3)
print(x)

– 输出结果:

tensor([[2.4835e+27, 2.5428e+30, 1.0877e-19],
        [1.5163e+23, 2.2012e+12, 3.7899e+22],
        [5.2480e+05, 1.0175e+31, 9.7056e+24],
        [1.6283e+32, 3.7913e+22, 3.9653e+28],
        [1.0876e-19, 6.2027e+26, 2.3685e+21]])
x = torch.rand(5, 3)
print(x)

– 输出结果:

tensor([[0.1368, 0.8070, 0.4567],
        [0.4369, 0.8278, 0.5552],
        [0.6848, 0.4473, 0.1031],
        [0.5308, 0.9194, 0.2761],
        [0.0484, 0.9941, 0.2227]])

– 对比有无初始化的矩阵: 当声明一个未初始化的矩阵时, 它本身不包含任何确切的值. 当创建一个未初始化的矩阵时, 分配给矩阵的内存中有什么数值就赋值给了这个矩阵, 本质上是毫无意义的数据.

x = torch.zeros(5, 3, dtype=torch.long)
print(x)

– 输出结果:

tensor([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]])
x = torch.tensor([2.5, 3.5])
print(x)

– 输出结果:

tensor([2.5000, 3.3000])

x = x.new_ones(5, 3, dtype=torch.double)
print(x)

y = torch.randn_like(x, dtype=torch.float)
print(y)

– 输出结果:

tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]], dtype=torch.float64)

tensor([[-0.1497, -0.5832, -0.3805],
        [ 0.9001,  2.0637,  1.3299],
        [-0.8813, -0.6579, -0.9135],
        [-0.1374,  0.1000, -0.9343],
        [-1.1278, -0.9140, -1.5910]])
print(x.size())

– 输出结果:

torch.Size([5, 3])
  • 注意:
    torch.Size函数本质上返回的是一个tuple, 因此它支持一切元组的操作.

Pytorch的基本运算操作

y = torch.rand(5, 3)
print(x + y)
输出结果:
tensor([[ 1.6978, -1.6979,  0.3093],
        [ 0.4953,  0.3954,  0.0595],
        [-0.9540,  0.3353,  0.1251],
        [ 0.6883,  0.9775,  1.1764],
        [ 2.6784,  0.1209,  1.5542]])
print(torch.add(x, y))
输出结果:
tensor([[ 1.6978, -1.6979,  0.3093],
        [ 0.4953,  0.3954,  0.0595],
        [-0.9540,  0.3353,  0.1251],
        [ 0.6883,  0.9775,  1.1764],
        [ 2.6784,  0.1209,  1.5542]])

result = torch.empty(5, 3)

torch.add(x, y, out=result)
print(result)
输出结果:
tensor([[ 1.6978, -1.6979,  0.3093],
        [ 0.4953,  0.3954,  0.0595],
        [-0.9540,  0.3353,  0.1251],
        [ 0.6883,  0.9775,  1.1764],
        [ 2.6784,  0.1209,  1.5542]])
y.add_(x)
print(y)
输出结果:
tensor([[ 1.6978, -1.6979,  0.3093],
        [ 0.4953,  0.3954,  0.0595],
        [-0.9540,  0.3353,  0.1251],
        [ 0.6883,  0.9775,  1.1764],
        [ 2.6784,  0.1209,  1.5542]])

注意:
所有in-place的操作函数都有一个下划线的后缀. 比如x.copy_(y), x.add_(y), 都会直接改变x的值.

用类似于Numpy的方式对张量进行操作:
print(x[:, 1])

解释:
python print(x[:, 1]) # 冒号代表取所有的行 ",1"代表取第一列
print(x[:,:3]) # 打印所有行、 0-2列
print(x[:,:2]) # 打印所有行、 0-1列

输出结果:
tensor([-2.0902, -0.4489, -0.1441,  0.8035, -0.8341])
x = torch.randn(4, 4)

y = x.view(16)

z = x.view(-1, 8)
print(x.size(), y.size(), z.size())
输出结果:
torch.Size([4, 4]) torch.Size([16]) torch.Size([2, 8])

详细注释版代码:


y = x.view(16)

z = x.view(-1, 8)
y2 = x.view(16,-1)
print(y)
print(y2)
print(x.size(),y.size(), z.size(),y2.size()) 
</code></pre>
<blockquote>
<p><strong>输出结果</strong>:</p>
</blockquote>
<pre><code class="language-python">tensor([-1.2186, -0.7919,  0.0411, -0.4893, -0.4517, 0.0588,  0.5275, -0.5617, 2.1183,  1.3618, -0.3788,  0.9497, -0.4051,  0.2710,  0.9537, -1.6315])
tensor([[-1.2186],
        [-0.7919],
        [ 0.0411],
        [-0.4893],
        [-0.4517],
        [ 0.0588],
        [ 0.5275],
        [-0.5617],
        [ 2.1183],
        [ 1.3618],
        [-0.3788],
        [ 0.9497],
        [-0.4051],
        [ 0.2710],
        [ 0.9537],
        [-1.6315]])
        torch.Size([4, 4]) torch.Size([16]) torch.Size([2, 8]) torch.Size([16, 1]) 
x = torch.randn(1)
print(x)
print(x.item())
&#x8F93;&#x51FA;&#x7ED3;&#x679C;:
tensor([-0.3531])
-0.3530771732330322

关于Torch Tensor和Numpy array之间的相互转换

a = torch.ones(5)
print(a)

输出结果: python tensor([1., 1., 1., 1., 1.])

b = a.numpy()
print(b)

输出结果:
[1. 1. 1. 1. 1.]

a.add_(1)
print(a)
print(b)

输出结果:

tensor([2., 2., 2., 2., 2.])
 [2. 2. 2. 2. 2.]
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out=a)
print(a)
print(b)

输出结果:

 [2. 2. 2. 2. 2.]
 tensor([2., 2., 2., 2., 2.],
dtype=torch.float64)

注意:
所有在CPU上的Tensors, 除了CharTensor, 都可以转换为Numpy array并可以反向转换.


if torch.cuda.is_available():

    device = torch.device("cuda")

    y = torch.ones_like(x, device=device)

    x = x.to(device)

    z = x + y

    print(z)

    print(z.to("cpu", torch.double))

输出结果:

tensor([0.6469], device='cuda:0') tensor([0.6469],
dtype=torch.float64)

小节总结

  • 学习了什么是Pytorch.

– Pytorch是一个基于Numpy的科学计算包, 作为Numpy的替代者, 向用户提供使用GPU强大功能的能力.

– 做为一款深度学习的平台, 向用户提供最大的灵活性和速度.

  • 学习了Pytorch的基本元素操作.

– 矩阵的初始化:
* 学习了Pytorch的基本运算操作.

– 加法操作:
– 其他若干操作:
* 学习了Torch Tensor和Numpy Array之间的相互转换.

– 将Torch Tensor转换为Numpy Array:
– 注意: 所有才CPU上的Tensor, 除了CharTensor, 都可以转换为Numpy Array并可以反向转换.

  • 学习了任意的Tensors可以用.to()方法来将其移动到任意设备上.

– x = x.to(device)

学习目标

  • 掌握自动求导中的Tensor概念和操作.

  • 掌握自动求导中的梯度Gradients概念和操作.

  • 在整个Pytorch框架中, 所有的神经网络本质上都是一个autograd package(自动求导工具包)
    – autograd package提供了一个对Tensors上所有的操作进行自动微分的功能.

关于torch.Tensor

  • torch.Tensor是整个package中的核心类, 如果将属性.requires_grad设置为True, 它将追踪在这个类上定义的所有操作. 当代码要进行反向传播的时候, 直接调用.backward()就可以自动计算所有的梯度. 在这个Tensor上的所有梯度将被累加进属性.grad中.

  • 如果想终止一个Tensor在计算图中的追踪回溯, 只需要执行.detach()就可以将该Tensor从计算图中撤下, 在未来的回溯计算中也不会再计算该Tensor.

  • 除了.detach(), 如果想终止对计算图的回溯, 也就是不再进行方向传播求导数的过程, 也可以采用代码块的方式with torch.no_grad():, 这种方式非常适用于对模型进行预测的时候, 因为预测阶段不再需要对梯度进行计算.

关于torch.Function:

  • Function类是和Tensor类同等重要的一个核心类, 它和Tensor共同构建了一个完整的类, 每一个Tensor拥有一个.grad_fn属性, 代表引用了哪个具体的Function创建了该Tensor.

  • 如果某个张量Tensor是用户自定义的, 则其对应的grad_fn is None.

关于Tensor的操作

x1 = torch.ones(3, 3)
print(x1)

x = torch.ones(2, 2, requires_grad=True)
print(x)
  • 输出结果:
tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]])

tensor([[1., 1.],
        [1., 1.]], requires_grad=True)
y = x + 2
print(y)
  • 输出结果:
tensor([[3., 3.],
        [3., 3.]], grad_fn=<AddBackward0>)
print(x.grad_fn)
print(y.grad_fn)
  • 输出结果:
None
<AddBackward0 object at 0x10db11208>
z = y * y * 3
out = z.mean()
print(z, out)
  • 输出结果:
tensor([[27., 27.],
        [27., 27.]], grad_fn=<MulBackward0>) tensor(27., grad_fn=<MeanBackward0>)
a = torch.randn(2, 2)
a = ((a * 3) / (a - 1))
print(a.requires_grad)
a.requires_grad_(True)
print(a.requires_grad)
b = (a * a).sum()
print(b.grad_fn)
  • 输出结果:
False
True
<SumBackward0 object at 0x7f191afd6be0>

关于梯度Gradients

out.backward()
print(x.grad)
  • 输出结果:
tensor([[4.5000, 4.5000],
        [4.5000, 4.5000]])
print(x.requires_grad)
print((x ** 2).requires_grad)

with torch.no_grad():
    print((x ** 2).requires_grad)
  • 输出结果:
True
True
False
print(x.requires_grad)
y = x.detach()
print(y.requires_grad)
print(x.eq(y).all())
  • 输出结果:
True
False
tensor(True)

小节总结

  • 学习了torch.Tensor类的相关概念.

– torch.Tensor是整个package中的核心类, 如果将属性.requires_grad设置为True, 它将追踪在这个类上定义的所有操作. 当代码要进行反向传播的时候, 直接调用.backward()就可以自动计算所有的梯度. 在这个Tensor上的所有梯度将被累加进属性.grad中.

– 执行.detach()命令, 可以将该Tensor从计算图中撤下, 在未来的回溯计算中不会再计算该Tensor.

– 采用代码块的方式也可以终止对计算图的回溯:

Original: https://blog.csdn.net/GCTTTTTT/article/details/127560463
Author: GCTTTTTT
Title: 1. Pytorch的基本语法

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/761204/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球