Reputation: 9579
I'm trying to code this expression in python but I'm having some difficulty.
This is the code I have so far and wanted some advice.
x = 1x2 vector
mu = 1x2 vector
Sigma = 2x2 matrix
xT = (x-mu).transpose()
sig = Sigma**(-1)
dotP = dot(xT ,sig )
dotdot = dot(dotP, (x-mu))
E = exp( (-1/2) dotdot )
Am I on the right track? Any suggestions?
Upvotes: 2
Views: 384
Reputation: 28846
Sigma ** (-1)
isn't what you want. That would raise each element of Sigma
to the -1
power, i.e. 1 / Sigma
, whereas in the mathematical expression it means the inverse, which is written in Python as np.linalg.inv(Sigma)
.
(-1/2) dotdot
is a syntax error; in Python, you need to always include *
for multiplication, or just do - dotdot / 2
. Since you're probably using python 2, division is a little wonky; unless you've done from __future__ import division
(highly recommended), 1/2
will actually be 0
, because it's integer division. You can use .5
to get around that, though like I said I do highly recommend doing the division import.
This is pretty trivial, but you're doing the x-mu
subtraction twice where it's only necessary to do once. Could save a little speed if your vectors are big by doing it only once. (Of course, here you're doing it in two dimensions, so this doesn't matter at all.)
Rather than calling the_array.transpose()
(which is fine), it's often nicer to use the_array.T
, which is the same thing.
I also wouldn't use the name xT
; it implies to me that it's the transpose of x
, which is false.
I would probably combine it like this:
# near the top of the file
# you probably did some kind of `from somewhere import *`.
# most people like to only import specific names and/or do imports like this,
# to make it clear where your functions are coming from.
import numpy as np
centered = x - mu
prec = np.linalg.inv(Sigma)
E = np.exp(-.5 * np.dot(centered.T, np.dot(prec, centered)))
Upvotes: 4