Sigma ** (-1)不是你想要的。这将提高 的每个元素Sigma的-1幂,即1 / Sigma,而在数学表达式中,它表示逆,用 Python 编写为np.linalg.inv(Sigma)。
(-1/2) dotdot是语法错误;在 Python 中,您需要始终包含*乘法,或者只需执行- dotdot / 2. 由于您可能使用的是 python 2,因此除法有点不稳定;除非你已经完成from __future__ import division(强烈推荐),1/2否则实际上会是0,因为它是整数除法。您可以使用.5它来解决这个问题,尽管就像我说的那样,我强烈建议您进行部门导入。
这是非常简单的,但是你在x-mu只需要做一次的情况下进行两次减法。如果您的向量很大,只需执行一次即可节省一点速度。(当然,这里你是在二维上做的,所以这根本不重要。)
the_array.transpose()与其调用(这很好),不如使用它通常更好the_array.T,这是同一件事。
我也不会使用这个名字xT;它向我暗示它是 的转置x,这是错误的。
我可能会这样组合它:
# 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)))