`
@torch.no_grad()
def evalarc(model,dataloader):
val_loss=0.0
for images,labels in tqdm(dataloader):
.
.
.
`
对
`
def evalarc(model,dataloader):
val_loss=0.0
with torch.no_grad():
for images,labels in tqdm(dataloader):
.
.
.
`
两者有什么区别?如果我在两者之间切换会有什么变化吗?
@torch.no_grad()
是一个函数装饰器,它包装了整个函数,因此函数内部发生的所有事情都是在没有梯度跟踪的情况下完成的。
with torch.no_grad()
删除 with torch.no_grad()
块内代码的梯度跟踪。
当您希望函数中的所有内容在没有梯度跟踪的情况下发生时,您可以使用
@torch.no_grad()
,或者当您只想从函数的特定部分删除梯度跟踪时,可以使用 with torch.no_grad()
。