Skip to content

min/max of empty arrays  #5032

Closed
Closed

Description

@bsipocz

A similar issue was raised in #2670, however the edge case of (0, ) shape is still not covered. I can go around it with checking for non-zero length in an if statement, but it would be more practical if np.min could handle this, too.

In [24]: [np.min(param[x][1]) for x in fields]
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-24-076aa74e3684> in <module>()
----> 1 [np.min(param[x][1]) for x in fields]

/data/wts/pipeline64/python/lib/python2.6/site-packages/numpy/core/fromnumeric.pyc in amin(a, axis, out)
   1893     except AttributeError:
   1894         return _wrapit(a, 'min', axis, out)
-> 1895     return amin(axis, out)
   1896 
   1897 

ValueError: zero-size array to minimum.reduce without identity

In [25]: param[x]
Out[25]: 
{1: array([], dtype=float64),
 2: array([], dtype=float64),
 3: array([], dtype=float64),
 4: array([], dtype=float64)}

In [26]: param[x][1].shape
Out[26]: (0,)

Activity

  1. seberg commented on Sep 3, 2014

    @seberg
    Member

    gh-2670 is a very different thing. There you calculate the min/max over 2 elements, you just happen to do it 0 times. Here you want to calculate the min/max over 0 elements and that is not well defined.

    What is min([])? We can define sum([]) as 0 easily. But -Inf/+Inf for min/max does not seem elegant/clear to be correct. So we raise an error instead at the moment.

  2. seberg commented on Sep 3, 2014

    @seberg
    Member

    I will close this for now, but please feel free to ask/post more and convince me otherwise :).

  3. bsipocz commented on Sep 3, 2014

    @bsipocz
    MemberAuthor

    OK, I see your point, however can't see why it behaves differently for different empty arrays (e.g. getting the minimum for axis=1 and axis=0 in #2670's example). Both are empty, still the minimum will be either an empty array or a ValueError.
    To be honest, I would be most happy with a nan as a result to min([]), at least it seems more reasonable than an error.

    In [12]: a = numpy.zeros((0,2))
    
    In [13]: a
    Out[13]: array([], shape=(0, 2), dtype=float64)
    
    In [14]: np.min(a, axis=1)
    Out[14]: array([], dtype=float64)
    
    In [15]: np.min(a, axis=0)
    ---------------------------------------------------------------------------
    ValueError                                Traceback (most recent call last)
    <ipython-input-15-c8666bcd2a35> in <module>()
    ----> 1 np.min(a, axis=0)
    
    /data/wts/pipeline64/python/lib/python2.6/site-packages/numpy/core/fromnumeric.pyc in amin(a, axis, out)
       1893     except AttributeError:
       1894         return _wrapit(a, 'min', axis, out)
    -> 1895     return amin(axis, out)
       1896 
       1897 
    
    ValueError: zero-size array to minimum.reduce without identity
    
  4. pv commented on Sep 3, 2014

    @pv
    Member

    As noted above, the difference is that axis=1 computes minimum over two elements, whereas axis=0 computes it over zero elements. Only the latter has to invent numbers with undefined values as the results.

    In principle, inf is the identity for minimum and -inf the identity for maximum, but min([]) == inf may be surprising.

  5. seberg commented on Sep 3, 2014

    @seberg
    Member

    Maybe to make the difference more clear, compare it with sum:

    In [2]: np.ones((2, 0)).sum(0)
    Out[2]: array([], dtype=float64)
    
    In [3]: np.ones((2, 0)).sum(1)
    Out[3]: array([ 0.,  0.])
    

    In one case, the result is empty itself, in the other case it is not. What happens if you got np.ones((0, 0)).min(0) is philosophical.

    Certainly not raising an error but returning something like NaN or Inf might be a reasonable choice, but I think it would be a rather largish change and changing it would have to follow a discussion the mailing list.
    Though to be clear, personally I prefer raising the error here, inconvenient for some, but not as surprising for others, and I doubt there will be much will to change it.

  6. njsmith commented on Sep 3, 2014

    @njsmith
    Member

    -10 on returning Nan (that's just wrong!), -1 on Inf (what do you do
    for dtypes that don't have inf?)

    and anyway all of the reduction operations behave like this, e.g.:

    In [2]: np.divide.reduce([])
    ValueError: zero-size array to reduction operation divide which has no identity
    
  7. ewmoore commented on Sep 3, 2014

    @ewmoore
    Contributor

    It seems to me that only thing you could really return is an empty array.
    But that ship sailed long ago. (And doesn't really seem useful).

  8. SomeoneSerge commented on Oct 25, 2017

    @SomeoneSerge

    I believe it'd be perfectly fine to provide an option to manually specify meaningful identity in a min/max/reduce call.
    Like np.zeros((0,0)).min(identity=np.inf) yields infty,
    while np.zeros((0,0)).min() can still throw a ValueError or whatever.

  9. eric-wieser commented on Oct 25, 2017

    @eric-wieser
    Member

    @RerumNovarum : Before anything like that can be implemented, #8955 needs to be merged

  10. hameerabbasi commented on Feb 20, 2018

    @hameerabbasi
    Contributor

    Repeating from #8955:

    I would suggest adding identities to np.minimum and np.maximum, which would be +inf and -inf respectively. This is intuitively and logically true, as max(a, -inf) = a and min(a, +inf) = a.

    I agree this probably doesn't match Python conventions but does make sense mathematically. Not to mention, np.nanmin(all-nan) and np.min([]) should be np.inf (Mathematically speaking).

    I agree it depends on how you define it, but this is probably the most widely accepted view.

  11. eric-wieser commented on Feb 20, 2018

    @eric-wieser
    Member

    Your argument for signed inf is valid (indeed, it is probably the best choice other than erroring), but there are valid arguments against it too:

    • min(np.array(data, int16)).dtype == np.int16 must be true even when len(data) == 0 - so returning inf is not possible for integer types. We could return np.iinfo(int16).min, but that would probably be surprising.
    • max(abs(complex_vals)) has a natural identity of 0, not -infinity, but there's no way for max to distinguish that case. Elsewhere a max_abs ufunc has been proposed to solve that problem.

    It's worth noting that core python has decided that max([]) should error, and that max([], default=-inf) is the way to spell the behavior you want. Perhaps we should aim for something similar.

  12. hameerabbasi commented on Feb 20, 2018

    @hameerabbasi
    Contributor

    min(np.array(data, int16)).dtype must return an int16 even when len(data) == 0 - so returning inf is not possible

    I guess you could cast and then return whatever is the maximum of int16, which would be valid too (as the universal set is the set of all int16). I guess it comes down to whether we want the maximum or the supremum (the only difference for finite sets being that the supremum would be what I say and and the maximum not well defined for empty sets).

    max(abs(complex_vals)) has a natural identity of 0, not -infinity, but there's no way for max to distinguish that case. Elsewhere a max_abs ufunc has been proposed to solve that problem.

    I would still argue that the identity value should be -inf in this case, and we should aim for np.max(np.abs(complex_vals), identity=0).

    Edit: Or maybe np.maximum(np.max(np.abs(complex_vals)), 0) would also work. I'd argue against adding identity= everywhere because it requires core changes.

  13. eric-wieser commented on Feb 20, 2018

    @eric-wieser
    Member

    I would still argue that the identity value should be -inf in this case

    I think this would be too surprising to be useful. Summarizing the problem:

    • Let X be some set of values
    • Let Y be N samples from X
    • Expectation: min(Y) is in X

    The only way this can hold when N == 0, and still satisfy the property of being an identity, is if min([]) == min(X) — but min has no way of know what min(X) is. When X is ℝ, then the answer is -inf. But in general, numpy shouldn't assume the invariants of the set of values the user is passing, even if the assumption is often correct.

    To quote the zen of python

    In the face of ambiguity, refuse the temptation to guess.

    So I'm also -1 on a default for empty arrays.

    I'm +1 on allowing np.max(np.abs(complex_vals), identity=0). I though that was blocked by gh-8955, but actually I think it was only blocked by gh-8952 (now merged), so a patch would be welcome!

    That patch would look something like adding an identity argument to the C PyUFunc_Reduce function, and using it in place of _get_identity(ufunc) if provided.

  14. hameerabbasi commented on Feb 20, 2018

    @hameerabbasi
    Contributor

    I'll look into it. I'm not too deep into the annals of core Numpy, if you could point me towards relevant files that'd be a big help. As long as they're Cython/Pure C++ I should be able to do it, but if they're Python API C++... I'm not entirely sure.

    Edit: I'm talking about implementing identity=

  15. 5 remaining items

  16. hameerabbasi commented on Feb 20, 2018

    @hameerabbasi
    Contributor

    Can you reopen the issue?

  17. reopened this on Mar 26, 2018
  18. seberg commented on Apr 26, 2018

    @seberg
    Member

    why reopen? Having an initial seems like the only thing to do here for sure?

  19. seberg commented on Apr 26, 2018

    @seberg
    Member

    Ooops misread, har :)

  20. carlosgmartin commented on Nov 28, 2023

    @carlosgmartin
    Contributor

    FWIW, I agree with @hameerabbasi. Just as the

    • sum of an empty array is the identity element of addition, which is zero
    • prod of an empty array is the identity element of multiplication, which is one

    It ought to be the case that the

    • max of an empty array is the identity element of max, which is the least element of its dtype
    • min of an empty array is the identity element of min, which is greatest element of its dtype

    This is the mathematically correct way to treat the supremum/infimum of an empty collection.

    Related: jax-ml/jax#18661.

  21. jakevdp commented on Nov 28, 2023

    @jakevdp
    Contributor

    Echoing some of my thoughts from jax-ml/jax#18661 here in case it is helpful:

    The problem with using the identity for min/max is that the supremum and infimum are only well-defined for bounded sets. Real numbers and integers are unbounded sets, so the supremum and infimum are not defined. While it's true that fixed-width approximations to these sets (like the sets of values representable by float64 or int64) are bounded, it would be confusing to use their supremum or infimum as identities of min and max, because these are properties of the implementation, not properties of the numbers that the implementation represents (and no, $\infty$ is not a real number 😁).

    Contrast this with sum/prod, in which the identities are well-defined for integers and real numbers, so it makes sense to return those identities in the case of a reduction over an empty array.

    All that to say, I think the current approach used by both NumPy and Python (where min/max of empty sequences errors, unless an explicit identity is provided) is the right default behavior.

  22. rkern commented on Nov 28, 2023

    @rkern
    Member

    FWIW, IEEE 754 floating point numbers model the affinely extended reals more so than the reals, per se, and -∞ and +∞ are perfectly fine members and indeed the well-defined infimum and supremum identity values for min and max.

    While I don't think it's necessary to define the result of min and max on empty typed arrays like that, I think it'd be valid and no more confusing than any of the other places where we use the properties of the specific dtype. For the integer dtypes, the finite bounds come into play elsewhere; I'm not sure why it would be confusing to use them in a mathematical place where such bounds are quite salient.

  23. jakevdp commented on Nov 28, 2023

    @jakevdp
    Contributor

    OK, fair enough. But I do think it would be quite surprising and confusing to the majority of NumPy users if np.arange(0).min() were to return 9223372036854775807.

  24. SomeoneSerge commented on Nov 28, 2023

    @SomeoneSerge

    +1 to throwing an exception but accepting an optional identity=; I forget what my use-case was at the time, but there were values that made sense in the specific context.

    We don't have to make assumptions about how exactly the end users interpret their numbers, so let's just not

  25. jakevdp commented on Nov 28, 2023

    @jakevdp
    Contributor

    +1 to throwing an exception but accepting an optional identity=

    Note that the identity argument is already available as of NumPy 1.15 (but it's called initial):

    >>> np.arange(0).min(initial=np.iinfo('int64').max)
    9223372036854775807
  26. carlosgmartin commented on Nov 28, 2023

    @carlosgmartin
    Contributor

    A possible compromise / feature that occurs to me is adding .max and .min attributes / properties directly to dtypes, instead of alternating between iinfo, finfo, and a special case for bool, depending on the type.

    a.max(initial=a.dtype.min)

    From an API design POV, it seems to me that the common fields of the objects returned by iinfo and finfo (min, max, bits) ought to be accessible via the same interface.

  27. seberg commented on Nov 29, 2023

    @seberg
    Member

    A possible compromise / feature that occurs to me is adding .max and .min attributes

    I have made a lot of work to allow adding such attributes to the dtype instances (not sure I like min/max, it feels like .info.min or just something longer may be better).
    In fact, I always thought that is where finfo/iinfo must move long term. So I would welcome work for going towards that.

    but it's called initial

    Right, just to note that the name is of course intentional, because identity hints to unrelated properties. Also I want(ed) the freedom to add a default= which is not used as the initial value for the reduce-like operation but returned for empty results. That would allow default=np.nan to return NaN for empty min.


    Besides boolean, where I guess it is fully unambigious. It seems to me that we will remain at: yes, it is plausible to use ±inf, but it is unclear that it is better.

    I do think both are valid choices, but it still seems like more guesswork to me than others (like mean([]) returning NaN, because it does sum([])/0 = 0/0).

    Probably the reason is that within many contexts the actual minimum value may be well defined, e.g. 0. Also, I would think you should give an "infinity created" (division by zero) warning, which would be tedious ;).

  28. carlosgmartin commented on Aug 23, 2024

    @carlosgmartin
    Contributor

    A possible compromise / feature that occurs to me is adding .max and .min attributes

    I have made a lot of work to allow adding such attributes to the dtype instances (not sure I like min/max, it feels like .info.min or just something longer may be better). In fact, I always thought that is where finfo/iinfo must move long term. So I would welcome work for going towards that.

    I'm interested in a uniform interface for accessing the minimum/maximum value of a given dtype (JAX example). Is there an open issue discussing this? If not, I could open one.

  29. seberg commented on Aug 24, 2024

    @seberg
    Member

    Not sure, #27231 is somewhat related, though. You can open a new one and even work on it if you like.

    (I am not sure how simple it would be to add these attributes. It might be very weedy in C, but actually, I think it may just be possible to do it in np.dtypes. in Python. In which case the only complicated thing is to make the decision.)

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