'''@torch.no_grad()''' 和 '''with torch.no_grad()''' 有什么区别

问题描述 投票:0回答:1

`

@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):
     .
     .
     . 

`

两者有什么区别?如果我在两者之间切换会有什么变化吗?

pytorch eval gradient
1个回答
0
投票

@torch.no_grad()
是一个函数装饰器,它包装了整个函数,因此函数内部发生的所有事情都是在没有梯度跟踪的情况下完成的。

with torch.no_grad()
删除
with torch.no_grad()
块内代码的梯度跟踪。

当您希望函数中的所有内容在没有梯度跟踪的情况下发生时,您可以使用

@torch.no_grad()
,或者当您只想从函数的特定部分删除梯度跟踪时,可以使用
with torch.no_grad()

© www.soinside.com 2019 - 2024. All rights reserved.