【问题标题】:Fast way to Hash Numpy objects for Caching散列 Numpy 对象以进行缓存的快速方法
【发布时间】:2011-07-20 04:35:47
【问题描述】:

实施一个系统,当涉及繁重的数学工作时,我希望尽可能少做。

我知道 numpy 对象的记忆存在问题,因此实现了惰性键缓存以避免整个“过早优化”参数。

def magic(numpyarg,intarg):
    key = str(numpyarg)+str(intarg)

    try:
        ret = self._cache[key]
        return ret
    except:
        pass

    ... here be dragons ...
    self._cache[key]=value
    return value

但是由于字符串转换需要相当长的时间...

t=timeit.Timer("str(a)","import numpy;a=numpy.random.rand(10,10)")
t.timeit(number=100000)/100000 = 0.00132s/call

人们认为什么是“更好的方法”?

【问题讨论】:

标签: python performance numpy


【解决方案1】:

this answer借来的...所以真的我猜这是重复的:

>>> import hashlib
>>> import numpy
>>> a = numpy.random.rand(10, 100)
>>> b = a.view(numpy.uint8)
>>> hashlib.sha1(b).hexdigest()
'15c61fba5c969e5ed12cee619551881be908f11b'
>>> t=timeit.Timer("hashlib.sha1(a.view(numpy.uint8)).hexdigest()", 
                   "import hashlib;import numpy;a=numpy.random.rand(10,10)") 
>>> t.timeit(number=10000)/10000
2.5790500640869139e-05

【讨论】:

  • 不错!对于多维数组,这会给出不同的散列(对于“相同”数组),具体取决于它是 fortran 还是 c 连续。如果这是个问题,拨打np.ascontiguousarray 应该可以解决。
  • 不知道为什么选择一个已知的慢散列函数sha1。 SHA-1 可以最大限度地减少哈希冲突,但速度很差。为了速度,您需要murmurhashxxhash 之类的东西(后者声称更快)。
  • @CongMa,感谢您提供的额外信息。有很多选择!但是您会注意到,这已经快了两个数量级。速度从来都不是唯一的问题。如果替代方案的速度只有百万分之几秒,那么使用易于理解的散列可能是值得的。
【解决方案2】:

有一个名为joblib 的包。发现自this问题。

from joblib import Memory
location = './cachedir'
memory = Memory(location)

# Create caching version of magic
magic_cached = memory.cache(magic)
result = magic_cached(...)

# Or (for one-time use)
result = memory.eval(magic, ...)

【讨论】:

  • 最好在您的答案中复制这些链接的报价,以防这些网站离线。
【解决方案3】:

对于小型 numpy 数组,这也可能是合适的:

tuple(map(float, a))

如果a 是 numpy 数组。

【讨论】:

  • 哦,是的,与列表相比,元组是可散列的!
猜你喜欢
  • 1970-01-01
  • 2017-08-18
  • 2019-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多