一、Pytorch第一步
1. 函数名后加"_"会修改Tensor本身,如加法的两种表达形式:y.add(x) 和 y.add_(x),前者不改变y的值,后者改变了y的值。
2. Tensor和Numpy的数组之间的互操作非常容易且快速,对于Tensor不支持的操作,可以先转化为Numpy数组尽力,之后再转回Tensor。且二者的对象共享内存,使得其转换很快,几乎不会消耗什么资源,但是这也意味着其中一个变了,另外一个也会随之改变。
import torch as t
import numpy as np
a = np.ones(5)
b = t.from_numpy(a)
print(a)
print(b)
b.add_(1)
print(a)
print(b)
3. 获取某个元素的值可以使用scalar.item。直接使用Tensor[idx]得到的还是一个Tensor,而scalar一般是指0-dim的tensor。
scalar = b[0]
scalar
scalar.size()
scalar.item()
tensor = t.tensor([2])
tensor, scalar #二者的区别
tensor.size(), scalar.size()
tensor.item(), scalar.item() #只有一个元素的tensor也可以使用item
4. torch.tensor接口yunp.array类似
5. torch.tensor()和tensor.clone()总会拷贝数据,新的tensor和原来的数据不共享内存;而想要共享内存,可以使用torch.from_numpy()或者tensor.detach()。
old_tensor = tensor
new_tensor = old_tensor.clone()
new_tensor[0] = 1111
old_tensor, new_tensor
new_tensor = old_tensor.detach()
new_tensor[0] = 1111
old_tensor, new_tensor
6. Tensor可以通过.cuda的方式转化为GPU的Tensor,从而来加速:
device = t.device("cuda:0" if t.cuda.is_available() else "cpu)
x = x.to(device)
y = y.to(device)
z = x+y
二、autograd:自动微分
1. 自动使用autograd功能,只需设置tensor.requires_grad=True。Variable主要包含三个属性:(1)data:保存Variable所包含的Tensor;(2)grad:保存data对应的梯度,它也是个Variable,而不是Tensor,与data的形状是一样的;(3)grad_fn:指向一个Function对象,这个Function用来反向传播计算输入的梯度。
x = t.ones(2, 2, requires_grad=True)
y = x.sum()
y
y.grad_fn
y.backward() #反向传播,计算梯度,x内每个元素的梯度均为1
x.grad
2. grad在反向传播的过程中是累加的,也就是说每一次运行反向传播,梯度都会累加之前的梯度,所以传播之前需要把