Python does not properly transpose series

Question:

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?

Asked By: r-learning-machine

||

Answers:

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]])
Answered By: AirSquid
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.