Python 在numpy.sum()中有一个名为;keepdims";。它有什么作用?
在Python 在numpy.sum()中有一个名为;keepdims";。它有什么作用?,python,numpy,sum,Python,Numpy,Sum,在numpy.sum()中有一个名为keepdims的参数。它有什么作用 正如您在文档中看到的: @内伊 @hpaulj是正确的,您需要进行实验,但我怀疑您没有意识到某些数组的求和可以沿轴进行。阅读文档时,请遵循以下步骤 >>> a array([[0, 0, 0], [0, 1, 0], [0, 2, 0], [1, 0, 0], [1, 1, 0]]) >>> np.sum(a, keepdims=
numpy.sum()中有一个名为keepdims
的参数。它有什么作用
正如您在文档中看到的:
@内伊
@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
数组,而第二个化身返回了标量。
类似地,当沿轴1(跨行)求和时,当keepdims=True
时,将再次返回2D
数组。
最后一个示例沿轴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
您是否尝试过使用和不使用此参数的示例?在交互式会话中进行测试应该很容易。如果您知道sum
在没有它的情况下可以做什么,则此参数最有意义。您熟悉结果的形状如何依赖于输入数组和轴选择吗?
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