@Ney @hpaulj is correct, you need to experiment, but I suspect you don't realize that summation for some arrays can occur along axes. Observe the following which reading the documentation

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

You will notice that if you don't specify an axis (1st two examples), the numerical result is the same, but the keepdims = True returned a 2D array with the number 6, whereas, the second incarnation returned a scalar. Similarly, when summing along axis 1 (across rows), a 2D array is returned again when keepdims = True. The last example, along axis 0 (down columns), shows a similar characteristic... dimensions are kept when keepdims = True.
Studying axes and their properties is critical to a full understanding of the power of NumPy when dealing with multidimensional data.

Answer from user1121588 on Stack Overflow
Top answer
1 of 2
102

@Ney @hpaulj is correct, you need to experiment, but I suspect you don't realize that summation for some arrays can occur along axes. Observe the following which reading the documentation

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

You will notice that if you don't specify an axis (1st two examples), the numerical result is the same, but the keepdims = True returned a 2D array with the number 6, whereas, the second incarnation returned a scalar. Similarly, when summing along axis 1 (across rows), a 2D array is returned again when keepdims = True. The last example, along axis 0 (down columns), shows a similar characteristic... dimensions are kept when keepdims = True.
Studying axes and their properties is critical to a full understanding of the power of NumPy when dealing with multidimensional data.

2 of 2
9

An example showing keepdims in action when working with higher dimensional arrays. Let's see how the shape of the array changes as we do different reductions:

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
🌐
IncludeHelp
includehelp.com › python › what-does-the-keepdims-parameter-do-with-numpy-sum-function.aspx
Python - What does the 'keepdims' parameter do with numpy.sum() function?
If the default value is passed, then keepdims will not be passed through to the sum method of sub-classes of ndarray, however, any non-default value will be. If the sub-class' method does not implement keepdims any exceptions will be raised. ... # Import numpy import numpy as np # Creating a numpy array arr = np.array([[0, 0, 0], [0, 1, 0], [0, 2, 0], [1, 0, 0], [1, 1, 0]]) # Display original array print("Original array:\n",arr,"\n") # Calculating sum res = np.sum(arr, keepdims=True) # Display result print("Sum:\n",res)
Discussions

