np.dot in NumPy printing the transpose of what should be expected

Viewed 101

I'm really new to Python and am wondering why this is printing the opposite of expected. A (7x4)(4x2)(2x1) multiplication should result in a 7x1 column vector.

import numpy as np

nutrition = np.array([[61, 100, 7, 2.2, 1, 7, 215],
                      [156, 340, 18, 7, 44, 5, 0],
                      [19, 110, 9, 3.3, 0, 6, 16],
                      [27, 60, 2, 0.5, 8, 2, 16]])

meals = np.array([[2, 1, 0, 0],
                  [0, 1, 1, 1]]

M = np.array([40, 10])


print(np.dot(nutrition.T, np.dot(meals.T, M)))

Instead, it is printing a 1x7 row vector:

[13140. 26700.  1570.   564.  2360.   890. 17520.]

Any explanation or problems to look into would be appreciated.

1 Answers

Your array M is of shape (2,) and NOT (2,1):

print(M.shape)
(2,)

Hence, the output shape is (7,) and NOT (7,1). Which makes it a 1-D array represented in a single row:

print(np.dot(nutrition.T, np.dot(meals.T, M)).shape)
(7,)

If you want a (7,1) output, simply reshape your M to (2,1):

M = M.reshape(-1,1)
#[[40]
# [10]]

And output would be:

[[13140.]
 [26700.]
 [ 1570.]
 [  564.]
 [ 2360.]
 [  890.]
 [17520.]]
Related