Skip to main content
 首页 » 编程设计

python之数字表达式错误 : "a = global_dict[name]"

2025年05月04日12飞鱼

我正在尝试使用 Numexpr 快速计算 Vector Norm与 Numpy's 比较的函数.我尝试以下操作:

import numexpr as ne 
import numpy as np 
 
def L2_Norm(vector_in): 
    vector1 = ne.evaluate("abs(vector_in)") 
    vector2 = ne.evaluate("vector1**2") 
    vector3 = ne.evaluate("sum(vector2)") 
    vector_out = ne.evaluate("sqrt(vector3)") 
    return vector_out` 
 
ve = np.arange(10) 
L2_Norm(ve) 

我明白了:

File "C:\Folder1\Folder2\src\test.py", line 11, in L2_Norm 
  vector3 = ne.evaluate("sum(vector2)")<br> 
File "C:\Python27\lib\site-packages\numexpr\necompiler.py", line 701, in evaluate 
  a = global_dict[name]<br> 
KeyError: 'a' 

我在他们的 User Guide 上基本上遵循了相同的步骤(这似乎是唯一的引用)。我唯一的线索是:

umexpr's principal routine is this:
evaluate(ex, local_dict=None, global_dict=None, **kwargs)

where ex is a string forming an expression, like "2*a+3*b". The values for a and b will by default be taken from the calling function's frame (through the use of sys._getframe()). Alternatively, they can be specified using the local_dict or global_dict arguments, or passed as keyword arguments

...我不太明白 - 我假设作者保持简单,因为包很简单。我忽略了什么?

请您参考如下方法:

原来“local_dict=None, global_dict=None”参数毕竟不是默认值。您需要专门将它们添加到您的 numexpr.evaluate 函数中。