在Python

时间:2016-09-25 14:45:30

标签: python numpy deep-learning reduce

我正在深入学习,我想抓住所有隐藏层的值。所以我最终编写了这样的函数:

def forward_pass(x, ws, bs):
    activations = []
    u = x
    for w, b in zip(ws, bs):
        u = np.maximum(0, u.dot(w)+b)
        activations.append(u)
    return activations

如果我没有得到中间值,我会使用更简洁的形式:

out = reduce(lambda u, (w, b): np.maximum(0, u.dot(w)+b), zip(ws, bs), x)

的Bam。一条线,美观大方。但是我不能保留任何中间值。

那么,有什么方法可以吃我的蛋糕(漂亮紧凑的单线)并吃它(返回中间值)?

编辑:我的结论到目前为止:
在Python 2.x中,没有干净的单行代码。
在Python 3中,有itertools.accumulate,但它仍然不是很干净,因为它不接受"初始"输入,如reduce所示 在Python 4中,我特此请求" map-reduce comprehension":

activations = [u=np.maximum(0, u.dot(w)+b) for w, b in zip(ws, bs) from u=x]  

这也可以为from关键字提供有用的工作,这通常只是在所有导入完成后无所事事。

4 个答案:

答案 0 :(得分:3)

一般情况下,itertools.accumulate()会执行reduce()所做的事情,但也会为您提供中间值。也就是说,累积不支持 start 值,因此它不适用于您的情况。

示例:

>>> import operator, functools, itertools
>>> functools.reduce(operator.mul, range(1, 11))
3628800
>>> list(itertools.accumulate(range(1, 11), operator.mul))
[1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]

答案 1 :(得分:2)

dot告诉我你正在使用一个或多个numpy数组。所以我会尝试:

In [28]: b=np.array([1,2,3])
In [29]: x=np.arange(9).reshape(3,3)
In [30]: ws=[x,x,x]

In [31]: forward_pass(x,ws,bs)
Out[31]: 
[array([[ 16,  19,  22],
        [ 43,  55,  67],
        [ 70,  91, 112]]), 
 array([[ 191,  248,  305],
        [ 569,  734,  899],
        [ 947, 1220, 1493]]), 
 array([[ 2577,  3321,  4065],
        [ 7599,  9801, 12003],
        [12621, 16281, 19941]])]

在py3中,我必须将reduce解决方案写为:

In [32]: functools.reduce(lambda u, wb: np.maximum(0,
                   u.dot(wb[0])+wb[1]), zip(ws, bs), x)
Out[32]: 
array([[ 2577,  3321,  4065],
       [ 7599,  9801, 12003],
       [12621, 16281, 19941]])

从一个评估传递到下一个评估的中间值u使列表理解变得棘手。

accumulate使用第一项作为开头。我可以使用像

这样的函数解决这个问题
def foo(u, wb):
    if u[0] is None: u=x   # x from global
    return np.maximum(0, u.dot(wb[0])+wb[1])

然后我需要为wsbs添加额外的起始值:

In [56]: list(itertools.accumulate(zip([None,x,x,x], np.array([0,1,2,3])), foo))
Out[56]: 
[(None, 0), 
 array([[ 16,  19,  22],
        [ 43,  55,  67],
        [ 70,  91, 112]]), 
 array([[ 191,  248,  305],
        [ 569,  734,  899],
        [ 947, 1220, 1493]]), 
 array([[ 2577,  3321,  4065],
        [ 7599,  9801, 12003],
        [12621, 16281, 19941]])]

这是一个列表理解版本,使用外部u

In [66]: u=x.copy()
In [67]: def foo1(wb):
    ...:     v = np.maximum(0, u.dot(wb[0])+wb[1])
    ...:     u[:]=v
    ...:     return v
    ...: 
In [68]: [foo1(wb) for wb in zip(ws,bs)]
Out[68]: 
[array([[ 16,  19,  22],
        [ 43,  55,  67],
        [ 70,  91, 112]]), 
 array([[ 191,  248,  305],
        [ 569,  734,  899],
        [ 947, 1220, 1493]]), 
 array([[ 2577,  3321,  4065],
        [ 7599,  9801, 12003],
        [12621, 16281, 19941]])]

与使用append的原始循环相比没有真正的优势。

numpy.ufuncaccumulate方法,但使用自定义Python函数并不容易。所以有一个np.maximum.accumulate,但我不确定在这种情况下如何使用它。 (np.cumsum也是np.add.accumulate

答案 2 :(得分:1)

实际上,您可以使用result = [y for y in [initial] for x in inputs for y in [f(x, y)]]有点奇怪的模式来执行此操作。注意,第一个for和第三个for var in [value]并不是真正的循环,而是分配-我们可以在理解中使用valuevar分配给def forward_pass(x, ws, bs): activations = [] u = x for w, b in zip(ws, bs): u = np.maximum(0, u.dot(w)+b) activations.append(u) return activations 。例如:

def forward_pass(x, ws, bs):
    return [u for u in [x] for w, b in zip(ws, bs) for u in [np.maximum(0, u.dot(w)+b)]]

相当于:

:=

Python 3.8 +:
Python 3.8引入了“海象”运算符def forward_pass(x, ws, bs): u = x return [u:=np.maximum(0, u.dot(w)+b) for w, b in zip(ws, bs)] ,这为我们提供了另一个选择:

handleChange

答案 3 :(得分:0)

在Python 2.x中,没有干净的单行代码。

在Python 3中,有itertools.accumulate,但它仍然不是很干净,因为它不接受" initial"输入,如减少。

这是一个功能,虽然不如内置的理解语法那么好,但是能够胜任。

def reducemap(func, sequence, initial=None, include_zeroth = False):
    """
    A version of reduce that also returns the intermediate values.
    :param func: A function of the form x_i_plus_1 = f(x_i, params_i)
        Where:
            x_i is the value passed through the reduce.
            params_i is the i'th element of sequence
            x_i_plus_i is the value that will be passed to the next step
    :param sequence: A list of parameters to feed at each step of the reduce.
    :param initial: Optionally, an initial value (else the first element of the sequence will be taken as the initial)
    :param include_zeroth: Include the initial value in the returned list.
    :return: A list of length: len(sequence), (or len(sequence)+1 if include_zeroth is True) containing the computed result of each iteration.
    """
    if initial is None:
        val = sequence[0]
        sequence = sequence[1:]
    else:
        val = initial
    results = [val] if include_zeroth else []
    for s in sequence:
        val = func(val, s)
        results.append(val)
    return results

试验:

assert reducemap(lambda a, b: a+b, [1, 2, -4, 3, 6, -7], initial=0) == [1, 3, -1, 2, 8, 1]
assert reducemap(lambda a, b: a+b, [1, 2, -4, 3, 6, -7]) == [3, -1, 2, 8, 1]
assert reducemap(lambda a, b: a+b, [1, 2, -4, 3, 6, -7], include_zeroth=True) == [1, 3, -1, 2, 8, 1]