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
{{ message }}
Repository navigation
ENH: Alternative to random.shuffle, with an axis argument. #5173
It would be nice to have an alternative to numpy.random.shuffle that accepts an axis argument, and that independently shuffles the one-dimensional slices. Here's an implementation that I'll call disarrange. It works, but it would be nice to have a more efficient C implementation.
def disarrange(a, axis=-1):
"""
Shuffle `a` in-place along the given axis.
Apply numpy.random.shuffle to the given axis of `a`.
Each one-dimensional slice is shuffled independently.
"""
b = a.swapaxes(axis, -1)
# Shuffle `b` in-place along the last axis. `b` is a view of `a`,
# so `a` is shuffled in place, too.
shp = b.shape[:-1]
for ndx in np.ndindex(shp):
np.random.shuffle(b[ndx])
return
Example:
In [156]: a = np.arange(20).reshape(4,5)
In [157]: a
Out[157]:
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
In [158]: disarrange(a, axis=-1)
In [159]: a
Out[159]:
array([[ 2, 0, 4, 3, 1],
[ 8, 6, 7, 9, 5],
[11, 14, 13, 10, 12],
[19, 18, 16, 17, 15]])
In [160]: a = np.arange(20).reshape(4,5)
In [161]: disarrange(a, axis=0)
In [162]: a
Out[162]:
array([[ 5, 11, 7, 13, 14],
[ 0, 6, 2, 3, 4],
[10, 1, 17, 18, 19],
[15, 16, 12, 8, 9]])
Reacted by Dennis O'Brien, Leonard Papenmeier, Anatol Grabowski, kiui, Inwan Yoo, Marcelo Villa, Adam Golinski, Daniel Darabos, Maximilian Simon, Tharindu Adikari and 4 more
Don't see why this would need to be an alternative -- why not just add an
axis argument to shuffle? Defaulting to None, like np.sum.
On Sat, Oct 11, 2014 at 9:36 PM, Warren Weckesser [email protected]
wrote:
It would be nice to have an alternative to numpy.random.shuffle that
accepts an axis argument, and that independently shuffles the
one-dimensional slices. Here's an implementation that I'll call disarrange.
It works, but it would be nice to have a more efficient C implementation.
def disarrange(a, axis=-1):
"""
Shuffle a in-place along the given axis.
Apply numpy.random.shuffle to the given axis of `a`.
Each one-dimensional slice is shuffled independently.
"""
b = a.swapaxes(axis, -1)
# Shuffle `b` in-place along the last axis. `b` is a view of `a`,
# so `a` is shuffled in place, too.
shp = b.shape[:-1]
for ndx in np.ndindex(shp):
np.random.shuffle(b[ndx])
return
The current behavior of shuffle is not really like axis=None. It treats its argument as a one-dimensional sequence.
In [181]: a = np.arange(20).reshape(4,5)
In [182]: np.random.shuffle(a)
In [183]: a
Out[183]:
array([[ 0, 1, 2, 3, 4],
[15, 16, 17, 18, 19],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
You can interpret that as being axis=0, but the missing feature is the independent shuffling of the 1-D slices.
For a 2-D array, you can shuffle a.T to emulate axis=1, but this won't get you independent shuffling:
In [184]: a = np.arange(20).reshape(4,5)
In [185]: np.random.shuffle(a.T)
In [186]: a
Out[186]:
array([[ 4, 1, 0, 3, 2],
[ 9, 6, 5, 8, 7],
[14, 11, 10, 13, 12],
[19, 16, 15, 18, 17]])
In disarrange, I would expect axis=None to act like np.random.shuffle(a.flat).
It would be fine if the alternative shuffling was implemented by adding appropriate arguments to shuffle that control how it behaves, but I don't have a proposal for that API.
Oh, ugh, I just assumed that it was more consistent with analogous
functions like sort :-(. It would be nicer if this kind of
shuffling-of-slices were written like idx = arange(...); shuffle(idx);
multi_dim_array[idx, ...]; but no-one asked me :-)
I'm +1 on a version of shuffle that has calling conventions that match
np.sort, though as a rule we should check with the list. They might have
suggestions on crucial issues like the best name too :-)
(Maybe "scramble"?)
On Sat, Oct 11, 2014 at 10:31 PM, Warren Weckesser <[email protected]
wrote:
The current behavior of shuffle is not really like axis=None. It treats
its argument as a one-dimensional sequence.
In disarrange, I would expect axis=None to act like
np.random.shuffle(a.flat).
It would be fine if the alternative shuffling was implemented by adding
appropriate arguments to shuffle that control how it behaves, but I don't
have a proposal for that API.
—
Reply to this email directly or view it on GitHub #5173 (comment).
Oh, ugh, I just assumed that it was more consistent with analogous functions like sort
I was surprised, too, and based on the comments on the stackoverflow question, at least two other experienced numpy users were surprised. I'll start a discussion on the mailing list.
I guess if the average user is currently getting it wrong then it's worth
mentioning the other option -- we could add an argument to choose between
the two behaviours, which starts out defaulting to the current behaviour,
and at some point switch the default after much FutureWarning and shouting
to warn people. But that's an ugly transition to make...
On Sat, Oct 11, 2014 at 11:00 PM, Warren Weckesser <[email protected]
wrote:
Oh, ugh, I just assumed that it was more consistent with analogous
functions like sort
I was surprised, too, and based on the comments on the stackoverflow
question, at least two other experienced numpy users were surprised. I'll
start a discussion on the mailing list.
—
Reply to this email directly or view it on GitHub #5173 (comment).
changed the title [-]Enhancement Request: Alternative to `random.shuffle`, with an `axis` argument.[/-][+]ENH: Alternative to `random.shuffle`, with an `axis` argument.[/+]on Jul 19, 2018
But shuffling in place is a performance choice, isn't it?
In-place can also be a coding style choice, when available. Perhaps a confusing, and maybe error-prone one.
My personal take is that when f(x, out=x) always feels a bit magical since it is sometimes used as a very non-obvious way to achieve something quick. f(x, inplace=True), despite not looking like anything else, seems much clearer (looks a bit like an old pandas pattern that has mostly been removed).
True, but it is a coding style choice that in NumPy seems typically spelled using out=... (unless you are using an in-place operator or a method). Or maybe it is a coding style choice that NumPy doesn't actively try to make easy in most cases currently...
I admit its a bit magical and an inplace= kwarg may be less magical, but also without real precedence? And I am not sure if the main reason it seems less magical is that the in-place shuffle is at the core of the algorithm here. Algorithmic details should not matter much to most students and in the end it using out= also safes approximately a single copy+the associated memory bandwidth, and is is comparable to ufuncs. (Fair enough, also for ufuncs out=input is maybe somewhat magical, but its common magic and a known pattern – for advanced users.)
While possible a bit tedious to write, and somewhat less quick to read, np.shuffled(x, out=x) seems very clear as to what the behaviour is. The non-obvious part seems only the performance impact, which to me seems like an issue reserved for advanced users to worry about.
A hypothetical question for those advocating the use of out: if we didn't have the existing functions numpy.sort and ndarray.sort, and we were adding a sorting function now, would the preferred API be numpy.sorted(a, axis=-1, kind=None, order=None, out=None) (with no need to implement the method ndarray.sort for in-place sorting)?
ndarray.sort is modelled after list.sort, so it probably is a sensible API choice regardless. That said, I would have been in favor of np.sort not existing, and np.sorted(..., out=...) instead.
Yes, I think np.sort should be named np.sorted (just like python's sorted() after all). Since only the method has the in-place behaviour, I don't see much of a concern though.
I am not sure about the "with no need to implemented the method ndarray.sort". I do not see anything wrong with the method (or its in-place behaviour). The question about the method is merely if we feel it is important enough to provide a convenient method short-hand.
I suppose there is also nothing wrong with having an in-place function version. The not-in-place version just seems nicer to new users and out= pattern common enough to me that advanced users are sufficiently well served.
I am not sure about the "with no need to implemented the method ndarray.sort". I do not see anything wrong with the method (or its in-place behaviour).
That was part of my API thought experiment. I'm didn't mean to imply that there is anything wrong with what we have now. I was just saying that, if we started from scratch--and I'll add to my hypothetical premises that we aren't concerned with matching the Python API for lists--then the preferred API for sorting would be numpy.sorted(..., out=...), and we wouldn't need anything else.
Another question, not so hypothetical: if using out is the preferred option here, then, for API consistency throughout NumPy, should we plan on eventually adding out to numpy.sort, numpy.partition, numpy.argsort, and, well, everything else that doesn't currently have it?
Yes, in my opinion adding an out= kwarg with the same semantics as for ufuncs is a good choice for practically all NumPy API function. Any lack of an out argument is generally an enhancement waiting to be made (although, I guess in practice it may be a small enhancement and in rare cases possibly not worth too much added code complexity).
Activity
njsmith commentedon Oct 11, 2014
Don't see why this would need to be an alternative -- why not just add an
axis argument to shuffle? Defaulting to None, like np.sum.
On Sat, Oct 11, 2014 at 9:36 PM, Warren Weckesser [email protected]
wrote:
Nathaniel J. Smith
Postdoctoral researcher - Informatics - University of Edinburgh
http://vorpus.org
WarrenWeckesser commentedon Oct 11, 2014
The current behavior of
shuffleis not really likeaxis=None. It treats its argument as a one-dimensional sequence.You can interpret that as being
axis=0, but the missing feature is the independent shuffling of the 1-D slices.For a 2-D array, you can shuffle
a.Tto emulateaxis=1, but this won't get you independent shuffling:In
disarrange, I would expectaxis=Noneto act likenp.random.shuffle(a.flat).It would be fine if the alternative shuffling was implemented by adding appropriate arguments to
shufflethat control how it behaves, but I don't have a proposal for that API.WarrenWeckesser commentedon Oct 11, 2014
Perhaps two arguments could be added to
shuffle:axisandindependent(or something along those lines). The new signature would be:When
independentis False, it acts like the currentshuffle. When True, it acts likedisarrange.njsmith commentedon Oct 11, 2014
Oh, ugh, I just assumed that it was more consistent with analogous
functions like sort :-(. It would be nicer if this kind of
shuffling-of-slices were written like idx = arange(...); shuffle(idx);
multi_dim_array[idx, ...]; but no-one asked me :-)
I'm +1 on a version of shuffle that has calling conventions that match
np.sort, though as a rule we should check with the list. They might have
suggestions on crucial issues like the best name too :-)
(Maybe "scramble"?)
On Sat, Oct 11, 2014 at 10:31 PM, Warren Weckesser <[email protected]
Nathaniel J. Smith
Postdoctoral researcher - Informatics - University of Edinburgh
http://vorpus.org
WarrenWeckesser commentedon Oct 11, 2014
Ah, describing the desired behavior as an analog of
sortis a good idea.WarrenWeckesser commentedon Oct 11, 2014
I was surprised, too, and based on the comments on the stackoverflow question, at least two other experienced numpy users were surprised. I'll start a discussion on the mailing list.
njsmith commentedon Oct 11, 2014
I guess if the average user is currently getting it wrong then it's worth
mentioning the other option -- we could add an argument to choose between
the two behaviours, which starts out defaulting to the current behaviour,
and at some point switch the default after much FutureWarning and shouting
to warn people. But that's an ugly transition to make...
On Sat, Oct 11, 2014 at 11:00 PM, Warren Weckesser <[email protected]
Nathaniel J. Smith
Postdoctoral researcher - Informatics - University of Edinburgh
http://vorpus.org
charris commentedon Oct 11, 2014
We need a function named Sue.
SuperElectric commentedon Apr 8, 2015
Just wanted to +1 this feature, as I too expected it to exist, analogously to sort(axis=N). Was there any decision made on the mailing list?
ewmoore commentedon Apr 8, 2015
The mailing list thread is here:
http://thread.gmane.org/gmane.comp.python.numeric.general/59014
[-]Enhancement Request: Alternative to `random.shuffle`, with an `axis` argument.[/-][+]ENH: Alternative to `random.shuffle`, with an `axis` argument.[/+]talesa commentedon Feb 5, 2019
This would be really useful!
Max16hr commentedon Feb 25, 2019
I also would appreciate that!
According to https://stackoverflow.com/a/35647011/3401634, for multi-dimensional arrays
Xis the same as
So why not implement
as
with the default
axis=0?17 remaining items
bashtage commentedon Jul 6, 2020
In-place can also be a coding style choice, when available. Perhaps a confusing, and maybe error-prone one.
My personal take is that when f(x, out=x) always feels a bit magical since it is sometimes used as a very non-obvious way to achieve something quick. f(x, inplace=True), despite not looking like anything else, seems much clearer (looks a bit like an old pandas pattern that has mostly been removed).
seberg commentedon Jul 6, 2020
True, but it is a coding style choice that in NumPy seems typically spelled using
out=...(unless you are using an in-place operator or a method). Or maybe it is a coding style choice that NumPy doesn't actively try to make easy in most cases currently...I admit its a bit magical and an
inplace=kwarg may be less magical, but also without real precedence? And I am not sure if the main reason it seems less magical is that the in-place shuffle is at the core of the algorithm here. Algorithmic details should not matter much to most students and in the end it usingout=also safes approximately a single copy+the associated memory bandwidth, and is is comparable to ufuncs. (Fair enough, also for ufuncsout=inputis maybe somewhat magical, but its common magic and a known pattern – for advanced users.)While possible a bit tedious to write, and somewhat less quick to read,
np.shuffled(x, out=x)seems very clear as to what the behaviour is. The non-obvious part seems only the performance impact, which to me seems like an issue reserved for advanced users to worry about.WarrenWeckesser commentedon Jul 6, 2020
A hypothetical question for those advocating the use of
out: if we didn't have the existing functionsnumpy.sortandndarray.sort, and we were adding a sorting function now, would the preferred API benumpy.sorted(a, axis=-1, kind=None, order=None, out=None)(with no need to implement the methodndarray.sortfor in-place sorting)?eric-wieser commentedon Jul 6, 2020
ndarray.sortis modelled afterlist.sort, so it probably is a sensible API choice regardless. That said, I would have been in favor ofnp.sortnot existing, andnp.sorted(..., out=...)instead.seberg commentedon Jul 6, 2020
Yes, I think
np.sortshould be namednp.sorted(just like python'ssorted()after all). Since only the method has the in-place behaviour, I don't see much of a concern though.I am not sure about the "with no need to implemented the method
ndarray.sort". I do not see anything wrong with the method (or its in-place behaviour). The question about the method is merely if we feel it is important enough to provide a convenient method short-hand.I suppose there is also nothing wrong with having an in-place function version. The not-in-place version just seems nicer to new users and
out=pattern common enough to me that advanced users are sufficiently well served.WarrenWeckesser commentedon Jul 6, 2020
That was part of my API thought experiment. I'm didn't mean to imply that there is anything wrong with what we have now. I was just saying that, if we started from scratch--and I'll add to my hypothetical premises that we aren't concerned with matching the Python API for lists--then the preferred API for sorting would be
numpy.sorted(..., out=...), and we wouldn't need anything else.WarrenWeckesser commentedon Jul 6, 2020
Another question, not so hypothetical: if using
outis the preferred option here, then, for API consistency throughout NumPy, should we plan on eventually addingouttonumpy.sort,numpy.partition,numpy.argsort, and, well, everything else that doesn't currently have it?seberg commentedon Jul 6, 2020
Yes, in my opinion adding an
out=kwarg with the same semantics as for ufuncs is a good choice for practically all NumPy API function. Any lack of anoutargument is generally an enhancement waiting to be made (although, I guess in practice it may be a small enhancement and in rare cases possibly not worth too much added code complexity).ENH: random: Add the method `permuted` to Generator. (#15121)