在 PyTorch 中打印每个时期的验证损失
Print the validation loss in each epoch in PyTorch
我想在每个 epoch 中打印模型的验证损失,获取和打印验证损失的正确方法是什么?
是这样的吗:
criterion = nn.CrossEntropyLoss(reduction='mean')
for x, y in validation_loader:
optimizer.zero_grad()
out = model(x)
loss = criterion(out, y)
loss.backward()
optimizer.step()
losses += loss
display_loss = losses/len(validation_loader)
print(display_loss)
或者像这样
criterion = nn.CrossEntropyLoss(reduction='mean')
for x, y in validation_loader:
optimizer.zero_grad()
out = model(x)
loss = criterion(out, y)
loss.backward()
optimizer.step()
losses += loss
display_loss = losses/len(validation_loader.dataset)
print(display_loss)
还是别的?谢谢。
没有!!!!
在任何情况下都不应使用验证/测试数据训练模型(即调用 loss.backward()
+ optimizer.step()
)!!!
如果您想验证您的模型:
model.eval() # handle drop-out/batch norm layers
loss = 0
with torch.no_grad():
for x,y in validation_loader:
out = model(x) # only forward pass - NO gradients!!
loss += criterion(out, y)
# total loss - divide by number of batches
val_loss = loss / len(validation_loader)
请注意 optimizer
如何与在验证集上评估模型无关。
您不根据验证数据更改模型 - 仅验证它。
我想在每个 epoch 中打印模型的验证损失,获取和打印验证损失的正确方法是什么?
是这样的吗:
criterion = nn.CrossEntropyLoss(reduction='mean')
for x, y in validation_loader:
optimizer.zero_grad()
out = model(x)
loss = criterion(out, y)
loss.backward()
optimizer.step()
losses += loss
display_loss = losses/len(validation_loader)
print(display_loss)
或者像这样
criterion = nn.CrossEntropyLoss(reduction='mean')
for x, y in validation_loader:
optimizer.zero_grad()
out = model(x)
loss = criterion(out, y)
loss.backward()
optimizer.step()
losses += loss
display_loss = losses/len(validation_loader.dataset)
print(display_loss)
还是别的?谢谢。
没有!!!!
在任何情况下都不应使用验证/测试数据训练模型(即调用 loss.backward()
+ optimizer.step()
)!!!
如果您想验证您的模型:
model.eval() # handle drop-out/batch norm layers
loss = 0
with torch.no_grad():
for x,y in validation_loader:
out = model(x) # only forward pass - NO gradients!!
loss += criterion(out, y)
# total loss - divide by number of batches
val_loss = loss / len(validation_loader)
请注意 optimizer
如何与在验证集上评估模型无关。
您不根据验证数据更改模型 - 仅验证它。