如何详细解析PyTorch中梯度计算与backward方法的原理和应用?
- 内容介绍
- 文章标签
- 相关推荐
本文共计1067个文字,预计阅读时间需要5分钟。
基础知识+tensors:在PyTorch中,tensor是一维或多维数组。我们可以通过指定参数reuqires_grad=True来创建一个可反向传播的tensor,从而计算梯度。PyTorch中的动态计算图(DCG)通常称为动态。
基础知识
tensors:
tensor在pytorch里面是一个n维数组。我们可以通过指定参数reuqires_grad=True来建立一个反向传播图,从而能够计算梯度。在pytorch中一般叫做dynamic computation graph(DCG)——即动态计算图。
import torch import numpy as np # 方式一 x = torch.randn(2,2, requires_grad=True) # 方式二 x = torch.autograd.Variable(torch.Tensor([2,3]), requires_grad=True) #方式三 x = torch.tensor([2,3], requires_grad=True, dtype=torch.float64) # 方式四 x = np.array([1,2,3] ,dtype=np.float64) x = torch.from_numpy(x) x.requires_grad = True # 或者 x.requires_grad_(True)
note1:在pytorch中,只有浮点类型的数才有梯度,故在方法四中指定np数组的类型为float类型。
本文共计1067个文字,预计阅读时间需要5分钟。
基础知识+tensors:在PyTorch中,tensor是一维或多维数组。我们可以通过指定参数reuqires_grad=True来创建一个可反向传播的tensor,从而计算梯度。PyTorch中的动态计算图(DCG)通常称为动态。
基础知识
tensors:
tensor在pytorch里面是一个n维数组。我们可以通过指定参数reuqires_grad=True来建立一个反向传播图,从而能够计算梯度。在pytorch中一般叫做dynamic computation graph(DCG)——即动态计算图。
import torch import numpy as np # 方式一 x = torch.randn(2,2, requires_grad=True) # 方式二 x = torch.autograd.Variable(torch.Tensor([2,3]), requires_grad=True) #方式三 x = torch.tensor([2,3], requires_grad=True, dtype=torch.float64) # 方式四 x = np.array([1,2,3] ,dtype=np.float64) x = torch.from_numpy(x) x.requires_grad = True # 或者 x.requires_grad_(True)
note1:在pytorch中,只有浮点类型的数才有梯度,故在方法四中指定np数组的类型为float类型。

