You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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,)
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.
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
+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
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.
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 ;).
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.
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.)
Activity
seberg commentedon Sep 3, 2014
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 definesum([])as0easily. But-Inf/+Inffor min/max does not seem elegant/clear to be correct. So we raise an error instead at the moment.seberg commentedon Sep 3, 2014
I will close this for now, but please feel free to ask/post more and convince me otherwise :).
bsipocz commentedon Sep 3, 2014
OK, I see your point, however can't see why it behaves differently for different empty arrays (e.g. getting the minimum for
axis=1andaxis=0in #2670's example). Both are empty, still the minimum will be either an empty array or aValueError.To be honest, I would be most happy with a
nanas a result tomin([]), at least it seems more reasonable than an error.pv commentedon Sep 3, 2014
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,
infis the identity forminimumand-infthe identity formaximum, butmin([]) == infmay be surprising.seberg commentedon Sep 3, 2014
Maybe to make the difference more clear, compare it with
sum: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.
njsmith commentedon Sep 3, 2014
-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.:
ewmoore commentedon Sep 3, 2014
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).
SomeoneSerge commentedon Oct 25, 2017
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 aValueErroror whatever.eric-wieser commentedon Oct 25, 2017
@RerumNovarum : Before anything like that can be implemented, #8955 needs to be merged
hameerabbasi commentedon Feb 20, 2018
Repeating from #8955:
I would suggest adding identities to
np.minimumandnp.maximum, which would be+infand-infrespectively. This is intuitively and logically true, asmax(a, -inf) = aandmin(a, +inf) = a.I agree this probably doesn't match Python conventions but does make sense mathematically. Not to mention,
np.nanmin(all-nan)andnp.min([])should benp.inf(Mathematically speaking).I agree it depends on how you define it, but this is probably the most widely accepted view.
eric-wieser commentedon Feb 20, 2018
Your argument for signed
infis 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.int16must be true even whenlen(data) == 0- so returning inf is not possible for integer types. We could returnnp.iinfo(int16).min, but that would probably be surprising.max(abs(complex_vals))has a natural identity of0, not-infinity, but there's no way formaxto distinguish that case. Elsewhere amax_absufunc has been proposed to solve that problem.It's worth noting that core python has decided that
max([])should error, and thatmax([], default=-inf)is the way to spell the behavior you want. Perhaps we should aim for something similar.hameerabbasi commentedon Feb 20, 2018
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 allint16). 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).I would still argue that the identity value should be
-infin this case, and we should aim fornp.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 addingidentity=everywhere because it requires core changes.eric-wieser commentedon Feb 20, 2018
I think this would be too surprising to be useful. Summarizing the problem:
The only way this can hold when N == 0, and still satisfy the property of being an identity, is if
min([]) == min(X)— butminhas no way of know whatmin(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
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
identityargument to the CPyUFunc_Reducefunction, and using it in place of_get_identity(ufunc)if provided.hameerabbasi commentedon Feb 20, 2018
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=5 remaining items
hameerabbasi commentedon Feb 20, 2018
Can you reopen the issue?
seberg commentedon Apr 26, 2018
why reopen? Having an initial seems like the only thing to do here for sure?
seberg commentedon Apr 26, 2018
Ooops misread, har :)
carlosgmartin commentedon Nov 28, 2023
FWIW, I agree with @hameerabbasi. Just as the
It ought to be the case that the
This is the mathematically correct way to treat the supremum/infimum of an empty collection.
Related: jax-ml/jax#18661.
jakevdp commentedon Nov 28, 2023
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$\infty$ is not a real number 😁).
float64orint64) 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,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.
rkern commentedon Nov 28, 2023
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
minandmax.While I don't think it's necessary to define the result of
minandmaxon 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 specificdtype. 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.jakevdp commentedon Nov 28, 2023
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 return9223372036854775807.SomeoneSerge commentedon Nov 28, 2023
+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
jakevdp commentedon Nov 28, 2023
Note that the identity argument is already available as of NumPy 1.15 (but it's called
initial):carlosgmartin commentedon Nov 28, 2023
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.
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.
seberg commentedon Nov 29, 2023
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.minor 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.
Right, just to note that the name is of course intentional, because
identityhints to unrelated properties. Also I want(ed) the freedom to add adefault=which is not used as the initial value for the reduce-like operation but returned for empty results. That would allowdefault=np.nanto returnNaNfor 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([])returningNaN, because it doessum([])/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 ;).carlosgmartin commentedon Aug 23, 2024
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.
seberg commentedon Aug 24, 2024
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.)