在numpy.sum()函数中有一个名为“keepdims”的参数,它的作用是什么?

62

numpy.sum()中有一个名为keepdims的参数,它是什么作用?

您可以在此处文档中看到:http://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html

numpy.sum(a, axis=None, dtype=None, out=None, keepdims=False)[source]
Sum of array elements over a given axis.

Parameters: 
...
keepdims : bool, optional
    If this is set to True, the axes which are reduced are left in the result as
    dimensions with size one. With this option, the result will broadcast
    correctly against the input array.
...

9
你尝试过使用和不使用这个参数的示例吗?在交互式会话中测试应该很容易。 - hpaulj
1
如果您了解sum函数的作用,那么这个参数就会更有意义。您是否熟悉结果的形状如何取决于输入数组和轴选择? - hpaulj
2个回答

94

@Ney @hpaulj 是正确的,你需要进行实验,但我怀疑你没有意识到对于某些数组,求和可以沿着轴发生。阅读文档时请注意以下内容。

>>> a
array([[0, 0, 0],
       [0, 1, 0],
       [0, 2, 0],
       [1, 0, 0],
       [1, 1, 0]])
>>> np.sum(a, keepdims=True)
array([[6]])
>>> np.sum(a, keepdims=False)
6
>>> np.sum(a, axis=1, keepdims=True)
array([[0],
       [1],
       [2],
       [1],
       [2]])
>>> np.sum(a, axis=1, keepdims=False)
array([0, 1, 2, 1, 2])
>>> np.sum(a, axis=0, keepdims=True)
array([[2, 4, 0]])
>>> np.sum(a, axis=0, keepdims=False)
array([2, 4, 0])

您会注意到,如果不指定轴(前两个示例),数值结果相同,但是keepdims = True返回了一个带有数字6的2D数组,而第二个实例返回了一个标量。 同样地,当沿着axis 1(跨行)求和时,当keepdims = True时再次返回一个2D数组。 最后一个示例,沿着axis 0(向下列)显示了类似的特征...当keepdims = True时保留维度。
研究轴及其属性对于全面理解处理多维数据时NumPy的强大功能至关重要。


8
一个示例展示了在处理较高维数组时,keepdims 是如何发挥作用的。让我们看看当我们执行不同的约简操作时,数组的形状如何变化:
import numpy as np
a = np.random.rand(2,3,4)
a.shape
# => (2, 3, 4)
# Note: axis=0 refers to the first dimension of size 2
#       axis=1 refers to the second dimension of size 3
#       axis=2 refers to the third dimension of size 4

a.sum(axis=0).shape
# => (3, 4)
# Simple sum over the first dimension, we "lose" that dimension 
# because we did an aggregation (sum) over it

a.sum(axis=0, keepdims=True).shape
# => (1, 3, 4)
# Same sum over the first dimension, but instead of "loosing" that 
# dimension, it becomes 1.

a.sum(axis=(0,2)).shape
# => (3,)
# Here we "lose" two dimensions

a.sum(axis=(0,2), keepdims=True).shape
# => (1, 3, 1)
# Here the two dimensions become 1 respectively

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接