【问题标题】:ordered reduce for multiple functions in pythonpython中多个函数的有序reduce
【发布时间】:2016-08-03 01:45:58
【问题描述】:

有序列表缩减

我需要减少一些列表,其中取决于元素类型,二元运算的速度和实现会有所不同,即通过首先减少一些具有特定功能的对可以大幅降低速度。 例如foo(a[0], bar(a[1], a[2])) 可能比bar(foo(a[0], a[1]), a[2]) 慢很多,但在这种情况下给出相同的结果。

我已经有代码以元组列表(pair_index, binary_function) 的形式生成最佳排序。我正在努力实现一个有效的函数来执行归约,理想情况下,它返回一个新的部分函数,​​然后可以在相同类型排序但不同值的列表上重复使用。

简单而缓慢(?)的解决方案

这是我的简单解决方案,涉及 for 循环、删除元素和关闭 (pair_index, binary_function) 列表以返回“预计算”函数。

def ordered_reduce(a, pair_indexes, binary_functions, precompute=False):
    """
    a: list to reduce, length n
    pair_indexes: order of pairs to reduce, length (n-1)
    binary_functions: functions to use for each reduction, length (n-1)
    """
    def ord_red_func(x):
        y = list(x)  # copy so as not to eat up
        for p, f in zip(pair_indexes, binary_functions):
            b = f(y[p], y[p+1])
            # Replace pair
            del y[p]
            y[p] = b
        return y[0]

    return ord_red_func if precompute else ord_red_func(a)

>>> foos = (lambda a, b: a - b, lambda a, b: a + b, lambda a, b: a * b)
>>> ordered_reduce([1, 2, 3, 4], (2, 1, 0), foos)
1
>>> 1 * (2 + (3-4))
1

以及预计算的工作原理:

>>> foo = ordered_reduce(None, (0, 1, 0), foos)
>>> foo([1, 2, 3, 4])
-7
>>> (1 - 2) * (3 + 4)
-7

但是,它涉及复制整个列表并且也(因此?)很慢。有没有更好/标准的方法来做到这一点?

(编辑:)一些时间:

from operators import add
from functools import reduce
from itertools import repeat
from random import random

r = 100000
xs = [random() for _ in range(r)]
# slightly trivial choices of pairs and functions, to replicate reduce
ps = [0]*(r-1)
fs = repeat(add)
foo = ordered_reduce(None, ps, fs, precompute=True)

>>> %timeit reduce(add, xs)
100 loops, best of 3: 3.59 ms per loop
>>> %timeit foo(xs)
1 loop, best of 3: 1.44 s per loop

这是一种最坏的情况,并且由于reduce不采用可迭代的函数,但有一点作弊(但没有顺序)仍然非常快:

def multi_reduce(fs, xs):
    xs = iter(xs)
    x = next(xs)
    for f, nx in zip(fs, xs):
        x = f(x, nx)
    return x

>>> %timeit multi_reduce(fs, xs)
100 loops, best of 3: 8.71 ms per loop

(EDIT2):为了好玩,一个大规模作弊的“编译”版本的性能,它给出了发生的总开销的一些概念。

from numba import jit

@jit(nopython=True)
def numba_sum(xs):
    y = 0
    for x in xs:
        y += x
    return y

>>> %timeit numba_sum(xs)
1000 loops, best of 3: 1.46 ms per loop

【问题讨论】:

  • 你能举一些例子,其中ordered_reduce 比直接计算慢(如foo([1, 2, 3, 4]) vs (1 - 2) * (3 + 4))?
  • 添加了一些计时! @ptrj
  • 只有在发布我的答案后,我才在您的 ord_red_func 上运行分析器。正如我所料,del y[p] 是罪魁祸首。该程序在示例中该行中几乎 90% 的时间用于添加数字,在我的示例中大约 50% 的时间用于矩阵。所以,我认为,任何摆脱这个del 的解决方案都可以。

标签: python performance list reduce partial-application


【解决方案1】:

当我看到这个问题时,我立刻想到了reverse Polish notation (RPN)。虽然它可能不是最好的方法,但在这种情况下它仍然可以显着加快速度。

我的第二个想法是,如果您适当地重新排序序列xs 以摆脱del y[p],您可能会得到相同的结果。 (可以说,如果整个 reduce 过程是用 C 编写的,则可以实现最佳性能。但这是另一回事。)

逆波兰表示法

如果您不熟悉 RPN,请阅读维基百科文章中的简短说明。基本上,所有的操作都可以写成不带括号的,例如在RPN中(1-2)*(3+4)1 2 - 3 4 + *,而1-(2*(3+4))变成1 2 3 4 + * -

这是一个 RPN 解析器的简单实现。我将一个对象列表从一个 RPN 序列中分离出来,这样同一个序列就可以直接用于不同的列表。

