Home > other >  Python does not properly transpose series
Python does not properly transpose series

Time:09-05

I noticed that in python for a vector, it does not matter the order you transpose it when calculating the inner product. Is this a bug?

If u is a series

import numpy as np
u = np.array([0,1,1,1])
u.T @ u

returns a scalar as it should.

But also,

u @ u.T

Is also returning a scalar. Any ideas of what could be going on?

CodePudding user response:

In numpy, if you intend to do linear algebra operations, you need to make 2-dimensional arrays. Your example above is 1-dim, so it is not recognized as a matrix.

There is still a "matrix" object in the numpy linalg library but it is deprecated, I believe, and the best way is just to make (or reshape) arrays into 2-d objects if you intend to do linear algebra

In [36]: import numpy as np

In [37]: u = np.array([1, 0, 2])

In [38]: u.T
Out[38]: array([1, 0, 2])

In [39]: u = u.reshape((1,3))

In [40]: u.T
Out[40]: 
array([[1],
       [0],
       [2]])

In [41]: u @ u.T
Out[41]: array([[5]])

In [42]: u.T @ u
Out[42]: 
array([[1, 0, 2],
       [0, 0, 0],
       [2, 0, 4]])
  • Related