gpt4 book ai didi

python - IPython.parallel 命名空间

转载 作者:行者123 更新时间:2023-11-30 23:43:58 24 4
gpt4 key购买 nike

我想使用 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)
...

但是,当我在模块中定义它并使用导入时:

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 提供了一个装饰器,如果您想在模块中定义函数,这些函数的行为应该像交互式定义一样(可以作为全局变量访问用户命名空间):

# mymodfrom IPython.parallel.util import interactive@interactivedef by_a(b):    """multiply a by b"    return a*b

并且以交互方式,您可以执行以下操作:

from mymod import by_ae0 = rc[0]e0.execute("a=5")print e0.apply_sync(by_a, 10) # 50e0.execute("a=10")print e0.apply_sync(by_a, 10) # 100

关于python - IPython.parallel 命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10461774/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com