来源:https://www.pytorchtutorial.com/pytorch-note1-what-is-pytorch/
参数
pytorch中有两种变量类型,一种是Tensor,一种是Variable。
Tensor:就像ndarray一样,一维Tensor叫Vector,二维Tensor叫Matrix,三维及以上称为Tensor。
Variable:是Tensor的一个wrapper,不仅保存了值,而且保存了这个值的creator,需要BP的网络都是Variable参与运算
1 | import torch |
输出的结果分别是
1 | tensor([[[0.0000, 0.0000, 0.0000, 0.0000], |
1 | a = torch.rand(2,3,4) |
两者相加,如下:
1 | tensor([[[0.7871, 0.1009, 0.8869, 0.1064], |
自动求导
pytorch的自动求导工具包在torch.autograd中
1 | from torch.autograd import Variable |
输出为:
1 | tensor([0.6657, 0.3089, 0.6539, 0.0688, 0.5952], requires_grad=True) |
神经网络
使用torch.nn包中的工具来构建神经网络 需要以下几步:
1.定义神经网络的权重,搭建网络结构
2.遍历整个数据集进行训练
3.将数据输入神经网络
4.计算loss
5.计算网络权重的梯度
6.更新网络权重:weight = weight + learning_rate*gradient
网络整体如下:
1 | import torch.nn as nn |