Skip to content

A replacement for np.matrix #13835

Open
Open

Description

@eric-wieser

As touched upon in in #13797

matrix was a collection of behaviors, some good and some bad:

  • .I and .H attributes. These were handy.
  • * means matmul - not inherently bad, but perhaps surprising, and certainly less necessary in the presence of @. I think there might still be some value in allowing "multiply (*)" on matrix objects to mean what @ does on array objects - it allows them to be dropped into some equations in place of scalars
  • Everything is always exactly 2d. This was the cause of almost all the pain within numpy when handling subclasses - it broke liskov substitution

I think there might be a good use case for a matrix with some subset of the following rules:

  • Construction fails if the input array is not ndim >= 2
  • Helpers for (stacks of) row and column vectors:
    • matrix.rowvec(rows) == matrix(rows[..., None, :])
    • matrix.colvec(cols) == matrix(cols[..., :, None])
  • Simpler indexing rules:
    • Shape of the returned array always matches ndarray
    • m[..., i, j], where i and j index and preserve the last two dimensions, returns a matrix object. Any type of indexing that discards the last two dimensions downcasts to array
  • .T means linalg.transpose(self), .H means .T.conj()
  • .I either means linalg.inverse(self) or perhaps an object with __mul__ = linalg.solve

Such as class would not be compatible with np.matrix, but it might be a good candidate for a new numpy/matrix package.

Activity

  1. rgommers commented on Jun 26, 2019

    @rgommers
    Member

    Thanks @eric-wieser, this feels like a good idea potentially. Not sure if it should live in numpy itself or not, but there's clearly an audience for this. This could be a duck array or subclass that plays nicely with the rest of numpy and the ecosystem.

  2. eric-wieser commented on Jun 26, 2019

    @eric-wieser
    MemberAuthor

    I think to build this effectively, some progress on #13768 would need to be made.

  3. charris commented on Jun 26, 2019

    @charris
    Member

    I think there were some old discussions related to this, mainly involving having distinguished row and column vectors instead of (n, 1) (1, n) matrices.

  4. mhvk commented on Jun 26, 2019

    @mhvk
    Contributor

    @eric-wieser - I think if I were to do a matrix class, I would do them using a sub-array for the matrix itself, i.e., the shape would just reflect the stack, not the matrix itself. At least, I once got started on a vector class, and quickly got stuck with keeping track of that last dimension with the vector, and then realizing I could not do things like transform to spherical and still keep the parts together, and that many of the standard array operations just do not make sense for vectors anyway. In contrast, astropy's Representation objects for 3-D vectors which have shapes that only represents how many there are, have turned out to be quite handy.

    I think the same would hold for a Matrix class. E.g., since you mentioned being able to sub in matrices in regular code, something like x - x.mean() has clear meaning if the mean is only taken over the vectors/matrices, but not if it is taken over their elements.

    Anyway, for such a Matrix class, any operation involving a non-Matrix would mean getting out of the sub-array. For instance, suppose the matrix itself is stored using a structured dtype([('matrix', '(n,m)f8')], the __array_ufunc__ method could look like:

     def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
            for input_ in inputs:
                if isinstance(input_, Matrix):
                    converted.append(input_['matrix'])
                else:
                    shape = getattr(input_, 'shape', ())
                    if shape:
                        converted.append(input_[..., np.newaxis, np.newaxis])
                    else:
                        converted.append(input_)
    

    (copied from https://github.com/astropy/astropy/blob/master/astropy/uncertainty/core.py, where a similar scheme is used to propagate distributions of samples, as a simple way of Monte-Carlo error propagation; the nice thing about structured dtypes is that almost no operation works on them by default, so it is not too easy to get nonsensical answers)

    Here, vectors could be represented by the matrices directly, just with m=1 or n=1 in the dtype.

    Anyway, this would be well beyond your proposal, of course. But my sense from it is that it makes most sense to provide some minimal conveniences on ndarray itself.

  5. bashtage commented on Jun 26, 2019

    @bashtage
    Contributor
    • * means matmul - not inherently bad, but perhaps surprising, and certainly less necessary in the presence of @. I think there might still be some value in allowing "multiply (*)" on matrix objects to mean what @ does on array objects - it allows them to be dropped into some equations in place of scalars

    -1 on this since there is no equivalent of .* in MATLAB. (I had a brief thought of making @ be element-by-elemet for matrix , but that would also be quite bad). Seems the best bet would be to have @ follow the rule of Linear Algebra, if possible.

  6. kjohnsen commented on Jun 12, 2020

    @kjohnsen

    I'm just learning about np.matrix and am wondering if there's a way to at least save the convenience of initializing a matrix with a string (e.g., np.array.fromstr('1 2; 3 4'). That compact syntax is one thing that makes Matlab more convenient for doing linear algebra, which could be easily implemented for np.array like it is for np.matrix.

    Even for someone like me, who prefers Python to Matlab, the cumbersome syntax for doing linear algebra tempts me to use Matlab instead.

  7. asmeurer commented on Dec 6, 2022

    @asmeurer
    Member

    If anything like this is ever implemented, either in NumPy or elsewhere, I would also suggest disallowing broadcasting in the last two dimensions for + and - (and possibly other operators as well). When working with matrices, adding a vector to a matrix is usually a mistake and it would be more useful to get an error.

  8. mhvk commented on Dec 6, 2022

    @mhvk
    Contributor

    @asmeurer - I agree. Indeed, similar logic let me to suggest the shape should not even include those last 2 dimensions in #13835 (comment)

  9. asmeurer commented on Dec 7, 2022

    @asmeurer
    Member

    Sorry, I hadn't read your comment that closely previously. I hadn't considered using a struct dtype. That's an interesting idea. I was actually thinking that one might also want * to just do scalar multiplication (i.e., only allow operands that broadcast to the shape of the stacked dimensions). That sort of broadcasting logic would be complex with a normal array but it makes perfect sense with this idea. You'd also want some helpers to interpret the matrix as an array in case you really do want to do a Hadamard product or some other elementwise operation, but I like the idea of always being explicit about that.

    The only downside of a struct dtype is that you have to nest indices. Perhaps that could be seen as a positive, explicitly keeping the stack and the matrix dimensions separate. Or the matrix class could handle the abstraction of automatically splitting indices.

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