Skip to content

ENH: expand_dims by multiple dimensions #12290

Closed

Description

@homocomputeris

Background: Quite frequently I would like (and others, it seems, too) to multiply a 1D array by an array of other arrays, say:

import numpy as np
c = np.array([1, 2, 3])
E = np.ones((3, 3))
Ev = np.array([E, E, E])
# and I'd like to do this using NumPy broadcasting possibilities: 
c * Ev

Clearly, one option is to use comprehensions. Another is to expand c to have a suitable shape (3,1,1) by expand_dims or by c[:, np.newaxis, np.newaxis].

Enh: allow expand_dims accept a tuple that shows where insert new dimensions.
If an int is passed, then do the same it does now.
If a tuple (p, q, r, s, ...) of length d is passed, then increase ndim by d, fill shape elements at the indices p, q, r, s ... with 1, fill the rest with the original array's dimensions.

Some examples that illustrate the idea:

def new_expand_dims(a, axes):
    # if int is passed, retain the same behaviour
    if type(axes) == int:
        return np.expand_dims(a, axes)
    # insert axes to given indices
    for ax in sorted(axes):
        a = np.expand_dims(a, ax)
    return a


c = np.array([1, 3, 3])
csize = c.size

M = np.random.rand(8, 3, 4)


def test_int():
    assert new_expand_dims(c, 0).shape == (1, csize)


def test_consecutive_tpl():
    assert new_expand_dims(c, (0, 1)).shape == (1, 1, csize)


def test_non_consecutive_tpl():
    assert new_expand_dims(c, (0, 2)).shape == (1, csize, 1)


def test_302_tpl():
    assert new_expand_dims(c, (3, 0, 2)).shape == (1, csize, 1, 1)


def test_123_tpl():
    assert new_expand_dims(c, (1, 2, 3)).shape == (csize, 1, 1, 1)


def test_int_nd():
    assert new_expand_dims(M, 0).shape == (1, *M.shape)


def test_302_tpl_nd():
    assert new_expand_dims(M, (3, 0, 2)).shape == (1, 8, 1, 1, 3, 4)

Numpy/Python version information:

1.15.3 3.7.1 (default, Oct 22 2018, 10:41:28)
[GCC 8.2.1 20180831]

