web-dev-qa-db-ja.com

numpy.sum()には、「keepdims」というパラメーターがあります。それは何をするためのものか?

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.
...
30
Ney J Torres

@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])

軸を指定しない場合(最初の2つの例)、数値の結果は同じですが、keepdims = Trueは番号6の2D配列を返し、2番目のインカネーションはスカラーを返しました。同様に、axis 1(行全体)に沿って合計すると、2Dのときにkeepdims = True配列が再び返されます。最後の例は、axis 0(下の列)に沿って、同様の特性を示しています... keepdims = Trueの場合、寸法は保持されます。
多次元データを扱う際のNumPyのパワーを完全に理解するには、軸とそのプロパティを調べることが重要です。

51
user1121588

高次元の配列を操作するときに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
0