keepdims在Numpy(Python)中起什么作用? [英] What is the role of keepdims in Numpy (Python)?

查看:198
本文介绍了keepdims在Numpy(Python)中起什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用np.sum时,遇到一个名为keepdims的参数.在查找文档之后,我仍然无法理解keepdims的含义.

When I use np.sum, I encountered a parameter called keepdims. After looking up the docs, I still cannot understand the meaning of keepdims.

keepdims:布尔型,可选

如果将其设置为True,则缩小的轴将保留为尺寸为1的尺寸.使用此选项,结果将针对原始arr正确广播.

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 original arr.

如果有人可以通过一个简单的例子对此有所了解,我将不胜感激.

I will appreciate it if anyone can make some sense of this with a simple example.

推荐答案

考虑一个小的2d数组:

Consider a small 2d array:

In [180]: A=np.arange(12).reshape(3,4)
In [181]: A
Out[181]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

各行之和;结果是一个(3,)数组

Sum across rows; the result is a (3,) array

In [182]: A.sum(axis=1)
Out[182]: array([ 6, 22, 38])

但是要用sum求和(或除)A,需要重塑

But to sum (or divide) A by the sum requires reshaping

In [183]: A-A.sum(axis=1)
...
ValueError: operands could not be broadcast together with shapes (3,4) (3,) 
In [184]: A-A.sum(axis=1)[:,None]   # turn sum into (3,1)
Out[184]: 
array([[ -6,  -5,  -4,  -3],
       [-18, -17, -16, -15],
       [-30, -29, -28, -27]])

如果我使用keepdims,则结果将针对A正确广播."

If I use keepdims, "the result will broadcast correctly against" A.

In [185]: A.sum(axis=1, keepdims=True)   # (3,1) array
Out[185]: 
array([[ 6],
       [22],
       [38]])
In [186]: A-A.sum(axis=1, keepdims=True)
Out[186]: 
array([[ -6,  -5,  -4,  -3],
       [-18, -17, -16, -15],
       [-30, -29, -28, -27]])

如果我用另一种方法求和,则不需要keepdims.自动广播此和:A.sum(axis=0)[None,:].但是使用keepdims没有什么害处.

If I sum the other way, I don't need the keepdims. Broadcasting this sum is automatic: A.sum(axis=0)[None,:]. But there's no harm in using keepdims.

In [190]: A.sum(axis=0)
Out[190]: array([12, 15, 18, 21])    # (4,)
In [191]: A-A.sum(axis=0)
Out[191]: 
array([[-12, -14, -16, -18],
       [ -8, -10, -12, -14],
       [ -4,  -6,  -8, -10]])

如果愿意,这些操作对于np.mean可能更有意义,可以对列或行上的数组进行标准化.无论如何,它都可以简化原始数组与和/均值之间的进一步数学运算.

If you prefer, these actions might make more sense with np.mean, normalizing the array over columns or rows. In any case it can simplify further math between the original array and the sum/mean.

这篇关于keepdims在Numpy(Python)中起什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