在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.
...发布于 2016-09-12 09:32:21
@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在处理多维数据时的强大功能至关重要。
发布于 2019-05-01 22:32:01
这是一个示例,展示了在使用高维数组时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 respectivelyhttps://stackoverflow.com/questions/39441517
复制相似问题