def rpn(arr, seq):
    '''
    Reverse Polish Notation algorithm
    (this version works only for binary operators)
    arr: array of objects 
    seq: rpn sequence containing indices of objects from arr and functions
    '''
    stack = []
    for x in seq:
        if isinstance(x, int):
        # it's an object: push it to stack
            stack.append(arr[x])
        else:
        # it's a function: pop two objects, apply the function, push the result to stack 
            b = stack.pop()
            #a = stack.pop()
            #stack.append(x(a,b))
            ## shortcut:
            stack[-1] = x(stack[-1], b)
    return stack.pop()

使用示例:

# Say we have an array 
arr = [100, 210, 42, 13] 
# and want to calculate 
(100 - 210) * (42 + 13) 
# It translates to RPN: 
100 210 - 42 13 + * 
# or 
arr[0] arr[1] - arr[2] arr[3] + * 
# So we apply `
rpn(arr,[0, 1, subtract, 2, 3, add, multiply])

要将 RPN 应用于您的案例,您需要从头开始生成 rpn 序列或将您的 (pair_indexes, binary_functions) 转换为它们。我还没有考虑过转换器,但肯定可以做到。

测试

你的原始测试是第一位的:

r = 100000
xs = [random() for _ in range(r)]
ps = [0]*(r-1)
fs = repeat(add)
foo = ordered_reduce(None, ps, fs, precompute=True)
rpn_seq = [0] + [x for i, f in zip(range(1,r), repeat(add)) for x in (i,f)]
rpn_seq2 = list(range(r)) + list(repeat(add,r-1))
# Here rpn_seq denotes (_ + (_ + (_ +( ... )...))))
# and rpn_seq2 denotes ((...( ... _)+ _) + _).
# Obviously, they are not equivalent but with 'add' they yield the same result. 

%timeit reduce(add, xs)
100 loops, best of 3: 7.37 ms per loop
%timeit foo(xs)
1 loops, best of 3: 1.71 s per loop
%timeit rpn(xs, rpn_seq)
10 loops, best of 3: 79.5 ms per loop
%timeit rpn(xs, rpn_seq2)
10 loops, best of 3: 73 ms per loop

# Pure numpy just out of curiosity:
%timeit np.sum(np.asarray(xs))
100 loops, best of 3: 3.84 ms per loop
xs_np = np.asarray(xs)
%timeit np.sum(xs_np)
The slowest run took 4.52 times longer than the fastest. This could mean that an intermediate result is being cached 
10000 loops, best of 3: 48.5 µs per loop

所以,rpnreduce 慢 10 倍,但比 ordered_reduce 快大约 20 倍。

现在,让我们尝试一些更复杂的事情:交替相加和相乘矩阵。我需要一个特殊的函数来测试reduce

add_or_dot_b = 1
def add_or_dot(x,y):
    '''calls 'add' and 'np.dot' alternately'''
    global add_or_dot_b
    if add_or_dot_b:
        out = x+y
    else:
        out = np.dot(x,y)
    add_or_dot_b = 1 - add_or_dot_b
    # normalizing out to avoid `inf` in results
    return out/np.max(out)

r = 100001      # +1 for convenience
                # (we apply an even number of functions) 
xs = [np.random.rand(2,2) for _ in range(r)]
ps = [0]*(r-1)
fs = repeat(add_or_dot)
foo = ordered_reduce(None, ps, fs, precompute=True)
rpn_seq = [0] + [x for i, f in zip(range(1,r), repeat(add_or_dot)) for x in (i,f)]

%timeit reduce(add_or_dot, xs)
1 loops, best of 3: 894 ms per loop
%timeit foo(xs)
1 loops, best of 3: 2.72 s per loop
%timeit rpn(xs, rpn_seq)
1 loops, best of 3: 1.17 s per loop

在这里,rpnreduce 慢大约 25%,比 ordered_reduce 快 2 倍以上。

【讨论】:

  • 之前听说过 RPN 但没有研究过,这似乎是一种自然的方法,可以在“收缩”二叉树时最小化存储的计算对的数量(也许是最优的?)。
  • 另外,出于兴趣,我认为您的 rpn 函数似乎是 deque 的完美位置(仅附加/弹出对吗?),但至少对我来说它比简单列表慢
  • @jawknee 不知道 RPN 在二叉树中是否最优。至于deque,我没有想到。如果我们只在最后弹出/推送,通常的列表会非常有效。
猜你喜欢
  • 1970-01-01
  • 2019-03-28
  • 2022-12-31
  • 1970-01-01
  • 2021-05-23
  • 2016-07-27
  • 2017-01-21
  • 1970-01-01
  • 2013-10-12
相关资源
最近更新 更多