CV第八课 PyTorch

PyTorch的三个抽象层次

Tensor: 可以认为是 可以运行在GPU上的 numpy的array

    通过 dtype = torch.cuda.FloatTensor

      x = torch.randn(N,D_in).type(dtype) 使得在GPU上运行。

 

 Variable:  Node in a computational graph, 存储数据与梯度 data and gradient

  1.设输入  x = Variable(torch.randn(N,D_in),requires_grad=False)

     则 x.data is a Tensor ;     x.grad is a Variable of gradients;       x.grad.data is a Tensor of gradients

  2.  Variable 和 tensor 有相同的API 

  3. Variable 通过参数 requires_grad = True 就可以计算 weight matrix 的梯度

  4. 每一次计算梯度前,要将上一次梯度清空 ,而且要记得要先判断,不然会报错 None type has no  attribute data

    if w1.grad:  w1.grad.data.zero_()

Module: torch.nn

  1. 像keras 一样的高级封装好的API,不需要打出computational graph

猜你喜欢

转载自www.cnblogs.com/ChevisZhang/p/12969547.html