如何替换神经网络权重中的 NaN 值?

How to replace NaN values in the weights of neural network?

我正在尝试用一些常量替换权重中的 NaN 值。但是我不知道如何做到这一点。

我知道要访问权重,我必须写。

for i in model.params:
    arr = i.clone()
    arr[torch.isnan(arr)] = 0
    param_list.append(nn.Parameter(arr))
    
model.params= param_list

但这破坏了计算图,你有什么更好的方法可以建议我这样做吗?

怎么样

with torch.no_grad():
  for p in model.parameters():
    p.data[torch.isnan(p.data)] = 0