当前位置 博文首页 > numpy.sum()的使用详解

    numpy.sum()的使用详解

    作者:Leekingsen 时间:2021-05-24 18:28

    numpy的sum函数可接受的参数是:

    sum(a, axis=None, dtype=None, out=None, keepdims=np._NoValue)

    在参数列表中:
    a是要进行加法运算的向量/数组/矩阵
    axis的值可以为None,也可以为整数和元组
    其形参的注释如下:

    a : array_like elements to sum.

    a:用于进行加法运算的数组形式的元素

    axis : None or int or tuple of ints, optional
    Axis or axes along which a sum is performed.
    The default, axis=None, will sum all of the elements of the input array.
    If axis is negative it counts from the last to the first axis.
    If axis is a tuple of ints, a sum is performed on all of the axes
    specified in the tuple instead of a single axis or all the axes as before.

    根据上文,可知:

    axis的取值有三种情况:1.None,2.整数, 3.整数元组。
    (在默认/缺省的情况下,axis取None)
    如果axis取None,即将数组/矩阵中的元素全部加起来,得到一个和。

    Example:

    >>> np.sum([0.5, 1.5])
    2.0
    >>> np.sum([0.5, 0.7, 0.2, 1.5], dtype=np.int32)
    1
    >>> np.sum([[0, 1], [0, 5]])
    6
    

    如果axis为整数,axis的取值不可大于数组/矩阵的维度,且axis的不同取值会产生不同的结果。

    先以2×2的二维矩阵为例:

    >>> np.sum([[0, 1], [0, 5]], axis=0)
    array([0, 6])
    >>> np.sum([[0, 1], [0, 5]], axis=1)
    array([1, 5])

    在上述例子中

    • 当axis为0时,是压缩行,即将每一列的元素相加,将矩阵压缩为一行
    • 当axis为1时,是压缩列,即将每一行的元素相加,将矩阵压缩为一列(这里的一列是为了方便理解说的,实际上,在控制台的输出中,仍然是以一行的形式输出的)

    具体理解如图:

    • 当axis取负数的时候,对于二维矩阵,只能取-1和-2(不可超过矩阵的维度)。
    • 当axis=-1时,相当于axis=1的效果,当axis=-2时,相当于axis=0的效果。

    如果axis为整数元组(x,y),则是求出axis=x和axis=y情况下得到的和。
    继续以上面的2×2矩阵为例

    >>>np.sum([[0,1],[0,5]],axis=(0,1))
    >>>6
    >>>np.sum([[0,1],[0,5]],axis=(1,0))
    >>>6

    另外,需要注意的是:如果要输入两个数组/矩阵/向量进行相加,那么就要先把两个数组/矩阵/向量用一个括号括起来,形成一个元组,这样才能够进行相加。因为numpy.sum的运算实现本质是通过矩阵内部的运算实现的。

    当然,如果只是向量/数组之间做加法运算,可以直接让两个向量/数组相加,但前提是它们必须为numpy的array数组才可以,否则只是单纯的列表相加

    Example:

    >>>v1 = [1, 2]
    >>>v2 = [3, 4]
    >>>v1 + v2
    [1, 2, 3, 4]
    
    >>>v1 = numpy.array[1, 2]
    >>>v2 = numpy.array[3, 4]
    >>>v1 + v2
    [4, 6]
    
    js
    下一篇:没有了