在 numpy.sum() 中有一个名为“keepdims”的参数。它有啥作用?

Posted

技术标签:

【中文标题】在 numpy.sum() 中有一个名为“keepdims”的参数。它有啥作用?【英文标题】:In numpy.sum() there is parameter called "keepdims". What does it do?在 numpy.sum() 中有一个名为“keepdims”的参数。它有什么作用? 【发布时间】:2017-01-19 08:55:45 【问题描述】:

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.
...

【问题讨论】:

你试过这些例子,有没有这个参数?它应该很容易在交互式会话中进行测试。 如果您知道sum 没有它会做什么,这个参数最有意义。您是否熟悉结果的形状如何取决于输入数组和轴的选择? 【参考方案1】:

一个例子展示了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

【讨论】:

【参考方案2】:

@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 的强大功能至关重要。

【讨论】:

以上是关于在 numpy.sum() 中有一个名为“keepdims”的参数。它有啥作用?的主要内容,如果未能解决你的问题,请参考以下文章

[Python] numpy.sum

numpy sum 给出错误

在React中实现和Vue一样舒适的keep-alive

等效于 OBIEE 中的 max() keep (partition by .. order by ..)

HTTP keep-alive和TCP keepalive的区别,你了解吗?

转:Connection: close和Connection: keep-alive有什么区别?