- torch.saves(state, dir)
- 保存/序列化
- torch.load(dir)
- 加载模型
- torch.get num threads():
- 获得用于并行化CPU操作的OpenMP线程数
- torch.set_ num threads(int):
- 设定用于并行化CPU操作的OpenMP线程数
- torch.is_ tensor()
- 如果是pytorch的tensor类型返回true
- torch.is_ storage()
- 如果是pytorch的storage类型返回ture
- torch.set flush_ denormal(mode)
- 防止- -些不正常的元素产生
- torch.set_default_ dtype(d)
- 对torch.tensor() 设置默认的浮点类型
- torch.set_printoptions(precision= None, threshold=None, edgeitems = None, linewidth=None, profile=None)
- 设置printing的打印参数
- torch.from_ numpy(ndarry)
- a.numpy()
import torch
import numpy as np
a = np.zeros([2, 2])
out = torch.from_numpy(a)
# out = out.to(torch.device("cuda"))
out = out.to(torch.device("cpu"))
2. AutoGrad的概念
-
torch.autograd.grad(outputs, inputs, grad_ outputs=None, retain graph= None,create_ graph=False, only_ inputs =True, allow_ unused= False)
计算和返回output关 于inputs的梯度的和。- outputs :函数的因变量,即需要求导的那个函数
- inputs :函数的自变量,
- grad_ _outputs :同backward
- only_ inputs:只计算input的梯度
- allow_ unused( bool,可选) :如果为False,当计算输出出错时(因此他们的梯度永远是0)指明不使用的inputs。
-
torch.autograd 包中的其他函数
- torch.autograd.enable_grad:启动梯度计算的上下文管理器
- torch.autograd.no_grad :禁止梯度计算的上下文管理器
- torch.autograd.set_ grad. enabled(mode):设置是否进行梯度计算的上下文管
理器。
-
torch.autograd.Function
- 每一个原始的自动求导运算实际上是两个在Tensor上运行的函数
- forward函数计算从输入Tensors获得的输出Tensors
- backward函数接收输出Tensors对于某个标量值的梯度,并且计算输入Tensors相对于该相同标量值的梯度
- 最后,利用apply方法执行相应的运算定义在Function类的父类Functionbase中定义的一 个方法
import torch
class line(torch.autograd.Function):
@staticmethod
def forward(ctx, w, x, b):
"""
前向传播
:param ctx:
:param w:
:param x:
:param b:
:return:
"""
#y = w*x +b
# 将变量存储
ctx.save_for_backward(w, x, b)
return w * x + b
@staticmethod
def backward(ctx, grad_out):
"""
反向传播
:param ctx:
:param grad_out:
:return:
"""
# 获取在forward中存储的变量
w, x, b = ctx.saved_tensors
grad_w = grad_out * x
grad_x = grad_out * w
grad_b = grad_out
return grad_w, grad_x, grad_b
w = torch.rand(2, 2, requires_grad=True)
x = torch.rand(2, 2, requires_grad=True)
b = torch.rand(2, 2, requires_grad=True)
out = line.apply(w, x, b)
out.backward(torch.ones(2, 2))
print(w, x, b)
print(w.grad, x.grad, b.grad)
3. torch.nn 库
-
torch.nn是专门为神经网络设计的模块化接口。
-
nn构建于autograd之上,可以用来定义和运行神经网络。
- nn.Parameter
- nn.Linear&nn.conv2d等等
- nn.functional
- nn.Module
- nn.Sequential
-
nn.Parameter
- 定义可训练参数
- self.my_ param = nn.Parameter(torch.randn(1))
- self.register_ parameter
- nn.ParameterList & nn.ParameterDict
-
nn.Linear&nn.conv2d&nn.ReLU&nn.MaxPool2d(2))&nn.MSELoss等等
- 各种神经网络层的定义,继承于nn.Module的子类
- self.conv1 = nn.Conv2d(1,6, (5,5))
- 调用时: self.conv1(x)
- 参数为parameter类型
- layer = nn.Linear(1,1)
- layer.weight = nn.Parameter(torch.FloatTensor([[0]]))
- layer.bias = nn.Parameter(torch.FloatTensor([0]))
- 各种神经网络层的定义,继承于nn.Module的子类
-
nn.functional
- 包含torch.nn库中所有函数,包含大量loss和activation function
- torch.nn.functional.conv2d(input, weight, bias=None,stride=1, padding=0, dilation=1, groups=1)
- torch.nn.conv2d 是一个类
- nn.functional.xxx是函数接口
- nn.functional.xxx无法与nn.Sequential结合使用
- 没有学习参数的(eg. maxpool, loss_func, activation func)等根据个人选择使用nn.functional.xxx或nn.Xxx 需要特别注意dropout层
- 包含torch.nn库中所有函数,包含大量loss和activation function
-
nn 与nn.functional有什么区别?.nn.functional.xxx是函数接口
- nn.Xxx是.nn.functional.xxx的类封装,并且nn.Xx×都继承于一个共同祖先 nn.Module
- nn.Xxx除了具有nn.functional.xxx功能之外,内部附带nn.Module相关的属性和方法,eg. train(), eval(),load_state_dict, state_dict
-
nn.Module
- 它是一个抽象概念,既可以表示神经网络中的某个层(layer),也可以表示一个包含很多层的神经网络
- model.parameters()
- model.buffers()
- model.state_dict()
- model.modules()
- forward(), to()
- https://pytorch.org/docs/stable/nn.html#torch.nn.Module
-
Parameters VS buffers
- 一种是反向传播需要被optimizer更新的,称之为parameter
- self.register_parameter(“param”, param)
- self.param = nn.Parameter(torch.randn(1))
- —种是反向传播不需要被optimizer更新,称之为buffer
- self.register_buffer(‘my_buffer’, torch.randn(1))
- 一种是反向传播需要被optimizer更新的,称之为parameter
-
state_dict() & load_state_dict
- 保存模型和加载模型
- torch.save(obj=model.state_dict(), f= “models/net.pth”)
- model.load_state_dict(torch.load(“models/net.pth”))
-
visdom : Facebook专门为Pytorch开发的一款可视化工具,开源于2017年3月,提供了大多数的科学运算可视化API:
- https://github.com/facebookresearch/visdom
- 支持数值(折线图,直方图等)、图像、文本以及视频等·支持Pytorch、Torch和Numpy
- 用户可以通过编程的方式组织可视化空间或者通过用户接口为数据打造仪表板,检查实验结果和调试代码。
- env:环境& pane:窗格
- 安装
- pip install visdom
- 启动服务
- python -m visdom.server
-
tensorboardX介绍
- scalar, image, figure, histogram, audio, text, graph,onnx_graph, embedding, pr_curve and videosummaries等不同的可视化展示方式
- pip3 install tensorboardX
- tensorboardX介绍
- scalar, image, figure, histogram, audio, text, graph,onnx_graph, embedding, pr_curve and videosummaries等不同的可视化展示方式
- pip3 install tensorboardX
- 使用方式
- 生成日志到指定的目录
- tensorboard --logdir 日志路径
from tensorboardX import SummaryWriter
# 定义文件路径
writer = SummaryWriter("log")
for i in range(100):
writer.add_scalar("a", i, global_step=i)
writer.add_scalar("b", i ** 2, global_step=i)
writer.close()
11488@DESKTOP-4KT7IH4 MINGW64 /g/SpellWorkSpace/PytorchSpace/pytorch-code-edu/base_api/log (master) $ tensorboard --logdir ./ 2021-10-15 10:24:01.331265: W tensorflow/stream_executor/platform/default/dso_loader.cc:59] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found 2021-10-15 10:24:01.331798: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine. Serving TensorBoard on localhost; to expose to the network, use a proxy or pass --bind_all TensorBoard 2.6.0 at http://localhost:6006/ (Press CTRL+C to quit)5. Torchvision介绍
- torchvision是独立于pytorch的关于图像操作的一些方便工具库。
- https://github.com/pytorch/vision
- https://pytorch.org/docs/master/torchvision/
- torchvision主要包括一下几个包:
- vision.datasets:几个常用视觉数据集,可以下载和加载
- vision.models:已经训练好的模型,例如: AlexNet, VGG,ResNet
- vision.transforms:常用的图像操作, 例如:随机切割, 旋转, 数据类型转换, 图像到tensor, numpy 数组到tensor, tensor到图像等
- vision.utils、vision.io、vision.ops



