1

如果我有一个像 $(x-\mu)^T \Sigma^{-1} (x-\mu)$ 这样的矩阵产品,那么为 numpy 数组编写这个的方法是reduce(numpy.dot,((x-mu).T, scipy.linalg.inv(Sigma), x-mu))?Matlab 和 R 语法要简单得多,以至于 numpy 没有等效的运算符语法似乎有点奇怪。

4

3 回答 3

4

你也可以试试:

x = x.view(np.matrix)
isigma = scipy.linalg.inv(Sigma).view(np.matrix)
result = (x-mu).T * isigma * (x-mu)

通过将数组视为矩阵,您可以.__mul__np.matrix使用*.

于 2012-08-21T14:22:10.970 回答
1

你也可以写(Numpy >= 1.4 左右)

from scipy.linalg import inv

(x - mu).T.dot(inv(Sigma)).dot(x - mu)

如另一个答案中所述,有限的运算符语法是由于 Python 中可用的运算符数量有限。

于 2012-08-24T09:48:59.663 回答
1

The main issue is that * is already defined as elementwise multiplication for numpy arrays, and there is no other obvious operator left for matrix multiplication. The solution, as Pierre suggests, is to convert to numpy matrices, where * means matrix multiplication.

There have been a few proposals to add new operator types to Python (PEP 225, for example) which would allow something like ~* to represent matrix multiplication.

于 2012-08-21T15:04:26.893 回答