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(),作用是一樣的。