python - 迭代后清除memoized函数缓存?

时间:2015-12-07 03:33:44

标签: python algorithm caching igraph memoization

我编写了一些代码,试图近似最小化反馈弧顶点的顶点排名/最大化有向图(最多n = 100个节点)的最大非循环子图,使用此处提到的一系列启发式算法和算法论文为反馈弧排序启发式算法 由德国帕绍大学的Franz J. Brandenburg和Kathrin Hanauer设定问题。

读入的数据是一个邻接矩阵,可以转换为igraph.Graph实例。

我正在记忆成本函数和筛选功能。两个函数的参数是一个rank(包含顶点排序的元组)和edgeList(包含表示边的元组的元组)。

由于我一次处理多个实例并且顶点由整数表示,我需要确保在处理一个实例(图形)后清除两个函数的缓存并且我不完全确定这是发生了。我发现了一些memoize定时缓存实现和memoize with _remove方法,虽然我一直得到相同的结果。

这是针对今天早些时候到期的项目(2015年6月12日下午5:00),但是和我一样顽固,我一直在努力,并希望确保我正确使用memoize方法。

我附上了我用过的相关代码:

@memoize
def cost(rank, edgeList):
    rankMap = {} 
    for i in range(len(rank)):
        rankMap[rank[i]] = i
    cost = 0
    for edge in edgeList:
        u, v = edge[0], edge[1]
        if rankMap[u] < rankMap[v]:
            cost += 1
    return cost

class memoize:

    """Gives the class it's core functionality."""
    def __call__(self, *args):
        if args not in self._memos:
            self._memos[args] = self._function(*args)
        return self._memos[args]

    def __init__(self, function):
        self._memos = {}
        self._function = function

    """Removes all memos. This is particularly useful if something that     affects the output has changed."""
    def remove_memos(self):
        self._memos = {}

def alg_star(algorithm, costFunc, graph, rank):
    edgeList = tuple([i.tuple for i in graph.es()])
    while True:
        rankPrime = rank
        rank = algorithm(tuple(rank), edgeList)
        if costFunc(tuple(rank), edgeList) <= costFunc(tuple(rankPrime), edgeList):
            break
    return rankPrime


@memoize
def sifting(rank, edgeList):
    copyRank = list(rank)
    rankValues = {}
    for node in rank:
        rankValues[tuple(copyRank)] = cost(tuple(copyRank), edgeList)
        for i in range(1,len(copyRank)):
            copyRank[i-1], copyRank[i] = copyRank[i], copyRank[i-1]
            rankValues[tuple(copyRank)] = cost(tuple(copyRank), edgeList)
        copyRank = list(argMax(rankValues))
    return copyRank

# def evaluateFAS(fileNameList):
rankings = []
for fileName in fileList:
print fileName
adjMatrix, incoming, outgoing = fasGraph(fileName)
instance = igraph.Graph.Adjacency(adjMatrix.tolist())
pre_process(instance)
# rank = kss200(instance)
rank = fasAlg(adjMatrix, incoming, outgoing)
rank = alg_star(sifting, cost, instance, rank)
rank = np.array(rank) + 1
rankings.append(rank)
cost.remove_memos() #not sure if working properly
sifting.remove_memos() # not sure if working properly
# return rankings

非常感谢任何帮助和指导。

1 个答案:

答案 0 :(得分:0)

对我来说没问题。让我们试一试吧

class memoize:

    """Gives the class it's core functionality."""
    def __call__(self, *args):
        if args not in self._memos:
            self._memos[args] = self._function(*args)
        return self._memos[args]

    def __init__(self, function):
        self._memos = {}
        self._function = function

    """Removes all memos. This is particularly useful if something that     affects the output has changed."""
    def remove_memos(self):
        self._memos = {}


@memoize
def f(x, y):
    print('f')
    return x + y

@memoize
def g(x, y):
    print('g')
    return x * y

print(f(2,3))
print(f(2,3))
print(g(2,3))
print(g(2,3))
print(f._memos)
print(g._memos)
f.remove_memos()
g.remove_memos()
print(f._memos)
print(g._memos)

输出

f
5
5
g
6
6
{(2, 3): 5}
{(2, 3): 6}
{}
{}

为什么你认为它没有正常工作?