pytorch使用注意事项
1. Numpy与Tensor相互转换
2. 梯度
2.1 设置梯度
可以使用以下两种方式设置梯度:
#方法一
x = torch.ones(2, 2, requires_grad=True)
#方法二
x.requires_grad_(True)
2.2 禁止autograd进行计算
2.3 梯度累加
2.4 梯度传值
3. 线性回归
def data_iter(batch_size,features,labels):
num_examples=len(features)
indices=list(range(num_examples))
random.shuffle(indices)#样本读取数据随机
for i in range(0,num_examples,batch_size):
j=torch.LongTensor(indices[i:min(i+batch_size,num_examples)])#最后一次可能不足一个batch_size
yield features.index_select(0,j),labels.index_select(0,j)#0,是按行索引,j是索引的行数。