pytorch使用注意事项

欢迎关注

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是索引的行数。

index_select使用方法

yield的使用方法(推荐)

发布了17 篇原创文章 · 获赞 7 · 访问量 1446

猜你喜欢

转载自blog.csdn.net/qq_40211493/article/details/103950766
今日推荐