在Jupyter Notebook中尝试%timeit
时出现错误;没有它,工作正常。
UnboundLocalError: local variable 'a' referenced before assignment
import torch
a = torch.rand(10)
b = torch.rand(10)
%timeit a = torch.where(b > 0.5, torch.tensor(0.), a)
这是怎么回事
最佳答案
起初,我认为这是因为%timeit
仅评估函数运行的时间。但是感谢@Shiva告诉我它可以计算其他事物的执行时间。我检查了文档here,发现这是真的。
因此,根据此answer,%timeit
存在重新分配问题,因为重新分配给a
会使函数具有a
局部变量,从而隐藏了全局变量。换句话说,您可以使用a
以外的任何其他变量将其分配给torch.where
:
#this works
%timeit c = torch.where(b > 0.5, torch.tensor(0.), a) #c instead of a
# this works
%timeit torch.where(b > 0.5, torch.tensor(0.), a)
# this doesn't work
%timeit a = torch.where(b > 0.5, torch.tensor(0.), a)
关于python - 测量 `UnboundLocalError`的时间时出现 `torch.where`错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62004680/