pytorch基础

1.训练时顺序

    #第一种写法
    
    #梯度置零,也就是把loss关于weight的导数变成0
    optimizer.zero_grad()
    
    #前馈计算输出和损失
    outputs = net(images)
    loss = criterion(outputs, labels)
    
    #反向传播
    loss.backward()
    optimizer.step()

	#第二种写法
	
	#前馈计算输出和损失
	outputs = net(images)
	loss = criterion(outputs, labels)
    
    #梯度置零,也就是把loss关于weight的导数变成0
    optimizer.zero_grad()
    
    #反向传播
    loss.backward()
    optimizer.step()
不管哪种写法,都是最后进行反向传播,至于梯度置0和前馈计算谁先谁后都行。

2.使用gpu

#1.设置decive,下面是一些常用的写法
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
device = torch.device('cuda:0') or  device = torch.device('cuda',0)
device = torch.device('cuda',1)  or torch.device('cpu',0)   
    
#2.定义的损失需要放到gpu中,用.to(device)
self.bce_with_logits_loss = nn.BCEWithLogitsLoss().to(device)

#3.模型需要放到gpu中,用.to(device)
model = NeuralNet().to(device)

for i, (images, labels) in enumerate(train_loader):
	#4.训练的images和labels需要放到gpu中,用.to(device)
    images = images.reshape(-1, 28 * 28).to(device)
    labels = labels.to(device)
对于1.0及以上版本使用 .to(device),低版本的可能会使用.cuda(),作用是一样的。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章