python - Numpy sum keepdims error - Stack Overflow
Python throws an error when calling numpy sum function on a matrix. probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True) More on stackoverflow.com
🌐 stackoverflow.com
What is the role of keepdims in Numpy (Python)? - Stack Overflow
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: bool, optional If this is set to True, the axes More on stackoverflow.com
🌐 stackoverflow.com
December 2, 2016
python - Numpy sum() got an 'keepdims' error - Stack Overflow
To expand a little bit, I'm asking ... sub-classes sum method does not implement keepdims any exceptions will be raised." so I'm wondering if your exp_scores is a sub-classed array that doesn't have the keepdims implementation. Does it work if exp_scores = np.ones((10, 10)) or ... More on stackoverflow.com
🌐 stackoverflow.com
np.sum with keepdims fails when input is a 1d array
There was an error while loading. Please reload this page More on github.com
🌐 github.com
4
May 6, 2017
🌐
DataCamp
datacamp.com › doc › numpy › sum
NumPy sum()
When maintaining the original dimensions' shape is crucial, set keepdims=True. Leverage array broadcasting. When summing over axes, ensure the array dimensions are compatible for efficient operations.
🌐
Sharp Sight
sharpsight.ai › blog › numpy-sum
How to Use the Numpy Sum Function - Sharp Sight
February 6, 2024 - But, it’s possible to change that behavior. If we set keepdims = True, the axes that are reduced will be kept in the output. So if you use np.sum on a 2-dimensional array and set keepdims = True, the output will be in the form of a 2-d array.
🌐
Note.nkmk.me
note.nkmk.me › home › python › numpy
NumPy: Meaning of the axis parameter (0, 1, -1) | note.nkmk.me
January 18, 2024 - For axis=0, the default setting correctly broadcasts as well, but keepdims=True is also acceptable. print(a + np.sum(a, axis=0)) # [[4 4 4 4] # [4 4 4 4] # [4 4 4 4]] print(a + np.sum(a, axis=0, keepdims=True)) # [[4 4 4 4] # [4 4 4 4] # [4 4 4 4]]
🌐
NumPy
numpy.org › doc › 2.3 › reference › generated › numpy.sum.html
numpy.sum — NumPy v2.3 Manual
numpy.sum(a, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)[source]#
🌐
NumPy
numpy.org › doc › 2.1 › reference › generated › numpy.sum.html
numpy.sum — NumPy v2.1 Manual
numpy.sum(a, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)[source]#
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.sum.html
numpy.sum — NumPy v2.5 Manual
numpy.sum(a, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)[source]#
Find elsewhere
🌐
DNMTechs
dnmtechs.com › understanding-the-keepdims-parameter-in-numpy-sum
Understanding the keepdims parameter in numpy.sum() – DNMTechs – Sharing and Storing Technology Knowledge
The keepdims parameter in the numpy.sum() function controls whether the dimensions of the input array are preserved in the output array. By default, keepdims is set to False, resulting in a reduced dimensionality of the output array. When keepdims is set to True, the output array retains the ...
🌐
Ancisoft
ancisoft.com › blog › what-is-the-role-of-keepdims-in-numpy-python
What is keepdims in NumPy? A Simple Guide with np.sum Examples (Python Explained) — ancisoft.com
For 1D arrays, keepdims has a subtle effect because there’s only one axis to aggregate. import numpy as np # 1D array arr_1d = np.array([1, 2, 3, 4]) # Sum with keepdims=False (default) sum_default = np.sum(arr_1d) print("Sum (keepdims=False):", sum_default) print("Shape (keepdims=False):", sum_default.shape) # Scalar has no shape # Sum with keepdims=True sum_keepdims = np.sum(arr_1d, keepdims=True) print("\nSum (keepdims=True):", sum_keepdims) print("Shape (keepdims=True):", sum_keepdims.shape)
🌐
GeeksforGeeks
geeksforgeeks.org › numpy-sum-in-python
numpy.sum() in Python - GeeksforGeeks
August 28, 2024 - This Python program uses numpy.sum() to compute the sum of elements in a 2D array. It calculates the total sum, sums along rows (axis=0), sums along columns (axis=1), and sums along columns while keeping the dimensions (keepdims=True).
Top answer
1 of 4
45

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

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

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

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

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

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

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.

2 of 4
5

You can keep the dimension with "keepdims=True" if you sum a matrix For example:

import numpy as np
x  = np.array([[1,2,3],[4,5,6]])
x.shape
# (2, 3)

np.sum(x, keepdims=True).shape
# (1, 1)
np.sum(x, keepdims=True)
# array([[21]]) <---the reault is still a 1x1 array

np.sum(x, keepdims=False).shape
# ()
np.sum(x, keepdims=False)
# 21 <--- the result is an integer with no dimesion
Top answer
1 of 1
10

Note that under the keepdims argument in the docs for numpy.sum() it states:

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.
If the default value is passed, then keepdims will not be passed through to the sum method of sub-classes of ndarray, however any non-default value will be. If the sub-classes sum method does not implement keepdims any exceptions will be raised.

So it states here that if you're using a sub-class of numpy.ndarray, then you'll get this error if the corresponding sum function for the sub-class hasn't been defined with it.

Notice that in your error it references line 1812 in numpy/core/fromnumeric.py. Take a look at that in context in the actual numpy 1.12.x source:

kwargs = {}
if keepdims is not np._NoValue:
    kwargs['keepdims'] = keepdims
if isinstance(a, _gentype):
    res = _sum_(a)
    if out is not None:
        out[...] = res
        return out
    return res
if type(a) is not mu.ndarray:
    try:
        sum = a.sum
    except AttributeError:
        pass
    else:
        return sum(axis=axis, dtype=dtype, out=out, **kwargs)
return _methods._sum(a, axis=axis, dtype=dtype,
                     out=out, **kwargs)

