1. Implementation of matrix multiplication
there are numpy.dot functions in numpy to handle multiplication between matrices:
In [2]: a = Np.reshape (Np.arange (6), (2,3)) in [3]: b = Np.reshape (Np.arange (6), (3,2)) in [4]: Np.dot (A, B) Out[4]:array ([[10 , 13], [28, 40]])
But if we're going to implement matrix A * b * c * d, then writing three Numpy.dot is a little cumbersome. We can define a function Mdot (a,b,c,d) to complete.
1. Using the Reduce
We can use reduce to achieve MDOT:
In [9]: def MDOT (*args): ...: return reduce (Np.dot, args) ...: in [ten]: a = Np.reshape (Np.arange (6), (2,3)) in [11]: b = Np.reshape (Np.arange (6), (3,2)) in []: Mdot (a,b,a,b) Out[12]:array ([[464, 650], [1400, 1964]])
2. Order of Control matrix multiplication
Suppose we want to get MDOT to perform an ordered multiplication by (), we need to write a recursive function to do it:
In [13]: import typesin [14]: def mdot (*args): ....: if len (args) == 1: ....: return args[0] ....: elif len ( args) == 2: ....: return _mdot_r (args[0], args[1]) ....: else: : return _mdot_r (Args[:-1], args[-1]) ....:in [15]: def _mdot_r (a, b): ....: if type (a) == types. Tupletype: ....: if len (a) > 1: ....: &Nbsp; a = mdot (*a) ....: else: ....: a = a[0] ....: if type (b) == types. Tupletype: ....: if len (b) > 1: ....: b = mdot (*b) ....: else: ....: b = b[0] ....: return np.dot (a, b) .....: In [16]: mdot (b, ((a, b), a)) Out[16]:array ([[ 120, 188, 256], [ 438, 688, 938],    [ 756, 1188, 1620]]) in [17]: aout[17]:array ([[0, 1, 2],        [3, 4, 5]]) in [18]: bout[18]:array ([[0, 1],        [2, 3],       [4, 5]])
2. Recarray
1. Using names to identify arrays
There are two ways to reach "Use name to identify an array": Recarrays and structured arrays.
Structured arrays as follows:
In [all]: from numpy import *in ["]: Ones (3, Dtype=dtype ([' foo ', int), (' Bar ', float)])) Out[34]:array ([(1, 1.0), (1, 1.0) , (1, 1.0)], dtype=[(' foo ', ' <i8 '), (' Bar ', ' <f8 ')]) in []: R = _in [approx]: r[' foo ']out[36]: Array ([1, 1, 1])
And we can use Recarray to convert R to: Recarray type
in [+]: r2 = R.view (Recarray) in [the]: R2out[49]:rec.array ([(1, 1.0), (1, 1.0), (1, 1.0)], dtype=[(' foo ', ' <i8 '), (' Bar ', ' <f8 ')]) in [[]: r2.fooout[50]: Array ([1, 1, 1])
But where is the difference between R and R2?
In []: r = = r2out[56]: Rec.array ([True, True, True], dtype=bool) in []: R.dtype = = r2.dtypeout[57]: Truein [+]: R.S Hape = = r2.shapeout[58]: Truein [max]: type (r) = = Type (r2) out[59]: Falsein [+]: type (r) out[60]: Numpy.ndarrayin [max]: type (R2) OUT[61]: Numpy.core.records.recarray
Cookbook/multidot,recarray