在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.
...
Run Code Online (Sandbox Code Playgroud)
小智 52
@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])
Run Code Online (Sandbox Code Playgroud)
您会注意到,如果未指定轴(前两个示例),则数值结果相同,但keepdims = True返回2D的数字为6,而第二个实体返回标量.类似地,当沿着axis 1(跨行)求和时,2D再次返回数组keepdims = True.最后一个例子,沿着axis 0(向下的列),显示了一个类似的特征......尺寸保持在何时keepdims = True.
研究轴及其属性对于在处理多维数据时充分理解NumPy的强大功能至关重要.
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
Run Code Online (Sandbox Code Playgroud)