首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在numpy.sum()中有一个名为"keepdims“的参数。是干什么的呢?

在numpy.sum()中有一个名为"keepdims“的参数。是干什么的呢?
EN

Stack Overflow用户
提问于 2016-09-12 07:10:53
回答 2查看 38.1K关注 0票数 53

numpy.sum()中有一个名为keepdims的参数。是干什么的呢?

正如您在文档中看到的:http://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html

代码语言:javascript
复制
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.
...
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-09-12 09:32:21

@Ney @hpaulj是正确的,你需要实验,但我怀疑你没有意识到一些数组的求和可能会沿着轴发生。阅读文档时,请注意以下几点

代码语言:javascript
复制
>>> 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在处理多维数据时的强大功能至关重要。

票数 84
EN

Stack Overflow用户

发布于 2019-05-01 22:32:01

这是一个示例,展示了在使用高维数组时keepdims的作用。让我们看看当我们做不同的缩减时,数组的形状是如何变化的:

代码语言:javascript
复制
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
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39441517

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档