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.

Answer from alkasm on Stack Overflow
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.

🌐
GitHub
github.com › dask › dask › issues › 5029
sum() got an unexpected keyword argument 'keepdims' · Issue #5029 · dask/dask
June 30, 2019 - sum() got an unexpected keyword argument 'keepdims'#5029 · #5035 · Copy link · Labels · dataframe · erdnaavlis · opened · on Jun 30, 2019 · Issue body actions · I'm not sure if this is related to #4311 because in my case it only occurs using Dask. Also, before, I was on Dask 1.2.0 and this error was inexistent: Dask 2.0.0+11.g7f26af69 ·
Author: dask
🌐
GitHub
github.com › theislab › diffxpy › issues › 203
TypeError: sum() got an unexpected keyword argument 'keepdims' · Issue #203 · theislab/diffxpy
July 14, 2021 - TypeError: sum() got an unexpected keyword argument 'keepdims'#203 · Copy link · Gibbsdavidl · opened · on Jul 14, 2021 · Issue body actions · Anyone know how to solve this? Seems like it's a dask / pandas conflict. I'm on ubuntu 20.04, pandas 1.3, and whatever the newest dask is (2021.7.0)?
Author: theislab
🌐
GitHub
github.com › timomernick › pytorch-capsule › issues › 3
TypeError: sum() got an unexpected keyword argument 'keepdim' · Issue #3 · timomernick/pytorch-capsule
November 7, 2017 - I get a error: File "/home/ai/pytorch-capsule-master/capsule_layer.py", line 53, in squash mag_sq = torch.sum(s**2, dim=2, keepdim=True) TypeError: sum() got an unexpected keyword argument 'keepdim' how to fix this? pip install torch-ver...
Author: timomernick
🌐
GitHub
github.com › cupy › cupy › issues › 9026
spmatrix.sum() got an unexpected keyword argument 'keepdims' · Issue #9026 · cupy/cupy
March 11, 2025 - Description Hi, When I use package scanpy in GPU to process data, I encountered an error in the title. It looks like the csr_matrix created by the cupyx.scipy method is not compatible with some pac...
Author: cupy
🌐
Stack Overflow
stackoverflow.com › questions › 62138655 › numpy-sum-with-keepdims-argument-raises-unexpected-keyword-argument
python - Numpy sum with keepdims argument raises unexpected keyword argument - Stack Overflow
June 1, 2020 - numpy.sum() gives `TypeError: sum() got an unexpected keyword argument 'dtype'` 1 · numpy sum gives error · 6 · Why does Python crash when I try to sum this numpy array? 0 · numpy sum gives an error · 64 · In numpy.sum() there is parameter called "keepdims".
🌐
CopyProgramming
copyprogramming.com › howto › numpy-sum-got-an-keepdims-error
Python: Error in 'keepdims' parameter observed in Numpy's sum() function
April 23, 2023 - The optional parameter "keepdims" can be set to True to retain the axes that have been reduced as dimensions with a size of one in the resulting array. This enables correct broadcasting against the input array. However, if the default value is used, "keepdims" will not be passed through to ...
🌐
GitHub
github.com › triton-lang › triton › issues › 3804
TypeError("sum() got an unexpected keyword argument 'keep_dims'") · Issue #3804 · triton-lang/triton
April 30, 2024 - with the error message shown in the title. However, I believe that sum should expect keep_dims to specify whether the dim is maintained or not (https://triton-lang.org/main/python-api/generated/triton.language.sum.html#triton.language.sum)
Author: triton-lang
Find elsewhere
🌐
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
🌐
GitHub
github.com › Leavingseason › rnn_recsys › issues › 3
TypeError: reduce_sum() got an unexpected keyword argument 'keepdims' · Issue #3 · Leavingseason/rnn_recsys
September 11, 2018 - 1.4.0 Traceback (most recent call last): File "train.py", line 233, in train_RS() File "train.py", line 124, in train_RS my_model = RNNRS(**hparams) File "/home/mldl/ub16_prj/rnn_recsys/models/RNNRS.py", line 35, in init self.predictions, self.error, self.loss, self.train_step, self.summary = self._build_model() File "/home/mldl/ub16_prj/rnn_recsys/models/RNNRS.py", line 65, in _build_model preds = tf.sigmoid( tf.reduce_sum(tf.multiply(u_t, self.Item), 1, keepdims = True) + global_bias , name= 'prediction') ##-- TypeError: reduce_sum() got an unexpected keyword argument 'keepdims' Exception ig
Author: Leavingseason
🌐
GitHub
github.com › numpy › numpy › issues › 7537
np.sum does not respect keepdims for np.ma.arrays · Issue #7537 · numpy/numpy
April 11, 2016 - Furthermore, if we try xm.sum(axis=1, keepdims=True) we get: TypeError: sum() got an unexpected keyword argument 'keepdims' For completeness: >>> np.__version__ '1.10.1' No one assigned · No labels · No labels · No type · No projects · No milestone · None yet · No branches or pull requests ·
Author: numpy
🌐
GitHub
github.com › numpy › numpy › issues › 4537
ma.sum() does not support keepdims argument · Issue #4537 · numpy/numpy
March 23, 2014 - ma.sum() does not support keepdims argument#4537 · Copy link · abalkin · opened · on Mar 23, 2014 · Issue body actions · >>> np.sum([1, 2], keepdims=True) array([3]) >>> ma.sum([1, 2], keepdims=True) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "numpy/ma/core.py", line 6025, in __call__ return method(MaskedArray(a), *args, **params) TypeError: sum() got an unexpected keyword argument 'keepdims' Reactions are currently unavailable ·
Author: numpy
🌐
NumPy
numpy.org › devdocs › reference › generated › numpy.sum.html
numpy.sum — NumPy v2.6.dev0 Manual
numpy.sum(a, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)[source]#
🌐
PyTorch Forums
discuss.pytorch.org › t › no-keepdim-in-pytorch › 2999
No `keepdim` in PyTorch - PyTorch Forums
May 15, 2017 - Dear guys, I figure out that some functions in PyTorch like torch.max() or torch.sum() don't have keepdim argument thought it is available in the document. For example, if I run the following code: import numpy as np…
🌐
Codeleading
codeleading.com › article › 48216316245
TypeError: sum() got an unexpected keyword argument ‘keepdims‘ - 代码先锋网
np.sum(a, axis = 0 ,keepdims = True) # 报错TypeError: sum() got an unexpected keyword argument 'keepdims' # 报错原因是输出已经为矩阵,所以keepdims参数无意义
🌐
Pandas
pandas.pydata.org › docs › _sources › whatsnew › v2.1.0.rst.txt
Show Source - Pandas - PyData |
August 30, 2023 - Pandas can now keep the dtypes ... df.sum() Notice that the dtype is now a masked dtype and PyArrow dtype, respectively, while previously it was a NumPy integer dtype. To allow DataFrame reductions to preserve extension dtypes, :meth:`.ExtensionArray._reduce` has gotten a new keyword parameter ``keepdims``. Calling ...
🌐
NumPy
numpy.org › doc › stable › release › 1.12.0-notes.html
NumPy 1.12.0 Release Notes — NumPy v2.4 Manual
Any user-provided value of keepdims is passed through as a keyword argument to the method. This will raise in the case where the method does not support a keepdims kwarg and the user explicitly passes in keepdims. The following functions are changed: sum, product, sometrue, alltrue, any, all, ...