Python和科学计算认证群组  - 讨论区

标题:关于tentative NumPy tutorial 中ix_()

2012年08月23日 星期四 20:34

The ix_() function

 

The ix_ function can be used to combine different vectors so as to obtain the result for each n-uplet. For example, if you want to compute all the a+b*c for all the triplets taken from each of the vectors a, b and c:

 

>>> a = array([2,3,4,5])
>>> b = array([8,5,4])
>>> c = array([5,4,6,8,3])
>>> ax,bx,cx = ix_(a,b,c)
>>> ax
array([[[2]],

       [[3]],

       [[4]],

       [[5]]])
>>> bx
array([[[8],
        [5],
        [4]]])
>>> cx
array([[[5, 4, 6, 8, 3]]])
>>> ax.shape, bx.shape, cx.shape
((4, 1, 1), (1, 3, 1), (1, 1, 5))
>>> result = ax+bx*cx
>>> result
array([[[42, 34, 50, 66, 26],
        [27, 22, 32, 42, 17],
        [22, 18, 26, 34, 14]],
       [[43, 35, 51, 67, 27],
        [28, 23, 33, 43, 18],
        [23, 19, 27, 35, 15]],
       [[44, 36, 52, 68, 28],
        [29, 24, 34, 44, 19],
        [24, 20, 28, 36, 16]],
       [[45, 37, 53, 69, 29],
        [30, 25, 35, 45, 20],
        [25, 21, 29, 37, 17]]])
>>> result[3,2,4]
17
>>> a[3]+b[2]*c[4]
17

 

You could also implement the reduce as follows:

 

def ufunc_reduce(ufct, *vectors):
    vs = ix_(*vectors)
    r = ufct.identity
    for v in vs:
        r = ufct(r,v)
    return r

 

and then use it as:

 

>>> ufunc_reduce(add,a,b,c)
array([[[15, 14, 16, 18, 13],
        [12, 11, 13, 15, 10],
        [11, 10, 12, 14,  9]],
       [[16, 15, 17, 19, 14],
        [13, 12, 14, 16, 11],
        [12, 11, 13, 15, 10]],
       [[17, 16, 18, 20, 15],
        [14, 13, 15, 17, 12],
        [13, 12, 14, 16, 11]],
       [[18, 17, 19, 21, 16],
        [15, 14, 16, 18, 13],
        [14, 13, 15, 17, 12]]])

The advantage of this version of reduce compared to the normal ufunc.reduce is that it makes use of the Broadcasting Rules in order to avoid creating an argument array the size of the output times the number of vectors.

-------------------------------------------------------------------

最后一句,不明白想说明什么,难道第一中没有简化的版本没有用广播?

2012年08月24日 星期五 10:59

ufunc.reduce(例如numpy.add.reduce)是对数组的某一个轴进行reduce运算。而本文编写的ufunc_reduce是先将一组数组通过ix_()转换为满足广播(Broadcasting Rules)的数组,然后进行运算。两个是完全不同的运算。

如果你要用ufunc.reduce实现这里的ufunc_reduce的功能,那么就得先通过那组数组产生一个巨大的多维数组,然后用ufunc.reduce对其某一轴进行运算。这就是最后那么所说的 creating an argument array the size of the output times the number of vectors。

2012年08月24日 星期五 11:04

啊,谢谢您啊,竟然把ufunc.reduce中的'.'看成句号了……原来是和ufunc.reduce来比较。

如下红色区域有误,请重新填写。

    你的回复:

    请 登录 后回复。还没有在Zeuux哲思注册吗?现在 注册 !

    Zeuux © 2024

    京ICP备05028076号