Python 树冠 NumPy : Running the code by pressing "Play" doesn't give the same result as copying and pasting the code in the command line

标签 python numpy canopy

我现在运行 Enthought Canopy 1.4.1 64 位一年了。 出于某种原因,我刚刚编写的代码在按下“播放”按钮时生成完全不同的图表(使用 matplotlib),与将代码复制并粘贴到命令行并按下 Enter 相比。

特别是,下面一行会产生两个不同的结果:

w1 = array(dot(matrix(C).I,R - 0.03)/sum(dot(matrix(C).I,R - 0.03)))[0]

当按下播放键时,我得到:

w1
Out[7]: array([ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.])

当复制和粘贴完全相同的代码并按 Enter 时,我得到:

w1
Out[9]: 
array([-0.53497564,  0.77325699,  0.3289724 ,  0.2127899 ,  0.29026341,
        0.18743744, -0.24510907, -0.1117449 , -0.2534066 ,  0.15694775,
        0.19556833])

我认为这就是我的图表困惑的原因,有人知道为什么会这样吗?

最佳答案

在没有看到您的其余代码的情况下,最有可能的候选者是 sum

  • 在 vanilla python 中(当您的脚本运行时),sum 是 python 内置函数,它不知道 numpy 数组。

  • 在 IPython 的 Pylab 模式中(在 Canopy 的 ipython 提示符下),它隐含地以 from numpy import * 开头(非常令人困惑,这也是 IPython 团队现在不鼓励使用他们的原因之一Pylab 模式,我猜 Canopy 不久就会采用),sum 是 numpy 函数,它的行为完全不同。

查找这两个 sum 函数,并尝试在脚本中使用 numpy.sum 而不是 sum

更多上下文:

@Senderle 对您的问题的第一条评论指出了对 ipython 中几乎所有此类差异的更一般性解释——当您运行脚本时,它不知道全局 ipython 命名空间中的任何值。当脚本运行时,默认情况下,它的全局命名空间被插入到您的 ipython 命名空间中,但反之则不然。因此 Ipython 命令可以检查正在运行的脚本的结果,但是正在运行的脚本无法查看/使用之前在 IPython 提示符下定义的值(包括导入)(除非它们被显式传递给正在运行的脚本)。

最常见的示例是本文中描述的示例: Modules are already available in Canopy's Python (PyLab) prompt, but not in a script ,但它也适用于 senderle 指向的数据值。

所以回到你的问题——你(或 Pylab 启动)在 IPython 提示符下定义了一些在运行脚本中没有以相同方式定义的东西的可能性是 100 比 1,这就是差异的原因.如果它不是sum,那么我建议你把它缩小到最简单的可能情况(只有几行),然后它就会跳出来;如果没有,您可以将其张贴在这里,它会跳到其他人身上。

关于Python 树冠 NumPy : Running the code by pressing "Play" doesn't give the same result as copying and pasting the code in the command line,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26407464/

相关文章:

python - 对键上的嵌套字典进行排序

python - 使用计数器的 While 循环

python - 用numpy数组中的最近邻居填充nan

python - 为多索引数据框更改热图的 yticks

python - np.exp() 的数值问题

python - 为什么 Python 不预先构建所需的库,如 pandas、numpy 等

python - numpy 一维数组 : mask elements that repeat more than n times

python - Keras 似乎在调用 fit_generator 后挂起

python - Visual Studio 2015 中的 TensorFlow,使用 Canopy 作为 Python 环境

Python Canopy 内核不断崩溃