代码是:
import numpy as np
def Mahalanobis(x, covariance_matrix, mean):
x = np.array(x)
mean = np.array(mean)
covariance_matrix = np.array(covariance_matrix)
return (x-mean)*np.linalg.inv(covariance_matrix)*(x.transpose()-mean.transpose())
#variables x and mean are 1xd arrays; covariance_matrix is a dxd matrix
#the 1xd array passed to x should be multiplied by the (inverted) dxd array
#that was passed into the second argument
#the resulting 1xd matrix is to be multiplied by a dx1 matrix, the transpose of
#[x-mean], which should result in a 1x1 array (a number)
但由于某些原因,当我输入参数时,我得到了一个输出矩阵
^{pr2}$输出:
out[]: array([[ 2. , 0. ],
[ 0. , 0.5]])
似乎我的函数只是给我在第二个参数中输入的2x2矩阵的倒数。在
可以使用
scipy
的mahalanobis()
函数来验证:你犯了一个经典的错误,假设*运算符是做矩阵乘法的。这在Python/numpy中是不正确的(请参见http://www.scipy-lectures.org/intro/numpy/operations.html和https://docs.scipy.org/doc/numpy-dev/user/numpy-for-matlab-users.html)。我把它分解成中间步骤并使用了点函数
生产
^{pr2}$相关问题 更多 >
编程相关推荐