gpt4 book ai didi

Numpy:带负轴的 np.sum

转载 作者:行者123 更新时间:2023-12-03 02:13:22 26 4
gpt4 key购买 nike

我想知道“如果轴为负数,则从最后一个轴计数到第一个轴。”在 中意味着什么docs ,我已经测试过这些:

>>> t
array([[1, 2],
[3, 4]])
>>> np.sum(t, axis=1)
array([3, 7])
>>> np.sum(t, axis=0)
array([4, 6])
>>> np.sum(t, axis=-2)
array([4, 6])

仍然很困惑,我需要一些易于理解的解释。

最佳答案

首先看一下长度为 2 的列表上的列表索引:

>>> L = ['one', 'two']
>>> L[-1] # last element
'two'
>>> L[-2] # second-to-last element
'one'
>>> L[-3] # out of bounds - only two elements in this list
# IndexError: list index out of range

axis 参数是类似的,只不过它指定 ndarray 的维度。如果使用非方阵会更容易看出:

>>> t = np.arange(1,11).reshape(2,5)
>>> t
array([[ 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10]])
>>> t.ndim # two-dimensional array
2
>>> t.shape # a tuple of length t.ndim
(2, 5)

那么让我们看看调用 sum 的各种方法:

>>> t.sum()  # all elements
55
>>> t.sum(axis=0) # sum over 0th axis i.e. columns
array([ 7, 9, 11, 13, 15])
>>> t.sum(axis=1) # sum over 1st axis i.e. rows
array([15, 40])
>>> t.sum(axis=-2) # sum over -2th axis i.e. columns again (-2 % ndim == 0)
array([ 7, 9, 11, 13, 15])

尝试 t.sum(axis=-3) 将出错,因为此数组中只有 2 个维度。不过,您可以在 3d 数组上使用它。

关于Numpy:带负轴的 np.sum,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50079622/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com