Activity

  1. eric-wieser commented on Oct 30, 2018

    @eric-wieser
    Member

    This gets a +1 from me - it's a natural extension of the axis arg in my opinion.

    Your implementation isn't quite right for negative axes - I think a correct implementation would look something like

    def expand_dims(arr, axis):
        if type(axis) not in (tuple, list):
            try:
                axis = [operator.index(axis)]
            except TypeError:
                pass
        out_ndim = len(axis) + arr.ndim
        axis = normalize_axis_tuple(axis, out_ndim)
    
        sl = [slice(None)] * out_ndim
        for ax in axis:
            sl[ax] = np.newaxis
        return arr[tuple(sl)]

    Or perhaps faster:

    def expand_dims(arr, axis):
        if type(axis) not in (tuple, list):
            try:
                axis = [operator.index(axis)]
            except TypeError:
                pass
        out_ndim = len(axis) + arr.ndim
        axis = normalize_axis_tuple(axis, out_ndim)
    
        shape_it = iter(arr.shape)
        shape = [1 if ax in axis else next(shape_it) for ax in range(out_ndim)]
        return arr.reshape(shape)
  2. homocomputeris commented on Oct 30, 2018

    @homocomputeris
    Author

    Your implementation isn't quite right for negative axes - I think a correct implementation would look something like

    I tried to show the idea and the possibility. Negative axes still confuse me, so if I knew how to implement it well, then I'd request a pull.

  3. seberg commented on Oct 30, 2018

    @seberg
    Member

    @homocomputeris pull requests are always welcome, and if there are some smaller changes necessary they can still be discussed on the PR.
    The normalize_axis_tuple function as far as I remember already handles negative ones, however, I think it might not be correct due to the fact that the output is larger then the input. I think it would have to be normalize_axis_tuple(axis, in_ndim) but then specifically allow axis == in_ndim (insert at end). Further, I think repeated axis should probably be allowed.

    EDIT: Just to note that I think it is a natural and very good extension of the API and I hope to see a PR! :)

  4. homocomputeris commented on Nov 10, 2018

    @homocomputeris
    Author

    It would be nice to be able to append a number of dims without specifying their position, e.g.:

    >>> a = np.ones((3,))
    >>> b = np.add_dims(a, 5)
    >>> b.ndim
    6
    >>> b.shape
    (3,1,1,1,1,1)
  5. mhvk commented on Nov 10, 2018

    @mhvk
    Contributor

    👍 to the general idea, which nicely makes expand_dims more closely the opposite of squeeze. I think the implementation of @eric-wieser with negative axes counting relative to the output number of dimensions makes most sense. @homocomputeris - do you want to try to make a PR? You could just use the implementation suggested by @eric-wieser but add test cases and adjust the documentation (both are very important but also a little tedious and often the reason things end up not getting done...).

    p.s. I'm a bit less enthusiastic about the add_dims idea; one can just do

    b = a.reshape(a.shape + (1,) * 5)
    
  6. eric-wieser commented on Nov 10, 2018

    @eric-wieser
    Member

    I'm a bit less enthusiastic about the add_dims idea;

    I feel the same way. Explicit is better than implicit, and it's not clear to me that inserting then at the end is obvious.

  7. eric-wieser commented on Nov 10, 2018

    @eric-wieser
    Member

    @seberg:

    I think it might not be correct due to the fact that the output is larger then the input.

    That's handled by passing in out_ndim rather than arr.ndim

  8. seberg commented on Nov 11, 2018

    @seberg
    Member

    @eric-wieser sure, but that means we specifcy the new axis based on the output dimension instead of input dimension. That seems odd to me right now, although maybe mostly because np.insert uses the input dimension IIRC. But also np.searchsorted or so would return indices based on the input dimension (although that is a bit different from inserting dimensions).

    Hmmm, I will have to think about it more:

    input_expand_dims(np.ones((2, 3, 4)), [1, 3, 3, 3]).shape == ((2, 1, 3, 4, 1, 1, 1))
    ouput_expand_dims(np.ones((2, 3, 4)), [1, 4, 5, 6]).shape == ((2, 1, 3, 4, 1, 1, 1))
    

    I think it might be good to ping the list before we decide. But that doesn't mean we can't start to have a PR, it should be pretty straight forward to adept the code in either direction.

  9. eric-wieser commented on Nov 11, 2018

    @eric-wieser
    Member

    Note that stack and expand_dims already use the axis argument to refer to output and not input dimensions

  10. eric-wieser commented on Nov 11, 2018

    @eric-wieser
    Member

    The choice is between:

    • normalize to in_arr.ndim + 1, allow duplicates
    • normalize to out_arr.ndim, forbid duplicates
  11. seberg commented on Nov 11, 2018

    @seberg
    Member

    Ah, whatever, expand dims indeed uses output dimension with respect to negative ones already (and with respect to negative it is nicer I agree). Maybe for axis it is the better convention and it is just not "inserting" axes in a sense.

  12. homocomputeris commented on Nov 16, 2018

    @homocomputeris
    Author

    @mhvk I'd like to try to make a pull request, but I've lost the thread of this output/input dimensions discussion.

  13. mhvk commented on Nov 16, 2018

    @mhvk
    Contributor

    @homocomputeris - thanks! I think the conclusion was that the model proposed by @eric-wieser made most sense, i.e., axis refers to the output. So, what I wrote above holds: start with his code (see #12290 (comment)) and add tests and documentation.

    p.s. If you need help, don't hesitate to ask - though I hope that our development guide is helpful: https://docs.scipy.org/doc/numpy/dev/

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