Skip to content

ENH: Alternative to random.shuffle, with an axis argument. #5173

Closed

Description

@WarrenWeckesser

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]])

This request was motivated by this question on stackoverflow: http://stackoverflow.com/questions/26310346/quickly-calculate-randomized-3d-numpy-array-from-2d-numpy-array/

Activity

  1. njsmith commented on Oct 11, 2014

    @njsmith
    Member

    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
    

    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]])

    This request was motivated by this question on stackoverflow:
    http://stackoverflow.com/questions/26310346/quickly-calculate-randomized-3d-numpy-array-from-2d-numpy-array/

    —
    Reply to this email directly or view it on GitHub
    #5173.

    Nathaniel J. Smith
    Postdoctoral researcher - Informatics - University of Edinburgh
    http://vorpus.org

  2. WarrenWeckesser commented on Oct 11, 2014

    @WarrenWeckesser
    MemberAuthor

    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.

  3. WarrenWeckesser commented on Oct 11, 2014

    @WarrenWeckesser
    MemberAuthor

    Perhaps two arguments could be added to shuffle: axis and independent (or something along those lines). The new signature would be:

    def shuffle(a, independent=False, axis=0)
    

    When independent is False, it acts like the current shuffle. When True, it acts like disarrange.

  4. njsmith commented on Oct 11, 2014

    @njsmith
    Member

    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 [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.

    —
    Reply to this email directly or view it on GitHub
    #5173 (comment).

    Nathaniel J. Smith
    Postdoctoral researcher - Informatics - University of Edinburgh
    http://vorpus.org

  5. WarrenWeckesser commented on Oct 11, 2014

    @WarrenWeckesser
    MemberAuthor

    Ah, describing the desired behavior as an analog of sort is a good idea.

  6. WarrenWeckesser commented on Oct 11, 2014

    @WarrenWeckesser
    MemberAuthor

    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.

  7. njsmith commented on Oct 11, 2014

    @njsmith
    Member

    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).

    Nathaniel J. Smith
    Postdoctoral researcher - Informatics - University of Edinburgh
    http://vorpus.org

  8. charris commented on Oct 11, 2014

    @charris
    Member

    They might have suggestions on crucial issues like the best name too.

    We need a function named Sue.

  9. SuperElectric commented on Apr 8, 2015

    @SuperElectric

    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?

  10. 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
  11. talesa commented on Feb 5, 2019

    @talesa

    This would be really useful!

  12. Max16hr commented on Feb 25, 2019

    @Max16hr

    I also would appreciate that!

    According to https://stackoverflow.com/a/35647011/3401634, for multi-dimensional arrays X

    np.random.shuffle(X)
    

    is the same as

    np.take(X, np.random.permutation(X.shape[0]), axis=0, out=X)
    

    So why not implement

    np.random.shuffle(X, axis=axis)
    

    as

    np.take(X, np.random.permutation(X.shape[axis]), axis=axis, out=X)
    

    with the default axis=0?

  13. 17 remaining items

  14. bashtage commented on Jul 6, 2020

    @bashtage
    Contributor

    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).

  15. seberg commented on Jul 6, 2020

    @seberg
    Member

    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.

  16. WarrenWeckesser commented on Jul 6, 2020

    @WarrenWeckesser
    MemberAuthor

    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)?

  17. eric-wieser commented on Jul 6, 2020

    @eric-wieser
    Member

    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.

  18. seberg commented on Jul 6, 2020

    @seberg
    Member

    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.

  19. WarrenWeckesser commented on Jul 6, 2020

    @WarrenWeckesser
    MemberAuthor

    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.

  20. WarrenWeckesser commented on Jul 6, 2020

    @WarrenWeckesser
    MemberAuthor

    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?

  21. seberg commented on Jul 6, 2020

    @seberg
    Member

    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).

  22. added a commit that references this issue on Sep 2, 2020
    f1d0378
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