https://pytorch.org/tutorials/beginner/pytorch_with_examples.html
这篇博客主要是介绍了tensor的概念、求导的方法、autograd的使用。
Tensors
使用类似于 numpy的array ,Pytorch提供一系列关于Tensor的操作。Tensor记录计算图和梯度,也可以作为科学计算的工具。
tensor.item() # 返回值a = torch.nn.Parameter(torch.randn(())) # 定义变量#定义可梯度的tensora = torch.full((), 0.0, device=device, dtype=dtype, requires_grad=True)注意:这两个a是有区别的,Parameter会自动绑定在网络的参数空间。
Autograd
定义地网络,继承 torch.nn.Module 模块,需要实现 forward方法
脚手架如下:
import torchclass Net(torch.nn.Module):def __init__(self):super().__init__()"""网络参数定义torch.nn.Parameter"""def forward(self,x):"""使用网络对 输入进行操作"""# 指定损失函数loss_fun = torch.nn.MSELoss(reduction='sum')# 指定求解器model = Net()optimizer = torch.optim.SGD(model.parameters(), lr=1e-6)for t in range(epcho):y_pred = model(x) # 预测loss = loss_fun(y_pred,y)if t%5 ==0:print(t,loss.item())optimizer.zero_grad() # 清零梯度loss.backward() # 计算梯度optimizer.step() #更新梯度
