numpy中的ufunc函数详解

  • 什么是universal function

A universal function (or ufunc for short) is a function that operates on ndarrays in an element-by-element fashion, supporting array broadcasting, type casting, and several other standard features. That is, a ufunc is a “vectorized” wrapper for a function that takes a fixed number of specific inputs and produces a fixed number of specific outputs
——来源:numpy.org
简言之,universal function是定义在ndarray上的运算,是元素-元素的运算
numpy中还有一个十分重要的概念:broadcast(广播),借助广播,能够使得shape不相同的array一同参与运算,可参考:广播

  • ufunc的一些简单属性
  1. nin: 输入的个数
  2. nout: 输出的个数
  3. nargs: The number of arguments. Data attribute containing the number of arguments the ufunc takes, including optional ones.
  4. ntypes: The number of numerical NumPy types - of which there are 18 total - on which the ufunc can operate
  5. types: Returns a list with types grouped input->output. Data attribute listing the data-type “Domain-Range” groupings the ufunc can deliver. The data-types are given using the character codes
  6. identity: Data attribute containing the identity element for the ufunc, if it has one. If it does not, the attribute value is None.
  7. signature: The signature determines how the dimensions of each input/output array are split into core and loop dimensions
    小技巧:调用ufunc.__doc__可以查看该函数的文档

例如

print(np.multiply.__doc__)
  • ufunc的方法(method):
    以下我们以add.reduce函数为例来讲解
  1. ufunc.reduce
    用法: reduce(a,axis,initial,keepdims)
    详见 reduce
    a是输入的矩阵
    axis是参与运算的维度(默认为0)
    例如:
import numpy as np
a=np.arange(9).reshape(3,3)
print(a)
# [[0 1 2]
#  [3 4 5]
#  [6 7 8]]
#如果我们想把矩阵按行(axis=0)进行划分,把各行相加
b=np.add.reduce(a,axis=0)
print(b)
# [ 9 12 15]

我们查看b的shape,得到的结果是(3,),可见运算完成后,axis=0已经被除去(reduce)了,当然,如果我们希望运算前后ndim不变,也就是不把axis=0给reduce掉,可以用keepdims=1实现

b=np.add.reduce(a,axis=0,keepdims=1)

如果我们希望最后的解果获得偏置,也就是使得结果的每个element都加一个5,可以调用initial这个参量

b=np.add.reduce(a,axis=0,keepdims=1,initial=5)
print(b)
#[[14 17 20]]

类似地,multiply.reduce和add.reduce是十分类似的,唯一的区别是把“相加”变成相乘,对于其他函数的reduce,也是类似的。

  1. ufunc.accumulate
    同样,我们以add.accumulate为例
    如果我们还是把矩阵的行(axis=0)进行划分,我们看看add.accumulate得到的结果是什么
import numpy as np
a=np.arange(9).reshape(3,3)
print(a)
# [[0 1 2]
#  [3 4 5]
#  [6 7 8]]
#如果我们想吧矩阵按行(axis=0)进行划分,把各行相加
b=np.add.accumulate(a,axis=0)
print(b)
# [[ 0  1  2]
#  [ 3  5  7]第一行+第二行
#  [ 9 12 15]]第一行+第二行+第三行
  1. ufunc.outer
    我们以add.outer为例
import numpy as np
a=np.array([1,2,3])
b=np.array([4,5,6])
print(np.add.outer(a,b))
# [[5 6 7]
#  [6 7 8]
#  [7 8 9]]

我们发现,a中的1被替换成了1+[4,5,6],2被替换成了2+[4,5,6],3被替换成了3+[4,5,6]
总结:add.outer(a,b)就相当于把a中的每个element替换为这个element与b的和,结果的shape为(a.shape,b.shape)

发布了19 篇原创文章 · 获赞 0 · 访问量 1141

猜你喜欢

转载自blog.csdn.net/Jinyindao243052/article/details/104212219