记住NumPy矢量化函数

luf*_*ffe 2 python numpy

我有一个函数is_prime(n),如果n是素数则返回True,否则返回False.在NumPy中我循环,检查数组是否包含素数,并且每次迭代时数组的开始都是相同的,所以我想记住is_prime(n)函数以避免大量不必要的计算.

由于我有一个数组,我想向量化is_prime(n),所以我可以逐个元素,NumPy样式应用于数组.我使用NumPy教程中的一行(稍后显示)执行此操作

我还使用了网上找到的memoization模板:

def memoize(function):
    cache = {}
    def decorated_function(*args):
        if args in cache:
            return cache[args]
        else:
            val = function(*args)
            cache[args] = val
            return val
    return decorated_function
Run Code Online (Sandbox Code Playgroud)

然后:

is_prime = memoize(is_prime)
Run Code Online (Sandbox Code Playgroud)

但是,如果我现在对memoized is_prime函数进行矢量化,那么V_prime现在是否已正确记忆?:

V_prime = np.vectorize(is_prime)
Run Code Online (Sandbox Code Playgroud)

谢谢

Sam*_*lar 5

好吧,让我们测试吧.

import numpy as np

def test(input):
    return input

def memoize(function):
    cache = {}
    def decorated_function(*args):
        if args in cache:
            print 'cached'
            return cache[args]
        else:
            print 'not cached'
            val = function(*args)
            cache[args] = val
            return val
    return decorated_function

test = memoize(test)
print test(9)
print test(9)
test = np.vectorize(test)
print test(9)
print test(10)
print test(10)
Run Code Online (Sandbox Code Playgroud)

我在我的机器上得到这个.

not cached
9
cached
9
cached
cached
9
not cached
10
cached
10
Run Code Online (Sandbox Code Playgroud)

所以是的,它是memoize,在我的机器上使用numpy 1.6.1

  • 没问题,memoization很酷,虽然要小心,因为它可以消耗相当多的内存,具体取决于你正在使用的对象类型......人们倾向于使用专用对象而不是字典来控制/监视内存并销毁/当内存不足或者有时没有访问它们时删除对象. (3认同)