Two things are important to note here: the sum function did parse your keepdims variable, since it pulled it above line 1812 and tried to put it in another function, so you know the error wasn't the way you used the variable. The other important thing is that the line 1812 which you're erroring on is only executing if type(a) is not mu.ndarray, i.e., if you're using a different class than ndarray. And this is exactly what the documentation is referencing. If you have a different class, then they need to implement this sum function with the keepdims argument, and if they don't it will raise an error.

Other classes like np.matrix for example will have a different sum function, and it seems that, even in numpy 1.13.x, sum for np.matrix types does not support the keepdim argument (because in numpy, matrices always are 2D). For example, it works fine with a np.array:

>>> import numpy as np
>>> A = np.eye(4)
>>> A
array([[ 1.,  0.,  0.,  0.],
       [ 0.,  1.,  0.,  0.],
       [ 0.,  0.,  1.,  0.],
       [ 0.,  0.,  0.,  1.]])
>>> np.sum(A, axis=1, keepdims=True)
array([[ 1.],
       [ 1.],
       [ 1.],
       [ 1.]])

But with a np.matrix, it doesn't:

>>> import numpy.matlib
>>> B = np.matlib.eye(4)
>>> np.sum(B, axis=1, keepdims=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File ".../numpy/core/fromnumeric.py", line 1832, in sum
    return sum(axis=axis, dtype=dtype, out=out, **kwargs)
TypeError: sum() got an unexpected keyword argument 'keepdims'

But, most array/matrix type objects can be easily cast to an array in numpy with np.array(<object>), and this should solve the problem for most sub-classed objects in numpy and likely your problem. You can also simply wrap the result back into a np.matrix if you need to.

>>> B = np.matlib.eye(4)
>>> B = np.array(B)
>>> np.sum(B, axis=1, keepdims=True)
array([[ 1.],
       [ 1.],
       [ 1.],
       [ 1.]])

However, if your class of object is a np.matrix type, then the keepdims argument is pointless. Matrices are always 2D, so the sum function won't reduce a dimension, and thus the argument wouldn't do anything. This is why it isn't implemented for matrices.

🌐
Netalith
netalith.com › blogs › tutorial › numpysum-in-python
numpy sum python — Examples, axis, dtype, keepdims | Netalith
February 22, 2026 - Use this to avoid overflow or to get a floating-point result (e.g., numpy sum dtype=float). out: optional array to store the result (numpy sum out parameter example). keepdims: if True, the reduced axes are retained with size 1 (numpy sum keepdims ...
🌐
Educative
educative.io › answers › what-is-numpysum-in-python
What is numpy.sum() in Python?
Python’s numpy.sum() computes the sum of an array over a specified axis. ... numpy.sum(a, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)
🌐
GitHub
github.com › numpy › numpy › issues › 9064
np.sum with keepdims fails when input is a 1d array · Issue #9064 · numpy/numpy
May 6, 2017 - got the following error when running np.sum(a, axis=1, keepdims=True): TypeError: sum() got an unexpected keyword argument 'keepdims' when a.shape is (100,2) everything works fine but when a.shape is (1,2) i get this error got it solved ...
Author: numpy
🌐
NumPy
numpy.org › doc › 2.0 › reference › generated › numpy.sum.html
numpy.sum — NumPy v2.0 Manual
numpy.sum(a, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)[source]#
🌐
DeepLearning.AI
community.deeplearning.ai › course q&a › deep learning specialization › sequence models
Dba = np.sum(dtanh,axis=1 or keepdims = True) - Sequence Models - DeepLearning.AI
March 27, 2023 - Hi friend and mentor, In the Exercise 5 - rnn_cell_backward of Building_a_Recurrent_Neural_Network_Step_by_Step, the hint said very clear that " To calculate dba , the ‘batch’ above is a sum across all ‘m’ examples (axis= 1). Note that you should use the keepdims = True option."
🌐
Tutorial Gateway
tutorialgateway.org › python-numpy-sum
Python numpy sum
September 18, 2022 - The syntax of this statistical Python numpy sum method is · numpy.sum(a, axis = None, dtype = None, out = None, keepdims = <no value>, initial = <no value>, where = <no value>)