我有一门课,我想用 Numba 加快速度。该类通过简单地创建具有特定种子的 NumPy 的 RandomState 实例来为每个实例使用“随机数生成器”(因此我可以稍后复制我的工作)。当我使用 Numba 的 autojit 时,我得到一个奇怪的错误,它不会出现在“常规”Python 中。
幸运的是,这种行为非常容易复制。这是一个说明错误的简单示例:
from numpy.random import RandomState
from numba import autojit
# ------- This works in "regular Python" ------------
class SillyClass1(object):
def __init__(self, seed):
self.RNG = RandomState(seed)
def draw_uniform(self):
return self.RNG.uniform(0,1)
test1 = SillyClass1(123456)
test1.draw_uniform()
# Output:
# 0.12696983303810094
# The following code -- exactly the same as above, but with the @autojit
# decorator, doesn't work, and throws an error which I am having a hard
# time understanding how to fix:
@autojit
class SillyClass2(object):
def __init__(self, seed):
self.RNG = RandomState(seed)
def draw_uniform(self):
return self.RNG.uniform(0,1)
test2 = SillyClass2(123456)
test2.draw_uniform()
# Output:
#
# ValueError Traceback (most recent call last)
# <ipython-input-86-a18f95c11a1b> in <module>()
# 10
# 11
# ---> 12 test2 = SillyClass2(123456)
# 13
# 14 test2.draw_uniform()
#
# ...
#
# ValueError: object of too small depth for desired array
我在 Ubuntu 13.10 上使用 Anaconda 发行版。
有什么想法吗?
编辑:我找到了一种解决方法,即简单地使用 Python 的标准“random.Random”而不是 NumPys 的“numpy.random.RandomState”
例子:
from random import Random
@autojit
class SillyClass3(object):
def __init__(self, seed):
self.RNG = Random(seed)
def draw_uniform(self):
return self.RNG.uniform(0,1)
test3 = SillyClass3(123456)
test3.draw_uniform()
# Output:
# 0.8056271362589
这适用于我的直接应用程序(尽管其他问题立即出现,万岁)。
但是,此修复不适用于我知道我需要使用 numpy.random.RandomState 的未来算法。所以我的问题仍然存在——是否有人对在 Numba 中使用 numy.random.RandomState 的原始错误和/或解决方法有任何见解?