[英]IPython.parallel namespaces
我想使用IPython.parallel并行化一个函数,当我在IPython shell中定义它时,它可以完美地工作:
Type: function
Base Class: <type 'function'>
String Form:<function gradient at 0x3ae0398>
Namespace: Interactive
File: /root/<ipython-input-30-cf7eabdfef84>
Definition: gradient(w)
Source:
def gradient(w):
s = (1.0 + exp(y * (X * w)))**-1
return C*X.T*((1 - s) * y)
rc = Client()
rc[:].apply_sync(gradient, w)
...
但是,当我在模块中定义它并使用import时:
Type: function
Base Class: <type 'function'>
String Form:<function gradient at 0x3933d70>
Namespace: Interactive
File: /root/mv.py
Definition: mv.gradient(w)
Source:
def gradient(w):
s = (1.0 + exp(y * (X * w)))**-1
return C*X.T*((1 - s) * y)
import mv
rc = Client()
rc[:].apply_sync(mv.gradient, w)
CompositeError: one or more exceptions from call to method: gradient
[0:apply]: NameError: global name 'y' is not defined
[1:apply]: NameError: global name 'y' is not define
此外,它运行Python 2.7.2 / IPython 0.12的本地系统工作正常,而使用最新的Starcluster Ubuntu AMI在Python 2.7.2 + / IPython 0.12上崩溃。
这里发生了什么?
更新:我从github安装了IPython 0.13.dev版本,现在它可以工作了。
不同之处在于模块全局变量。 在模块中定义函数时,全局名称空间是模块的名称空间(即mv.y
)。 当该模块是__main__
,例如交互式定义的函数,则全局命名空间是Engine上的user_ns,并受execute("y=5")
。
IPython提供了一个装饰器,如果你想在模块中定义函数,这些函数应该像交互式定义一样(可以作为全局变量访问用户命名空间):
# mymod from IPython.parallel.util import interactive @interactive def by_a(b): """multiply a by b" return a*b
交互式地,您可以:
from mymod import by_a e0 = rc[0] e0.execute("a=5") print e0.apply_sync(by_a, 10) # 50 e0.execute("a=10") print e0.apply_sync(by_a, 10) # 100
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.