Python - matrix multiplication

Viewed 123

i have an array y with shape (n,), I want to compute the inner product matrix, which is a n * n matrix However, when I tried to do it in Python

np.dot(y , y)

I got the answer n, this is not what I am looking for I have also tried:

np.dot(np.transpose(y),y)
np.dot(y, np.transpose(y))

I always get the same answer n

4 Answers

I think you are looking for:

np.multiply.outer(y,y)

or equally:

y = y[None,:]
y.T@y

example:

y = np.array([1,2,3])[None,:]

output:

#[[1 2 3]
# [2 4 6]
# [3 6 9]]

You can try to reshape y from shape (70,) to (70,1) before multiplying the 2 matrices.

# Reshape
y = y.reshape(70,1)

# Either below code would work
y*y.T

np.matmul(y,y.T)

Looks like what you need is the @ matrix multiplication operator. dot method is only to compute dot product between vectors, what you want is matrix multiplication.

>>> a = np.random.rand(70, 1)
>>> (a @ a.T).shape
(70, 70)

UPDATE:

Above answer is incorrect. dot does the same things if the array is 2D. See the docs here.

np.dot computes the dot product of two arrays. Specifically,

  • If both a and b are 1-D arrays, it is inner product of vectors (without complex conjugation).
  • If both a and b are 2-D arrays, it is matrix multiplication, but using matmul or a @ b is preferred.

Simplest way to do what you want is to convert the vector to a matrix first using np.matrix and then using the @. Although, dot can also be used @ is better because conventionally dot is used for vectors and @ for matrices.

>>> a = np.random.rand(70)
(70,)
>>> a.shape
>>> a = np.matrix(a).T
>>> a.shape
(70, 1)
>>> (a @ a.T).shape
(70, 70)

One-liner?

np.dot(a[:, None], a[None, :])

transpose doesn't work on 1-D arrays, because you need atleast two axes to 'swap' them. This solution adds a new axis to the array; in the first argument, it looks like a column vector and has two axes; in the second argument it still looks like a row vector but has two axes.

Related