Make matrix multiplication operator @ work for scalars in numpy

In python 3.5, the operator @for matrix multiplication was introduced , after PEP465 . This is implemented, for example. in numpy as a matmul statement .

However, as suggested by PEP, the numpy operator throws an exception when called with a scalar operand:

>>> import numpy as np
>>> np.array([[1,2],[3,4]]) @ np.array([[1,2],[3,4]])    # works
array([[ 7, 10],
       [15, 22]])
>>> 1 @ 2                                                # doesn't work
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: unsupported operand type(s) for @: 'int' and 'int'

This is a real turn for me, because I implement algorithms for processing numerical signals that should work for both scalars and matrices. The equations for both cases are mathematically exactly equivalent, which is not surprising, since “1-D x 1-D matrix multiplication” is equivalent to scalar multiplication. However, the current state forces me to write repeated code in order to handle both cases correctly.

, , , @ ? __matmul__(self, other) , , . __matmul__ numpy, 1x1?

, , ? .

+4
1

ajcr, , , . : atleast_1d atleast_2d, , @: 1 1.

x = 3
y = 5
z = np.atleast_1d(x) @ np.atleast_1d(y)   # returns 15 
z = np.atleast_2d(x) @ np.atleast_2d(y)   # returns array([[15]])

:

  • atleast_2d , x y - 1D-,
  • atleast_1d , , , , .
  • , np.dot(x, y), .

, atleast_1d , @scalar = scalar: , . z.T z.shape ? 1 1, . Python 1 1, , .

+1

Source: https://habr.com/ru/post/1663966/


All Articles