0

So if I have this code which is basically the same as the demonstartion on the numpy reference page:

import numpy as np
import matplotlib.pyplot as plt

mean = [0,0]
cov = [[1,-0.5], [-0.5,1]]

n = int(input("How many random points?"))

x, y = np.random.multivariate_normal(mean, cov, size = n).T

plt.plot(x,y, 'x')
plt.show()

I don't understand the meaning of the .T at the end of line 9, but without it the program gives the error

ValueError: too many values to unpack (expected 2)

Can someone explain this error and the meaning of the .T which fixes it

Thanks

big daddy
  • 65
  • 1
  • 9

2 Answers2

1

.T transposes a matrix. So in your case, if n=2, your code will work (or at least, will run without error) without the transpose, because a matrix such as:

>>> np.random.multivariate_normal(mean, cov, size = 2)
array([[ 1.4594626 , -0.55863612],
       [-1.17139735, -0.36484634]])

Can be split into 2 arrays (x will be [ 1.4594626 , -1.17139735] and y will be [-0.55863612, -0.36484634]). Note that this is not necessarily what you are looking for, and you might end up plotting the wrong thing (depending what you're trying to do).

But for anything bigger (or smaller), it won't:

>>> np.random.multivariate_normal(mean, cov, size = 5)
array([[-0.34091962,  2.2368088 ],
       [-1.11081547,  0.93089064],
       [ 1.45452483, -0.40007311],
       [ 0.96038401,  0.26206106],
       [ 0.3079481 ,  0.66869094]])

Because that is essentially 5 arrays that you are trying to unpack into 2 variables (hence the error). However when you transpose it:

>>> np.random.multivariate_normal(mean, cov, size = 5).T
array([[ 0.04466423,  0.88384196,  0.09108559, -2.30473587,  1.58497064],
       [ 0.66190894,  0.90202853,  0.31090378,  0.95697681, -0.61557393]])

You're good to go. Your x array will be the first "row": [ 0.04466423, 0.88384196, 0.09108559, -2.30473587, 1.58497064] and y will be your second: [ 0.66190894, 0.90202853, 0.31090378, 0.95697681, -0.61557393]

Crysishy
  • 57
  • 8
sacuL
  • 49,704
  • 8
  • 81
  • 106
  • 1
    "if `n=2`, your code will work without the transpose". No, it won't. It won't throw an error but it will plot the wrong thing. – Joooeey Oct 03 '18 at 23:37
  • 1
    True, good point. I meant it will work as in that array will be able to be unpacked into 2 variables. I've made a note in my answer, thanks! – sacuL Oct 03 '18 at 23:38
0

ndarray.T is a transposition of the rows and columns.

mVChr
  • 49,587
  • 11
  • 107
  • 104