python - 测量 `UnboundLocalError`的时间时出现 `torch.where`错误

标签 python time error-handling pytorch

在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/

相关文章:

python - 获取 Pandas 中 2 个相应系列的最小和最大元素

python - 如何获取 python pandas 数据框中值的不同计数

Java随时间递减

python - 问 : Python 3: Why bytearray element comparison b'ABC'[0] == b'A' equals False?

python - pandas - 创建客户移动矩阵

c++ 获取用户选择的日期和实际日期之间的年数(计算天数、月数、年数)

c# - 使用 Noda Time 将奥尔森时区 ID 转换为 Windows 标准格式

objective-c - 在数据库类iPhone中使用异常

javascript - 在 Facebook API 中输入错误代码 191 - 我做错了什么?

python - CRITICAL :root:twint. 得到什么 :User: Error mean?