Skip to content

Add keepdims argument to argmin and argmax #8710

Closed

Description

@eric-wieser

For consistency with min and max, so that the returned object is the same shape.

Activity

  1. eric-wieser commented on Feb 27, 2017

    @eric-wieser
    MemberAuthor

    This might actually be done best by making argmin a gufunc?

  2. eric-wieser commented on Feb 28, 2017

    @eric-wieser
    MemberAuthor

    Trivial implementation:

    def argmin(*args, keepdims=False, **kwargs):
        res = np.argmin(*args, **kwargs)
        axis = kwargs.get('axis', none)
        if axis is not None:
            res = np.expand_dims(res, axis=axis)
        return res
  3. shoyer commented on Feb 28, 2017

    @shoyer
    Member

    This might actually be done best by making argmin a gufunc?

    The challenge here is that only ufunc.reduce has the logic for axis handling. That's not something that exists for general ufuncs, though it probably should (#5197), at least for simple cases like these where the ufunc signature looks like (n)->().

  4. eric-wieser commented on Dec 1, 2018

    @eric-wieser
    MemberAuthor

    The next problem is that argmin supports axis=None, which ufuns do not. Perhaps argmin should just wrap a ufunc?

  5. FabianSchuetze commented on Mar 9, 2019

    @FabianSchuetze

    I would be glad about this features. As I was thinking of trying to contribute to numpy for some time, would somebody mind if I simply tried to implement the feature according to the development workflow?

  6. yarki commented on Jul 14, 2019

    @yarki

    Folks, below is the workaround I'm currently using. Please reply if you see a better way to preserve original dimensions. Thanks.

    def argmax_keepdims(x, axis):
        """
        Returns the indices of the maximum values along an axis.
    
        The axis which is reduced is left in the result as dimension with size one.
        The result will broadcast correctly against the input array.
    
        Original numpy.argmax() implementation does not currently support the keepdims parameter.
        See https://github.com/numpy/numpy/issues/8710 for further information.
        """
        output_shape = list(x.shape)
        output_shape[axis] = 1
        return np.argmax(x, axis=axis).reshape(output_shape)
  7. arvoelke commented on Sep 12, 2020

    @arvoelke
    Contributor

    In my case np.unravel_index(np.argmax(x), x.shape) did what I needed (flattens the array, takes the argmax, and then reinterprets the index with respect to the original shape). Your mileage may vary depending on what you are trying to do of course.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions